From alan.gauld at blueyonder.co.uk Sat May 1 04:39:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 1 04:39:37 2004 Subject: [Tutor] Looking for feedback Message-ID: <005001c42f57$de9455e0$6401a8c0@xp> I've just uploaded the first few pages of my re-written tutorial. The look and feel is a bit more modern (only slightly!) and is based on the style sheet created for the Czech version by Petr Prykl. The rewritten chapters contain more material, more diaghrams and use VBScript and Javascript instead of QBASIC and Tcl as comparison languages. There is more info on the alternate languages too. They also try to address most of the comon questions raised by newbies on this list - like how to stop programs running and immediately closing etc... I'd appreciate any early feedback on the new look, the new content, and the use of VBScript and Javascript. The new pages are the ones from the top down to "Add a little style". The pages are here: http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ Further chapters will be added as I get round to them, but don't hold your breath, as it's a slow process and my time is short at the moment. The original tutor will still be around, at least until the new version is completed, and probably in zip format for longer still. Send feedback to me directly rather than to the list please. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From project5 at redrival.net Sat May 1 05:28:15 2004 From: project5 at redrival.net (Andrei) Date: Sat May 1 05:28:34 2004 Subject: [Tutor] Re: double backslash in Windows paths References: <20040430162118.N70165-100000@localhost.name> Message-ID: wrote on Fri, 30 Apr 2004 16:21:34 -0700 (PDT): > hi everybody, what do you guys use to convert a Windows path, with single > backslash, to double backslash ? I ask this because I've been using > os.path.normpath, and it leaves A LOT to be desired. If you pass it a > path, and say some directory in the path starts with a number, > os.path.normpath WILL mangle the path by inserting a '\x{hex value}' > instead of the desired behavior, '\\{dirname}'. Then you have to go back > and clean up and add in the extra backslash in the string before using it. I use forward slashes in paths. Works in Windows too from Python and you don't have to escape them. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From thorsten at thorstenkampe.de Sat May 1 06:10:38 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat May 1 06:10:50 2004 Subject: [Tutor] Re: Looking for feedback References: <005001c42f57$de9455e0$6401a8c0@xp> Message-ID: * Alan Gauld (2004-05-01 10:39 +0100) > I've just uploaded the first few pages of my re-written tutorial. > The look and feel is a bit more modern (only slightly!) and is > based on the style sheet created for the Czech version by Petr Prykl. > > The rewritten chapters contain more material, more diaghrams and > use VBScript and Javascript instead of QBASIC and Tcl as > comparison languages. There is more info on the alternate > languages too. They also try to address most of the comon > questions raised by newbies on this list - like how to stop > programs running and immediately closing etc... > > I'd appreciate any early feedback on the new look, the new content, > and the use of VBScript and Javascript. You'd probably get more feedback if the the new version would be downloadable for offline browsing - at the moment the download links lead to a 404. I'd prefer a white or beige (or perhaps light grey) background for readability reasons. By the way: frames are generally not useful and make the use of a website more difficult. Thorsten From magnus at thinkware.se Sat May 1 11:42:06 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 1 11:38:06 2004 Subject: [Tutor] Tkinter In-Reply-To: <20040429202010.GE21154@wdfs.graniteweb.com> References: <40916214.1070907@city.ee> <20040429194414.5354.qmail@city.ee> <20040429200710.GB21154@wdfs.graniteweb.com> <40916214.1070907@city.ee> Message-ID: <5.2.1.1.0.20040501173214.02f7fc30@www.thinkware.se> At 15:20 2004-04-29 -0500, David Rock wrote: >* Olavi Ivask [2004-04-29 23:14]: > > David Rock wrote: > > > > > >label = Label(root, text="Label1").grid() > > > > > >assigns the grid object to the variable label, while Does the .grid() method return a "grid object"? What is a grid object? In my experience, the .grid() method returns None, so label = Label(...).grid() is as meaningless as x = [1,4,2,7,4].sort() You really must understand the return type for each method/function to understand these things. E.g. the Twisted networking framework uses the practice of having many methods return "self", so that you can write: x = AClass().method1().method2().method3() instead of x = AClass() x.method1() x.method2() x.method3() I'm not convinced this is a good thing though... > > >label = Label(root, text="Label1") > > > > > >assigns the LABEL object to label. The second one is probably better > > >because you are working with the primary object that you can call ALL > > >methods for, not just grid(), while the first is limited to JUST grid() > > > > > > > > can i do something like that: > > I "define" several widgets: > > label = Label(root, text="text") > > label = Label(root, text="text2") > > ... > > label.grid() > > > > right now, it shows only second widget. > >No. you are overwriting the first assignment with the second. You would >have to use label1, label2, etc. Ideally, label would be something >vaguely descriptive so you could tell at a glance _which_ label it is >and what it's for. If you have plenty of labels and don't want to repeat yourself, you can do something like: for text in ["text", "text", ...]: label = Label(root, text=text) label.grid() For other controls, it's likely that you want to keep some kind of handle to it, so that you can do things like enable/disable etc, but with labels, we often don't care about keeping references after we made them. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sat May 1 11:55:43 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 1 11:52:02 2004 Subject: [Tutor] env shebang with options In-Reply-To: References: <1cau2djhoe168$.dlg@thorstenkampe.de> Message-ID: <5.2.1.1.0.20040501175257.024dfe20@www.thinkware.se> At 22:50 2004-04-29 -0700, Danny Yoo wrote: >Ok, after reading this a bit, I'm guessing that > > #!/usr/bin/env python {options} > >might not be so portable, as the shebang feature seems to behave subtly >different between all the the Unices. Yes, it seems that #!/usr/bin/env python and #!/usr/bin/python -Ot works, but not #!/usr/bin/env python -Ot in Linux. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From hloughf at hotmail.com Sat May 1 12:00:03 2004 From: hloughf at hotmail.com (Marina _) Date: Sat May 1 12:00:09 2004 Subject: [Tutor] module re Message-ID: Hi, I need to write a program, that delete white spaces, comments, tabs etc. I used module re.compile(text, re.X). The problem is: the result is not a string, but an sre object, so I can?t print it. Does anyone knows how can it be done? I have python2.3, Suse Linux 9.0 Marina _________________________________________________________________ Wu?ten Sie, da? Sie Ihren Hotmail-Posteingang auch ?ber den MSN Messenger abrufen k?nnen? http://www.msn.de/messenger Jetzt kostenlos downloaden und einfach testen! From magnus at thinkware.se Sat May 1 12:21:56 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 1 12:18:05 2004 Subject: [Tutor] double backslash in Windows paths In-Reply-To: <20040430162118.N70165-100000@localhost.name> Message-ID: <5.2.1.1.0.20040501180026.024ecdb8@www.thinkware.se> At 16:21 2004-04-30 -0700, tpc@csua.berkeley.edu wrote: >hi everybody, what do you guys use to convert a Windows path, with single >backslash, to double backslash ? I don't understand what your problem is. You typically don't convert strings to double up backslashes. You use backslashes as escape characters in string lterals. This means that the string literal "hello\tthere" in your Python source code conweys the message to Python that you want the letters h, e, l, l, o, followed by a TAB character and then there is t, h, e, r and e in your string. There is no way you can change a tab character to a backslash followed by a t by trying to change \ to \\. So, if you type string literals, you either need to use raw strings, such as in d = r"c:\this\there", or use double backslashes as in d = "c:\\this\\there". Both those strings contain exactly the same thing after the Python interpreter has parsed them. They contain just what the first (raw) string suggests. If you for instance read strings from files or from raw_input, this is not an issue. You need to use eval() etc to make Python read \t as if it would be a tab character. Alternatively, you can use d = "c:/this/there" instead, and about the whole issue. The exception to this is when you will pass your strings to some external program or library that expects strings with backslashes being escapes, such as the regular expression library (re) or some external OS command. In those cases, the string escapeas will be interpreted twice, by two different systems, so that "\\t" will be translated to "\t" and that will be translated to a tab in the second step, and if you actually need "\t" after the second step, you might need to write a string literal as "\\\\t" which is the same as reading in a string containing \\t. Confused now? ;^) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Sat May 1 12:31:55 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat May 1 12:28:16 2004 Subject: [Tutor] module re In-Reply-To: Message-ID: <5.2.1.1.0.20040501182412.024d9d88@www.thinkware.se> At 18:00 2004-05-01 +0200, Marina _ wrote: >Hi, > >I need to write a program, that delete white spaces, comments, tabs etc. I >used module re.compile(text, re.X). The problem is: the result is not a >string, but an sre object, so I can't print it. Does anyone knows how can >it be done? I have python2.3, Suse Linux 9.0 I'm not sure what you did, because re substitute functions return strings. Deletion is the same as replacing with "", right? >>> import re >>> x = re.sub("s", "z", "see his snowy sidewalk") >>> type(x) >>> print x zee hiz znowy zidewalk Anyway, you can certainly extract text from regular expression objects, but I don't see why you want that. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From thorsten at thorstenkampe.de Sat May 1 19:42:25 2004 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat May 1 19:42:31 2004 Subject: [Tutor] except AttributeError, TypeError: Message-ID: What is the best way to except two errors, when the except handling in both cases is the same? "except:" would just except every error and not just those I want. except Attribute error: do_much_stuff except TypeError: do_the_same_stuff is bad because of the duplication and def do_it(): do_much_stuff except Attribute error: do_it() except TypeError: do_it() would work but is rather unelegant? What is the best way to except to errors with the same exception handling? Thorsten From dyoo at hkn.eecs.berkeley.edu Sat May 1 20:16:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat May 1 20:17:03 2004 Subject: [Tutor] module re In-Reply-To: <5.2.1.1.0.20040501182412.024d9d88@www.thinkware.se> Message-ID: On Sat, 1 May 2004, Magnus [iso-8859-1] Lyck=E5 wrote: > I'm not sure what you did, because re substitute functions return > strings. Deletion is the same as replacing with "", right? Marina used re.compile(), which returns a 'regex' object. I think there's some confusion in the usage: > > I used module re.compile(text, re.X). What Marina probably wants to do is first compile a pattern, and then apply that pattern to text. For example, if we have something like this: ### >>> space_pattern =3D re.compile(' ') ### then what we are holding now is a regular expression "pattern" object that knows how to look at spaces: ### >>> space_pattern <_sre.SRE_Pattern object at 0x60a20> ### This 'space' pattern object can be applied to things like string substitution: ### >>> space_pattern.sub('*', 'hello world this is a test') 'hello*world*this*is*a*test' ### But note that trying to re.compile() the text we're trying to manipulate isn't too effective: ### >>> pattern =3D re.compile('hello world this is a test') ## ?? ### because we're inadvertantly reversing the roles of the text and the pattern. We need to make a distinction between the "pattern" we're trying to recognize, and the "text" we want to apply the pattern on. Maybe this is the point of confusion; I'm not sure about this, though, since I haven't seen more of Marina's program. Marina, have you seen the Regex HOWTO tutorial yet? It has quite a few examples of doing regular expressions in Python, written by A.M. Kuchling. It's quite nice, and may help clear things up. Here's a link to the tutorial: http://www.amk.ca/python/howto/regex/ From dyoo at hkn.eecs.berkeley.edu Sat May 1 20:24:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat May 1 20:24:15 2004 Subject: [Tutor] except AttributeError, TypeError: In-Reply-To: Message-ID: On Sun, 2 May 2004, Thorsten Kampe wrote: > What is the best way to except two errors, when the except handling in > both cases is the same? Hi Thorsten, Ah! There's an slightly cleaner way to do this. Let's say that we have this: ### def do_it(): try: do_much_stuff() except AttributeError: do_it() except TypeError: do_it() ### Here's another way to write the same thing: ### def do_it(): try: do_much_stuff() except (AttributeError, TypeError): do_it() ### We are allowed to pass a tuple of exceptions that we want to handle uniformly. The Official Python Tutorial covers this usage here: http://www.python.org/doc/tut/node10.html#SECTION0010300000000000000000 and it shows another way to do a kind of 'wildcarding' except clause that captures everything. If you have more questions, please feel free to ask. Good luck! From rick at niof.net Sun May 2 02:03:39 2004 From: rick at niof.net (Rick Pasotto) Date: Sun May 2 02:03:53 2004 Subject: [Tutor] env shebang with options In-Reply-To: <5.2.1.1.0.20040501175257.024dfe20@www.thinkware.se> References: <1cau2djhoe168$.dlg@thorstenkampe.de> <5.2.1.1.0.20040501175257.024dfe20@www.thinkware.se> Message-ID: <20040502060339.GV11788@niof.net> On Sat, May 01, 2004 at 05:55:43PM +0200, Magnus Lyck? wrote: > At 22:50 2004-04-29 -0700, Danny Yoo wrote: > >Ok, after reading this a bit, I'm guessing that > > > > #!/usr/bin/env python {options} > > > >might not be so portable, as the shebang feature seems to behave > >subtly different between all the the Unices. > > Yes, it seems that > > #!/usr/bin/env python > > and > > #!/usr/bin/python -Ot > > works, but not > > #!/usr/bin/env python -Ot > > in Linux. I believe that's because '#!command' can take only *one* option string. In the last case the command is '/usr/bin/env' and that option is 'python'. Anything after that is ignored. -- "...in a stateless society there would be no regular, legalized channel for crime and aggression, no government apparatus the control of which provides a secure monopoly for invasion of person and property." -- Power and Market Rick Pasotto rick@niof.net http://www.niof.net From alan.gauld at blueyonder.co.uk Sun May 2 13:47:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun May 2 13:46:50 2004 Subject: [Tutor] module re References: <5.2.1.1.0.20040501182412.024d9d88@www.thinkware.se> Message-ID: <00bc01c4306d$8bf5d950$6401a8c0@xp> >I need to write a program, that delete white spaces, comments, tabs etc. I >used module re.compile(text, re.X). The problem is: the result is not a >string, but an sre object, The sre object is what you use to perform the replacements. myRE = re.compile(reString,re.X) myString = myRE.replace(myString) myString now has the modified version of the original according to the re you compiled in the previous step. Is that anything like what you did? Alan G From magnus at thinkware.se Sun May 2 14:27:55 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun May 2 14:23:55 2004 Subject: [Tutor] except AttributeError, TypeError: In-Reply-To: References: Message-ID: <5.2.1.1.0.20040502201249.02f23220@www.thinkware.se> At 17:24 2004-05-01 -0700, Danny Yoo wrote: > try: > do_much_stuff() > except (AttributeError, TypeError): > do_it() Note that you *must* *not* forget the parenthesis here. It's perfectly legal to write... try: do_much_stuff() except AttributeError, TypeError: do_it() ...but it won't do what you expect! Remember that you can write: try: do_much_stuff() except AttributeError, my_attribute_error_object: print my_attribute_error_object In other words, the except statement takes two parameters, first an exception class (or a tuple of exceptions classes), and secondly the variable you want to reference your exception object. Both arguments are optional, but since they are positional, you can't write the second argument without writing the first, i.e. you must write a class name (at least) to be able to get the exception object to a variable. This isn't a problem though, since you don't need to write the concrete class that the exception object belongs to. Any super class is also fine, so the base class for all exception will catch all exceptions. I.e. except Exception e: will catch all exceptions, and you will get a reference to the exception object through the variable 'e'. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From isrgish at fastem.com Sun May 2 18:01:46 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun May 2 18:01:36 2004 Subject: [Tutor] RE: [PythonCE] shutil import failure Message-ID: It seems that the module shutil needs a DLL file in the windows directory called shutil.dll. After looking in my windows directory I see that I have one. If you need it I can e-mail it to you. My machine is a xscale witch is compatible with StrongArm. so if you have either it should work for you. All the best, Isr -----Original Message----- >From: "Richard Deeley" >Sent: 5/1/04 9:08:44 PM >To: "PythonCE@python.org" >Subject: [PythonCE] shutil import failure > > >After processing a set of import statements OK, the thing died >on importing shutil. I checked the lib directory and there is >a shutil.pyc there. The error message is > >NameError: Can't find file for module shutil >(filename shutil.dll) > >Any ideas how to resolve ? > >Richard. > >(imports that were processed OK include os,time,re,string) > > > > > >__________________________________ >Do you Yahoo!? >Win a $20,000 Career Makeover at Yahoo! HotJobs >http://hotjobs.sweepstakes.yahoo.com/careermakeover > >_______________________________________________ >PythonCE mailing list >PythonCE@python.org >http://mail.python.org/mailman/listinfo/pythonce From tpc at csua.berkeley.edu Mon May 3 04:22:22 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon May 3 04:22:42 2004 Subject: [Tutor] list iteration Message-ID: <20040503012111.O95181-100000@localhost.name> hi everybody, when iterating through lists, may I assume that for all intents and purposes, 'for item in itemslist' is the same as 'for item in itemslist[:]' ? I first encountered the latter statement today, and am puzzled why one would use it as opposed to the former, which seems simpler and more straightforward. From dyoo at hkn.eecs.berkeley.edu Mon May 3 04:50:16 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 3 04:50:24 2004 Subject: [Tutor] list iteration [iteration and mutation?] In-Reply-To: <20040503012111.O95181-100000@localhost.name> Message-ID: On Mon, 3 May 2004 tpc@csua.berkeley.edu wrote: > when iterating through lists, may I assume that for all intents and > purposes, 'for item in itemslist' is the same as > 'for item in itemslist[:]' ? I first encountered the latter statement > today, and am puzzled why one would use it as opposed to the former, which > seems simpler and more straightforward. Hi tpc, The second approach, for item in itemslist[:]: makes a copy of the list 'itemslist', and then iterates across this copy. In contrast: for item in itemslist: iterates directly across itemslist. So the difference is the list copying. Offhand, I'd prefer the first approach, unless we were doing something funny, like mutating itemslist within the loop. Mutating the same list that we're iterating across is often a bug-prone situation. For example, the following code is broken: ### >>> def removeEvens(numbers): ... for i in range(len(numbers)): ... if numbers[i] % 2 == 0: ... del numbers[i] ... >>> upToTwenty = range(20) >>> removeEvens(upToTwenty) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in removeEvens IndexError: list index out of range ### Do you see why we're getting an error here? If not, then look at it more closely. *grin* Without seeing the context of the code that you're looking at, my best guess is that an issue similar to the one above is possible if the loop iterates directly on the list. But by iterating on a copy of the list, we try to work around the issue of things like having indicies being yanked right under our feet as we iterate. If that's case, it might be nicer to explicitely rewrite: for item in itemslist[:]: ... as two statements: copiedList = itemslist[:] for item in copiedList: ... The intent, to iterate across the copy of a list, is odd enough that it probably needs explanation, either with a comment, or with the two-statement breakup that we have above, so that we make that intent very clear to a human reader. Good luck to you! From flaxeater at yahoo.com Mon May 3 10:34:17 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon May 3 10:34:24 2004 Subject: [Tutor] list iteration [iteration and mutation?] In-Reply-To: Message-ID: <20040503143417.13615.qmail@web11601.mail.yahoo.com> > If that's case, it might be nicer to explicitely > rewrite: > > for item in itemslist[:]: ... > > as two statements: > > copiedList = itemslist[:] > for item in copiedList: ... > > The intent, to iterate across the copy of a list, is > odd enough that it > probably needs explanation, either with a comment, > or with the > two-statement breakup that we have above, so that we > make that intent very > clear to a human reader. > > > Good luck to you! I wanted to chime in a moment about this. I recently ran in to this very bug where I needed to remove items from a list. I was making a GUI two list box's you click on a button to send items from one listbox to the other and backand forth. Naturally when deleted items I got an out of index error. What I did was built a list of index numbers then iterated over them from highest to lowest using .reverse(). self.buildlist=list(self.origin.GetSelections()) for v in self.buildlist: self.destlist.append(self.emotionlist[v]) self.buildlist.reverse() for v in self.buildlist: del self.emotionlist[v] Nothing fantastic. __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From magnus at thinkware.se Mon May 3 13:42:14 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon May 3 13:42:26 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gbGlzdCBpdGVyYXRpb24gIFtpdGVyYXRpb24gYW5kIG11dGF0aW9uP10=?= Message-ID: Chad Crabtree wrote: > I wanted to chime in a moment about this. I > recently ran in to this very bug where I needed to > remove items from a list. I was making a GUI two list > box's you click on a button to send items from one > listbox to the other and backand forth. Naturally > when deleted items I got an out of index error. What > I did was built a list of index numbers then iterated > over them from highest to lowest using .reverse(). > > self.buildlist=list(self.origin.GetSelections()) > for v in self.buildlist: > self.destlist.append(self.emotionlist[v]) > self.buildlist.reverse() > for v in self.buildlist: > del self.emotionlist[v] Often, it's simplest to just iterate over a reversed range, such as in: l = for i in range(len(l)-1, -1, -1): if we_want_to_remove(l[i]): del l[i] Modification of a list while we iterate over it, is probably something many Python programmers have stumbled over at some time (but we learn...) Here is a little study to display the phenomena in a simple case. Remove all strings in a list that start with 'm'. >>> l =['molly', 'monkey', 'polly', 'dolly', 'mike', 'pike', 'moo', 'mew'] >>> for name in l: .. if name.startswith('m'): .. l.remove(name) >>> l ['monkey', 'polly', 'dolly', 'pike', 'mew'] Oops. This trivial implementation fails when there are adjacent strings that start with 'm'. After the first turn in the loop, 'molly' has been removed, so 'monkey' is at index 0, but we've done that location in the list, so we go on with index 1, which is now 'polly'. 'monkey' never gets tested. >>> l =['molly', 'monkey', 'polly', 'dolly', 'mike', 'pike', 'moo', 'mew'] >>> for ix, name in enumerate(l): .. if name.startswith('m'): .. del l[ix] >>> l ['monkey', 'polly', 'dolly', 'pike', 'mew'] Since the problem was in our test, it doesn't make a difference whether we try to delete with "l.remove(name)" or "del l[ix]". Same result as above. >>> l =['molly', 'monkey', 'polly', 'dolly', 'mike', 'pike', 'moo', 'mew'] >>> for name in l[:]: .. if name.startswith('m'): .. l.remove(name) >>> l ['polly', 'dolly', 'pike'] This time it works, because we iterate over the copy, find all names, and use "l.remove(name)" which doesn't care about indices to manipulate the list. It doesn't matter that l and l[:] gets unsynched. No reversal here, but it still works. >>> l =['molly', 'monkey', 'polly', 'dolly', 'mike', 'pike', 'moo', 'mew'] >>> for ix, name in enumerate(l[:]): .. if name.startswith('m'): .. del l[ix] Traceback (most recent call last): File "", line 4, in -toplevel- del l[ix] IndexError: list assignment index out of range On the other hand, if we try to do "del l[ix]" repeatedly while we iterate over l[:] we obviously get in trouble, since l[i] and l[:][i] will point to different things once we start to modify l. >>> l =['molly', 'monkey', 'polly', 'dolly', 'mike', 'pike', 'moo', 'mew'] >>> for ix in range(len(l)-1, -1, -1): print ix, l[ix] if l[ix].startswith('m'): del l[ix] >>> l ['polly', 'dolly', 'pike'] Here, we use range with arguments that looks strange the first time you see them. Reading from right to left, we have: step = -1, i.e. step backwards, 5, 4, 3, etc, stop = -1, i.e. 0 should be the last number included in our range, and finally, start = len[l]-1, i.e. start with the index for the last object in l. By iterating backwards, we will only change location in the list for items that we have already processed. I think there are three lessons we can learn from this: 1. Modifying a list that we are iterating over is error prone. 2. Iterating backwards, from the end to the beginning, typically makes this problem go away. 3. Identifying objects by *what* they are, is often more robust that to identify them based on *where* they are. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From sigurd at 12move.de Mon May 3 15:26:07 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Mon May 3 15:30:50 2004 Subject: [Tutor] list iteration [iteration and mutation?] In-Reply-To: (Magnus Lycka's message of "Mon, 3 May 2004 19:42:14 +0200") References: Message-ID: On 3 May 2004, Magnus Lycka <- magnus@thinkware.se wrote: [...] > Here is a little study to display the phenomena in a simple case. Remove > all strings in a list that start with 'm'. [some approaches to delete items from a list] > I think there are three lessons we can learn from this: > 1. Modifying a list that we are iterating over is error prone. > 2. Iterating backwards, from the end to the beginning, typically > makes this problem go away. > 3. Identifying objects by *what* they are, is often more robust > that to identify them based on *where* they are. Right. But there is a forth lesson to learn. 4. Try a functional approach. e.g.: filter(lambda i: predicate(i), lst) or [i for i in lst if predicate(i)] So with your example: >>> filter(lambda s: not s.startswith('m'), l) ['polly', 'dolly', 'pike'] >>> [s for s in l if not s.startswith('m')] ['polly', 'dolly', 'pike'] Karl -- Please do *not* send copies of replies to me. I read the list From flaxeater at yahoo.com Mon May 3 17:19:15 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon May 3 17:19:28 2004 Subject: [Tutor] list iteration [iteration and mutation?] In-Reply-To: Message-ID: <20040503211915.83794.qmail@web11601.mail.yahoo.com> > Right. But there is a forth lesson to learn. > > 4. Try a functional approach. e.g.: > > filter(lambda i: predicate(i), lst) > > or > > [i for i in lst if predicate(i)] > > So with your example: > > >>> filter(lambda s: not s.startswith('m'), l) > ['polly', 'dolly', 'pike'] > >>> [s for s in l if not s.startswith('m')] > ['polly', 'dolly', 'pike'] > That's pretty cool. I keep seeing cool tricks like this but I can never think of them. In addition I have been unable to teach myself a functional language. Someday. The neet thing is that is just about as comprehensible as Haskell. Which is comprehensible like gabriels horn is comprehenisble. __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From glingl at aon.at Mon May 3 17:26:20 2004 From: glingl at aon.at (Gregor Lingl) Date: Mon May 3 17:25:34 2004 Subject: [Tutor] list iteration [iteration and mutation?] In-Reply-To: <20040503211915.83794.qmail@web11601.mail.yahoo.com> References: <20040503211915.83794.qmail@web11601.mail.yahoo.com> Message-ID: <4096B8FC.8070807@aon.at> Chad Crabtree schrieb: >Which is >comprehensible like gabriels horn is comprehenisble. > > > > OOPs! What's gabriels horn? (Did I miss something?) Gregor > > >__________________________________ >Do you Yahoo!? >Win a $20,000 Career Makeover at Yahoo! HotJobs >http://hotjobs.sweepstakes.yahoo.com/careermakeover > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From magnus at thinkware.se Mon May 3 18:01:49 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Mon May 3 18:01:56 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gbGlzdCBpdGVyYXRpb24gIFtpdGVyYXRpb24gYW5kIG11dGF0aW9uP10=?= Message-ID: Karl Pfl?sterer wrote: > > I think there are three lessons we can learn from this: > > > 1. Modifying a list that we are iterating over is error prone. > > 2. Iterating backwards, from the end to the beginning, typically > > makes this problem go away. > > 3. Identifying objects by *what* they are, is often more robust > > that to identify them based on *where* they are. > > Right. But there is a forth lesson to learn. > > 4. Try a functional approach. e.g.: Ok, but the real difference between your approach and the examples I showed is that you avoid the entire problem by making a new list containing the objects that I wouldn't remove. It took me a long time to grok map, filter and reduce. Once I did, they were obvious, but I was still reluctant to use them, since I feared other people reading my code would be as confused as I had once been. It seems to me that the problem is smaller with list comprehensions, so I don't avoid that on purpose. :) >>> l = [s for s in l if not s.startswith('m')] is basically just a different syntax for... >>> new_list = [] >>> for s in l: ... if not s.startswith('m'): ... new_list.append(s) >>> l = new_list; del new_list ...so I think your lesson is maybe rather "avoid modifying your list. Make a new list instead." This usually works well, but sometimes, it isn't practical due to memory size reasons, if the list we manipulate is very big, but all my examples suffer from the same problem. :( This memory problem with two big lists can easily be fixed by changing my "range(len(l)-1, -1, -1)" to "xrange(len(l)-1, -1, -1)". (The range function actually builds a list of integers, but xrange handles this with an iterator instead.) Also, we're not always working with a Python list as I did in my example. The sequence we're iterating over might be a GUI listbox or something like that. It could really look something like this: for i in xrange(lb.count_items()-1, -1, -1): if lb.get_item(i).startswith('m'): lb.del_item(i) > filter(lambda i: predicate(i), lst) > > or > > [i for i in lst if predicate(i)] > > So with your example: > > >>> filter(lambda s: not s.startswith('m'), l) > ['polly', 'dolly', 'pike'] > >>> [s for s in l if not s.startswith('m')] > ['polly', 'dolly', 'pike'] -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From chyumm at yahoo.com Mon May 3 21:20:25 2004 From: chyumm at yahoo.com (Jay Li) Date: Mon May 3 21:20:29 2004 Subject: [Tutor] Where can I get the Numeric.py Message-ID: <20040504012025.43182.qmail@web60201.mail.yahoo.com> Dear all, I'm very new to Python. I need to run a program written in Python, but it always had such an error "from Numeric import * ImportError: No module named Numeric" I searched online archive. Seems Numeric.py should be a common class in Python. I installed the Python-2.2.3.exe downloaded from the Python website on Windows XP, but there's no Numeric.py on my computer. Where can I get Numeric.py? Could anybody give me a hint? Thanks a lot in advance. Jay --------------------------------- Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040503/851f9655/attachment.html From flaxeater at yahoo.com Mon May 3 21:42:44 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon May 3 21:42:49 2004 Subject: [Tutor] Where can I get the Numeric.py In-Reply-To: <20040504012025.43182.qmail@web60201.mail.yahoo.com> Message-ID: <20040504014244.7516.qmail@web11608.mail.yahoo.com> --- Jay Li wrote: > Dear all, > > I'm very new to Python. I need to run a program > written in Python, but it always had such an error > "from Numeric import * > ImportError: No module named Numeric" > > I searched online archive. Seems Numeric.py should > be a common class in Python. I installed the > Python-2.2.3.exe downloaded from the Python website > on Windows XP, but there's no Numeric.py on my > computer. Where can I get Numeric.py? Could anybody > give me a hint? Thanks a lot in advance. > Sure sure. http://www.pfdubois.com/numpy/ __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From John.Ertl at fnmoc.navy.mil Tue May 4 16:55:25 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Tue May 4 16:51:11 2004 Subject: [Tutor] Logging with different formats Message-ID: All, I am looking at using logging for a program that I am working on but I cannot figure out how to have logging use different formats for different types of Events. For instance the output needs to look like: As you can see there is a lot of info that needs to be in each TAG but most of it is the same for each "type". I cannot see how to easily switch the formatter to look like APPEVENT, APPERR or one of the others that I need to log. I am new to OO programming but I was originally logging this with a class that I created and just called different functions and used the print statement...this worked but I think using logging would be better if I could figure it out. Any examples or advice is appreciated, Thanks. John Ertl From alan.gauld at blueyonder.co.uk Tue May 4 16:54:14 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 4 16:53:55 2004 Subject: [Tutor] Looking for feedback References: <005001c42f57$de9455e0$6401a8c0@xp> <000701c431d6$d7a20b20$9124933e@spir> Message-ID: <010101c43219$f53ca4e0$6401a8c0@xp> A couple of folks have pointed out that the new version of my tutor doesn't have working zip or tarball links, that's deliberate because it is changing so frequently just now the continual maintenance would be too messy (yes I could write a Python program to automate it but I'd rather spend time finishing the tutor! :-) So sorry, but its read it online only for now. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ ----- Original Message ----- From: "denis" To: "Alan Gauld" Sent: Tuesday, May 04, 2004 1:53 PM Subject: Re: [Tutor] Looking for feedback > Couldn't download your new version from that place : neither > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/tutor.tgz > nor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/tutor.zip > seem to be available. > > denis From alan.gauld at blueyonder.co.uk Tue May 4 17:01:49 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 4 17:01:32 2004 Subject: [Tutor] list iteration [iteration and mutation?] References: Message-ID: <011101c4321b$046acb30$6401a8c0@xp> > Often, it's simplest to just iterate over a reversed range, such as in: > > l = > >for i in range(len(l)-1, -1, -1): > if we_want_to_remove(l[i]): > del l[i] I haven't seen it mentioned yet but list comprehensions can often be used for this kind of task. Re-working Magnus' generic code: L = [some kind of list we want to remove from] L = [ item for item in L if not we_want_to_remove(item)] In other words create a new list containing those items we don't want to remove. It's even fairly readable! By reversing the logic of we_want_to_remove() so that it represents we_want_to_keep(), it becomes the even more readable L = [item for item in L if we_want_to_keep(item)] HTH, Alan G. From alan.gauld at blueyonder.co.uk Tue May 4 17:04:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 4 17:04:03 2004 Subject: [Tutor] list iteration [iteration and mutation?] References: <20040503211915.83794.qmail@web11601.mail.yahoo.com> Message-ID: <011801c4321b$60773f30$6401a8c0@xp> >> have been unable to teach myself a functional > language. Someday. The neet thing is that is just > about as comprehensible as Haskell. Which is > comprehensible like gabriels horn is comprehenisble. :-) Have you tried my tutor topic on functional programming with Python? It tries to explain both the concepts of FP and how they can be applied in Python and also gives some ideas about how rigourously we should apply them! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From chyumm at yahoo.com Wed May 5 11:46:03 2004 From: chyumm at yahoo.com (Jay Li) Date: Wed May 5 11:46:14 2004 Subject: [Tutor] Is Python module case sensitive? Message-ID: <20040505154603.54797.qmail@web60203.mail.yahoo.com> Dear all, I'm trying to use Atamai Viewer which is written in Python. I've installed Python and numarray package and Scientific package. When I tried to run that that program, it always showed an error "from Numeric import * ImportError: No module named Numeric" I checked the sys.path by useing the "Path Bowser". Python22\lib\site-packages which includes numarray package is there. there's a file named numeric.py in the package. I doubt if Python's module is case sensitive, if so, can I just modify the numeric.py to Numeric.py without any latent problems? Thanks a lot! Jay --------------------------------- Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040505/02f01a5b/attachment.html From magnus at thinkware.se Wed May 5 12:50:55 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed May 5 12:51:05 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSXMgUHl0aG9uIG1vZHVsZSBjYXNlIHNlbnNpdGl2ZT8=?= Message-ID: Jay Li wrote: > I'm trying to use Atamai Viewer which is written in Python. I've installed Python and numarray package and Scientific package. When I tried to run that that program, it always showed an error "from Numeric import * > ImportError: No module named Numeric" > > I checked the sys.path by useing the "Path Bowser". Python22\lib\site-packages which includes numarray package is there. there's a file named numeric.py in the package. I doubt if Python's module is case sensitive, if so, can I just modify the numeric.py to Numeric.py without any latent problems? Thanks a lot! Are you sure that's the right Numeric? There is a Numeric package which predates numarray, see http://sourceforge.net/projects/numpy I suspect that's what the Atamai Viewer is looking for... As far as I understand, Numeric is no longer maintained, and people are encouraged to use Numarray instead, but I don't think that you can expect programs written for Numeric to work with Numarray. Try installing the last version of Numeric from http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=1351 -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Chad.Crabtree at nationalcity.com Wed May 5 13:22:11 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Wed May 5 13:22:26 2004 Subject: [Tutor] list iteration [iteration and mutation?] Message-ID: <66F587DFDD46D511B65200508B6F8DD612B99417@nt-kalopsapp07.ntl-city.com> > Have you tried my tutor topic on functional programming with Python? > It tries to explain both the concepts of FP and how they can be > applied in Python and also gives some ideas about how rigourously > we should apply them! > I had used your tutorial about 2 years ago I didn't get it then but I get it more now. Thank you for reminding me. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From pinvest at westnet.com.au Sun May 2 03:15:06 2004 From: pinvest at westnet.com.au (msp) Date: Wed May 5 13:40:56 2004 Subject: [Tutor] Inter-related modules Message-ID: <40949FFA.8010307@westnet.com.au> I have a problem with several modules all needing to use another module. This is quite common, but I'll use curses as an example as it's familiar to many. I start my main program which imports curses and calls initscr(). It asks the user what they want to do, and they select something from module 'a'. Module 'a' needs to use the screen to interact with the user. If module 'a' imports curses, this copy of curses knows that initscr() hasn't been calledand fails. If it calls initscr(), I have two sets of curses talking to the screen at once. This may be OK for curses (it saves and restores the starting screen state) but not for some other modules which I also have this problem with. Some might suggest that I have an intermediate interface module so that all screen i/o is done in one place. This is fine, except that I now have the same problem with that module instead. For some of my own modules (i.e. not curses) I could instantiate a class at the top level and pass it to everything which needs it. The problem with this is that the class is unknown at parse time, so errors wouldn't be found until a piece of code was actually used. This might be months later for some obscure bits. Having a basic moduile which is needed by many others must be a common problem. How is it normally handled? From robertf at eskimo.com Mon May 3 00:52:31 2004 From: robertf at eskimo.com (Bob Fleming) Date: Wed May 5 13:40:59 2004 Subject: [Tutor] Output to a printer Message-ID: <3.0.3.32.20040502215231.00ae0860@pop3.eskimo.com> I am learning Python on a Windows system (Win95). All of the tutorials, documentation, and a book that I am studying all assume printing to the console (stdout). I live in the real world and will need to print out to my laser printer or other device. How do I modify the print or write statements, or redirect stdout, to print to a printer? Thank you, Bob Fleming robertf@eskimo.com From CMAnastasi at aol.com Tue May 4 23:07:12 2004 From: CMAnastasi at aol.com (CMAnastasi@aol.com) Date: Wed May 5 13:41:01 2004 Subject: [Tutor] module problems Message-ID: I'm importing the string module and using the functions but getting no result from any of them. I have version 2.2.3 and am using widnows 2k pro, aside from this no other modules are working either. Please help! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040504/9f6bd3fb/attachment.html From ajay_4may at yahoo.co.in Wed May 5 04:45:10 2004 From: ajay_4may at yahoo.co.in (=?iso-8859-1?q?ajay=20singh?=) Date: Wed May 5 13:41:03 2004 Subject: [Tutor] Help: CGI Error in a Python Application Message-ID: <20040505084510.51866.qmail@web8201.mail.in.yahoo.com> I have wriiten a Python Script, which runs through a Webserver. The script generates a form, where the user feeds data and submits the form. The values submitted by the user, populates a MySql database. The problem is: After submitting the values, the database gets updated, but an error is generated which is quoted below, as seen in the browser: ------------------------------------------------ CGI Error The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: ----------------------------------------------- The Python code is as below: -------------------------------------------- #!c:\python23\python import cgi import sys,os import string import MySQLdb db=MySQLdb.connect(host="localhost",user="root",passwd="",db="power") cursor=db.cursor() print "" print "" print "" print "" s=os.environ['QUERY_STRING'] q=cgi.parse_qs(s) sname=q['txtname'].pop() scapacity=q['capacity'].pop() sstate=q['txtstate'].pop() sregion=q['region'].pop() sfre1=q['frequency1'].pop() sfre2=q['frequency2'].pop() sfre3=q['frequency3'].pop() sfre4=q['frequency4'].pop() cursor.execute("insert into station(name,region,capacity,state,fre1,fre2,fre3,fre4) values(%s,%s,%s,%s,%s,%s,%s,%s)", (sname,sregion,scapacity,sstate,sfre1,sfre2,sfre3,sfre4)) print "" print "" ------------------------------------------------- Can any one help me on this?? Ajay Singh ________________________________________________________________________ Yahoo! India Matrimony: Find your partner online. http://yahoo.shaadi.com/india-matrimony/ From dyoo at hkn.eecs.berkeley.edu Wed May 5 13:46:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 5 13:47:03 2004 Subject: [Tutor] Is Python module case sensitive? In-Reply-To: <20040505154603.54797.qmail@web60203.mail.yahoo.com> Message-ID: On Wed, 5 May 2004, Jay Li wrote: > I'm trying to use Atamai Viewer which is written in Python. I've > installed Python and numarray package and Scientific package. When I > tried to run that that program, it always showed an error "from Numeric > import * ImportError: No module named Numeric" > > I checked the sys.path by useing the "Path Bowser". > Python22\lib\site-packages which includes numarray package is there. > there's a file named numeric.py in the package. I doubt if Python's > module is case sensitive, if so, can I just modify the numeric.py to > Numeric.py without any latent problems? Thanks a lot! Hi Jay, Numarray is the next-generation version of Numeric. I'm not sure, though, if they both are interchangable. You may need to install Numeric as well, since it seems that Atamai Viewer is using Numeric. You can find Numeric here: http://www.pfdubois.com/numpy/ To answer your original question: yes, modules are case sensitive. But don't rename Numarray.numeric: that will probably break anything that depends on Numarray. *grin* Instead, install Numeric; I think the latest release of it is 22.0. Numarray and Numeric are designed not to conflict with each other. You may also want to talk with the folks who have written Atamai and see if they'd be willing to retarget their code to use Numarray. Good luck to you! From Chad.Crabtree at nationalcity.com Wed May 5 13:46:03 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Wed May 5 13:47:14 2004 Subject: [Tutor] Help: CGI Error in a Python Application Message-ID: <66F587DFDD46D511B65200508B6F8DD612B99419@nt-kalopsapp07.ntl-city.com> > ------------------------------------------------ > CGI Error > The specified CGI application misbehaved by not > returning a complete set of HTTP headers. The headers > it did return are: > ----------------------------------------------- > > > The Python code is as below: > > -------------------------------------------- > > #!c:\python23\python > import cgi > import sys,os > import string > import MySQLdb > db=MySQLdb.connect(host="localhost",user="root",passwd="",db="power") > cursor=db.cursor() *************************** print "Content-Type: text/plain\n\n" **************************** You need this so that the server and the browser know what to do with the content. Some browsers will choke others will work or not format it. I found this helpful when I was writing my first python cgi's http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ > print "" > print "" > print "" > print "" > s=os.environ['QUERY_STRING'] > q=cgi.parse_qs(s) > sname=q['txtname'].pop() > scapacity=q['capacity'].pop() > sstate=q['txtstate'].pop() > sregion=q['region'].pop() > sfre1=q['frequency1'].pop() > sfre2=q['frequency2'].pop() > sfre3=q['frequency3'].pop() > sfre4=q['frequency4'].pop() > cursor.execute("insert into > station(name,region,capacity,state,fre1,fre2,fre3,fre4) > values(%s,%s,%s,%s,%s,%s,%s,%s)", > (sname,sregion,scapacity,sstate,sfre1,sfre2,sfre3,sfre4)) > > print "" > print "" ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From dyoo at hkn.eecs.berkeley.edu Wed May 5 13:52:03 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 5 13:52:08 2004 Subject: [Tutor] module problems In-Reply-To: Message-ID: On Tue, 4 May 2004 CMAnastasi@aol.com wrote: > I'm importing the string module and using the functions but getting no > result from any of them. Hi CMAnastasi, Can you show us what you're doing? Do a cut-and-paste of the text that you're typing, as well as the response from Python, and send the reply back to the list. We need more information to see what's going on. (There are several problems that fit the symptom of "not getting any result" --- that's why we need to narrow down the possibilities a little more.) The Official Python Tutorial has a sample that shows how to use a module: http://www.python.org/doc/tut/node8.html#SECTION008200000000000000000 Test to see if you can import the 'sys' module from the interactive prompt. From Chad.Crabtree at nationalcity.com Wed May 5 14:05:28 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Wed May 5 14:05:50 2004 Subject: [Tutor] Output to a printer Message-ID: <66F587DFDD46D511B65200508B6F8DD612B9941A@nt-kalopsapp07.ntl-city.com> > -----Original Message----- > From: Bob Fleming [mailto:robertf@eskimo.com] > Sent: Monday, May 03, 2004 12:53 AM > To: tutor@python.org > Subject: [Tutor] Output to a printer > > > I am learning Python on a Windows system (Win95). All of the > tutorials, > documentation, and a book that I am studying all assume > printing to the > console (stdout). I live in the real world and will need to > print out to > my laser printer or other device. How do I modify the print or write > statements, or redirect stdout, to print to a printer? > > Thank you, > Bob Fleming > I couldn't find much but check out this thread. http://mail.python.org/pipermail/python-list/2002-September/121462.html ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From kp8 at mac.com Thu May 6 04:51:49 2004 From: kp8 at mac.com (kevin parks) Date: Thu May 6 04:53:59 2004 Subject: [Tutor] random floats in range func In-Reply-To: Message-ID: <9CC670AE-9F3A-11D8-8DEB-003065555ABC@mac.com> One of the things i am constantly having to do, (and one of the odd things left out of the random module is to get a random FLOAT in a certain range, like say i want a random value from 4 to 9 i would do: x = ((random.random()*5) + 4) # give us random floats in range 4-9 my scripts are full of these. What might be nice, would be to wrap this in a func that i can put in a module and then just import and make my code more readable and easier to write. I could do: def irand(base, upperbound): scale = upperbound - base return (random.random() * scale) + base which works fine... but i would like to have it be smart and not just barf if some one puts in erroneous values like making the base higher than the upperbound, etc. Is there a way to make this more rubust like that AND i wouldn't mind being able to quantize the out put so that i would say round to the nearest .1 or .25 or .333 or something.... of course in the case of rounding to 1 we already have randrange in the random module. cheers, kevin From pan at uchicago.edu Thu May 6 05:57:18 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Thu May 6 05:57:30 2004 Subject: [Tutor] cgi cross import problem In-Reply-To: References: Message-ID: <1083837438.409a0bfe2d535@webmail.uchicago.edu> I have 2 modules: mod1.py mod2.py Each is used for cgi, so they both start with: #!C:\python22\python.exe print 'Content-type: text/html' print And they both perform cgi function normally. Now, in mod2, I want to use the classes in mod1, so in mod2 I added: import mod1 Unfortunately, this import results in a 'Content-type: text/html' showing up as the first line on the webpage when calling mod2.py. I tried to import only the class I need: from mod1 import MyClass But the 'Content-type: text/html' still shows up. Can I avoid this in any way??? (certainly, I want both mod1 and mod2 able to perform cgi normally) thx in advance. pan From jmatthews at mcb-inc.com Thu May 6 08:51:11 2004 From: jmatthews at mcb-inc.com (John Matthews) Date: Thu May 6 08:52:05 2004 Subject: [Tutor] How can I format rows of irregular sized strings to print in colu mns? Message-ID: <91CC7C2A28D4D7118CFE0007E97E358B17629D@MCBFS1> I wrote a little program to look for graphics files and tell me the image size and the file size of each file. The data prints out like this: (292, 240) 35638 defender.bmp (1024, 768) 2359350 evolution3.bmp (78, 76) 17990 GRID1A.bmp How can I make it so that it looks more like this: ( 292, 240) 35,638 defender.bmp (1024, 768) 2,359,350 evolution3.bmp ( 78, 76) 17,990 GRID1A.bmp Below is the code. I am not really a programmer, so it probably looks clunky to you guys! Thanks! ---------------------- import os, glob, Image print "\n Where are the .bmp graphics?" path = raw_input(" example: C:\\foldername\\ >") os.chdir(path) bmpfiles = glob.glob('*.bmp') print '\nThere are',len(bmpfiles),'bmp files: \n' bmpfiles.reverse() while len(bmpfiles)>0: im=Image.open(bmpfiles[-1]) imagesize=im.size print imagesize, os.path.getsize(bmpfiles[-1]), bmpfiles[-1] bmpfiles.pop() raw_input('\nPress Enter to end the program') -- John Matthews McDonald, Cassell & Bassett, Inc. 600 West Spring Street Columbus, Ohio 43215 (614) 628-0630 (614) 628-0633 Fax -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040506/e1e23d30/attachment.html From denis.spir at free.fr Thu May 6 06:08:41 2004 From: denis.spir at free.fr (denis) Date: Thu May 6 09:54:49 2004 Subject: [Tutor] random floats in range func References: <9CC670AE-9F3A-11D8-8DEB-003065555ABC@mac.com> Message-ID: <009401c43371$90b33080$2627933e@spir> ----- Original Message ----- From: kevin parks To: Sent: Thursday, May 06, 2004 10:51 AM Subject: Re: [Tutor] random floats in range func > One of the things i am constantly having to do, (and one of the odd > things left out of the random > module is to get a random FLOAT in a certain range, like say i want a > random value from 4 to 9 > i would do: > > x = ((random.random()*5) + 4) # give us random floats in range 4-9 > > > my scripts are full of these. What might be nice, would be to wrap this > in a func that i can put in > a module and then just import and make my code more readable and easier > to write. I could do: > > > > def irand(base, upperbound): > scale = upperbound - base > return (random.random() * scale) + base > > > which works fine... but i would like to have it be smart and not just > barf if some one puts in erroneous values > like making the base higher than the upperbound, etc. Is there a way to > make this more rubust like that AND Here, you obviously write the solution along with the problem... > i wouldn't mind being able to quantize the out put so that i would say > round to the nearest .1 or .25 or .333 or something.... of course in > the case of rounding to 1 we already have randrange in the random > module. something like that (?) : >>> def fraction_round(x,fraction_int): ... x *= fraction_int # trick 1 of 2 : mult ... x = round(x) ... return float(x) / fraction_int # trick 2 of 2 : div round to 1/3 : >>> for i in range(10): ... print fraction_round(random.random(),3) ... 1.0 0.333333333333 0.666666666667 1.0 0.333333333333 0.666666666667 0.0 1.0 0.666666666667 0.333333333333 of, course, the range may be other than 0->1 ; say 10->15, and round to 1/2 : >>> for i in range(10): ... print fraction_round(random.random()*5+10,2) ... 10.0 11.5 13.0 12.5 10.5 13.5 13.5 14.5 15.0 14.0 > cheers, > > kevin cheers, denis From pythonTutor at venix.com Thu May 6 10:12:38 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu May 6 10:12:45 2004 Subject: [Tutor] cgi cross import problem In-Reply-To: <1083837438.409a0bfe2d535@webmail.uchicago.edu> References: <1083837438.409a0bfe2d535@webmail.uchicago.edu> Message-ID: <1083852757.3224.10.camel@laptop.venix.com> On Thu, 2004-05-06 at 05:57, pan@uchicago.edu wrote: > I have 2 modules: > > mod1.py > mod2.py > > Each is used for cgi, so they both start with: > > #!C:\python22\python.exe > print 'Content-type: text/html' > print The python import actually executes the statements it finds in the file being imported. You may have seen scripts with the line if __name__ == '__main__: This line allows a file to detect if it is being imported or being run. __name__ == '__main__' is only true when the file is being run. To use your cgi script as an importable module, add this if test and fix your code so that the statements that only pertain to running the script are only executed when it is actually run and not simply imported. e.g. if __name__ == '__main__: print 'Content-type: text/html' print It is often preferable to package the "run part" into a function and only call that function when the file is run. > > And they both perform cgi function normally. > > Now, in mod2, I want to use the classes in mod1, so in mod2 I added: > > import mod1 > > Unfortunately, this import results in a 'Content-type: text/html' > showing up as the first line on the webpage when calling mod2.py. > > I tried to import only the class I need: > > from mod1 import MyClass > > But the 'Content-type: text/html' still shows up. > > Can I avoid this in any way??? > (certainly, I want both mod1 and mod2 able to perform cgi normally) > > thx in advance. > > pan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From mhansen at cso.atmel.com Thu May 6 10:48:32 2004 From: mhansen at cso.atmel.com (mhansen@cso.atmel.com) Date: Thu May 6 10:48:39 2004 Subject: [Tutor] RE: Help: CGI Error in a Python Application Message-ID: ----- Original Message ----- >From "Crabtree, Chad" Date Wed, 5 May 2004 13:46:03 -0400 To "'ajay singh'" Cc "'tutor@python.org'" Subject RE: [Tutor] Help: CGI Error in a Python Application > ------------------------------------------------ > CGI Error > The specified CGI application misbehaved by not > returning a complete set of HTTP headers. The headers > it did return are: > ----------------------------------------------- > > > The Python code is as below: > > -------------------------------------------- > > #!c:\python23\python > import cgi > import sys,os > import string > import MySQLdb > db=MySQLdb.connect(host="localhost",user="root",passwd="",db="power") > cursor=db.cursor() >>*************************** >>print "Content-Type: text/plain\n\n" >>**************************** Shouldn't that be .. print "Content-Type: text/html\n\n" or does it make a difference? Also, this is a nit, but it should also print the doc type for HTML 4 or for XHTML transitional... In any event, it might be a good ideas to check your output through the w3c's validator... http://validator.w3.org/ I realize if you are just experimenting/testing code, then the doc type and validator probably isn't necessary. If it's production code, then I strongly suggest putting in the doc type and validate your output to make it clean HTML or XHTML. Mike From tim.one at comcast.net Thu May 6 12:05:23 2004 From: tim.one at comcast.net (Tim Peters) Date: Thu May 6 12:05:43 2004 Subject: [Tutor] random floats in range func In-Reply-To: <9CC670AE-9F3A-11D8-8DEB-003065555ABC@mac.com> Message-ID: [kevin parks] > One of the things i am constantly having to do, (and one of the odd > things left out of the random module is to get a random FLOAT in a > certain range, like say i want a random value from 4 to 9 For that much, you can use random.uniform(4, 9): http://docs.python.org/lib/module-random.html#l2h-1152 From Chad.Crabtree at nationalcity.com Thu May 6 12:59:57 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Thu May 6 13:00:09 2004 Subject: [Tutor] Logging with different formats Message-ID: <66F587DFDD46D511B65200508B6F8DD612B9941F@nt-kalopsapp07.ntl-city.com> > If you have some time...I am digging myself a deep hole and I > can't seam to > climb out. I have tried to modify my old log script that > used a class with > different functions that just printed statements to standard > out. Standard > out was directed to file. When I try to use logging.py I > either loose most > of the functionality or can't make it work. I have attached my latest > failure. Any ideas. I need to have different formats for > different events > but I want to keep the .info .error etc of logging.py. > I've carefully looked over your code. But I still don't know what you are trying to do and how it's failing. Would you post a traceback or something. I just don't know what's going wrong for you. I'm not sure but I think perhaps you should just roll your own. It wouldn't be that hard and you wouldn't have to spend time learning the logging api. ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From kpage at esri.com Wed May 5 20:01:25 2004 From: kpage at esri.com (Krista Page) Date: Thu May 6 13:06:20 2004 Subject: [Tutor] Relative Paths Message-ID: Does anyone know how to set relative paths in Windows? For example: I have a file called C:\Student\PYTH\Database\Coordinates.txt on my machine. Is there anyway to just specify \Database\Coordinates.txt and have it look on my machine for that folder? I thought four backslashes would do it, but I can't seem to get it to work. Any help would be appreciated. Thanks Krista From Chad.Crabtree at nationalcity.com Thu May 6 14:01:37 2004 From: Chad.Crabtree at nationalcity.com (Crabtree, Chad) Date: Thu May 6 14:01:59 2004 Subject: FW: [Tutor] Relative Paths Message-ID: <66F587DFDD46D511B65200508B6F8DD612B99422@nt-kalopsapp07.ntl-city.com> > Does anyone know how to set relative paths in Windows? > > For example: > > I have a file called C:\Student\PYTH\Database\Coordinates.txt > on my machine. > Is there anyway to just specify \Database\Coordinates.txt and > have it look > on my machine for that folder? > I thought four backslashes would do it, but I can't seem to > get it to work. > to go up a tree you would need to do './subdir/subdir/filename' it's the '.' infront that says this directory or '../siblingdirectory/subsibling/filename' the '..' in this case moves down one dir. so your could go down four levels bye typeing '../../../../dir/filename' ------------------------------------------------------------------------------------------- ***National City made the following annotations ------------------------------------------------------------------------------------------- This communication is a confidential and proprietary business communication. It is intended solely for the use of the designated recipient(s). If this communication is received in error, please contact the sender and delete this communication. =========================================================================================== From alan.gauld at blueyonder.co.uk Thu May 6 14:06:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu May 6 14:06:04 2004 Subject: [Tutor] Output to a printer References: <3.0.3.32.20040502215231.00ae0860@pop3.eskimo.com> Message-ID: <002401c43394$cf8c95d0$6401a8c0@xp> > I am learning Python on a Windows system (Win95). All of the tutorials, > documentation, and a book that I am studying all assume printing to the > console (stdout). That's coz its easy! :-) > I live in the real world and will need to print out to > my laser printer or other device. How do I modify the print or write > statements, or redirect stdout, to print to a printer? On Win 95 its also easy for text at least. Just open the 'LPT1:' or 'PRN:' device as if it were a file for writing and squirt the text to it. Unfortunately that won't work on later versions of Windsows (NW"K and XP variants specifically). Nor does it work easily for fancy formatting. THis is a problem in all programming languages on Windows because basically Windows treats documents to be printed as graphics, so you have to convert your document into something windows can print. Its possible but painful (unless you find a module somewhere, in which case let me know!) Meantime I generally generate HTML as a temporary file then print that via my web broweser, either by hand or using COM or the os.system function. You can also generate PDF or RTF via supporting modules and print them in a similar way (using Acrobat/ghostview/Word etc) On Unix its slightly easier because the printer is again a file type device... HTH Alan G. From alan.gauld at blueyonder.co.uk Thu May 6 14:07:01 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu May 6 14:06:52 2004 Subject: [Tutor] module problems References: Message-ID: <002c01c43394$edda9c80$6401a8c0@xp> > I'm importing the string module and using the functions but getting no result > from any of them. I have version 2.2.3 and am using widnows 2k pro, aside > from this no other modules are working either. > Please help! Its easier for us to answer if you give us an example of what you mean. Otherwise its hard to guess what exactly you are doing! Alan G. From pythonTutor at venix.com Thu May 6 15:04:19 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu May 6 15:04:33 2004 Subject: [Tutor] Relative Paths In-Reply-To: References: Message-ID: <1083870259.3224.59.camel@laptop.venix.com> filepath = os.path.join('Database','Coordinates.txt') filepath will have a relative path that will work from r'c:\Student\PYTH' While forward slashes will usually work within Windows, it can confues people if the path appears in an error message. os.path will do the right thing should you upgrade to Linux and keep a similar directory structure. On Wed, 2004-05-05 at 20:01, Krista Page wrote: > Does anyone know how to set relative paths in Windows? > > For example: > > I have a file called C:\Student\PYTH\Database\Coordinates.txt on my machine. > Is there anyway to just specify \Database\Coordinates.txt and have it look > on my machine for that folder? > I thought four backslashes would do it, but I can't seem to get it to work. > > Any help would be appreciated. > Thanks > Krista > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From justinstraube at charter.net Thu May 6 19:21:36 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Thu May 6 16:15:18 2004 Subject: [Tutor] Python & XML Message-ID: <200405062013.i46KDpDu074974@mxsf06.cluster1.charter.net> Hello, Ive used the httplib module and the examples given in the 2.3 docs to retrieve my or a given users stats from SETI, http://setiathome2.ssl.berkeley.edu/fcgi- bin/fcgi?cmd=user_xml&email=XXXX (where XXXX is the registered email address) The string retrieved is in XML format. Ive begun looking at the some of the docs for the different XML modules in 2.3 but this is a bit confusing. Im not sure where to start. I am guessing that this should be a fairly simple project as the tags for the fields in the user stats shouldnt change. I would just need to extract the wanted data for display. Can anyone can point me to anything on how to go about this? #### import httplib SETI = "setiathome2.ssl.berkeley.edu" print = '\t\tPSETI' usrmail = raw_input('\nYour Email Address: ') addr = '/fcgi-bin/fcgi?cmd=user_xml&email=' + usrmail conx = httplib.HTTPConnection(SETI) conx.request('GET', addr) response = conx.getresponse() print response.status, response.reason data = response.read() conx.close() print data raw_input('Press Enter to continue') #### Thanks, Justin --- From missive at hotmail.com Thu May 6 18:31:31 2004 From: missive at hotmail.com (Lee Harr) Date: Thu May 6 18:31:39 2004 Subject: [Tutor] Re: How can I format rows of irregular sized strings to print in columns? Message-ID: >I wrote a little program to look for graphics files and tell me the image >size and the file size of each file. The data prints out like this: > >(292, 240) 35638 defender.bmp >(1024, 768) 2359350 evolution3.bmp >(78, 76) 17990 GRID1A.bmp > >How can I make it so that it looks more like this: > >( 292, 240) 35,638 defender.bmp >(1024, 768) 2,359,350 evolution3.bmp >( 78, 76) 17,990 GRID1A.bmp > Please post only in plain text. You will want to look at the string formatting operator: http://docs.python.org/lib/typesseq-strings.html One handy example: >>>a='(292, 240)';b=35638; c='defender.bmp' >>>print '%10s %10s %20s' % (a, b, c) (292, 240) 35638 defender.bmp _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From dyoo at hkn.eecs.berkeley.edu Thu May 6 18:35:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 6 18:35:12 2004 Subject: [Tutor] Is Python module case sensitive? Message-ID: [Jay] >>> I'm trying to use Atamai Viewer which is written in Python. I've >>> installed Python and numarray package and Scientific package. When I [Danny] >> Numarray is the next-generation version of Numeric. I'm not sure, >> though, if they both are interchangable. You may need to install >> Numeric as well, [Jay] > Thank you very much for your help. The viewer is looking for Numeric > package not the numarray package. Now it's working fine. Hi Jay, No problem; I'm relieved that it's working now. If you have any Python-related questions, please feel free to send them over to Python-Tutor. Talk to you later! From bgailer at alum.rpi.edu Thu May 6 21:43:12 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu May 6 21:42:57 2004 Subject: [Tutor] Re: How can I format rows of irregular sized strings to print in columns? In-Reply-To: References: Message-ID: <6.0.0.22.0.20040506192523.02683cc8@mail.mric.net> At 04:31 PM 5/6/2004, Lee Harr wrote: >>I wrote a little program to look for graphics files and tell me the image >>size and the file size of each file. The data prints out like this: >> >>(292, 240) 35638 defender.bmp >>(1024, 768) 2359350 evolution3.bmp >>(78, 76) 17990 GRID1A.bmp >> >>How can I make it so that it looks more like this: >> >>( 292, 240) 35,638 defender.bmp >>(1024, 768) 2,359,350 evolution3.bmp >>( 78, 76) 17,990 GRID1A.bmp >Please post only in plain text. > >You will want to look at the string formatting operator: >http://docs.python.org/lib/typesseq-strings.html > >One handy example: > >>>>a='(292, 240)';b=35638; c='defender.bmp' >>>>print '%10s %10s %20s' % (a, b, c) >(292, 240) 35638 defender.bmp This solution is close, but I think the OP wants the numbers in () to be individually aligned in columns. The desired output in proportional font doesn't show this, but if you copy/paste into a fixed font editor you will see this more clearly. So the challenge is to parse the numbers out and format them individually. I think this is best done using re: import re m = re.match(r'\((\d+),\s*(\d+)\)', im.size) # generates a match object with 2 groups # m.groups() is ('292', '240') '(%4s, %4s)' % m.groups() # is '( 292, 240)' re can be daunting at first but is well worth the learning curve. So let''s break the regular expression \((\d+),\s*(\d+)\) into pieces: \( # match a left parentheses \s* # match 0 or more "whitespace" characters (\d+) # match one or more digits and place them in a group , # match a comma \s* # match 0 or more "whitespace" characters (\d+) # match one or more digits and place them in another group \) # match a right parenthesis The result is placed in a "match object". m.groups() returns all the groups in a tuple, which is the desired right argument type for % Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040506/cd6de66e/attachment.html From tim at johnsons-web.com Thu May 6 23:11:10 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Thu May 6 23:08:22 2004 Subject: [Tutor] problem with str.count and str.split Message-ID: <20040507031110.GQ7467@johnsons-web.com> Hello: I am importing TAB-delimited text data. Each line is read in as a string with the newline removed. Each line is parsed into a list with TAB as a delimiter. code: vals = line.split('\t') It is expected that this line should have 75 TAB characters imbedded, and that the resulting list (vals) should have 76 members, An exception is thrown when a line is 'split' into a list with only 44 members, and when the exception is thrown, I use line.count('\t') to retrieve the number of embedded TABS and line.count('\t') returns the number 43. Visual Inspection: If I look at this line in an editor that allows TABS to be visible, I can manually count 75 TAB characters. Alternative Methods: This service was prototyped in another programming language (rebol) and all lines are being split successfully, finding 75 TABS and returning a list with 75 members. I'd welcome comments, suggestions on this matter. I'm not about to get goofy and claim I've found a bug in python, I'm guessing that I should be using a more pythonesque approach to parsing these lines. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Thu May 6 23:58:27 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Thu May 6 23:55:29 2004 Subject: [Tutor] problem with str.count and str.split In-Reply-To: <20040507031110.GQ7467@johnsons-web.com> References: <20040507031110.GQ7467@johnsons-web.com> Message-ID: <20040507035827.GR7467@johnsons-web.com> Correction below: * Tim Johnson [040506 19:17]: > Hello: > I am importing TAB-delimited text data. > > Each line is read in as a string with the newline removed. > > Each line is parsed into a list with TAB as a delimiter. > code: > vals = line.split('\t') > > It is expected that this line should have 75 TAB characters > imbedded, and that the resulting list (vals) should have 76 members, > > An exception is thrown when a line is 'split' into a list > with only 44 members, and when the exception is thrown, > I use line.count('\t') to retrieve the number of embedded > TABS and line.count('\t') returns the number 43. > > Visual Inspection: > If I look at this line in an editor that allows > TABS to be visible, I can manually count 75 TAB characters. > > Alternative Methods: > This service was prototyped in another > programming language (rebol) and all lines are > being split successfully, finding 75 TABS and returning > a list with 75 members. a list with *76* members... > > I'd welcome comments, suggestions on this matter. I'm not about > to get goofy and claim I've found a bug in python, I'm guessing > that I should be using a more pythonesque approach to parsing > these lines. > > thanks > tim > -- > Tim Johnson > http://www.alaska-internet-solutions.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From bgailer at alum.rpi.edu Thu May 6 23:59:47 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu May 6 23:59:30 2004 Subject: {Spam?} Re: [Tutor] problem with str.count and str.split In-Reply-To: <20040507035827.GR7467@johnsons-web.com> References: <20040507031110.GQ7467@johnsons-web.com> <20040507035827.GR7467@johnsons-web.com> Message-ID: <6.0.0.22.0.20040506215903.03b27fd0@mail.mric.net> At 09:58 PM 5/6/2004, Tim Johnson wrote: >Correction below: >* Tim Johnson [040506 19:17]: > > Hello: > > I am importing TAB-delimited text data. Could you attach a sample file, and your code? > > > > Each line is read in as a string with the newline removed. > > > > Each line is parsed into a list with TAB as a delimiter. > > code: > > vals = line.split('\t') > > > > It is expected that this line should have 75 TAB characters > > imbedded, and that the resulting list (vals) should have 76 members, > > > > An exception is thrown when a line is 'split' into a list > > with only 44 members, and when the exception is thrown, > > I use line.count('\t') to retrieve the number of embedded > > TABS and line.count('\t') returns the number 43. > > > > Visual Inspection: > > If I look at this line in an editor that allows > > TABS to be visible, I can manually count 75 TAB characters. > > > > Alternative Methods: > > This service was prototyped in another > > programming language (rebol) and all lines are > > being split successfully, finding 75 TABS and returning > > a list with 75 members. > a list with *76* members... > > > > I'd welcome comments, suggestions on this matter. I'm not about > > to get goofy and claim I've found a bug in python, I'm guessing > > that I should be using a more pythonesque approach to parsing > > these lines. > > > > thanks > > tim > > -- > > Tim Johnson > > http://www.alaska-internet-solutions.com > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > >-- >Tim Johnson > http://www.alaska-internet-solutions.com > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From david at graniteweb.com Fri May 7 00:22:58 2004 From: david at graniteweb.com (David Rock) Date: Fri May 7 00:23:01 2004 Subject: [Tutor] Relative Paths In-Reply-To: <1083870259.3224.59.camel@laptop.venix.com> References: <1083870259.3224.59.camel@laptop.venix.com> Message-ID: <20040507042258.GA13411@wdfs.graniteweb.com> * Lloyd Kvam [2004-05-06 15:04]: > While forward slashes will usually work within Windows, it can confues > people if the path appears in an error message. os.path will do the > right thing should you upgrade to Linux and keep a similar directory > structure. "Upgrade", funny ;-) -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040506/05c89a5f/attachment.bin From tim at johnsons-web.com Fri May 7 00:32:22 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Fri May 7 00:29:25 2004 Subject: [Tutor] Re: .....str.count and str.split/solved In-Reply-To: <6.0.0.22.0.20040506215903.03b27fd0@mail.mric.net> References: <20040507031110.GQ7467@johnsons-web.com> <20040507035827.GR7467@johnsons-web.com> <6.0.0.22.0.20040506215903.03b27fd0@mail.mric.net> Message-ID: <20040507043222.GT7467@johnsons-web.com> Duh! Found it. Lines ended with a '\t'. Had used rsplit to strip newline, also stripped all ending '\t', I'll bet.... Thanks for listening - wonder what perl->chomp would do... tim * Bob Gailer [040506 20:05]: > At 09:58 PM 5/6/2004, Tim Johnson wrote: > >Correction below: > >* Tim Johnson [040506 19:17]: > >> Hello: > >> I am importing TAB-delimited text data. > > Could you attach a sample file, and your code? > > >> > >> Each line is read in as a string with the newline removed. > >> > >> Each line is parsed into a list with TAB as a delimiter. > >> code: > >> vals = line.split('\t') > >> > >> It is expected that this line should have 75 TAB characters > >> imbedded, and that the resulting list (vals) should have 76 members, > >> > >> An exception is thrown when a line is 'split' into a list > >> with only 44 members, and when the exception is thrown, > >> I use line.count('\t') to retrieve the number of embedded > >> TABS and line.count('\t') returns the number 43. > >> > >> Visual Inspection: > >> If I look at this line in an editor that allows > >> TABS to be visible, I can manually count 75 TAB characters. > >> > >> Alternative Methods: > >> This service was prototyped in another > >> programming language (rebol) and all lines are > >> being split successfully, finding 75 TABS and returning > >> a list with 75 members. > > a list with *76* members... > >> > >> I'd welcome comments, suggestions on this matter. I'm not about > >> to get goofy and claim I've found a bug in python, I'm guessing > >> that I should be using a more pythonesque approach to parsing > >> these lines. > >> > >> thanks > >> tim > >> -- > >> Tim Johnson > >> http://www.alaska-internet-solutions.com > >> > >> _______________________________________________ > >> Tutor maillist - Tutor@python.org > >> http://mail.python.org/mailman/listinfo/tutor > > > >-- > >Tim Johnson > > http://www.alaska-internet-solutions.com > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell -- Tim Johnson http://www.alaska-internet-solutions.com From david at graniteweb.com Fri May 7 00:31:11 2004 From: david at graniteweb.com (David Rock) Date: Fri May 7 00:31:13 2004 Subject: [Tutor] How can I format rows of irregular sized strings to print in colu mns? In-Reply-To: <91CC7C2A28D4D7118CFE0007E97E358B17629D@MCBFS1> References: <91CC7C2A28D4D7118CFE0007E97E358B17629D@MCBFS1> Message-ID: <20040507043111.GB13411@wdfs.graniteweb.com> * John Matthews [2004-05-06 08:51]: > I wrote a little program to look for graphics files and tell me the image > size and the file size of each file. The data prints out like this: > > (292, 240) 35638 defender.bmp > (1024, 768) 2359350 evolution3.bmp > (78, 76) 17990 GRID1A.bmp > > How can I make it so that it looks more like this: > > ( 292, 240) 35,638 defender.bmp > (1024, 768) 2,359,350 evolution3.bmp > ( 78, 76) 17,990 GRID1A.bmp You should probably look at the printf style formatting: http://www.python.org/doc/current/lib/typesseq-strings.html#l2h-206 In general, your output string will probably look something like this: print "(%5d,%5d) %12d %s" % (x,y,size,filename) This is _very_ generic, and probably breaks often, but it should give you an idea of what to look for. -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040506/edbf89c5/attachment.bin From alan.gauld at blueyonder.co.uk Fri May 7 04:41:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri May 7 04:41:13 2004 Subject: [Tutor] problem with str.count and str.split References: <20040507031110.GQ7467@johnsons-web.com> Message-ID: <006d01c4340f$15ad28c0$6401a8c0@xp> Hi Tim, > Visual Inspection: > If I look at this line in an editor that allows > TABS to be visible, I can manually count 75 TAB characters. Any chance we can have the same insight? ie Can you post such a line for us to look at. My immediate suspician is that there is a newline character or somesuch in the middle of the line that fools Python. But without seeing it I can't tell. Alan G From sciboy at sciboy.zer0host.com Fri May 7 05:08:19 2004 From: sciboy at sciboy.zer0host.com (sciboy@sciboy.zer0host.com) Date: Fri May 7 05:08:27 2004 Subject: [Tutor] What is a fun basic game project. Message-ID: Hi, this is my first message to this mailing list. Anyone know of a fun game project that is good for beginners, and what aspects they involve. eg. conditions, arrays etc. From wilson at visi.com Fri May 7 07:33:46 2004 From: wilson at visi.com (Tim Wilson) Date: Fri May 7 07:33:47 2004 Subject: [Tutor] What is a fun basic game project. In-Reply-To: Message-ID: On 5/7/04 4:08 AM, "sciboy@sciboy.zer0host.com" wrote: > Anyone know of a fun game project that is good for beginners, and what aspects > they involve. Hangman is a classic. I created the following assignment for my programming students a couple years ago. Most implementations of this sort of program use simple lists as containers for guessed letters and the list of words to draw from. http://isd197.org/sibley/cs/icp/assignments/hangman_html -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From bgailer at alum.rpi.edu Fri May 7 09:21:44 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri May 7 09:21:25 2004 Subject: [Tutor] Re: How can I format rows of irregular sized strings to print in columns? In-Reply-To: <6.0.0.22.0.20040506192523.02683cc8@mail.mric.net> References: <6.0.0.22.0.20040506192523.02683cc8@mail.mric.net> Message-ID: <6.0.0.22.0.20040507071313.026729e8@mail.mric.net> At 07:43 PM 5/6/2004, Bob Gailer wrote: >At 04:31 PM 5/6/2004, Lee Harr wrote: >>>I wrote a little program to look for graphics files and tell me the image >>>size and the file size of each file. The data prints out like this: >>> >>>(292, 240) 35638 defender.bmp >>>(1024, 768) 2359350 evolution3.bmp >>>(78, 76) 17990 GRID1A.bmp >>> >>>How can I make it so that it looks more like this: >>> >>>( 292, 240) 35,638 defender.bmp >>>(1024, 768) 2,359,350 evolution3.bmp >>>( 78, 76) 17,990 GRID1A.bmp >>Please post only in plain text. >> >>You will want to look at the string formatting operator: >>http://docs.python.org/lib/typesseq-strings.html >> >>One handy example: >> >>>>>a='(292, 240)';b=35638; c='defender.bmp' >>>>>print '%10s %10s %20s' % (a, b, c) >>(292, 240) 35638 defender.bmp > >This solution is close, but I think the OP wants the numbers in () to be >individually aligned in columns. The desired output in proportional font >doesn't show this, but if you copy/paste into a fixed font editor you will >see this more clearly. OOPS. I have now done my "homework" and realize that im.size returns a tuple of numbers rather than a string. So we don't need re after all. The solution now is print '(%4s, %4s)' % imagesize, '%10s' % os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1] >[snip] And now for some code refinement: bmpfiles.reverse() while len(bmpfiles)>0: im=Image.open(bmpfiles[-1]) imagesize=im.size print '(%4s, %4s)' % imagesize, '%10s' % os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1] bmpfiles.pop() Can be simplified using a for loop: for bmpfile in bmpfiles: im=Image.open(bmpfile) imagesize=im.size print '(%4s, %4s)' % imagesize, '%10s' % os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040507/cd233b57/attachment.html From jmatthews at mcb-inc.com Fri May 7 09:57:59 2004 From: jmatthews at mcb-inc.com (John Matthews) Date: Fri May 7 09:58:51 2004 Subject: [Tutor] Re: How can I format rows of irregular sized strings to print in columns? Message-ID: <91CC7C2A28D4D7118CFE0007E97E358B1762A1@MCBFS1> At 07:43 PM 5/6/2004, Bob Gailer wrote: At 04:31 PM 5/6/2004, Lee Harr wrote: I wrote a little program to look for graphics files and tell me the image size and the file size of each file. The data prints out like this: (292, 240) 35638 defender.bmp (1024, 768) 2359350 evolution3.bmp (78, 76) 17990 GRID1A.bmp How can I make it so that it looks more like this: ( 292, 240) 35,638 defender.bmp (1024, 768) 2,359,350 evolution3.bmp ( 78, 76) 17,990 GRID1A.bmp Please post only in plain text. You will want to look at the string formatting operator: http://docs.python.org/lib/typesseq-strings.html One handy example: a='(292, 240)';b=35638; c='defender.bmp' print '%10s %10s %20s' % (a, b, c) (292, 240) 35638 defender.bmp This solution is close, but I think the OP wants the numbers in () to be individually aligned in columns. The desired output in proportional font doesn't show this, but if you copy/paste into a fixed font editor you will see this more clearly. OOPS. I have now done my "homework" and realize that im.size returns a tuple of numbers rather than a string. So we don't need re after all. The solution now is print '(%4s, %4s)' % imagesize, '%10s' % os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1] [snip] And now for some code refinement: bmpfiles.reverse() while len(bmpfiles)>0: im=Image.open(bmpfiles[-1]) imagesize=im.size print '(%4s, %4s)' % imagesize, '%10s' % os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1] bmpfiles.pop() Can be simplified using a for loop: for bmpfile in bmpfiles: im=Image.open(bmpfile) imagesize=im.size print '(%4s, %4s)' % imagesize, '%10s' % os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell Thanks Bob, this is exactly what I was looking for! To the others that provided input, thankyou too! -- John Matthews McDonald, Cassell & Bassett, Inc. 600 West Spring Street Columbus, Ohio 43215 (614) 628-0630 (614) 628-0633 Fax -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040507/6081f9f9/attachment-0001.html From alan.gauld at blueyonder.co.uk Fri May 7 10:41:52 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri May 7 10:41:31 2004 Subject: [Tutor] What is a fun basic game project. References: Message-ID: <009301c43441$701bdf90$6401a8c0@xp> > Hi, this is my first message to this mailing list. > > Anyone know of a fun game project that is good for beginners, and what aspects they involve. > > eg. conditions, arrays etc. A couple of easy games to start with are OXO and Conway's Game of Life. Both involve arrays and conditionals and loops and some degree of graphical representation plus user input. Paper/Rock/Scissors is another that can be easily implemented in plain text and later have a graphical wrap added. HTH, Alan G From Andy at joslin.isa-geek.com Fri May 7 11:08:40 2004 From: Andy at joslin.isa-geek.com (Andy Joslin) Date: Fri May 7 11:08:48 2004 Subject: [Tutor] What is a fun basic game project. In-Reply-To: <009301c43441$701bdf90$6401a8c0@xp> References: <009301c43441$701bdf90$6401a8c0@xp> Message-ID: <409BA678.8050503@joslin.isa-geek.com> Add the "Towers of Hanoi" puzzle/game to the list. It is the one with 3 pegs and a few disks of various sizes that start stacked biggest to smallest on one peg... The goal is to move the whole stack from one peg to another, only moving one at a time and never putting a large disk on top of a smaller disk. Try to figure out the algorithm to solve it automatically. You can build the engine to use a text display, or try to use a gui. This is one that many CompSci students have to do in the first year... Alan Gauld wrote: >>Hi, this is my first message to this mailing list. >> >>Anyone know of a fun game project that is good for beginners, and >> >> >what aspects they involve. > > >>eg. conditions, arrays etc. >> >> > >A couple of easy games to start with are OXO and Conway's Game of >Life. >Both involve arrays and conditionals and loops and some degree of >graphical representation plus user input. > >Paper/Rock/Scissors is another that can be easily implemented in plain >text and later have a graphical wrap added. > >HTH, > >Alan G > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From godoy at ieee.org Fri May 7 12:25:22 2004 From: godoy at ieee.org (Jorge Godoy) Date: Fri May 7 12:41:06 2004 Subject: [Tutor] Re: What is a fun basic game project. References: <009301c43441$701bdf90$6401a8c0@xp> <409BA678.8050503@joslin.isa-geek.com> Message-ID: On Sex 07 Mai 2004 12:08, Andy Joslin wrote: > Add the "Towers of Hanoi" puzzle/game to the list. It is the one with > 3 pegs and a few disks of various sizes that start stacked biggest to > smallest on one peg... The goal is to move the whole stack from one peg > to another, only moving one at a time and never putting a large disk on > top of a smaller disk. Try to figure out the algorithm to solve it > automatically. You can build the engine to use a text display, or try > to use a gui. > > This is one that many CompSci students have to do in the first year... I have one school project to write -- as if I didn't have to write clients programs... -- for a project management class (I am graduating in August -- I hope -- in Electrical Engineering, in the telecommunications area) and it was requested that we did one simple thing: write a program that divides a squared area in four equal parts, allowing the user to draw one of the divisions and replicating it to other. There are infinite solutions for this problem and it might go from too simple to too complex. Since I don't know if I'll have time to write it myself or we'll have to hire someone -- it is allowed, since we're having engineering stuff and not software programming classes -- to do it, I would really like to see some solutions for this on Python :-) There are a few constraints that you might come up while solving the problem, depending on how you approached it. For instance, if you divide the squared area into four smaller squares, you can't allow the user to make two lines join and create a fifth visible area. It prevents the user from drawing a line/curve/whatever from the lower left point to the upper right point. Got the idea? ;-) Oh! It has to be used with the mouse, for keeping end user's sane and interested on it. I think this might become something that will be donated to schools and/or to entertain children. Be seeing you, -- Godoy. From areedades at yahoo.com Fri May 7 08:43:57 2004 From: areedades at yahoo.com (Alexander Ades) Date: Fri May 7 13:49:06 2004 Subject: [Tutor] Beginner in need of help! Message-ID: <20040507124357.46147.qmail@web12401.mail.yahoo.com> I wrote a program in IDLE and I tried to run it in python command line but no matter what I tried it never worked. What do I do to run my simple calculator program in python command line? Please help, AA --------------------------------- Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040507/d8321516/attachment.html From sciboy at sciboy.org Fri May 7 04:34:23 2004 From: sciboy at sciboy.org (sciboy@sciboy.org) Date: Fri May 7 13:49:37 2004 Subject: [Tutor] What is a fun basic game project. Message-ID: Hi, this is my first message to this mailing list. Anyone know of a fun game project that is good for beginners, and what aspects they involve. eg. conditions, arrays etc. From wilson at visi.com Fri May 7 13:59:47 2004 From: wilson at visi.com (Tim Wilson) Date: Fri May 7 13:59:47 2004 Subject: [Tutor] Beginner in need of help! In-Reply-To: <20040507124357.46147.qmail@web12401.mail.yahoo.com> Message-ID: On 5/7/04 7:43 AM, "Alexander Ades" wrote: > I wrote a program in IDLE and I tried to run it in python command line but no > matter what I tried it never worked. What do I do to run my simple calculator > program in python command line? Was an error message generated? If so, please include that in your message. It's always the first question. -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From magnus at thinkware.se Fri May 7 14:06:56 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 7 14:02:48 2004 Subject: [Tutor] Inter-related modules In-Reply-To: <40949FFA.8010307@westnet.com.au> Message-ID: <5.2.1.1.0.20040507184110.028bba38@www.thinkware.se> At 15:15 2004-05-02 +0800, msp wrote: >I have a problem with several modules all needing to use >another module. This is quite common, but I'll use curses >as an example as it's familiar to many. > >I start my main program which imports curses and calls initscr(). >It asks the user what they want to do, and they select something from >module 'a'. Module 'a' needs to use the screen to interact with the user. >If module 'a' imports curses, this copy of curses knows that initscr() >hasn't been calledand fails. If it calls initscr(), I have two sets of curses >talking to the screen at once. This may be OK for curses (it saves and >restores the starting screen state) but not for some other modules which >I also have this problem with. This isn't really a problem with modules, but with any object, where you just want one occurence. You could as well call some kind of initialization routine several times in the same module, and run into similar trouble. Right? The problem is that you have some kind of shared resource, and you want several clients to use the same resource, not to get a copy each. This should prefereably happen without the different clients needing to know about each other. (In the case of curses, I suppose you will get total chaos if several parts of the code tries to update the same screen independently of each other, but there are certainly other cases when you want something like this to work.) You should be clear about one thing though: You can only import a module *once* in Python with the import statement. Let's imagine that you have two modules, main and sub, and they look like this: main.py: ------------- import curses import sub def m(): sub.s() m() ------------- sub.py: ------------- import curses def s(): ------------- This code is equivalent with: main.py: ------------- import curses import sub sub.curses = curses def m(): sub.s() m() ------------- sub.py: ------------- def s(): ------------- Or prefereably... main.py: ------------- import curses import sub sub.init_curses(curses) def m(): sub.s() m() ------------- sub.py: ------------- def init_curses(curses_module): global curses curses = curses_module def s(): ------------- On other words, unless you use the reload() function, you can only import a module ONCE. Any subsequent call of 'import' on the same module will only create a new variable name in the local scope which refers to the import module you already loaded. >Some might suggest that I have an intermediate interface module so that >all screen i/o is done in one place. This is fine, except that I now have the >same problem with that module instead. :) Don't be so sure. Look at the Borg pattern at the Activestate Python Cookbook, or any implementation of the Singleton pattern. >For some of my own modules (i.e. not curses) I could instantiate a class at >the top level and pass it to everything which needs it. The problem with >this is that the class is unknown at parse time, so errors wouldn't be found > until a piece of code was actually used. This might be months later for some >obscure bits. This is always a problem with a dynamically typed language like Python. I don't see how you can avoid that by avoiding parameter passing. Or do you mean that you don't want to set a global variable in a module like I did above? I can understand that you don't want that. It make themodule which expects an importer to set things up difficult to use and understand. But I don't think you can escape the need to test your code in such a way that things like this are found during development. There might be *any* fault in a piece of code, related to logical errors as well as to imports. Deploying them and just hoping that they will work untested a few months from now is not a good idea. This is why we write test programs to test our programs. >Having a basic moduile which is needed by many others must be a common >problem. How is it normally handled? Sure, and as I said, this problem exists for many objects, not just modules. Alex Martelli's Borg pattern looks like this. class Borg: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state # and whatever else you want in your class -- that's all! You could imagine something like this: >>> class InitOnce: __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state if not self.__dict__: print "First Call, initialize" self.init = 1 else: print "I'm already initialized, not need to repeat" >>> x1=InitOnce() First Call, initialize >>> x2=InitOnce() I'm already initialized, not need to repeat Or with curses it might be something like: class CursesWrapper: __shared_state = {} def __init__(sef): self.__dict__ = self.__shared_state if not self.__dict__: import curses self.curses = curses curses.initscr() (I never used curses, but I hope you understand how to apply this) I guess you might be able to replace import curses with import curseswrapper cw = curseswrapper.CursesWrapper().curses I know, it's a bit long and repetetive, but I'm sure you can adapt it. Naturally, you don't need to call initscr in __init__. You can have a CursesWrapper.initscr() like this: class CursesWrapper: __shared_state = {} def __init__(sef): self.__dict__ = self.__shared_state if not self.__dict__: import curses self.curses = curses self._init = 0 def initscr(self, *args, **kwargs): if not self._init: self.curses.initscr(*args, **kwargs) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From dyoo at hkn.eecs.berkeley.edu Fri May 7 14:06:00 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 7 14:06:07 2004 Subject: [Tutor] Using the 'csv' module to parse tab-delimited data In-Reply-To: <20040507031110.GQ7467@johnsons-web.com> Message-ID: On Thu, 6 May 2004, Tim Johnson wrote: > I am importing TAB-delimited text data. Hi Tim, Glad that you found the problem (stripping the "empty" record at the end)! The Standard Library has a nice 'csv' library that takes care of parsing delimited lines: http://www.python.org/doc/lib/module-csv.html For example: ### >>> import csv >>> from StringIO import StringIO >>> sample_file = StringIO("this\tis\ta\ttest\ndo\tyou\tsee\tthis?\n") >>> reader = csv.reader(sample_file) >>> for row in reader: ... print row ... ['this\tis\ta\ttest'] ['do\tyou\tsee\tthis?'] ### Ooops! I forgot that the default delimiter in 'csv' is the comma character. Let me fix that... let's see what other kind of dialects are supported by 'csv'. ### >>> csv.list_dialects() ['excel-tab', 'excel'] ### Ok, let me switch the mode to 'excel-tab'; that sounds like it should use tabs as the column delimiters: ### >>> reader = csv.reader(sample_file, dialect='excel-tab') >>> sample_file.seek(0) >>> for row in reader: ... print row ... ['this', 'is', 'a', 'test'] ['do', 'you', 'see', 'this?'] ### Better. *grin* Hope this helps! From dyoo at hkn.eecs.berkeley.edu Fri May 7 14:17:04 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 7 14:17:10 2004 Subject: [Tutor] What is a fun basic game project. [uselesspython not being maintained?] In-Reply-To: Message-ID: On Fri, 7 May 2004 sciboy@sciboy.zer0host.com wrote: > Hi, this is my first message to this mailing list. > > Anyone know of a fun game project that is good for beginners, and what > aspects they involve. > > eg. conditions, arrays etc. Hi Sciboy, The Useless Python page might be fun for you... wait, it's down? There's a link to the old URL here: http://uselesspython.com/oldindex.html But this is sad news that it's not being maintained! From bgailer at alum.rpi.edu Fri May 7 15:27:51 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri May 7 15:27:59 2004 Subject: [Tutor] Beginner in need of help! In-Reply-To: References: <20040507124357.46147.qmail@web12401.mail.yahoo.com> Message-ID: <6.0.0.22.0.20040507132530.0262ef88@mail.mric.net> >On 5/7/04 7:43 AM, "Alexander Ades" wrote: > > I wrote a program in IDLE and I tried to run it in python command line > but no > matter what I tried it never worked. What do I do to run my simple > calculator > program in python command line? Please show us the program. Please tell us how and where you got the "python command line" and what you typed there. What did you see happen? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From glingl at aon.at Fri May 7 15:32:15 2004 From: glingl at aon.at (Gregor Lingl) Date: Fri May 7 15:31:28 2004 Subject: [Tutor] What is a fun basic game project. [uselesspython not being maintained?] In-Reply-To: References: Message-ID: <409BE43F.4010508@aon.at> Danny Yoo schrieb: >Hi Sciboy, > > >The Useless Python page might be fun for you... wait, it's down? > > >There's a link to the old URL here: > > http://uselesspython.com/oldindex.html > > >But this is sad news that it's not being maintained! > > > Yes, really sad news. Thanks to Rob, he did a good and huge job. So big, that he apparently didn't find anybody to follow him in maintaining the site? (It was veryhelpful for me, when I started to learn Python some 3 years ago.) And concerning game-programming for beginners, there is the notable livewires-package, http://www.livewires.org.uk/python/ which is "intended to teach the Python programming language to people who have never programmed before", and which contains a set of funny and interesting games. Regards, Gregor From dyoo at hkn.eecs.berkeley.edu Fri May 7 19:38:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 7 19:39:06 2004 Subject: [Tutor] Re: .....str.count and str.split/solved In-Reply-To: <20040507191810.GV7467@johnsons-web.com> Message-ID: On Fri, 7 May 2004, Tim Johnson wrote: > This was caused by not taking into consideration the differences in line > enders between linux,windows and Mac, and compounded by processing on > linux what is produced in windows. > > I need to whip up a read_lines routine for python that's as predicatable > as the read/lines routine in rebol. [bringing tutor@python.org back to CC] Hi Tim, Ah! You probably don't need to do anything too special. If you open the file in "universal newline" mode, then Python will automagically handle platform-specific newline stuff. See: http://www.python.org/doc/lib/built-in-funcs.html#l2h-25 Look at the 'U' mode for universal newlines --- I think it should do what you want. Hope this helps! From tim at johnsons-web.com Fri May 7 22:01:34 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Fri May 7 21:58:31 2004 Subject: [Tutor] Re: .....str.count and str.split/solved In-Reply-To: References: <20040507191810.GV7467@johnsons-web.com> Message-ID: <20040508020134.GZ7467@johnsons-web.com> * Danny Yoo [040507 15:50]: > > > On Fri, 7 May 2004, Tim Johnson wrote: > <....> > > > Ah! You probably don't need to do anything too special. If you open the > file in "universal newline" mode, then Python will automagically handle > platform-specific newline stuff. See: > > http://www.python.org/doc/lib/built-in-funcs.html#l2h-25 > > Look at the 'U' mode for universal newlines --- I think it should do what > you want. I'm currently using ver 2.2 on RH 9.0 --- mode 'rU' is recognized. I commented out the code that removes '\r' line.rstrip('\r') '\r' remained in the line, Using "U" throws IOError I'll read through those doc some more. thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From pan at uchicago.edu Sun May 9 01:02:06 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Sun May 9 01:02:12 2004 Subject: [Tutor] import problem In-Reply-To: References: Message-ID: <1084078926.409dbb4e97232@webmail.uchicago.edu> Hi, I wanna import a class MyClass from a module myModule.py but something weird just happened : [1] import myModule ===> ok [2] from myModule import * ===> ok [3] from myModule import MyClass ===> ImportError: cannot import name MyClass [4] But when I put [3] inside a class: class NewClass(object): def __init__(self): from myModule import MyClass # <======= self.item = MyClass() x = NewClass() print x.item.__doc__ ===> THIS IS OK !!! How come a class can't be imported when the statement: "from myModule import MyClass" is placed globally, but no problem at all when it is inside a class ???? This is really confusing ... pan From flaxeater at yahoo.com Sun May 9 09:55:23 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sun May 9 09:55:29 2004 Subject: [Tutor] import problem In-Reply-To: <1084078926.409dbb4e97232@webmail.uchicago.edu> Message-ID: <20040509135523.9792.qmail@web11602.mail.yahoo.com> --- pan@uchicago.edu wrote: > Hi, > > I wanna import a class MyClass from a module > myModule.py but something > weird just happened : > > [1] import myModule ===> ok > > [2] from myModule import * ===> ok > > [3] from myModule import MyClass ===> ImportError: > cannot import name MyClass > > [4] But when I put [3] inside a class: > > class NewClass(object): > def __init__(self): > from myModule import MyClass # <======= > self.item = MyClass() > > x = NewClass() > print x.item.__doc__ > > ===> THIS IS OK !!! > > How come a class can't be imported when the > statement: > "from myModule import MyClass" is placed globally, > but > no problem at all when it is inside a class ???? > > This is really confusing ... > Well I do not believe there is quite enough information. If the code you showed is all that is in the script then it would apear to work but not really work because it has not been instantiated. Investigate a little. You should at the interactive prompt type import myModule then type dir(myModule) and see if your class is there. If not then something strange has happend I'm sure. In addition when you do this paste a traceback of the error. __________________________________ Do you Yahoo!? Win a $20,000 Career Makeover at Yahoo! HotJobs http://hotjobs.sweepstakes.yahoo.com/careermakeover From isrgish at fastem.com Sun May 9 11:56:14 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun May 9 11:56:17 2004 Subject: [Tutor] Python & XML Message-ID: Don't know anything about XML. But just wanted to mention that it's not advisable to assign anything to a built-in function name, or keyward. The line: print = '\t\tPSETI' is doing just that. "print" is a built in keyword. All the best Isr -----Original Message----- >From: "justinstraube@charter.net" >Sent: 5/6/04 7:21:36 PM >To: "tutor@python.org" >Subject: [Tutor] Python & XML > >Hello, > >Ive used the httplib module and the examples given in the 2.3 docs to >retrieve my or a given users stats from SETI, > >http://setiathome2.ssl.berkeley.edu/fcgi- >bin/fcgi?cmd=user_xml&email=XXXX >(where XXXX is the registered email address) > >The string retrieved is in XML format. Ive begun looking at the some of >the docs for the different XML modules in 2.3 but this is a bit >confusing. Im not sure where to start. > >I am guessing that this should be a fairly simple project as the tags >for the fields in the user stats shouldnt change. I would just need to >extract the wanted data for display. > >Can anyone can point me to anything on how to go about this? > >#### >import httplib > >SETI = "setiathome2.ssl.berkeley.edu" > >print = '\t\tPSETI' >usrmail = raw_input('\nYour Email Address: ') >addr = '/fcgi-bin/fcgi?cmd=user_xml&email=' + usrmail > >conx = httplib.HTTPConnection(SETI) >conx.request('GET', addr) >response = conx.getresponse() >print response.status, response.reason >data = response.read() >conx.close() >print data > >raw_input('Press Enter to continue') >#### > > >Thanks, > >Justin > >--- > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Ralf.Steckel at AtosOrigin.com Sun May 9 23:53:26 2004 From: Ralf.Steckel at AtosOrigin.com (Steckel, Ralf) Date: Sun May 9 23:53:33 2004 Subject: [Tutor] bug in eval() ? or doing something forbidden ? Message-ID: <42BF8717D22EB1409F03483C993F46A70DE878@DEACX002.ikossvan.de> Dear Tutor, I'm trying to get the string representation of a string variable containing the unicode representation of a string via eval(). This works fine as long as I don't have any ' or " preceeded with a backslash in the representation. Is there a bug in eval() or am I doing something wrong? >From the first statement in the snapshot of Idle (see below), I would expect that eval() should processes backslashes in the representation of unicode strings and ' or " preceeded by a backslash is a valid token for an unicode string. Thanks for any help, Ralf Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 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.0 >>> print u'\'abcd\"' 'abcd" >>> a="u'\'abcd\"'" >>> print eval(a) Traceback (most recent call last): File "", line 1, in -toplevel- print eval(a) File "", line 1 u''abcd"' ^ SyntaxError: invalid syntax >>> >>> a="u'\'abcd\''" >>> print eval(a) Traceback (most recent call last): File "", line 1, in -toplevel- print eval(a) File "", line 1 u''abcd'' ^ SyntaxError: invalid syntax >>> From george at visp.com.au Mon May 10 04:33:50 2004 From: george at visp.com.au (George Patterson) Date: Mon May 10 04:34:08 2004 Subject: [Tutor] Multiple Dimension (array/list/whatever it is are). Message-ID: <20040510180350.20cf91fb@beast.spyderweb.com.au> Hi All. A could of quick questions: 1. What is the data structure below called? Apart from G :-P Is it an array, a list or something else. The original article was very vague on the commenting. See bottom of email for URL. G = {'s':{'u':10, 'x':1}, 'u':{'v':1, 'x':2}, 'v':{'y':4}, 'x':{'u':3, 'v':9, 'y':2}, 'y':{'s':7, 'v':6} } 2. How would I alter the above data structure such that all instances of 'x' ends up being equal to 5. As per sample below. {'s':{'u':10, 'x':5}, 'u':{'v':1, 'x':5}, 'v':{'y':4}, 'x':{'u':3, 'v':9, 'y':2}, 'y':{'s':7, 'v':6} } For those that want the rest of the code see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466 George Patterson From thomi at imail.net.nz Mon May 10 05:09:51 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Mon May 10 05:10:04 2004 Subject: [Tutor] Multiple Dimension (array/list/whatever it is are). In-Reply-To: <20040510180350.20cf91fb@beast.spyderweb.com.au> References: <20040510180350.20cf91fb@beast.spyderweb.com.au> Message-ID: <200405102109.51440.thomi@imail.net.nz> On Monday 10 May 2004 20:33, George Patterson wrote: > 1. What is the data structure below called? Apart from G :-P Is it an > array, a list or something else. The original article was very vague on the > commenting. See bottom of email for URL. > > G = {'s':{'u':10, 'x':1}, > 'u':{'v':1, 'x':2}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } > This is a dictionary....containing other dictionaries. They're used to provide key->value mappings. > > 2. How would I alter the above data structure such that all instances of > 'x' ends up being equal to 5. As per sample below. > > {'s':{'u':10, 'x':5}, > 'u':{'v':1, 'x':5}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } > not sure what you mean here.. doing "G['x']" would return "{'u':3, 'v':9, 'y':2}". i.e.- another dictionary, not a numeric value... HTH -- Thomi Richards, thomi@once.net.nz From Janssen at rz.uni-frankfurt.de Mon May 10 05:25:06 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon May 10 05:25:21 2004 Subject: [Tutor] Multiple Dimension (array/list/whatever it is are). In-Reply-To: <20040510180350.20cf91fb@beast.spyderweb.com.au> References: <20040510180350.20cf91fb@beast.spyderweb.com.au> Message-ID: On Mon, 10 May 2004, George Patterson wrote: > Hi All. > > > > > A could of quick questions: > > 1. What is the data structure below called? Apart from G :-P Is it an > array, a list or something else. The original article was very vague on > the commenting. See bottom of email for URL. > > G = {'s':{'u':10, 'x':1}, > 'u':{'v':1, 'x':2}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } it's a dictionary mapping keys s,u,v,x,y to subdictionaries. Read more tutorials to get this: http://www.python.org/doc/current/tut/tut.html Section 5.4 http://www.python.g2swaroop.net/ Chapter 9 > 2. How would I alter the above data structure such that all instances of > 'x' ends up being equal to 5. As per sample below. > > {'s':{'u':10, 'x':5}, > 'u':{'v':1, 'x':5}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } first you will need to iterate through the toplevel dictionary. Then you should test if the dictionary has a key "x" and set it to 5. So you have to figure out, how to iterate ("for-loop") through a dictionary, how to test the existence of a key and how to reassign it. Might be a good training for you, so I won't spoil it with a solution. Michael From Janssen at rz.uni-frankfurt.de Mon May 10 08:21:24 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon May 10 08:22:44 2004 Subject: [Tutor] bug in eval() ? or doing something forbidden ? In-Reply-To: <42BF8717D22EB1409F03483C993F46A70DE878@DEACX002.ikossvan.de> References: <42BF8717D22EB1409F03483C993F46A70DE878@DEACX002.ikossvan.de> Message-ID: On Mon, 10 May 2004, Steckel, Ralf wrote: > Dear Tutor, > > I'm trying to get the string representation of a string variable containing > the unicode representation of a string via eval(). eval evaluates python expressions. >>> eval("1+1") 2 >>> a="abc" >>> eval("a") 'abc' >>> eval("(a == 'abc')") True and things like this. "string representation" is done with repr(): >>> print repr(a) 'abc' Michael From python at rcn.com Mon May 10 12:24:40 2004 From: python at rcn.com (Raymond Hettinger) Date: Mon May 10 13:09:00 2004 Subject: [Tutor] RE: Tutor Digest, Vol 3, Issue 14 In-Reply-To: Message-ID: <006f01c436ab$4b8177a0$e841fea9@oemcomputer> > 1. What is the data structure below called? Apart from G :-P Is it an > array, a list or something else. The original article was very vague on > the commenting. See bottom of email for URL. > > G = {'s':{'u':10, 'x':1}, > 'u':{'v':1, 'x':2}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } It is a directed graph, with path weights. Think of airline routes. >From airport S you can fly to either airport u or airport x. It takes 10 hours to get to u but only one hour to get to x. > 2. How would I alter the above data structure such that all instances of > 'x' ends up being equal to 5. As per sample below. > > {'s':{'u':10, 'x':5}, > 'u':{'v':1, 'x':5}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } for airpost, destinations in G: for dest, cost in destinations: if dest == 'x': destinations['x'] = 5 Raymond Hettinger From dyoo at hkn.eecs.berkeley.edu Mon May 10 14:30:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 10 14:30:28 2004 Subject: [Tutor] Multiple Dimension (array/list/whatever it is are). In-Reply-To: <200405102109.51440.thomi@imail.net.nz> Message-ID: > On Monday 10 May 2004 20:33, George Patterson wrote: > > 1. What is the data structure below called? Apart from G :-P Is it an > > array, a list or something else. The original article was very vague on the > > commenting. See bottom of email for URL. > > > > G = {'s':{'u':10, 'x':1}, > > 'u':{'v':1, 'x':2}, > > 'v':{'y':4}, > > 'x':{'u':3, 'v':9, 'y':2}, > > 'y':{'s':7, 'v':6} > > } On Mon, 10 May 2004, Thomas Clive Richards wrote: > > This is a dictionary....containing other dictionaries. They're used to > provide key->value mappings. Hi George, And in this particular case, G lets us get from a given vertex to its "edges". We can interpret: ### G_simpler = {'s': {'u':10, 'x':1}, 'u': {'x':2} } ### as representing a directed graph. Graphs are made of vertices and edges --- circles and arrows. 10 s -----------> u \ / \ / 1 \ / 2 \ / \ / | V x If it helps, treat the graph as an Abstract Data Structure: don't explicitely touch the graph itself, but write helper functions that touch the graph for you. ### def neighbors(graph, vertex): """Returns all names of the neighbors of the vertex.""" ## ... [fill me in] def setEdge(graph, start_vertex, end_vertex, cost): """Sets an edge between the start_vertex and the end_vertex with a cost.""" ## ... [fill me in] def getEdgeCost(graph, start_vertex, end_vertex): """Looks up the cost for the edge between start_vertex and end_vertex. If no such edge exists, throws LookupError.""" ## ... [fill me in] ### Something like that. All of the implementations need to be filled in. The advantage of writing helper functions is that we can then manipulate graphs at a more meaningful level. Instead of saying: G['s']['x'] = 42 and worrying about managing a dictionary that contains another dictionary, we can say: setEdge(G, 's', 'x', 42) where the "graphiness" of our problem become more transparent. The code in the Cookbook doesn't do this ADT stuff only because the author assumed that a dictionary within a dictionary is "obvious". Obviously, this isn't obvious. *grin* > > 2. How would I alter the above data structure such that all instances > > of 'x' ends up being equal to 5. As per sample below. > > > > {'s':{'u':10, 'x':5}, > > 'u':{'v':1, 'x':5}, > > 'v':{'y':4}, > > 'x':{'u':3, 'v':9, 'y':2}, > > 'y':{'s':7, 'v':6} > > } The question is ambiguous. Are we trying to make all edges that go into 'x' into five? Or are we trying to change all the edges that go out of x into five? Or something else? The main problem is that the question is in terms of dictionaries, but the intent is not clear to us. Can you rephrase your question in terms of graphs? What's nice about Python is that it's very easy to create compound data structures with dictionaries. What's not so nice is that it's all too easy to treat all compound data structures as dictionaries. *grin* You may find it less confusing to write helper functions, like the "Abstract Data Type" stuff above, and manipulate your graph through these ADT functions. That way, you don't have to worry about manipulating dictionaries within dictionaries: instead, you can think in terms of the graph problem you're trying to solve. Good luck! From alan.gauld at blueyonder.co.uk Mon May 10 18:40:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon May 10 18:40:18 2004 Subject: [Tutor] Multiple Dimension (array/list/whatever it is are). References: <20040510180350.20cf91fb@beast.spyderweb.com.au> Message-ID: <008e01c436df$cf3461a0$6401a8c0@xp> > 1. What is the data structure below called? > G = {'s':{'u':10, 'x':1}, > 'u':{'v':1, 'x':2}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } A dictionary of dictionaries. ( key1:value1, key2:value2,...} is how to declare a dictionary, and in this case each value is also a dictionary. > 2. How would I alter the above data structure such that all > instances of 'x' ends up being equal to 5. As per sample below. > > {'s':{'u':10, 'x':5}, > 'u':{'v':1, 'x':5}, > 'v':{'y':4}, > 'x':{'u':3, 'v':9, 'y':2}, > 'y':{'s':7, 'v':6} > } I assume you mean during program execution? for key in G: try: key['x'] = 5 except keyError: pass Or something similar... You might find the section on dictionaries in my new tutor helpful: http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/tutdata.htm HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/ From george at visp.com.au Mon May 10 20:37:56 2004 From: george at visp.com.au (George Patterson) Date: Mon May 10 20:38:08 2004 Subject: [Tutor] Multiple Dimension (array/list/whatever it is are). In-Reply-To: <20040510180350.20cf91fb@beast.spyderweb.com.au> References: <20040510180350.20cf91fb@beast.spyderweb.com.au> Message-ID: <20040511100756.44f2344c@beast.spyderweb.com.au> On Mon, 10 May 2004 18:03:50 +0930 George Patterson wrote: > Hi All. > > > > > A could of quick questions: > snipped:- no longer relevant. > > For those that want the rest of the code see > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466 > Thanks to everyone that gave me some pointers. A couple of people were confused as to why i wanted to set the value of several edges to the same value, well you can have a point that is equal distance from at least three points on a plane. Also what if the plane is not regularly spaced but virtual? I am involved in a computer network project that uses OSPF which happens to use the same algorithm (Dijkstra's algorithm). The length of the edge translates into cost of sending data over that route. Two main rules 1. Use the shortest path through the least number of vertexes or hops. This involves not routing a packet from one end of the network to the other. Hence keeping local traffic local, subject to rule two. 2. Don't send traffic through a possibly congested node. This involves setting the cost higher as the bandwidth is used and routing around the node. As you do so the congested node can clear the back log and you can go back to routing via that node. I gotta say that this mail list is a great idea. No spoon feeding!! Give someone the directions on opening the tin and let them feed themselves. Works for me. :-D Regards George Patterson From dyoo at hkn.eecs.berkeley.edu Mon May 10 21:36:04 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 10 21:36:12 2004 Subject: [Tutor] Multiple Dimension (array/list/whatever it is are). In-Reply-To: <20040511100756.44f2344c@beast.spyderweb.com.au> Message-ID: On Tue, 11 May 2004, George Patterson wrote: > I am involved in a computer network project that uses OSPF which happens > to use the same algorithm (Dijkstra's algorithm). The length of the edge > translates into cost of sending data over that route. Hi George, OSPF? Googling... http://www.ietf.org/rfc/rfc2328.txt Ah, ok. I see it: """ 16.1. Calculating the shortest-path tree for an area This calculation yields the set of intra-area routes associated with an area (called hereafter Area A). A router calculates the shortest-path tree using itself as the root.[22] The formation of the shortest path tree is done here in two stages. In the first stage, only links between routers and transit networks are considered. Using the Dijkstra algorithm, a tree is formed from this subset of the link state database. In the second stage, leaves are added to the tree by considering the links to stub networks. The procedure will be explained using the graph terminology that was introduced in Section 2. The area's link state database is represented as a directed graph. The graph's vertices are routers, transit networks and stub networks. [text cut] """ Wow. Sounds like heady and exciting stuff. I wish I were taking a networking class... Well, good luck in implementing it! *grin* If you have more Python related questions, please feel free to ask. From pan at uchicago.edu Mon May 10 22:04:41 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Mon May 10 22:04:46 2004 Subject: [Tutor] Re: import problem (Chad Crabtree) In-Reply-To: References: Message-ID: <1084241081.40a034b9e09a2@webmail.uchicago.edu> > --- pan@uchicago.edu wrote: > > Hi, > > > > I wanna import a class MyClass from a module > > myModule.py but something > > weird just happened : > > > > [1] import myModule ===> ok > > > > [2] from myModule import * ===> ok > > > > [3] from myModule import MyClass ===> ImportError: > > cannot import name MyClass > > > > [4] But when I put [3] inside a class: > > > > class NewClass(object): > > def __init__(self): > > from myModule import MyClass # <======= > > self.item = MyClass() > > > > x = NewClass() > > print x.item.__doc__ > > > > ===> THIS IS OK !!! > > > > How come a class can't be imported when the > > statement: > > "from myModule import MyClass" is placed globally, > > but > > no problem at all when it is inside a class ???? > > Investigate a little. You should at the interactive > prompt type import myModule > then type dir(myModule) and see if your class is > there. If not then something strange has happend I'm > sure. In addition when you do this paste a traceback > of the error. Thx for who replied. I found a solution to fix the problem (although I still can't fully explain some weird behaviors). In myModule, there's a function 'cgiBrowser' placed BEFORE the class definition of MyClass. That function has error in some circumstances, resulting in a termination of myModule loading. After modifying that function, the problem is gone. The funny thing (before the problem was corrected) is, when the test_MyClass is executed the first time, it returns: >>> Traceback (most recent call last): File "C:\Python22\Lib\site- packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "D:\Pan\PC\Prog\lang\py\cgi\test_MyClass.py", line 8, in ? from myModule import MyClass File "D:\Pan\PC\Prog\lang\py\cgi\myModule.py", line 6, in ? from test_MyClass import cgiBrowser #<========================== [a] File "D:\Pan\PC\Prog\lang\py\cgi\test_MyClass.py", line 8, in ? from myModule import MyClass ImportError: cannot import name MyClass But if it is executed from the 2nd time and beyond, it returns: >>> Traceback (most recent call last): File "C:\Python22\Lib\site- packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "D:\Pan\PC\Prog\lang\py\cgi\test_MyClass.py", line 8, in ? from myModule import MyClass ImportError: cannot import name MyClass Note that at the first time it reports the error @ cgiBrowser (marked as line [a] ), but since then more executions only report that it can't import the class MyClass. From isrgish at fastem.com Tue May 11 00:16:17 2004 From: isrgish at fastem.com (Isr Gish) Date: Tue May 11 00:16:32 2004 Subject: [Tutor] Problem with os.walk Message-ID: The docs say that you can del the dirnames list. But when I tried doing it, it didn't work. Here is the help info: ### Help on function walk in module os: walk(top, topdown=True, onerror=None) Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). If optional arg 'topdown' is true or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top down). If topdown is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom up). When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, or to impose a specific order of visiting. Modifying dirnames when topdown is false is ineffective, since the directories in dirnames have already been generated by the time dirnames itself is generated. ### I tried del and dirnames = dirnames[0:0] Both didn't work. The only thing that wOrked was. for d in dirnames[:]: dirnames.remove(d) And if I didn't make a copy it didn't work correctly. (it seems that for i in list works with indexing behindethe seigns). All help in this will be appreciated. All the best Isr From pan at uchicago.edu Tue May 11 02:10:04 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Tue May 11 02:10:10 2004 Subject: [Tutor] documentations for attributes/properties ??? In-Reply-To: References: Message-ID: <1084255804.40a06e3cee1a9@webmail.uchicago.edu> Hi, I know that python uses 'documentation string' __doc__ for functions and classes. Is there something similar for attributes and properties ??? pan From justinstraube at charter.net Tue May 11 07:23:58 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Tue May 11 04:21:49 2004 Subject: [Tutor] Python & XML Message-ID: <200405110816.i4B8G4OF027215@mxsf12.cluster1.charter.net> On Sun, 9 May 2004 11:56:14 -0400, Isr wrote: > >Don't know anything about XML. But just wanted to mention that it's not advisable to assign anything to a built-in function name, or keyward. The line: >print = '\t\tPSETI' >is doing just that. "print" is a built in keyword. Thanks for pointing that out. That was just sloppy, sorry. Ive managed a way to extract the wanted data from the xml string, though Im not sure if Im going about this in the best way. I think this should work for any SETI user. ################################# ##### PSETI ################# ################################# import httplib from xml.dom import minidom _name_ = 'PSETI' _auth_ = 'justinstraube@charter.net' _date_ = 'May 11 2004' _ver_ = '0.0004' _inf_ = 'Python 2.3 www.Python.org' SETI = "setiathome2.ssl.berkeley.edu" while 1: print '\t', _name_, _ver_, '\t', _date_ print '\n\tCreated by:', _auth_ print '\tWritten in:', _inf_ usrmail = raw_input('\nYour Email Address: ') if usrmail == '': usrmail = _auth_ add = '/fcgi-bin/fcgi?cmd=user_xml&email=' + usrmail conx = httplib.HTTPConnection(SETI) conx.request("GET", add) response = conx.getresponse() if response.status == 500: print response.status, response.reason print """\n\t\tServer Error\n The page or site is temporarily down or disabled. Sorry for the inconvienience. Please try again later.\n""" break data = response.read() if data[-33:] == 'No user with that name was found.': print """\n\t\tNo user with that name was found. Please check the email address and try again.\n""" break conx.close() xdata = minidom.parseString(data) ud = {} #users dictionary usr = xdata.childNodes[1].childNodes for item in usr: if item.nodeType == item.ELEMENT_NODE: if item.tagName == 'userinfo': for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'name': uname = node.toxml() ud[1] = uname[6:-7] + ' <' + usrmail + '>' node.unlink elif node.tagName == 'numresults': num = node.toxml() ud[2] = num[12:-13] node.unlink elif node.tagName == 'cputime': cput = node.toxml() ud[3] = cput[9:-10] node.unlink elif node.tagName == 'avecpu': avg = node.toxml() ud[4] = avg[8:-9] node.unlink elif node.tagName == 'resultsperday': rpd = node.toxml() ud[5] = rpd[15:-16] node.unlink elif node.tagName == 'lastresulttime': lrr = node.toxml() ud[6] = lrr[16:-17] node.unlink elif node.tagName == 'regdate': regd = node.toxml() ud[7] = regd[9:-10] node.unlink elif node.tagName == 'usertime': usrt = node.toxml() ud[8] = usrt[10:-11] node.unlink else: node.unlink else: node.unlink elif item.tagName == 'groupinfo': flist = '' # if user has started multiple groups. for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'founder': found = node.toxml() found = found[82:-14] flist = flist + ', ' + found node.unlink elif node.tagName == 'group': group = node.toxml() ud[10] = group[80:-12] node.unlink else: node.unlink else: node.unlink # founder list is added after all tags have been # sliced,if user has started multiple groups ud[9] = flist elif item.tagName == 'rankinfo': for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'rank': rank = node.toxml() ud[11] = rank[6:-7] node.unlink elif node.tagName == 'ranktotalusers': total = node.toxml() ud[12] = total[16:-17] node.unlink elif node.tagName == 'num_samerank': same = node.toxml() ud[13] = same[14:-15] node.unlink elif node.tagName == 'top_rankpct': pct = node.toxml() ud[14] = pct[13:-14] node.unlink else: node.unlink else: node.unlink elif item.tagName == 'certinfo': for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'cert': # Should be the highest certificate. cert = node.toxml() cert = cert[69:] cert = cert[len(usrmail):] ud[15] = cert[45:-11] node.unlink break else: node.unlink else: node.unlink # if user has not founder of a group if ud[9] == '': ud[9] = '' #if user has no certificates yet if ud.has_key(15) == False: ud[15] = '' print '\nUser:\t\t', ud[1] print 'Finished Units:', ud[2], 'over', ud[3] print 'Results/Day:\t', ud[4], ' Avg:', ud[5] print 'Last Result:\t', ud[6] print 'Registered on:\t', ud[7] print 'User for\t', ud[8] print 'Founder of: \t', ud[9][2:] print 'Member of: \t', ud[10] print 'Rank:\t\t', ud[11], 'of', ud[12], 'users total.' print 'Your Rank:\t', ud[13], ',', ud[14], 'users share the same rank.' print 'Highest Cert: \t', ud[15] break #### regards, Justin From justinstraube at charter.net Tue May 11 07:31:04 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Tue May 11 04:25:56 2004 Subject: [Tutor] Python & XML Message-ID: <200405110823.i4B8NATl018662@mxsf18.cluster1.charter.net> Sorry, for the repost but I accidentally sent before I could ask for a small bit of help. Can anyone spare a minute to look over this and give any points as to what I may be doing wrong or what could be done better? Ive managed a way to extract the wanted data from the xml string, though Im not sure if Im going about this in the best way. I think this should work for any SETI user. Thanks for your time, justin ################################# ##### PSETI ################# ################################# import httplib from xml.dom import minidom _name_ = 'PSETI' _auth_ = 'justinstraube@charter.net' _date_ = 'May 11 2004' _ver_ = '0.0004' _inf_ = 'Python 2.3 www.Python.org' SETI = "setiathome2.ssl.berkeley.edu" while 1: print '\t', _name_, _ver_, '\t', _date_ print '\n\tCreated by:', _auth_ print '\tWritten in:', _inf_ usrmail = raw_input('\nYour Email Address: ') if usrmail == '': usrmail = _auth_ add = '/fcgi-bin/fcgi?cmd=user_xml&email=' + usrmail conx = httplib.HTTPConnection(SETI) conx.request("GET", add) response = conx.getresponse() if response.status == 500: print response.status, response.reason print """\n\t\tServer Error\n The page or site is temporarily down or disabled. Sorry for the inconvienience. Please try again later.\n""" break data = response.read() if data[-33:] == 'No user with that name was found.': print """\n\t\tNo user with that name was found. Please check the email address and try again.\n""" break conx.close() xdata = minidom.parseString(data) ud = {} #users dictionary usr = xdata.childNodes[1].childNodes for item in usr: if item.nodeType == item.ELEMENT_NODE: if item.tagName == 'userinfo': for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'name': uname = node.toxml() ud[1] = uname[6:-7] + ' <' + usrmail + '>' node.unlink elif node.tagName == 'numresults': num = node.toxml() ud[2] = num[12:-13] node.unlink elif node.tagName == 'cputime': cput = node.toxml() ud[3] = cput[9:-10] node.unlink elif node.tagName == 'avecpu': avg = node.toxml() ud[4] = avg[8:-9] node.unlink elif node.tagName == 'resultsperday': rpd = node.toxml() ud[5] = rpd[15:-16] node.unlink elif node.tagName == 'lastresulttime': lrr = node.toxml() ud[6] = lrr[16:-17] node.unlink elif node.tagName == 'regdate': regd = node.toxml() ud[7] = regd[9:-10] node.unlink elif node.tagName == 'usertime': usrt = node.toxml() ud[8] = usrt[10:-11] node.unlink else: node.unlink else: node.unlink elif item.tagName == 'groupinfo': flist = '' # if user has started multiple groups. for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'founder': found = node.toxml() found = found[82:-14] flist = flist + ', ' + found node.unlink elif node.tagName == 'group': group = node.toxml() ud[10] = group[80:-12] node.unlink else: node.unlink else: node.unlink # founder list is added after all tags have been # sliced,if user has started multiple groups ud[9] = flist elif item.tagName == 'rankinfo': for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'rank': rank = node.toxml() ud[11] = rank[6:-7] node.unlink elif node.tagName == 'ranktotalusers': total = node.toxml() ud[12] = total[16:-17] node.unlink elif node.tagName == 'num_samerank': same = node.toxml() ud[13] = same[14:-15] node.unlink elif node.tagName == 'top_rankpct': pct = node.toxml() ud[14] = pct[13:-14] node.unlink else: node.unlink else: node.unlink elif item.tagName == 'certinfo': for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName == 'cert': # Should be the highest certificate. cert = node.toxml() cert = cert[69:] cert = cert[len(usrmail):] ud[15] = cert[45:-11] node.unlink break else: node.unlink else: node.unlink # if user has not founder of a group if ud[9] == '': ud[9] = '' #if user has no certificates yet if ud.has_key(15) == False: ud[15] = '' print '\nUser:\t\t', ud[1] print 'Finished Units:', ud[2], 'over', ud[3] print 'Results/Day:\t', ud[4], ' Avg:', ud[5] print 'Last Result:\t', ud[6] print 'Registered on:\t', ud[7] print 'User for\t', ud[8] print 'Founder of: \t', ud[9][2:] print 'Member of: \t', ud[10] print 'Rank:\t\t', ud[11], 'of', ud[12], 'users total.' print 'Your Rank:\t', ud[13], ',', ud[14], 'users share the same rank.' print 'Highest Cert: \t', ud[15] break #### regards, Justin From denis.spir at free.fr Tue May 11 04:15:51 2004 From: denis.spir at free.fr (denis) Date: Tue May 11 06:14:52 2004 Subject: [Tutor] Message-ID: <002601c43740$a5cc97e0$3e25933e@spir> Hello, I'm starting a new thread, rather a thread class in fact ;-), about Python's 'art' of bindind variables and data. I have been and still am surprised about that --maybe because I didn't learn programming with this idiom. In a short series of messages prefixed like this one, I'll try and introduce my own surprises & discoverings, leading to temporary conclusions & questions. Thus, much of what I introduce may be wrong ! I hope this will be useful to many, expecting comments, corrections and... wonders. denis PS: The first thread starts today. There may be 3 to 5 threads abouts several aspects of the var:data topic. Hope you welcome. From op73418 at mail.telepac.pt Tue May 11 06:41:04 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue May 11 06:38:18 2004 Subject: [Tutor] documentations for attributes/properties ??? In-Reply-To: <1084255804.40a06e3cee1a9@webmail.uchicago.edu> References: <1084255804.40a06e3cee1a9@webmail.uchicago.edu> Message-ID: <3ab1a01ro75p8pbvohq7kh8loksadcb0fg@4ax.com> Em Tue, 11 May 2004 01:10:04 -0500, pan@uchicago.edu atirou este peixe aos pinguins: >Hi, > >I know that python uses 'documentation string' __doc__ for >functions and classes. Is there something similar for attributes and >properties ??? For properties yes (After all, they are syntactic sugar for function calls) for attributes no. Any info pertaining to attributes is usually in the class's docstring ot the class's __init__ docstring. With my best regards, G. Rodrigues From sigurd at 12move.de Tue May 11 08:28:38 2004 From: sigurd at 12move.de (=?iso-8859-1?q?Karl_Pfl=E4sterer?=) Date: Tue May 11 08:30:45 2004 Subject: [Tutor] Problem with os.walk In-Reply-To: (Isr Gish's message of "Tue, 11 May 2004 00:16:17 -0400") References: Message-ID: On 11 May 2004, Isr Gish <- isrgish@fastem.com wrote: > The docs say that you can del the dirnames list. But when I tried doing it, it > didn't work. Here is the help info: [...] > I tried del and dirnames = dirnames[0:0] > Both didn't work. The only thing that wOrked was. > for d in dirnames[:]: > dirnames.remove(d) What did you write exactly? I tried the example from the docs and it worked as expected import os from os.path import join, getsize for root, dirs, files in os.walk('.'): print root, "consumes", print sum([getsize(join(root, name)) for name in files]), print "bytes in", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories I ran that in a directory where if have a CVS subdirectory and that didn't get visited. Karl -- Please do *not* send copies of replies to me. I read the list From tim.one at comcast.net Tue May 11 10:56:00 2004 From: tim.one at comcast.net (Tim Peters) Date: Tue May 11 10:55:59 2004 Subject: [Tutor] Problem with os.walk In-Reply-To: Message-ID: [Isr Gish] > The docs say that you can del the dirnames list. "the caller can modify the dirnames list in-place (e.g., via del or slice assignment)" "in-place" means things of the form del dirnames[1:] or dirnames[:] = ['new directory'] > But when I tried doing it, it didn't work. You have to show the exact code you used, else nobody can guess. ... > I tried del That's not enough to guess. Maybe you did del dirnames ? That indeed would not work. > and dirnames = dirnames[0:0] The binds dirnames to a brand new object, so is not an in-place modification either. If you want to empty dirnames entirely, two ways to do it in-place are del dirnames[:] or dirnames[:] = [] > Both didn't work. The only thing that wOrked was. > for d in dirnames[:]: > dirnames.remove(d) The two above will also work. > And if I didn't make a copy it didn't work correctly. (it seems > that for i in list works with indexing behindethe seigns). Yes. This is documented in the Language Reference manual (not the Library Reference manual), in the section on "for" loops. From denis.spir at free.fr Tue May 11 12:14:07 2004 From: denis.spir at free.fr (denis) Date: Tue May 11 12:15:54 2004 Subject: [Tutor] assignment Message-ID: <001401c43773$10e92ca0$262ae4d5@spir> [first thread of the 'var:data' class :-)] Q: what happens with 'myVar = myVal'? Qbis: why such a question? When a variable is assigned for the first time, the language itself --python's 'decoder' which is not written in python, but in C instead-- has to yield a link between the variable and its associated data . There are at least to things (not to say: onject') involved: the variable's name and the value itself. The value must obviously be stored somehow, if it's not already, which actually means it must be put somewhere in a memory site --that is: yield data. Then, Python must draw a kind of name --> value mapping to recover it when needed, let's call that 'registration'. This is of course, you have noted it ;-) the structure of a Python dictionary: name1: value1, name2: value2, name3: value3, ... or a pair of associated lists (by indexes): name1, name2, name3, ... | | | value1, value2, value3, ... Consider this: class C: i=1 x=1.0 t='text' l=['voici', 'mes', 'articles'] d={1:'un', 2:'deux'} >>> dir(C) ['__doc__', '__module__', 'd', 'i', 'l', 't', 'x'] >>> C.__dict__ {'__module__': '__main__', 'd': {1: 'un', 2: 'deux'}, 'i': 1, 'l': ['voici', 'mes', 'articles'], 't': 'text', 'x': 1.0, '__doc__': None} Now, this doesn't mean that in the language's blackbox (in C), variable registration is really implemented as a dictionary. Yet the language needs not know where actually the value is. And if someone used python to design another language, and dictionaries for variable registration, the actual memory location of the data would be unknown and un-needed. Now, consider the following line, using particuliar Python features: >>> t1='salut' >>> t2='salut' >>> t1==t2, id(t1), id(t2), t1 is t2 (True, 18654912, 18654912, True) >>> t2='hallo' >>> t1==t2, id(t1), id(t2), t1 is t2 (False, 18654912, 18655776, False) 'id()' returns the so-called 'identity' of a variable, if fact the memory address of its bound data, and 'is' checks if two variables have the same id-s. The above lines tell us several things: First, when a value already exists, it isn't created again and stored in another place. Second, two variables can thus share same value *and* same id: there synonyms, or aliases. Third, conversely, when a value changes, its place changes, too. All of this leads (me) to question the above dictionary-like model. It seems that, instead of values, the id-s are bound to variable names. This better explains the three comments above: name1: address1, name2: address2, name3: address3, ... (address=id) or a pair of associated lists: name1, name2, name3, ... | | | address1, address2, address3, ... Of course, both of the models would be possible; the second one is right in python, as other noticeable facts will show it. These models can be better designed and distinguished by another picture: [you'll need a fixed-width font] >>> a=1; b=1; c=2 >>> id(a), id(b),id(c) (7742480, 7742480, 7748592) >>> a is b, a is c, b is c (True, False, False) --- 'a' --> | 1 | --- --- 'b' --> | 1 | first model --- --- 'c' --> | 2 | --- or: ------ 'a' --> | adr1 | \ ------ \ --- > | 1 | ------ / --- 'b' --> | adr1 | / second model ------ ------ --- 'c' --> | adr2 | --> | 2 | ------ --- In other words, in the second case we have on one side a set of name:address pairs, and on the other side a set of data (see C pointers). In the first case, we could see a variable as a kind of labeled box holding a simple value, hence representing an assignment with: a <- 1 (a) 'gets' 1 Or we could see variables like names whose purpose is to label data, the data beeing boxes holding values, and thus an assignment could be represented: a -> 1 'a' 'is fixed to' 1 Neither (?) of these pictures match the actual variable processing by Python. In python, we could eventually see variables as labeled boxes holding adresses, pointing to data ; while the data would be unlabeled boxes holding values: a --> 1 a 'points to' 1 (C pointers, bis) Now, consider the case of compound data: >>> l1=[1,2] >>> l2=[1,2] >>> l1 == l2, l1 is l2 (True, False) This contredicts the first rule saying that if a data exists, it needs not beeing created again. l1 and l2 hold the same data --there're equal--, but not at the same place --they're not identical in the sense of Python's idiom. We can explain this (at first sight) strange behaviour by recursively applying the other rule, the one saying that a variable isn't bound to a value, but to an address instead. If we compare a list to an object holding (named) data: object data: list data: line_count item#0 file_name item#1 In the case of the object, it's obvious that both attributes, say 'sub_variables', will behave like 'real' variables, that is names associated to addresses, where is actual data take place. Hence, the consequence is that the object's data won't be a list of values, but a list of name:adress pairs instead! ----- ------------------------ 'object_name' --> | adr | --> | list of name:adr pairs | ----- ------------------------ | '--> actual data The same for a list; except that names are replaced by indexes (thus, an index is a particuliar form of a key, indeed). ----- ------------------------ 'list_name' --> | adr | --> | list of indexed adresses | ----- ------------------------ | '--> actual data If you think you have understood the mysteries of pythonesque data , read this: >>> l1=[1] >>> l2=[1] >>> l1 is l2 False >>> l1=l2=[1] >>> l1 is l2 True >>> l1=[1]; l2=[1] >>> l1 is l2 False >>> l1=l2 >>> l1 is l2 True [homework] denis From bgailer at alum.rpi.edu Tue May 11 12:29:24 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue May 11 12:28:57 2004 Subject: [Tutor] assignment In-Reply-To: <001401c43773$10e92ca0$262ae4d5@spir> References: <001401c43773$10e92ca0$262ae4d5@spir> Message-ID: <6.0.0.22.0.20040511102739.03bcfa48@mail.mric.net> At 10:14 AM 5/11/2004, denis wrote: >[first thread of the 'var:data' class :-)] I'm having trouble understanding the purpose of this thread, and especially its presence on a Tutor list. Could you tell us what you want from us? [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From denis.spir at free.fr Tue May 11 13:29:36 2004 From: denis.spir at free.fr (denis) Date: Tue May 11 13:31:11 2004 Subject: [Tutor] assignment References: <001401c43773$10e92ca0$262ae4d5@spir> <6.0.0.22.0.20040511102739.03bcfa48@mail.mric.net> Message-ID: <003201c4377d$985eb600$3942933e@spir> corrections, comments, critics... such things It's a trial to explain (also to myself). As I say in the text, I'm not sure that the model is right. denis PS : Is tutor a right place for this? Who knows? (The title prefix makes it easy to delete overloading messages if ever needed.) ----- Original Message ----- From: Bob Gailer To: denis ; tutor python Sent: Tuesday, May 11, 2004 6:29 PM Subject: Re: [Tutor] assignment > At 10:14 AM 5/11/2004, denis wrote: > >[first thread of the 'var:data' class :-)] > > I'm having trouble understanding the purpose of this thread, and especially > its presence on a Tutor list. Could you tell us what you want from us? > [snip] > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > From pan at uchicago.edu Tue May 11 14:16:32 2004 From: pan at uchicago.edu (pan@uchicago.edu) Date: Tue May 11 14:16:40 2004 Subject: [Tutor] Re: documentations for attributes/properties ??? In-Reply-To: References: Message-ID: <1084299392.40a118801b812@webmail.uchicago.edu> > >I know that python uses 'documentation string' __doc__ for > >functions and classes. Is there something similar for attributes and > >properties ??? > > For properties yes (After all, they are syntactic sugar for function > calls) for attributes no. Any info pertaining to attributes is usually > in the class's docstring ot the class's __init__ docstring. So, how does the docstring for properties work ? Can you give an example ? From jfabiani at yolo.com Tue May 11 14:22:27 2004 From: jfabiani at yolo.com (John Fabiani) Date: Tue May 11 14:20:36 2004 Subject: [Tutor] tutorial for dbapi 2.0 how to use data Message-ID: <40A119E3.8050104@yolo.com> Hi, mycur=con.cursor() mycur.execute("select * from sosord") mydata=mycur.fetchmany(10) The above works and returns data. But know I need to understand how to view the data. Maybe there is a way to convert the returned list into a dictionary. A dictionary would allow me to get information by key (the field name). Anyway, is there some paper or tutorial I can read on how to view the return data? TIA John From mruiz at polymedco.com Mon May 10 14:58:05 2004 From: mruiz at polymedco.com (mruiz) Date: Tue May 11 14:32:55 2004 Subject: [Tutor] 1 quick question Message-ID: We have an intranet and we use python for searching our web server for documents(pdf, ppt, doc, and etc.). Right now if we do a search by text it finds all docs and list them but I wanted to tweek it so that it can show 1st 50 characters of document. A programmer before put this in place but with no documentation. I was wondering is there a script that I can tweek to make this happen. Michael Ruiz Programmer/Analyst Polymedco, Inc. www.polymedco.com Please visit our educational websites: www.cholesterol-tests.com and www.diabetes-tests.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040510/237b41ac/attachment.html From magnus at thinkware.se Tue May 11 14:50:50 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue May 11 14:50:59 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gMSBxdWljayBxdWVzdGlvbg==?= Message-ID: For instance, Nuxeo's CPS does this. See http://www.nuxeo.org/cps CPS does a lot more than that, and I don't know how easy it is to extract the relevant parts, but the transforms seems to be here: http://cvs.nuxeo.org/cgi-bin/viewcvs.cgi/PortalTransforms/transforms/ -----Ursprungligt meddelande----- Fr?n: mruiz Skickat: 2004-05-10 20:58:05 Till: tutor@python.org ?mne: [Tutor] 1 quick question > We have an intranet and we use python for searching our web server for > documents(pdf, ppt, doc, and etc.). Right now if we do a search by text > it finds all docs and list them but I wanted to tweek it so that it can > show 1st 50 characters of document. A programmer before put this in > place but with no documentation. I was wondering is there a script that > I can tweek to make this happen. > > > Michael Ruiz > Programmer/Analyst > Polymedco, Inc. www.polymedco.com > Please visit our educational websites: www.cholesterol-tests.com > and www.diabetes-tests.com > > > -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Tue May 11 14:51:29 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 11 14:51:37 2004 Subject: [Tutor] tutorial for dbapi 2.0 how to use data In-Reply-To: <40A119E3.8050104@yolo.com> Message-ID: On Tue, 11 May 2004, John Fabiani wrote: > Hi, > mycur=con.cursor() > mycur.execute("select * from sosord") > mydata=mycur.fetchmany(10) > > The above works and returns data. But know I need to understand how to > view the data. Maybe there is a way to convert the returned list into a > dictionary. A dictionary would allow me to get information by key (the > field name). Anyway, is there some paper or tutorial I can read on how > to view the return data? Hi John, If you are using MySQLdb, then yes, there is a way of getting a customized cursor that returns dictionaries instead of tuples. For example: ### >>> import MySQLdb.cursors >>> cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) >>> cursor.execute("select * from pub_term where is_obsolete='n'") 57562L >>> cursor.fetchone() {'parentage': None, 'definition': 'A complex containing a heterodimer of a catalytic subunit and a regulatory (adaptor) subunit of any phosphoinositide 3-kinase (PI3K).', 'pub_object_id': 47030L, 'public_comment': None, 'date_entered': , 'name': 'phosphoinositide 3-kinase complex', 'reference': None, 'date_updated': , 'is_obsolete': 'n', 'pub_gene_id': None, 'entered_by': None, 'tair_keyword_id': 1L, 'go_external_id': 'GO:0005942', 'is_temporary': 'n', 'replaced_by': None, 'type': 'comp', 'id': 291L, 'date_last_synchronized': , 'updated_by': None} ### Hmmm... that was a little messy. Let me use the pprint module to pretty-print that output: ### >>> from pprint import pprint >>> pprint(cursor.fetchone()) {'date_entered': , 'date_last_synchronized': , 'date_updated': , 'definition': None, 'entered_by': None, 'go_external_id': 'GO:0005943', 'id': 292L, 'is_obsolete': 'n', 'is_temporary': 'n', 'name': '1-phosphatidylinositol-4-phosphate kinase, class IA complex', 'parentage': None, 'pub_gene_id': None, 'pub_object_id': 47031L, 'public_comment': None, 'reference': None, 'replaced_by': None, 'tair_keyword_id': 2L, 'type': 'comp', 'updated_by': None} ### There you go. *grin* Even if other database modules don't support this dictionary cursor directly, the DBI API 2.0 reference at: http://python.org/peps/pep-0249.html says that all cursors need to have a 'description' attribute that gets set whenever we execute a query: ### >>> cursor = conn.cursor() ## using the default cursor >>> cursor.execute('select * from pub_term limit 1') >>> pprint(cursor.description) (('id', 3, 3, 12, 12, 0, 0), ('go_external_id', 253, 10, 20, 20, 0, 1), ('pub_object_id', 3, 5, 12, 12, 0, 1), ('name', 253, 33, 200, 200, 0, 1), ('type', 253, 4, 4, 4, 0, 1), ('date_entered', 10, 10, 10, 10, 0, 1), ('entered_by', 3, 0, 12, 12, 0, 1), ('definition', 252, 133, 65535, 65535, 0, 1), ('reference', 253, 0, 100, 100, 0, 1), ('pub_gene_id', 3, 0, 12, 12, 0, 1), ('is_temporary', 254, 1, 1, 1, 0, 1), ('date_updated', 10, 10, 10, 10, 0, 1), ('updated_by', 3, 0, 12, 12, 0, 1), ('is_obsolete', 254, 1, 1, 1, 0, 0), ('replaced_by', 3, 0, 12, 12, 0, 1), ('parentage', 252, 0, 65535, 65535, 0, 1), ('tair_keyword_id', 3, 1, 12, 12, 0, 1), ('date_last_synchronized', 10, 10, 10, 10, 0, 1), ('public_comment', 252, 0, 65535, 65535, 0, 1)) ### and given this, we can probably cook up a 'fetch_dict()' function from any cursor. Hope this helps! From magnus at thinkware.se Tue May 11 16:47:44 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue May 11 16:47:54 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gPHZhcjpkYXRhPiBhc3NpZ25tZW50?= Message-ID: Hi Denis, I think it's a really good initiative to bring something like this up on the Tutor list. (This is obviously the right place to bring up such questions.) I hope it will enlighten more people on the list. To really understand these kinds of fundamental aspects of a programming language, and of programming in general, is certainly a big advantage if we want to be able to write working programs in a predictable manner. You are very close to the Pythonic view of variables and names when you draw the parallel with a dictionary. You are slightly off target though. The id() function *does* tell you the location of the actual object in question. There is no extra level of indirection involved. Denis wrote: > --- > 'a' --> | 1 | > --- > --- > 'b' --> | 1 | first model > --- > --- > 'c' --> | 2 | > --- > > or: > > ------ > 'a' --> | adr1 | \ > ------ \ --- > > | 1 | > ------ / --- > 'b' --> | adr1 | / second model > ------ > > ------ --- > 'c' --> | adr2 | --> | 2 | > ------ --- Both these models are wrong. What happens is that for some kinds of immutable objects, that we are likely to use repeatedly, such as small integers and short strings, Python doesn't create duplicates, but reuses already created values/objects. This is called interning. In other words, the correct model is as simple as this: 'a' \ \ --- > | 1 | / --- 'b' / --- 'c' --> | 2 | --- Note that it's only for particular object that this interned use is utilized. E.g. >>> i1 = 5 >>> id(i1) 8146912 >>> i2 = 5 >>> id(i2) 8146912 >>> i3 = 123456789 >>> id(i3) 8638132 >>> i4 = 123456789 >>> id(i4) 8566052 I.e. 'i1' \ \ --- > | 5 | / --- 'i2' / ----------- 'i3' --> | 123456789 | ----------- ----------- 'i4' --> | 123456789 | ----------- >>> s1 = "Hello" >>> s2 = "Hello" >>> s1 is s2 True 's1' \ \ ------- > | Hello | / ------- 's2' / >>> s1 = "Hello there, how is it out in the dark and cold world?" >>> s2 = "Hello there, how is it out in the dark and cold world?" >>> s1 is s2 False -------------------------------------------------------- 's1' --> | Hello there, how is it out in the dark and cold world? | -------------------------------------------------------- -------------------------------------------------------- 's2' --> | Hello there, how is it out in the dark and cold world? | -------------------------------------------------------- If you know that you use a particular string often, or need to make it faster to i.e. speed up dictionary access with this string as a key, you can force Python to intern it. (It's only for strings you can do this.) >>> s3 = intern("Hello there, how is it out in the dark and cold world?") >>> s4 = intern("Hello there, how is it out in the dark and cold world?") >>> s3 is s4 True 's3' \ \ -------------------------------------------------------- > | Hello there, how is it out in the dark and cold world? | / -------------------------------------------------------- 's4' / I'm not sure exactly what algorithm Python uses to decide which objects to intern automagically. Python never interns mutable objects. Why? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From alan.gauld at blueyonder.co.uk Tue May 11 17:11:47 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 11 17:11:30 2004 Subject: [Tutor] assignment References: <001401c43773$10e92ca0$262ae4d5@spir> Message-ID: <006101c4379c$921852f0$6401a8c0@xp> Hi Denis, Some quite profound things here, slightly confused because you have happened to stumble on some special optimisations in Python for your examples! > data. Then, Python must draw a kind of name --> value mapping to recover it > when needed, let's call that 'registration'. This is of course, you have > noted it ;-) the structure of a Python dictionary: Indeed, almost everything in Python is implemented upon dictionaries. > Now, this doesn't mean that in the language's blackbox (in C), variable > registration is really implemented as a dictionary. But in fact it is. > Third, conversely, when a value changes, its place changes, too. Not quite. When a value changes a new value is stored in its place. The old value is lost. Or at least it is for immutable types such as the numbers and strings that you are using. For mutable types such as lists the pictire changes. > All of this leads (me) to question the above dictionary-like model. It seems > that, instead of values, the id-s are bound to variable names. No, in these cases they are bound to addresses as you point out later. There are no names involved, either in Python or even in C. > Python. In python, we could eventually see variables as labeled boxes > holding adresses, pointing to data ; while the data would be unlabeled > boxes holding values: Absolutely correct, and the variables therefore are the labels. That is variable names in Python are just that names. Names used as keys in a dictionary and the values are the addresses of the data objects. > Now, consider the case of compound data: > > >>> l1=[1,2] > >>> l2=[1,2] > >>> l1 == l2, l1 is l2 > (True, False) > > This contredicts the first rule saying that if a data exists, it needs not > beeing created again. l1 and l2 hold the same data --there're equal--, > but not at the same place --they're not identical Correct because lists are not immutable. Python has a clear distinction in the way it handles mutable and imutable data. > We can explain this (at first sight) strange behaviour by recursively > applying the other rule, the one saying that a variable isn't bound to a > value, but to an address instead. Correct, the address of the list in this case. > >>> l1=[1] > >>> l2=[1] > >>> l1 is l2 > False Which is as you would expect since the two lists are different although they hold references to the same object l1 -> [] -> 1 ^ | l2 -> [] ---+ > >>> l1=l2=[1] > >>> l1 is l2 > True Because they point to the same list l1 -> [] -> 1 ^ | l2 ----+ > >>> l1=[1]; l2=[1] > >>> l1 is l2 > False Exactly the same as the first example > >>> l1=l2 > >>> l1 is l2 > True Exactly the same as the second example except that the list doesn't contain any data. BTW This is all explained in the Python Language Reference albeit in fairly technical words... And if you read C you can always read the source! :-) Alan G. From alan.gauld at blueyonder.co.uk Tue May 11 17:18:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 11 17:18:00 2004 Subject: [Tutor] assignment Message-ID: <007401c4379d$7a214390$6401a8c0@xp> > Correct because lists are not immutable. Python has a clear > distinction in the way it handles mutable and imutable data. Actually as Magnus pointed out it's not really the immutability that's the issue here it's the internalisation of short strings and low value integers. The fact that they happen to be immutable is somewhat orthogonal to the discussion. However I don't think that minor faux pas changes too much of the rest of what I said! Alan G. From dyoo at hkn.eecs.berkeley.edu Tue May 11 17:24:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 11 17:24:38 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gPHZhcjpkYXRhPiBhc3NpZ25tZW50?= In-Reply-To: Message-ID: > If you know that you use a particular string often, or need to make it > faster to i.e. speed up dictionary access with this string as a key, you > can force Python to intern it. (It's only for strings you can do this.) > > >>> s3 = intern("Hello there, how is it out in the dark and cold world?") > >>> s4 = intern("Hello there, how is it out in the dark and cold world?") > >>> s3 is s4 > True > > 's3' \ > \ -------------------------------------------------------- > > | Hello there, how is it out in the dark and cold world? | > / -------------------------------------------------------- > 's4' / > > I'm not sure exactly what algorithm Python uses to decide which objects > to intern automagically. Hi Magnus, According to: http://www.python.org/doc/lib/non-essential-built-in-funcs.html#l2h-84 the names that are used in Python programs are interned for performance reasons. The word "intern" really should apply to strings; I don't think intern() works on arbitrary objects. Let's check: ### >>> intern(100) Traceback (most recent call last): File "", line 1, in ? TypeError: intern() argument 1 must be string, not int ### Yup, just strings. As an optimization hack, the integers in the half-open interval range [-5, 100) are created in advance and are kept alive in the Python runtime, so that a request for a small integer is quickly fulfilled by dipping into this "small integer" pool. [For the C programmers here: the relevant performance hack lives in the Python source code under Objects/intobject.c. Here's a small snippet: /******/ #ifndef NSMALLPOSINTS #define NSMALLPOSINTS 100 #endif #ifndef NSMALLNEGINTS #define NSMALLNEGINTS 5 #endif #if NSMALLNEGINTS + NSMALLPOSINTS > 0 /* References to small integers are saved in this array so that they can be shared. The integers that are saved are those in the range -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). */ static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS]; /******/ This is an optimization hack, and the code explicitely shows that Python can easily do without it: if we set NSMALLPOSINTS and NSMALLNEGINTS both to zero, and recompile Python, we should see no difference in behavior (although we'll probably see a drop in performance.) At least, I think the C code can handle this situation... *grin*] > Python never interns mutable objects. Why? Aliasing reasons. If strings were mutable, then something like: ### Pseudocode word1 = intern("hello") word2 = intern("hello") word2[1] = 'a' ### would raise havok: what would we expect word1 to contain, "hello" or "hallo"? Interning is a caching technique, and caching objects like strings works best when we treat object as immutable "value" objects. But as soon as we try caching mutable objects, there's a lot of complex aliasing behavior that might happen. So Python doesn't provide us an automatic way to do it. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue May 11 17:30:51 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 11 17:30:58 2004 Subject: [Tutor] tutorial for dbapi 2.0 how to use data (fwd) Message-ID: [Forwarding to Tutor: please make sure to keep Tutor@python.org in CC; if I'm busy, we still want you to be able to get responses from the group.] ---------- Forwarded message ---------- Date: Tue, 11 May 2004 13:36:38 -0700 From: John Fabiani To: Danny Yoo Subject: Re: [Tutor] tutorial for dbapi 2.0 how to use data Danny Yoo wrote: >On Tue, 11 May 2004, John Fabiani wrote: >>mycur=con.cursor() >>mycur.execute("select * from sosord") >>mydata=mycur.fetchmany(10) >> >>The above works and returns data. But know I need to understand how to >>view the data. Maybe there is a way to convert the returned list into a >>dictionary. A dictionary would allow me to get information by key (the >>field name). Anyway, is there some paper or tutorial I can read on how >>to view the return data? >> > >If you are using MySQLdb, then yes, there is a way of getting a customized >cursor that returns dictionaries instead of tuples. For example: > >### > > >>>>import MySQLdb.cursors >>>>cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) >>>>cursor.execute("select * from pub_term where is_obsolete='n'") >>>> >>>> >57562L > > >>>>cursor.fetchone() >>>> >>>> >{'parentage': None, 'definition': 'A complex containing a heterodimer of a >catalytic subunit and a regulatory (adaptor) subunit of any >phosphoinositide 3-kinase (PI3K).', 'pub_object_id': 47030L, [text cut] This is a great first step! I'm using the Postgres pgPySQL module. How can I tell if the module supports the cursors that MySQL supports? description appears to return a tuple that contains tuples. The first column returns the field name - any chance you know what the other columns mean? So how do I setup the dictionary as in {"id": 123, "go_external_id": 456, "name":"john", "type": "dumb", "date_entered": 01/01/04 ...........} The bottom line is I want to be able to access and change the data. Isn't there some tutorial or something I can read that explains how this is suppose to work? I'd like to do things like the following: loop thru the data make some test change some of the data in the current row/ list Save the data... The above would be just normal database activities..... Thanks John From dyoo at hkn.eecs.berkeley.edu Tue May 11 18:41:21 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 11 18:41:29 2004 Subject: [Tutor] Python & XML In-Reply-To: <200405110823.i4B8NATl018662@mxsf18.cluster1.charter.net> Message-ID: On Tue, 11 May 2004 justinstraube@charter.net wrote: > Sorry, for the repost but I accidentally sent before I could ask for a > small bit of help. Can anyone spare a minute to look over this and give > any points as to what I may be doing wrong or what could be done better? Hi Justin, Code review time! *grin* Here are some suggestions: It might be good to break out some of the functions into separate functions. For example: > print '\t', _name_, _ver_, '\t', _date_ > print '\n\tCreated by:', _auth_ > print '\tWritten in:', _inf_ could be given a name like printWelcome(): ### def printWelcome(): print '\t', _name_, _ver_, '\t', _date_ print '\n\tCreated by:', _auth_ print '\tWritten in:', _inf_ ### Another part that can be broken out is the grabbing of the XML data: > add = '/fcgi-bin/fcgi?cmd=user_xml&email=' + usrmail > > conx = httplib.HTTPConnection(SETI) > conx.request("GET", add) > response = conx.getresponse() > > if response.status == 500: > print response.status, response.reason > print """\n\t\tServer Error\n > The page or site is temporarily down or disabled. > Sorry for the inconvienience. > > Please try again later.\n""" > break > > data = response.read() > > if data[-33:] == 'No user with that name was found.': > print """\n\t\tNo user with that name was found. > Please check the email address and try again.\n""" > break > > conx.close() > > xdata = minidom.parseString(data) This block can be given a name like 'getXmlDomTree()': ### def getXmlDomTree(usrmail): add = '/fcgi-bin/fcgi?cmd=user_xml&email=' + usrmail conx = httplib.HTTPConnection(SETI) conx.request("GET", add) response = conx.getresponse() if response.status == 500: print response.status, response.reason print """\n\t\tServer Error\n The page or site is temporarily down or disabled. Sorry for the inconvienience. Please try again later.\n""" break data = response.read() if data[-33:] == 'No user with that name was found.': print """\n\t\tNo user with that name was found. Please check the email address and try again.\n""" break conx.close() xdata = minidom.parseString(data) return xdata ### Breaking things down into smaller functions is not really for the computer, but for us humans. *grin* It's a little easier to understand a small function, because we can limit the scope of what we're look at to a "paragraph" of program text. The block of code that starts of as: > for node in item.childNodes: > if node.nodeType == node.ELEMENT_NODE: > if node.tagName == 'name': > uname = node.toxml() > ud[1] = uname[6:-7] + ' <' + usrmail + '>' > node.unlink > elif node.tagName == 'numresults': > num = node.toxml() > ud[2] = num[12:-13] > node.unlink > elif node.tagName == 'cputime': > cput = node.toxml() > ud[3] = cput[9:-10] > node.unlink > elif node.tagName == 'avecpu': > avg = node.toxml() > ud[4] = avg[8:-9] > node.unlink > elif node.tagName == 'resultsperday': > rpd = node.toxml() > ud[5] = rpd[15:-16] > node.unlink > elif node.tagName == 'lastresulttime': > lrr = node.toxml() > ud[6] = lrr[16:-17] > node.unlink > elif node.tagName == 'regdate': > regd = node.toxml() > ud[7] = regd[9:-10] > node.unlink > elif node.tagName == 'usertime': > usrt = node.toxml() > ud[8] = usrt[10:-11] > node.unlink > else: > node.unlink is repetitive. Long chains of if/elif/elif/elif can often be simplified if we put some of the program as data, rather than as explicit program logic. What does this mean? Here's another way to get a similar effect: ###### # dispatchTable is a mapping from the tagName we're looking for, to a # triple (ud_offset, left_slice, right_slice) dispatchTable = { 'name' : (1, 6, -7), 'numresults' : (2, 12, -13), 'cputime' : (3, 9, -10), 'avecpu' : (4, 8, -9), 'resultsperday': (5, 15, -16), 'lastresultime': (6, 16, -17), 'regdate' : (7, 9, -10), 'usertime' : (8, 10, -11), } for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName in dispatchTable: offset, left_slice, right_slice = dispatchTable[node.tagName] ud[offset] = node.toxml()[left_slice : right_slice] node.unlink() else: node.unlink() ###### We can get rid of the repetitive logic, and keep the thing that is really changing --- the index into 'ud' that we assign into, and the left and right indices of our slice. Not only is the code shorter, but it probably is a little easier to debug: if we find that one of the numbers is wrong, we can quickly zoom in, since all the numbers are visually collected together. We did lose a little, because now 'name' is being handled the same way as the other tags. But we can fix this by treating it as a special case: ### dispatchTable = { ## name is treated as a special case 'numresults' : (2, 12, -13), 'cputime' : (3, 9, -10), 'avecpu' : (4, 8, -9), 'resultsperday': (5, 15, -16), 'lastresultime': (6, 16, -17), 'regdate' : (7, 9, -10), 'usertime' : (8, 10, -11), } for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName in dispatchTable: offset, left_slice, right_slice = dispatchTable[node.tagName] ud[offset] = node.toxml()[left_slice : right_slice] node.unlink() elif node.tagName == 'name': uname = node.toxml() ud[1] = uname[6:-7] + ' <' + usrmail + '>' node.unlink() else: node.unlink() ### So we benefit of treating the general case in a uniform way, but also leave some room for doing special-case stuff if we really need it. One other thing, though: we don't have to do the node.toxml()/slicing technique to get at the text within a node. That approach is error prone, since it tries to work with indices that can change at the whim of an XML DOM implementation. Instead, take a look at the example in: http://www.python.org/doc/lib/dom-example.html The example uses a 'getText()' function that's more robust. Look at the example, and then just cut-and-paste it. *grin* This alone should cut down on a lot of the manual string-slicing that you must have calculated by hand. With the techniques above, you can probably cut down the program considerably to something very concise and sweet. Please feel free to ask questions on any of this. Good luck to you! From lbblair at adaptisinc.com Tue May 11 19:28:39 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Tue May 11 19:29:07 2004 Subject: [Tutor] tutorial for dbapi 2.0 how to use data (fwd) Message-ID: I am doing the same kind of stuff currently. Here is what I am using for oracle and using cx's modules. To see the data I put a print row after the last line in the for. This creates a list. A dictionary is any harder to do. cur.execute("select file_name,tablespace_name ,bytes from dba_data_files where tablespace_name not in (select DISTINCT TABLESPACE_NAME from dba_rollback_segs where owner <> 'SYS')") for row in cur.fetchall(): item = [row[0],row[1],row[2],"DATAFILE"] DatabaseFileAttributes.append(item) -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Tuesday, May 11, 2004 2:31 PM To: Tutor Cc: jfabinani@yolo.com Subject: Re: [Tutor] tutorial for dbapi 2.0 how to use data (fwd) [Forwarding to Tutor: please make sure to keep Tutor@python.org in CC; if I'm busy, we still want you to be able to get responses from the group.] ---------- Forwarded message ---------- Date: Tue, 11 May 2004 13:36:38 -0700 From: John Fabiani To: Danny Yoo Subject: Re: [Tutor] tutorial for dbapi 2.0 how to use data Danny Yoo wrote: >On Tue, 11 May 2004, John Fabiani wrote: >>mycur=con.cursor() >>mycur.execute("select * from sosord") >>mydata=mycur.fetchmany(10) >> >>The above works and returns data. But know I need to understand how to >>view the data. Maybe there is a way to convert the returned list into a >>dictionary. A dictionary would allow me to get information by key (the >>field name). Anyway, is there some paper or tutorial I can read on how >>to view the return data? >> > >If you are using MySQLdb, then yes, there is a way of getting a customized >cursor that returns dictionaries instead of tuples. For example: > >### > > >>>>import MySQLdb.cursors >>>>cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) >>>>cursor.execute("select * from pub_term where is_obsolete='n'") >>>> >>>> >57562L > > >>>>cursor.fetchone() >>>> >>>> >{'parentage': None, 'definition': 'A complex containing a heterodimer of a >catalytic subunit and a regulatory (adaptor) subunit of any >phosphoinositide 3-kinase (PI3K).', 'pub_object_id': 47030L, [text cut] This is a great first step! I'm using the Postgres pgPySQL module. How can I tell if the module supports the cursors that MySQL supports? description appears to return a tuple that contains tuples. The first column returns the field name - any chance you know what the other columns mean? So how do I setup the dictionary as in {"id": 123, "go_external_id": 456, "name":"john", "type": "dumb", "date_entered": 01/01/04 ...........} The bottom line is I want to be able to access and change the data. Isn't there some tutorial or something I can read that explains how this is suppose to work? I'd like to do things like the following: loop thru the data make some test change some of the data in the current row/ list Save the data... The above would be just normal database activities..... Thanks John _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor __________________________________ Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s) and may contain information that is confidential privileged and/or exempt from disclosure under applicable law. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. From magnus at thinkware.se Tue May 11 20:25:56 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue May 11 20:26:06 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gPHZhcjpkYXRhPiBhc3NpZ25tZW50?= Message-ID: I wrote: > > If you know that you use a particular string often, or need to make it > > faster to i.e. speed up dictionary access with this string as a key, you > > can force Python to intern it. (It's only for strings you can do this.) .. > > I'm not sure exactly what algorithm Python uses to decide which objects > > to intern automagically. Danny responded: > The word "intern" really should apply to strings; I don't think intern() > works on arbitrary objects. I just wrote that! But I guess I am a bit sloppy when I use the same word for basically the same thing being done on integers as on strings. God forbid using the name of builtin functions for any other purpose! ;) Do you have a better term for this sharing of objects? > As an optimization hack, the integers in the half-open interval range > > [-5, 100) > > are created in advance and are kept alive in the Python runtime, so that a > request for a small integer is quickly fulfilled by dipping into this > "small integer" pool. Aha. Do you know how it's done with short strings? (Don't tell me that strings such as "Hello" are created in advance by Python! :) As I look further, it seems that it has nothing to do with size as I thought, but that all strings that are valid Python identifiers are interned. The manual says that "Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys." It's obviously more extensive than that. All string *literals* that could possibly be names used in Python programs seems to get interned. Note that it only happens automatically with string literals, not with strings that are the result of an expression (as far as I can see). >>> s1 = 'Hexllpwioutpreoiuwptriwpwreioptwr243523452345345___' >>> s2 = 'Hexllpwioutpreoiuwptriwpwreioptwr243523452345345___' >>> s1 is s2 True >>> s1 = 'a.' >>> s2 = 'a.' >>> s1 is s2 False >>> s1 = 'z'*2 >>> s2 = 'z'*2 >>> s1 is s2 False >>> s1 = 'z' + 'a' >>> s2 = 'z' + 'a' >>> s1 is s2 False > > Python never interns mutable objects. Why? > > Aliasing reasons. If strings were mutable, then something like: > > ### Pseudocode > word1 = intern("hello") > word2 = intern("hello") > word2[1] = 'a' > ### > > would raise havok: what would we expect word1 to contain, "hello" or > "hallo"? Yes, yes I know. This was intended as a pedagogical question for the "pupil", not for the "professor"! ;) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue May 11 20:38:51 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Tue May 11 20:38:58 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gdHV0b3JpYWwgZm9yIGRiYXBpIDIuMCBob3cgdG8gdXNlIGRhdGE=?= Message-ID: John Fabiani wrote: > mycur=con.cursor() > mycur.execute("select * from sosord") > mydata=mycur.fetchmany(10) > > The above works and returns data. But know I need to understand how to > view the data. Maybe there is a way to convert the returned list into a > dictionary. A dictionary would allow me to get information by key (the > field name). Anyway, is there some paper or tutorial I can read on how > to view the return data? There are some links at: http://www.thinkware.se/cgi-bin/thinki.cgi/ObjectRelationalMappersForPython For instance, you can use db_row: http://opensource.theopalgroup.com/files/db_row.html dtuple, SQLDict and dbObj do similar things. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From isrgish at fastem.com Tue May 11 21:30:11 2004 From: isrgish at fastem.com (Isr Gish) Date: Tue May 11 21:30:19 2004 Subject: [Tutor] Problem with os.walk Message-ID: Thanks Timyfor the help. I hadn't relized that it has to be changed *in place*. Isr -----Original Message----- >From: "Tim Peters" >Sent: 5/11/04 10:56:00 AM >To: "Isr Gish" >Cc: "tutor@python.org" >Subject: RE: [Tutor] Problem with os.walk > >[Isr Gish] >> The docs say that you can del the dirnames list. > >"the caller can modify the dirnames list in-place (e.g., via del or slice >assignment)" > >"in-place" means things of the form > > del dirnames[1:] > >or > > dirnames[:] = ['new directory'] > >> But when I tried doing it, it didn't work. > >You have to show the exact code you used, else nobody can guess. > >... > >> I tried del > >That's not enough to guess. Maybe you did > > del dirnames > >? That indeed would not work. > >> and dirnames = dirnames[0:0] > >The binds dirnames to a brand new object, so is not an in-place modification >either. If you want to empty dirnames entirely, two ways to do it in-place >are > > del dirnames[:] > >or > > dirnames[:] = [] > >> Both didn't work. The only thing that wOrked was. >> for d in dirnames[:]: >> dirnames.remove(d) > >The two above will also work. > >> And if I didn't make a copy it didn't work correctly. (it seems >> that for i in list works with indexing behindethe seigns). > >Yes. This is documented in the Language Reference manual (not the Library >Reference manual), in the section on "for" loops. > From dyoo at hkn.eecs.berkeley.edu Tue May 11 21:59:12 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 11 21:59:17 2004 Subject: [Tutor] assignment [Python under the hood: optimizations at the C level] In-Reply-To: Message-ID: On Wed, 12 May 2004, Magnus Lycka wrote: > I wrote: > > > If you know that you use a particular string often, or need to make it > > > faster to i.e. speed up dictionary access with this string as a key, you > > > can force Python to intern it. (It's only for strings you can do this.) > .. > > > I'm not sure exactly what algorithm Python uses to decide which objects > > > to intern automagically. > > Danny responded: > > The word "intern" really should apply to strings; I don't think intern() > > works on arbitrary objects. > > I just wrote that! Hi Magnus, My apologies! I read your message too quickly, and skipped over the part where you mentioned that it worked on strings only. I have a bad habit of tunnel vision --- good when debugging code, but not so good when communicating with people. *grin* I will try to be a better listener next time. > As I look further, it seems that it has nothing to do with size as I > thought, but that all strings that are valid Python identifiers are > interned. > > The manual says that "Normally, the names used in Python programs are > automatically interned, and the dictionaries used to hold module, class > or instance attributes have interned keys." > > It's obviously more extensive than that. All string *literals* that > could possibly be names used in Python programs seems to get interned. Yes, it's done at bytecode-compile time. In Python/compile.c, there's a step that interns all variable names and literals that are "name"-like characters: /******/ PyCodeObject * PyCode_New(int argcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab) { [some code cut] intern_strings(names); intern_strings(varnames); intern_strings(freevars); intern_strings(cellvars); /* Intern selected string constants */ for (i = PyTuple_Size(consts); --i >= 0; ) { PyObject *v = PyTuple_GetItem(consts, i); if (!PyString_Check(v)) continue; if (!all_name_chars((unsigned char *)PyString_AS_STRING(v))) continue; PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i)); } /******/ (Code taken from Python 2.3.3 C source) Again, this is an C optimization hack that isn't documented: it's not documented because we really shouldn't depend on this behavior! *grin* In fact, I have no idea what Jython does. Let's check it: ### [dyoo@tesuque dyoo]$ jython Jython 2.1 on java1.4.1_01 (JIT: null) Type "copyright", "credits" or "license" for more information. >>> id("hello world") 17064560 >>> id("hello world") 22629283 >>> id("hello world") 11354272 ### Ah. Yup, it does something different in Jython. Hence, it's really an implemention detail that we really shouldn't be looking at. But I get the feeling we've completely strayed off the original topic anyway. *grin* From phil at xfr.co.uk Wed May 12 06:03:00 2004 From: phil at xfr.co.uk (Philip Kilner) Date: Wed May 12 06:03:52 2004 Subject: [Tutor] assignment In-Reply-To: <003201c4377d$985eb600$3942933e@spir> References: <001401c43773$10e92ca0$262ae4d5@spir> <6.0.0.22.0.20040511102739.03bcfa48@mail.mric.net> <003201c4377d$985eb600$3942933e@spir> Message-ID: <40A1F654.70301@xfr.co.uk> Hi Denis, denis wrote: > corrections, comments, critics... such things > > It's a trial to explain (also to myself). > As I say in the text, I'm not sure that the model is right. > > denis > > PS : Is tutor a right place for this? Who knows? > (The title prefix makes it easy to delete overloading messages if ever > needed.) > I think it is - it's helping me visualise what is going on, so it's helping me, at least! -- Regards, PhilK Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518 "The lyf so short, the craft so long to learne" - Chaucer From tpc at csua.berkeley.edu Wed May 12 14:19:09 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed May 12 14:19:20 2004 Subject: [Tutor] index of a list of lists of strings Message-ID: <20040512111517.N94652-100000@localhost.name> hi everybody, let's say I have a list called donorValuesList that stores lists of strings, such that donorValuesList[0] would return ['NULL', 'NULL', 'James', 'NULL', 'Smith' ... etc] and donorValuesList[1] would return ['NULL', 'Mr', 'William', 'NULL', 'Johnson' ... etc]. Could I find the index of a specific list if I knew only a few of the strings and their positions ? For example, I want to find the index in donorValuesList of a list where 'John' is the third value, 'NULL' is the fourth, and 'Brown' is the fifth, but I don't have enough information to construct a complete list to pass to donorValuesList.index(). Is this possible ? From magnus at thinkware.se Wed May 12 15:19:57 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Wed May 12 15:20:05 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gaW5kZXggb2YgYSBsaXN0IG9mIGxpc3RzIG9mIHN0cmluZ3M=?= Message-ID: tpc@csua.berkeley.edu wrote: > hi everybody, let's say I have a list called donorValuesList that stores > lists of strings, such that donorValuesList[0] would return ['NULL', > 'NULL', 'James', 'NULL', 'Smith' ... etc] and donorValuesList[1] would > return ['NULL', 'Mr', 'William', 'NULL', 'Johnson' ... etc]. Could I > find the index of a specific list if I knew only a few of the strings and > their positions ? For example, I want to find the index in > donorValuesList of a list where 'John' is the third value, 'NULL' is the > fourth, and 'Brown' is the fifth, but I don't have enough information to > construct a complete list to pass to donorValuesList.index(). Is this > possible ? Of course it's possible. You simply loop through the list and test each record. I'm not sure it's an optimal solution though. First of all, there is a particualar value in Python called None. I assume 'NULL' is supposed to indicate that a value is missing, but one of these days you will run into a Mr Null who prefers his names to be written in all caps... With Python's dynamic typing, there is no reason to abuse strings or integers by letting particular values such as 'NULL' or 99999 have exceptional meanings. So, it's better to use something like: [None, None, 'James', None, 'Smith' ... etc] instead of ['NULL', 'NULL', 'James', 'NULL', 'Smith' ... etc] The None value is never a string, it's just itself. It's clear that its noones name. I'm not sure a list of list is the data structure you really need though. If you want a pure Python solution, you are probably better off making a Donor class, and a DonorCatalog class which can handle queries. Another option that seems to fit your requirements is to store the data in a relational database. For a small database which doesn't require any server setup etc, look at sqlite. See http://pysqlite.sourceforge.net/ Then you create a table roughly like this: CREATE TABLE DONOR ( ID INT NOT NULL PRIMARY KEY, SOMETHING SOME_TYPE, SALUTATION CHAR(5), FIRST_NAME CHAR(30), LAST_NAME CHAR(30), ETC SOME_TYPE ) Once you've populated your table, you can search it for people with the surname 'Brown' like this: SELECT * FROM DONOR WHERE LAST_NAME = 'Brown' All this can be wrapped in Python, either by using SQL inside cursor.execute() as per the Python DB-API, or you can "hide" all these SQLities behind classes using an OO-RDBMS wrapper such as SQLObject. See http://sqlobject.org/ Then you'd query your database like this: donors_called_brown = Donor.select(Donor.q.lastName='Brown') I realize that it might be a bit much to learn SQL as well if programming is new for you, but relational databases are much more convenient for the kind of ad hoc searches you seem to do, and they provide persistence and scalability in a neat package. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From chidorex-pytutor at yahoo.com Thu May 13 01:49:36 2004 From: chidorex-pytutor at yahoo.com (Rex) Date: Thu May 13 01:49:42 2004 Subject: [Tutor] Re: Python & XML - coding tips In-Reply-To: Message-ID: <20040513054936.60189.qmail@web13425.mail.yahoo.com> Beautiful use of the dictionary to eliminate the endless elifs. Great tip. Thanks Danny. Rex From: Danny Yoo Subject: RE: [Tutor] Python & XML To: justinstraube@charter.net Cc: Tutor Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII On Tue, 11 May 2004 justinstraube@charter.net wrote: Hi Justin, Code review time! *grin* Here are some suggestions: ###### # dispatchTable is a mapping from the tagName we're looking for, to a # triple (ud_offset, left_slice, right_slice) dispatchTable = { 'name' : (1, 6, -7), 'numresults' : (2, 12, -13), 'cputime' : (3, 9, -10), 'avecpu' : (4, 8, -9), 'resultsperday': (5, 15, -16), 'lastresultime': (6, 16, -17), 'regdate' : (7, 9, -10), 'usertime' : (8, 10, -11), } for node in item.childNodes: if node.nodeType == node.ELEMENT_NODE: if node.tagName in dispatchTable: offset, left_slice, right_slice = dispatchTable[node.tagName] ud[offset] = node.toxml()[left_slice : right_slice] node.unlink() else: node.unlink() ###### We can get rid of the repetitive logic, and keep the thing that is really changing From lsloan at umich.edu Thu May 13 08:34:26 2004 From: lsloan at umich.edu (Lance E Sloan) Date: Thu May 13 08:34:39 2004 Subject: [Tutor] recommended CSV module? Message-ID: <2147483647.1084437266@[192.168.2.201]> Looking around the Vaults of Parnassus, I see there are several Python modules for parsing files in CSV (comma-separated values) format. Those of you that work with CSVs in Python, which module would you recommend I use? -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From lsloan at umich.edu Thu May 13 08:44:11 2004 From: lsloan at umich.edu (Lance E Sloan) Date: Thu May 13 08:44:19 2004 Subject: [Tutor] Re: recommended CSV module? In-Reply-To: <2147483647.1084437266@[192.168.2.201]> References: <2147483647.1084437266@[192.168.2.201]> Message-ID: <2147483647.1084437851@[192.168.2.201]> --On Thursday, May 13, 2004 8:34 AM -0400 Lance E Sloan wrote: > Looking around the Vaults of Parnassus, I see there are several Python > modules for parsing files in CSV (comma-separated values) format. Those > of you that work with CSVs in Python, which module would you recommend I > use? *sigh* This is the second time I've made a fool of myself here asking for third-party module recommendations when there's one that's included with Python. :P Unless somebody has a good reason to recommend that I should use some third-party CSV module, I'll use the stock one. -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From pythonTutor at venix.com Thu May 13 09:16:57 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu May 13 09:17:04 2004 Subject: [Tutor] Re: recommended CSV module? In-Reply-To: <2147483647.1084437851@[192.168.2.201]> References: <2147483647.1084437266@[192.168.2.201]> <2147483647.1084437851@[192.168.2.201]> Message-ID: <1084454216.5059.11.camel@laptop.venix.com> It's hard to keep up with all of the available modules. My experience is that the standard cvs module is better than the third party alternatives. On Thu, 2004-05-13 at 08:44, Lance E Sloan wrote: > --On Thursday, May 13, 2004 8:34 AM -0400 Lance E Sloan > wrote: > > Looking around the Vaults of Parnassus, I see there are several Python > > modules for parsing files in CSV (comma-separated values) format. Those > > of you that work with CSVs in Python, which module would you recommend I > > use? > > *sigh* This is the second time I've made a fool of myself here asking for > third-party module recommendations when there's one that's included with > Python. :P > > Unless somebody has a good reason to recommend that I should use some > third-party CSV module, I'll use the stock one. > > -- > Lance E Sloan, Systems Research Programmer III > U-M WATS: Web Applications, Technologies, and Solutions > Full-service web and database design, development, and hosting. > http://www.itcs.umich.edu/wats/ - "Putting U on the Web" > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From rcher at inter.net.il Thu May 13 09:55:13 2004 From: rcher at inter.net.il (roman) Date: Thu May 13 09:51:02 2004 Subject: [Tutor] why does this raise an exception... Message-ID: <1084456513.5514.5.camel@linuxbox> When converting a few string values to integers with int() I found out that trying to convert "2.1", i.e. a string that represents a floating point value to an integer raises an exception. Why does this raise an exception while something like float("9") does not? From wilson at visi.com Thu May 13 09:57:41 2004 From: wilson at visi.com (Tim Wilson) Date: Thu May 13 09:57:54 2004 Subject: [Tutor] why does this raise an exception... In-Reply-To: <1084456513.5514.5.camel@linuxbox> Message-ID: On 5/13/04 8:55 AM, "roman" wrote: > When converting a few string values to integers with int() I found out > that trying to convert "2.1", i.e. a string that represents a floating > point value to an integer raises an exception. Why does this raise an > exception while something like float("9") does not? Since 9 = 9.0, I wouldn't expect float("9") to raise an exception. But what should the computer do with 2.1 when converting to an int? I don't think I want my code changing 2.1 to 2, for example, without letting me know. You can also round your float and then convert to int, if that's the behavior you're looking for. -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 public key: 0x8C0F8813 From denis.spir at free.fr Thu May 13 10:04:36 2004 From: denis.spir at free.fr (denis) Date: Thu May 13 10:08:52 2004 Subject: [Tutor] value changes Message-ID: <002801c438f3$a6cbd0c0$3043933e@spir> Hello, Some comments and corrections about the previous message (thanks to Magnus & Danny) pointed Python's feature called interning: the first aspect of this feature is that integers in range(-5,100) (I didn't know about negative ones) are generated and stored as data by python; the second is that they won't be duplicated, but used 'in place' instead, each time the value is needed: >>> x=1; y=1 ; x is y True >>> x = -1; y = -1 ; x is y True This means that x and y are at the same memory location, in other words 'x' and 'y' are aliases: >>> id(x); id(y) 7678960 7678960 Now, let's (try and) check this does not with out-of-range (sic!) values: >>> x=100; y=100 ; x is y True >>> x=1000; y=1000 ; x is y True What's up ? (I've really been surprised!) A more careful trial: >>> x=1000 >>> y=1000 >>> x is y False >>> x=100 >>> y=100 >>> x is y False >>> x=99 >>> y=99 >>> x is y True This difference of result shows that two 'equivalent' syntactic forms aren't processed the same way. I guess that, on optimisation ground, a short-term interning is done for multi-assignment lines (what about "x,y = a,a"?). How long does it last ? Is it further available ? >>> x=100; y=100 ; x is y True >>> z=100 ; x is z; y is z False False Now, what about strings ? >>> x='a' >>> y='a' >>> x is y True >>> x='1' >>> y='1' >>> x is y True >>> x='Freude, sch?ner G?tterfunken,..." SyntaxError: EOL while scanning single-quoted string # ?$%#~!!! >>> x='Freude, sch?ner G?tterfunken,...' >>> y='Freude, sch?ner G?tterfunken,...' >>> x is y False >>> x='Freude, sch?ner G?tterfunken,...'; y='Freude, sch?ner G?tterfunken,...' ; x is y # this was one single line in IDLE True As expected, basic interning is available for small strings (what are the criteria?); and the short-term interning form works too. What about sequences ? >>> x=('a') >>> y=('a') >>> x is y True >>> x=['a'] >>> y=['a'] >>> x is y False >>> x=['a']; y=['a'] ; x is y False >>> x=[]; y=[] ; x is y False >>> x=[True]; y=[True] ; x is y False Very probable conclusion : yes for immutables, no for mutables. It doesn't even work for empty lists or built-in constants. Now, I really want to explore this difference deeper. First, let's enlarge x a bit: >>> x+=[False] >>> x [True, False] >>> x+='a' >>> x [True, False, 'a'] >>> a='ciao!' >>> x+=[a] >>> x [True, False, 'a', 'ciao!'] >>> x+=1 Traceback (most recent call last): File "", line 1, in -toplevel- x+=1 TypeError: argument to += must be iterable I typed the last line just for fun, but I am surprised that python accepts x+='a', as 'a' is no list, and refuses x+=1 (?). I would expect to be obliged to write x.append(item) for both strings and numbers, as both are immutable --but strings are sequences (what about tuples?). And with a dictionary ? >>> d={} >>> x+=d >>> x [True, False, 'a', 'ciao!'] # no success ;-( >>> x+=[d] >>> x [True, False, 'a', 'ciao!', {}] # :-) >>> d={1:'un', 2:'deux'} >>> x+=d >>> x [True, False, 'a', 'ciao!', {}, 1, 2] # the keys, only! >>> x+= [d] >>> x [True, False, 'a', 'ciao!', {}, 1, 2, {1: 'un', 2: 'deux'}] Well, interesting, isn't it? You can, as a choice, append to a list either a dictionary's keys or its key:value pairs, both without even explicitely calling the append() method. Now, what about adresses? (let's not be distracted) >>> id(x) 10763120 >>> for i in range(len(x)): print id(x[i]) # items' addresses 504028992 504028976 6759872 10763168 10790352 7678960 7677952 10639664 >>> id(1);id(2) 7678960 7677952 # right! >>> id(d) 10639664 # right again! True and False are rather close, but not aside; 1 and 2 are strangely far (?). All items are separated from the list, they're not "in" the list. Which means, as expected, that the list holds its elements' addresses -- only its elements' addresses. >>> id(d) 10639664 >>> for i in range(len(d)): print id(d.keys()[i]) # keys' addresses 7678960 7677952 >>> for i in range(len(d)): print id(d[d.keys()[i]]) # values' ones 10763872 10762944 It also clear that for a dictionary the dict. itself, its keys and its values are totally separated. Just as a recall about value changes by immutable types: >>> t='Freude, sch?ner G?tterfunken,...' ; id(t) 6742216 >>> t='? joie, divine ?tincelle de beaut?...' ; id(t) 10781656 The (whole) variable's address changes. What happens when I change x, now? There are two kinds of changes: >>> id(x); id(x[3]) 10763120 10763168 >>> x[3]='ol?!' # first --I mean zeroth: partial change >>> id(x); id(x[3]) 10763120 10764064 >>> x=[1,'a',d] # first: global change >>> id(x) 10763216 By immutable types, only the item(s) changed move(s) when they're directly addressed: the list's address hasn't changed. But the global variable moves when addressed as a whole. [Just as foretaste (?) on this topic...] denis From bgailer at alum.rpi.edu Thu May 13 10:43:05 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu May 13 10:54:41 2004 Subject: [Tutor] value changes In-Reply-To: <002801c438f3$a6cbd0c0$3043933e@spir> References: <002801c438f3$a6cbd0c0$3043933e@spir> Message-ID: <6.0.0.22.0.20040513084113.02665380@mail.mric.net> At 08:04 AM 5/13/2004, denis wrote: >Hello, > >Some comments and corrections about the previous message (thanks to Magnus & >Danny) pointed Python's feature called interning: the first aspect of this >feature is that integers in range(-5,100) (I didn't know about negative >ones) are generated and stored as data by python; the second is that they >won't >be duplicated, but used 'in place' instead, each time the value is needed: > > >>> x=1; y=1 ; x is y >True > >>> x = -1; y = -1 ; x is y >True > >This means that x and y are at the same memory location, in other words 'x' >and 'y' are aliases: > > >>> id(x); id(y) >7678960 >7678960 > >Now, let's (try and) check this does not with out-of-range (sic!) values: > > >>> x=100; y=100 ; x is y >True > >>> x=1000; y=1000 ; x is y >True > >What's up ? (I've really been surprised!) A more careful trial: > > >>> x=1000 > >>> y=1000 > >>> x is y >False Put these lines in a module and run it Output is True: x=1000 y=1000 print x is y > >>> x=100 > >>> y=100 > >>> x is y >False > >>> x=99 > >>> y=99 > >>> x is y >True > >This difference of result shows that two 'equivalent' syntactic forms aren't >processed the same way. I guess that, on optimisation ground, a short-term >interning is done for multi-assignment lines (what about "x,y = a,a"?). How >long does it last ? Is it further available ? > > >>> x=100; y=100 ; x is y >True > >>> z=100 ; x is z; y is z >False >False > >Now, what about strings ? > > >>> x='a' > >>> y='a' > >>> x is y >True > >>> x='1' > >>> y='1' > >>> x is y >True > >>> x='Freude, sch?ner G?tterfunken,..." >SyntaxError: EOL while scanning single-quoted string # ?$%#~!!! > >>> x='Freude, sch?ner G?tterfunken,...' > >>> y='Freude, sch?ner G?tterfunken,...' > >>> x is y >False > >>> x='Freude, sch?ner G?tterfunken,...'; y='Freude, sch?ner >G?tterfunken,...' ; x is y # this was one single line in IDLE >True > >As expected, basic interning is available for small strings (what are the >criteria?); and the short-term interning form works too. >What about sequences ? > > >>> x=('a') > >>> y=('a') > >>> x is y >True > > >>> x=['a'] > >>> y=['a'] > >>> x is y >False > >>> x=['a']; y=['a'] ; x is y >False > >>> x=[]; y=[] ; x is y >False > >>> x=[True]; y=[True] ; x is y >False > >Very probable conclusion : yes for immutables, no for mutables. It doesn't >even work for empty lists or built-in constants. > > > >Now, I really want to explore this difference deeper. First, let's enlarge x >a bit: > > >>> x+=[False] > >>> x >[True, False] > >>> x+='a' > >>> x >[True, False, 'a'] > >>> a='ciao!' > >>> x+=[a] > >>> x >[True, False, 'a', 'ciao!'] > >>> x+=1 > >Traceback (most recent call last): > File "", line 1, in -toplevel- > x+=1 >TypeError: argument to += must be iterable > >I typed the last line just for fun, but I am surprised that python accepts >x+='a', as >'a' is no list, and refuses x+=1 (?). I would expect to be obliged to write >x.append(item) for both strings and numbers, as both are immutable --but >strings are sequences (what about tuples?). And with a dictionary ? > > >>> d={} > >>> x+=d > >>> x >[True, False, 'a', 'ciao!'] # no success ;-( > >>> x+=[d] > >>> x >[True, False, 'a', 'ciao!', {}] # :-) > >>> d={1:'un', 2:'deux'} > >>> x+=d > >>> x >[True, False, 'a', 'ciao!', {}, 1, 2] # the keys, only! > >>> x+= [d] > >>> x >[True, False, 'a', 'ciao!', {}, 1, 2, {1: 'un', 2: 'deux'}] > >Well, interesting, isn't it? You can, as a choice, append to a list either a >dictionary's keys or its key:value pairs, both without even explicitely >calling the append() method. >Now, what about adresses? (let's not be distracted) > > >>> id(x) >10763120 > >>> for i in range(len(x)): > print id(x[i]) # items' addresses >504028992 >504028976 >6759872 >10763168 >10790352 >7678960 >7677952 >10639664 > >>> id(1);id(2) >7678960 >7677952 # right! > >>> id(d) >10639664 # right again! > >True and False are rather close, but not aside; 1 and 2 are strangely far >(?). All items are separated from the list, they're not "in" the list. Which >means, as expected, that the list holds its elements' addresses -- only its >elements' addresses. > > >>> id(d) >10639664 > >>> for i in range(len(d)): > print id(d.keys()[i]) # keys' addresses >7678960 >7677952 > >>> for i in range(len(d)): > print id(d[d.keys()[i]]) # values' ones >10763872 >10762944 > >It also clear that for a dictionary the dict. itself, its keys and its >values are totally separated. >Just as a recall about value changes by immutable types: > > >>> t='Freude, sch?ner G?tterfunken,...' ; id(t) >6742216 > >>> t='? joie, divine ?tincelle de beaut?...' ; id(t) >10781656 > >The (whole) variable's address changes. What happens when I change x, now? >There are two kinds of changes: > > >>> id(x); id(x[3]) >10763120 >10763168 > > >>> x[3]='ol?!' # first --I mean zeroth: partial change > >>> id(x); id(x[3]) >10763120 >10764064 > > >>> x=[1,'a',d] # first: global change > > >>> id(x) >10763216 > >By immutable types, only the item(s) changed move(s) when they're directly >addressed: the list's address hasn't changed. But the global variable moves >when addressed as a whole. >[Just as foretaste (?) on this topic...] > >denis > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From lsloan at umich.edu Thu May 13 11:37:05 2004 From: lsloan at umich.edu (Lance E Sloan) Date: Thu May 13 11:37:15 2004 Subject: [Tutor] reading Excel CSVs? (was: Re: recommended CSV module?) In-Reply-To: <1084454216.5059.11.camel@laptop.venix.com> References: <2147483647.1084437266@[192.168.2.201]> <2147483647.1084437851@[192.168.2.201]> <1084454216.5059.11.camel@laptop.venix.com> Message-ID: <2147483647.1084448225@[192.168.2.201]> --On Thursday, May 13, 2004 9:16 AM -0400 Lloyd Kvam wrote: > It's hard to keep up with all of the available modules. My experience > is that the standard csv module is better than the third party > alternatives. Thanks for the confirmation, Lloyd. I'm trying to use the equivalent of "hello, world" for csv (from the example given in the documentation) to read and parse lines from a CSV file produced by Excel. The code: import csv reader = csv.reader(file("true-csv.csv"), dialect='excel') for row in reader: print row Some of the CSV: PHRASE,ITEM,MONTH,YEAR,PAGE^M"Investments, 2001-2002",Alternative asset commitment approved with Yorktown Energy Partners V L.P.,April,2002,283^M"Investments, 2001-2002",Alternative asset commitment approved with BPG Investment Partnership VI L.P.,April,2002,283^M That CSV came directly from Excel. Note that the "^M" shown here are actually carriage returns in the file. I just loaded it into vi and copied a few lines into this message. When I run the program, I get this error: Traceback (most recent call last): File "samplecsv", line 3, in ? for row in reader: _csv.Error: newline inside string I've tried telling the csv.reader that the lineterminator is '\n' or '\r' in place of its default '\n\r', but neither worked. How do other folks use the csv module to read Excel files? BTW, I'm running this on a Mac OS X machine. I've tried this with CSVs from Excel running on both Windows and Mac and it comes out the same. (Nice that it's consistent.) -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From magnus at thinkware.se Thu May 13 12:32:34 2004 From: magnus at thinkware.se (Magnus Lycka) Date: Thu May 13 12:32:41 2004 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUmU6IHJlY29tbWVuZGVkIENTViBtb2R1bGU/?= Message-ID: Lance E Sloan wrote: > *sigh* This is the second time I've made a fool of myself here asking for > third-party module recommendations when there's one that's included with > Python. :P > > Unless somebody has a good reason to recommend that I should use some > third-party CSV module, I'll use the stock one. The good reason not to use the std lib version would be that you need to use a Python version prior to 2.3 I think it's the third party module called 'csv' that got included as 'csv' in Python. I haven't noticed any difference... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Thu May 13 13:51:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 13 13:51:12 2004 Subject: [Tutor] value changes In-Reply-To: <002801c438f3$a6cbd0c0$3043933e@spir> Message-ID: On Thu, 13 May 2004, denis wrote: > Now, let's (try and) check this does not with out-of-range (sic!) > values: > > >>> x=100; y=100 ; x is y > True > >>> x=1000; y=1000 ; x is y > True > > What's up ? (I've really been surprised!) A more careful trial: Hi Denis, [Note: really obscure CPython optimization discussion; do we really want to talk about this? *grin*] It's an optimization based on what Python is doing during interactive interpretation. It actually does have a little bit to do with the multiple statements that you're doing, but it's more general than that: ### >>> while True: ... x = 1000 ... y = 1000 ... break ... >>> x is y True ### Notice that we're getting a different result from your previous experiment: > >>> x=1000 > >>> y=1000 > >>> x is y > False When we run Python as an interactive interpreter, Python first does a byte-code compilation pass over the things we are typing, and then executes that bytecode. That is, when we're doing: ### >>> x=1000 >>> y=1000 >>> x is y False ### behind each statement is a mini-compile step going on. That's what the '>>>' is saying: that the Python interpreter is ready to compile and execute another statement. Since each statement is compiled and executed separately, Python won't even try to do any global analysis: it won't try to see that x and y are directed at the same constant '1000'. The scope of optimization is the "block" of code that the byte-compiler sees. On the other hand, when we send the interactive interpreter something like: ### >>> while True: ### Python can't immediately byte-compile this: it must see the whole while block through and through, before doing anything else. And that's why it prompts us for more information, with the '...' prompt: ### >>> while True: ... x = 1000 ... y = 1000 ... break ... >>> x is y True ### So the byte-compiler is fed the whole 'while' loop. Since it can see the whole block as one unit, all at once, it has a bit more room to infer that 'x' and 'y' are the same thing, and can set them to the same constant object '1000'. > This difference of result shows that two 'equivalent' syntactic forms > aren't processed the same way. It has less to do with syntax, more to do with the way the interactive interpreter is working. If we were to run Python on a file, then we'd see that the byte-code compiler is able to analyze the whole module file, as Bob Gailer mentions. All of this discussion, though, is on a really obscure optimization that isn't advertised Python behavior. It works only on constant "immutable" values because it doesn't change Python's observable behavior. All the optimzations that Python does, behind the scenes, are supposed to be practically invisible to us. From denis.spir at free.fr Thu May 13 14:22:14 2004 From: denis.spir at free.fr (denis) Date: Thu May 13 14:23:59 2004 Subject: [Tutor] value changes References: <002801c438f3$a6cbd0c0$3043933e@spir> <6.0.0.22.0.20040513084113.02665380@mail.mric.net> Message-ID: <003201c43917$4aea0be0$cf40933e@spir> ----- Original Message ----- From: Bob Gailer To: denis ; tutor python Sent: Thursday, May 13, 2004 4:43 PM Subject: Re: [Tutor] value changes > >>> x=1000 > >>> y=1000 > >>> x is y >False Put these lines in a module and run it Output is True: x=1000 y=1000 print x is y Right! So 'ad-hoc' interning is done by python only by 'real' program run, not in IDLE. Or what? From firephreek at earthlink.net Thu May 13 15:13:59 2004 From: firephreek at earthlink.net (firephreek) Date: Thu May 13 15:23:33 2004 Subject: [Tutor] Return key from value Message-ID: <004b01c4391e$72bf2c70$6f01010a@Rachel> I thought there was a method for it, but I can't seem to find it. Does anyone know how I can return the matching key from a dictionary if I know the value? I'm working with some very large data structures, and I don't want to have to duplicate them. Stryder From orbitz at ezabel.com Thu May 13 15:37:44 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Thu May 13 15:38:31 2004 Subject: [Tutor] Return key from value In-Reply-To: <004b01c4391e$72bf2c70$6f01010a@Rachel> References: <004b01c4391e$72bf2c70$6f01010a@Rachel> Message-ID: <20040513153744.142eef7a.orbitz@ezabel.com> key -> value have a one to one relationship. value -> key have a 1 to many relatinoship. You will most likley need to iterate over your dictionary and check if the value matches, and construct a list of keys. If you have such a large datastructure, I wonder why you are doing this in the first place? On Thu, 13 May 2004 12:13:59 -0700 "firephreek" wrote: > I thought there was a method for it, but I can't seem to find it. > > Does anyone know how I can return the matching key from a dictionary if > I know the value? I'm working with some very large data structures, and > I don't want to have to duplicate them. > > Stryder > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu May 13 15:49:36 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 13 15:49:44 2004 Subject: [Tutor] Return key from value In-Reply-To: <004b01c4391e$72bf2c70$6f01010a@Rachel> Message-ID: On Thu, 13 May 2004, firephreek wrote: > I thought there was a method for it, but I can't seem to find it. > > Does anyone know how I can return the matching key from a dictionary if > I know the value? I'm working with some very large data structures, and > I don't want to have to duplicate them. Hi Stryder, A simple dictionary is good for defining a mapping from a key to a value --- but it's not so good for going the other way. It's possible to just do a linear scan across the items() of a dictionary: ### >>> d = {1:'one', 2:'two', 3:'three'} >>> d.items() [(1, 'one'), (2, 'two'), (3, 'three')] ### You mentioned that the data structure is large: the linear scan might a bad idea, then. If so, then the most straightforward thing I can think of at the moment is to duplicate: have one dictionary map from keys to values, and another dictionary to go the other way. This approach trades off space for fast lookup. But what are your keys and values, by the way? Depending on what the data is, we might be able to use something like the "range" data structures surveyed by Bentley and Friedman. If you have an ACM account, then you might like to read: http://portal.acm.org/citation.cfm?id=356797&dl=ACM&coll=portal which is a nice introduction to these structures. If the keys and values can be treated as numbers, then a KD-tree can work: http://www.nist.gov/dads/HTML/kdtree.html The BioPython project has an optimized KD tree implementation, so you might be able to get away without having to write much. *grin* One other alternative is to cheat and use a relational database like Sqlite: http://www.sqlite.org/ *grin* From zmerch at 30below.com Thu May 13 15:55:25 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu May 13 15:54:25 2004 Subject: [Tutor] reading Excel CSVs? (was: Re: recommended CSV module?) In-Reply-To: <2147483647.1084448225@[192.168.2.201]> References: <1084454216.5059.11.camel@laptop.venix.com> <2147483647.1084437266@[192.168.2.201]> <2147483647.1084437851@[192.168.2.201]> <1084454216.5059.11.camel@laptop.venix.com> Message-ID: <5.1.0.14.2.20040513151451.00aee7b0@mail.30below.com> At 11:37 AM 5/13/2004 -0400, Lance E Sloan wrote: I've never used the CSV module, I've always profiled my data & split it by hand, but... > Some of the CSV: > > PHRASE,ITEM,MONTH,YEAR,PAGE^M"Investments, 2001-2002",Alternative asset > commitment approved with Yorktown Energy Partners V > L.P.,April,2002,283^M"Investments, 2001-2002",Alternative asset > commitment approved with BPG Investment Partnership VI > L.P.,April,2002,283^M > >That CSV came directly from Excel. Note that the "^M" shown here are >actually carriage returns in the file. I just loaded it into vi and >copied a few lines into this message. > >When I run the program, I get this error: > > Traceback (most recent call last): > File "samplecsv", line 3, in ? > for row in reader: > _csv.Error: newline inside string > >I've tried telling the csv.reader that the lineterminator is '\n' or '\r' >in place of its default '\n\r', but neither worked. > >How do other folks use the csv module to read Excel files? Quick-n-dirty? Load the CSV into StarOffice / OpenOffice, then resave. Most programs put quotes around all strings *no matter what* and only leave numerical fields unquoted. Excel puts quotes around strings *only if they contain commas*. Very odd behaviour, and fairly difficult to parse. >BTW, I'm running this on a Mac OS X machine. I've tried this with CSVs >from Excel running on both Windows and Mac and it comes out the same. >(Nice that it's consistent.) Maybe across platforms, but not across different versions of Excel... sometimes they change the behaviour a bit during updates. Very odd. If all your data is string-based (a.k.a. no numerical fields) I usually load/resave with StarOffice, then split on quotes instead of commas, then take every other field... but that's just me. I have some sample code where I've done just that - if you'd like to see it, email me offlist & i'd be happy to forward it to you. HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | "Bugs of a feather flock together." sysadmin, Iceberg Computers | Russell Nelson zmerch@30below.com | From magnus at thinkware.se Fri May 14 04:21:26 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 14 04:16:48 2004 Subject: [Tutor] reading Excel CSVs? (was: Re: recommended CSV module?) In-Reply-To: <2147483647.1084448225@[192.168.2.201]> References: <1084454216.5059.11.camel@laptop.venix.com> <2147483647.1084437266@[192.168.2.201]> <2147483647.1084437851@[192.168.2.201]> <1084454216.5059.11.camel@laptop.venix.com> Message-ID: <5.2.1.1.0.20040514094453.02124ea8@www.thinkware.se> At 11:37 2004-05-13 -0400, Lance E Sloan wrote: >I'm trying to use the equivalent of "hello, world" for csv (from the >example given in the documentation) to read and parse lines from a CSV >file produced by Excel. The code: > > import csv > reader = csv.reader(file("true-csv.csv"), dialect='excel') > for row in reader: > print row I think csv is confused by the fact that there is no line feed character in line endings on the Mac. Unix uses \n, WinDOS uses \r\n and Mac uses \r. I'd try opening the files with file("true-csv.csv", "rU") Note capital U. This is the universal line ending mode. See file function in Library reference section 2.1. The manual says you must open in binary mode, i.e. file("true-csv.csv", "rb"), but I don't think that will work with Mac file. I think your Windows files only appear to be like the Mac files becuase you open them in text mode, so Python converts them to native line ending format. If you use file("true-csv.csv", "rb") I think the Windows file (but not the Mac file) will work. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus at thinkware.se Fri May 14 06:12:37 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 14 06:08:02 2004 Subject: [Tutor] why does this raise an exception... In-Reply-To: <1084456513.5514.5.camel@linuxbox> Message-ID: <5.2.1.1.0.20040514110344.02126830@www.thinkware.se> At 16:55 2004-05-13 +0300, roman wrote: >When converting a few string values to integers with int() I found out >that trying to convert "2.1", i.e. a string that represents a floating >point value to an integer raises an exception. Why does this raise an >exception while something like float("9") does not? This is just the way it's described in the manual. I guess the real answer is that Guido felt that this was the most reasonable behaviour. If you think more about it, I suspect you will agree. It might seem strange that "int(2.7)" will truncate the float to an integer with value 2, and "int('2')" will convert the string "2" to the integer 2, but you can't do both things at once, i.e. get the string "2.7" converted to the integer 2 in one step. But when you look at it like this, you realize that it means that you would either first have to convert the string "2.7" to a float, and then truncate and convert that to an integer, or you would have to cut the string after the first uninterrupted sequence of digits (or maybe interpret the string in some more advanced way). It's one of Python's mottos that "Explicit is better than implicit", so Pythonistas generally think that if "int(float(aString))" is what you want, you should spell that out, not let the python interpreter guess whether "int(aString)" with "aString='3.7'" implies "int(float(aString))" or whether the input value was actually outside the intended range. And if we allow "int('2.7')" I suppose we should also allow something like "int('2e30')". "int(2e30)" works, but if you think it will return 2000000000000000000000000000000 you are wrong. It yields 2000000000000000039769249677312. This is because floating point numbers like 2e30 are approximations. There is a limited precision in floats, and people who work with floats should be aware of that. Ints and longs are exact. So, if you do "int(float(2e30))" you *should* expect to get 2000000000000000039769249677312. But what should you expect to get from int("2e30")? Some might argue that it should be the same as "int(float(2e30))", but it also seems reasonable to say that int("2e30") should be the same as "int(2000000000000000000000000000000)". I think most Python programmer would expect that. After all, 2e30 is mathematically an integer, even if the literal "2e30" is interpreted as a float in Python in for instance "big = 2e30". And what about "int('2.5e1')". That should yield 25 just like "int(2.5e1)", right? It's very useful that you allow the int() constructor to convert floats to ints, and the decision has been made to truncate decimals towards zero. Fine, this is something you often do, and if you want to round to nearest, or towards plus or minus infinity, you can use int(round(x)), int(math.ceil(x)) or int(math.floor(x)). So, int complements the other existing functions. There is no ambiguity here. For strings, the decision has been made to only allow a sequence of at least one digit optionally preceeded by a plus or minus and optionally surrounded by leading and trailing whitespace. All other strings are rejected. I think this is a good choice, since allowing more than that would open for various interpretations of what value to expect from a certain string. It's also a practical choice. It's much easier to write the C code to handle the strings like the ones int() accepts than to write a parser that does the right things with things like -12342.345435345e-2 without going via floats that loose the integer precision for large integers. It will also run faster. Even if performance isn't considered the most important aspect of Python, I doubt that programmers in general would like int() to be slowed down to make int("2.5") work. If you want "int(float(x))" and think it's too much typing, you can write a function for it: def flint(x): return int(float(x)) If you want things like int("2.56e30") to give an exact result (which flint won't), you have to write some more code. This is an unusual use case, and fits better in a custom module than in the Python core. I for one is more interested in converting local conventions for numeric strings such as "1.000.000,00" or "1,000,000.00" or "1 000 000,00" than scientific notations. Sometimes I want to convert unit prefixes such as k, M, G etc as well. Neither of these things belong in the core of the language. See also http://diveintopython.org/unit_testing/stage_1.html for a more exotic way of converting strings to numbers and vice versa. A special case for someone with the name Roman... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From firephreek at earthlink.net Fri May 14 12:33:12 2004 From: firephreek at earthlink.net (firephreek) Date: Fri May 14 12:42:47 2004 Subject: [Tutor] Return key from value In-Reply-To: <20040513153744.142eef7a.orbitz@ezabel.com> Message-ID: <001001c439d1$26ff4c30$6f01010a@Rachel> I'm writing a program to help with some database migration issues. We have an system running an inventory/sales/invoicing program. We're going to open up another part of the program to help automate some of our cost control/inventory tracking. Unfortunatly this means inputting a vendor name/info along with all products that we purchase from said vendor. This is on order of several thousand items. More even...So we're looking at several months worth of data entry. I type decently fast, but not that fast. But the way the system is, we can't put in the data, without actually using that portion of the program, which will conflict with the way we currently use the program. I (re: my employer) isn't willing to do that. So, the idea behind this program is that it'll read data from my Main System, and allow me to match data from my incoming products/vendors to what exists in my system, after several months of this when we've gotten everything together, we can run a complete list of everything on my external db, and then have 3-4 people do all the entry in a week. System goes on with minimal downtime, and we're only missing maybe 2% of total possible inventory, which is an acceptable amount that we can make up for as time goes on. Bah. So, I need to build something stupid proof for my fellow employees. I'm the only one here who knows his elbow from a cat5 cable so to speak. I thought about duplicating my dictionary set (which will hold k/v to match vend/# to vend/name so I can search against both. But because the set is going to be pretty big (I'll need to cross match item# vs. item/name) I was looking for the most efficient route, the other option that occurred is to do a sql query against whatever attribute is entered, and that may be the route I go with. We have our own MySQL server (love! Like python!), is it very different from sqlite? Both key and value on all sets will be unique, so I'm not worried about that. When is 'big' too big? How far can I push before I see a performance hit? I think I'm just going to stop caring about performance and let them suck it up. Though it hurts to think that...ugh. That's the long and short of it. I make no qualms about the fact that I'm new to some of this, but I'm also not a complete idiot. I can use a hammer, I'll make this work one way or another. *grin* Stryder PS: gui is gonna be wxPython, and that's a whole 'nother bag of fish. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of orbitz@ezabel.com Sent: Thursday, May 13, 2004 12:38 PM To: tutor@python.org Subject: Re: [Tutor] Return key from value key -> value have a one to one relationship. value -> key have a 1 to many relatinoship. You will most likley need to iterate over your dictionary and check if the value matches, and construct a list of keys. If you have such a large datastructure, I wonder why you are doing this in the first place? On Thu, 13 May 2004 12:13:59 -0700 "firephreek" wrote: > I thought there was a method for it, but I can't seem to find it. > > Does anyone know how I can return the matching key from a dictionary > if I know the value? I'm working with some very large data > structures, and I don't want to have to duplicate them. > > Stryder > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From firephreek at earthlink.net Fri May 14 14:47:34 2004 From: firephreek at earthlink.net (firephreek) Date: Fri May 14 14:57:11 2004 Subject: [Tutor] Return key from value In-Reply-To: <20040514141434.41df1d0b.orbitz@ezabel.com> Message-ID: <001301c439e3$ebc174a0$6f01010a@Rachel> Crazy stupid-implementation, or crazy employer asking for a lot all at once? For the stupid proof, I thought that I might set up combo boxes with wxPython, using the k/v to match, but I'm gonna re-work that I think and use sql, maybe a combination, haven't set it in stone. Danny Yoo mentioned SQLite, and after looking into that a little, I think it might be just what I'm looking for. We'll see. Being new and self taught, I'm not always sure about which is the best way of doing things. I have that tendency to overanlyze myself to a standstill, and that doesn't help. Biggest differences between mySQL and PostgreSQL? I've heard of the second, I use the first currently for some minor tracking and for temperature recording. It was the first thing I heard of that interfaces with php and so I picked it up. I'm happy with it, but if there's that big a difference, I'll happily consider moving. Stryder -----Original Message----- From: orbitz@ezabel.com [mailto:orbitz@ezabel.com] Sent: Friday, May 14, 2004 11:15 AM To: firephreek Subject: Re: [Tutor] Return key from value Hrm, what yo uare doing sounds pretty crazy. IMO, let SQL handle the referencing and have your python rely on that. Let's face it, Python IS SLOW. The interpreter is slow at doing things. And unless I read you wrong, you want speed. SQL engines were made for this sorting through things quickly, and your SQL engine is most likely way smarter than your OS at keeping information paged in/out that is goign to be accessed often so it can make things fast. On another note, dump MySQL for PostgreSQL, MySQL is junk:), but I doubt you can since it's your employerr and it sounds like most of what you have is already written for mysql. Anyways good luck. On Fri, 14 May 2004 08:56:27 -0700 "firephreek" wrote: > I'm writing a program to help with some database migration issues. We > have an system running an inventory/sales/invoicing program. We're > going to open up another part of the program to help automate some of > our cost control/inventory tracking. Unfortunatly this means > inputting a vendor name/info along with all products that we purchase > from said vendor. This is on order of several thousand items. More > even...So we're looking at several months worth of data entry. I type > decently fast, but not that fast. But the way the system is, we can't > put in the data, without actually using that portion of the program, > which will conflict with the way we currently use the program. I (re: > my employer) isn't willing to do that. So, the idea behind this > program is that it'll read data from my Main System, and allow me to > match data from my incoming products/vendors to what exists in my > system, after several months of this when we've gotten everything > together, we can run a complete list of everything on my external db, > and then have 3-4 people do all the entry in a week. System goes on > with minimal downtime, and we're only missing maybe 2% of total > possible inventory, which is an acceptable amount that we can make up for as time goes on. > > Bah. So, I need to build something stupid proof for my fellow > employees. I'm the only one here who knows his elbow from a cat5 > cable so to speak. > > I thought about duplicating my dictionary set (which will hold k/v to > match vend/# to vend/name so I can search against both. But because > the set is going to be pretty big (I'll need to cross match item# vs. > item/name) I was looking for the most efficient route, the other > option that occurred is to do a sql query against whatever attribute > is entered, and that may be the route I go with. We have our own > MySQL server (love! Like python!), is it very different from sqlite? > Both key and value on all sets will be unique, so I'm not worried > about that. When is 'big' too big? How far can I push before I see a > performance hit? I think I'm just going to stop caring about > performance and let them suck it up. Though it hurts to think > that...ugh. > > That's the long and short of it. I make no qualms about the fact that > I'm new to some of this, but I'm also not a complete idiot. I can use > a hammer, I'll make this work one way or another. *grin* > > Stryder > > PS: gui is gonna be wxPython, and that's a whole 'nother bag of fish. > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On > Behalf Of orbitz@ezabel.com > Sent: Thursday, May 13, 2004 12:38 PM > To: tutor@python.org > Subject: Re: [Tutor] Return key from value > > > key -> value have a one to one relationship. > value -> key have a 1 to many relatinoship. > > You will most likley need to iterate over your dictionary and check if > the value matches, and construct a list of keys. > > If you have such a large datastructure, I wonder why you are doing > this in the first place? > > > On Thu, 13 May 2004 12:13:59 -0700 > "firephreek" wrote: > > > I thought there was a method for it, but I can't seem to find it. > > > > Does anyone know how I can return the matching key from a dictionary > > if I know the value? I'm working with some very large data > > structures, and I don't want to have to duplicate them. > > > > Stryder > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri May 14 16:14:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 14 16:14:17 2004 Subject: [Tutor] Return key from value In-Reply-To: <001001c439d1$26ff4c30$6f01010a@Rachel> Message-ID: On Fri, 14 May 2004, firephreek wrote: > I thought about duplicating my dictionary set (which will hold k/v to > match vend/# to vend/name so I can search against both. But because the > set is going to be pretty big (I'll need to cross match item# vs. > item/name) I was looking for the most efficient route, the other option > that occurred is to do a sql query against whatever attribute is > entered, and that may be the route I go with. We have our own MySQL > server (love! Like python!), is it very different from sqlite? Ah, you have MySQL set up already? Thnk it might be easiest to start with that. There's a nice 'MySQLdb' Python module that you can use: http://sourceforge.net/projects/mysql-python So you may not need to maintain a dictionary: you can probably just use SQL to handle the data processing for you. Good luck to you! From magnus at thinkware.se Fri May 14 18:05:20 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri May 14 18:00:35 2004 Subject: [Tutor] value changes In-Reply-To: <002801c438f3$a6cbd0c0$3043933e@spir> Message-ID: <5.2.1.1.0.20040514160712.021354f0@www.thinkware.se> At 16:04 2004-05-13 +0200, denis wrote: >Some comments and corrections about the previous message (thanks to Magnus & >Danny) pointed Python's feature called interning: BTW I saw in that PEP 237 uses the term interning for this handling of small integers (although with double quotes on the first use). I suppose that means it's ok to use that term also for non-strings. >the first aspect of this >feature is that integers in range(-5,100) (I didn't know about negative >ones) are generated and stored as data by python; the second is that they >won't >be duplicated, but used 'in place' instead, each time the value is needed: [lots of experiments removed] I think the important thing to learn here is when to use "a==b" and when to use "a is b". From a technical point of view we can say that "a==b" is a test on whether the values that the names a and b refer to are equal (which is not as strict as to say that they are identical), and "a is b" is technically a test to see whether "a" and "b" refer to the same location in memory. I think we can ignore those technical details though. To put it simply, we typically use the comparision "a == b" in our programs when we want to check if two things are "the same". "a is b" is a fairly rare bird. Forgetting about memory locations, equality and identity are different things. For instance, you never use the is-operator to compare numbers or strings in normal code. It's really pure nonsense. It's like asking the bank clerk if this is really the bank notes you deposited when you make a withdrawal. (Only Goofy does things like that.) Never rely on interning. If you need to check that a value is an integer of value 0, and not a float of that value, you can't use "a == 0", because 0.0 == 0 returns true, but even if "a is 0" will actually work today (on CPython) there is no guarantee that it always will. In this case, you should use "a == 0 and type(a) is int". The most common use for the is-operator on normal python code is tests for singletons. For instance, these is only one None object in a Python program. Type objects, such as int, str, float etc, are also singletons. So, "if a is None:" or "if type(a) is not int:" are statement that make sense. You can also write "if a == None:" or "if type(a) != int:", but that's a bit like asking me "Is your name Magnus Lyck??" instead of "Are you Magnus Lyck??" if you meet me and are a bit uncertain on whether that guy in front of me is that guy on the Tutor mailing list. You're not really interested in whether I have a certain name, you are intested in whether of not I am a certain person. Python is obviously implemented to reuse immutable objects at times, which means that some pairs of objects that we require to return True on a test like "a == b", will also return true on "a is b". This might not happen, but it *can* happen for immutables. As usual, it's safer to assume as little as possible... >As expected, basic interning is available for small strings (what are the >criteria?); and the short-term interning form works too. >What about sequences ? > > >>> x=('a') > >>> y=('a') > >>> x is y >True Those aren't sequences. Parenthesis don't imply tuples. Comma imples tuples. Sometimes you need to use parenthesis around tuples to disambiguate things, but in general parenthesis has the same meaning in Python as in English or in traditional mathematical notation. >>> a=2 >>> a, (2,) >>> (a) 2 See? You are always allowed to end list or tuple literals with a trailing comma, but for tuples with only one member, it's compulsory. x and y above are thus strings. We already know that strings that look like identifiers are interned. Tuples are not interned. >>> a, b = (1,2), (1,2) >>> a is b False > >>> x=['a'] > >>> y=['a'] > >>> x is y >False > >>> x=['a']; y=['a'] ; x is y >False > >>> x=[]; y=[] ; x is y >False > >>> x=[True]; y=[True] ; x is y >False > >Very probable conclusion : yes for immutables, no for mutables. It doesn't >even work for empty lists or built-in constants. It would be disastrous if Python interned mutable objects. That would for instance mean that you can't create more than one empty list in a program. That would really be stupid, since we often create empty list which we poppulate with values in some kind of look or recursive process. >Now, I really want to explore this difference deeper. First, let's enlarge x >a bit: > > >>> x+=[False] > >>> x >[True, False] > >>> x+='a' > >>> x >[True, False, 'a'] [snip] >I typed the last line just for fun, but I am surprised that python accepts >x+='a', as >'a' is no list, and refuses x+=1 (?). I would expect to be obliged to write >x.append(item) for both strings and numbers, as both are immutable --but >strings are sequences (what about tuples?). And with a dictionary ? But you failed to test how it treats this "sequence" by using a list with only one member. Does it convert the string to a list, or does it just append the string? >>> a = [] >>> a += 'hello' >>> a ['h', 'e', 'l', 'l', 'o'] Ok. That explains why "a += 1" won't work, but I'm still a bit surprised. Does the old list.extend() method work like this? >>> a.extend(' there') >>> a ['h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e'] Yes it does, so it's nothing new with augmented assignment ("a += b" behaves just like "a.extend(b)"). I suppose this behaviour isn't so strange after all. It's actaully consistent with how Python regularly convert sequences to lists, or rather how python accepts any sequence as input in functions that returns lists. It works like this in other cases too: >>> map(None, ['h','e','l','l','o'], 'there') [('h', 't'), ('e', 'h'), ('l', 'e'), ('l', 'r'), ('o', 'e')] >>> [x.upper() for x in 'a string'] ['A', ' ', 'S', 'T', 'R', 'I', 'N', 'G'] > >>> d={} > >>> x+=d > >>> x >[True, False, 'a', 'ciao!'] # no success ;-( Try a non-empty dictionary instead. >>> d = {'first': 0, 'second': 1} >>> d {'second': 1, 'first': 0} >>> a = [] >>> a += d >>> a ['second', 'first'] Keys. Right. Same thing would happen if you did this: >>> a = [] >>> for key in d: a.append(key) >>> a ['second', 'first'] I think you need to read a bit about iterators to get on top of this. http://docs.python.org/tut/node11.html#SECTION0011900000000000000000 http://www-106.ibm.com/developerworks/library/l-pycon.html?n-l-9271 http://www.python.org/peps/pep-0234.html >True and False are rather close, but not aside; 1 and 2 are strangely far >(?). All items are separated from the list, they're not "in" the list. Which >means, as expected, that the list holds its elements' addresses -- only its >elements' addresses. Yep, it's the same with other builtin singletons such as None, int, str, file >>> map(id, (str, int, float, long, file, True, False, None)) [504166464, 504108944, 504077792, 504119480, 504076280, 504029048, 504029032, 504130904] What about things like builtin functions? >>> map(id, (range, min, max)) [8107072, 8106912, 8106872] Nope, they are allocated on the heap just as "normal" object. >It also clear that for a dictionary the dict. itself, its keys and its >values are totally separated. Certainly. All containers in Python are filled with references to objects, not with the objects themselves. So, if you do, >>> l1 = [1,2,{'three':3}] >>> l2 = l1 you have just one list, >>> l1 is l2 True and then if you do, >>> l3 = l1[:] you get a copy of that list, so now you have two lists, >>> l1 is l3 False but you still only have one dict, which both lists contain as it's last element. >>> l1[-1] is l3[-1] True So, it you change the first element of l3, the two lists won't be identical any more, >>> l1[0]=1.1 >>> l1==l3 False but if you change the *content* if the last element, that will be visible in both lists. >>> l1[-1]['four']=4 >>> l1 [1.1000000000000001, 2, {'four': 4, 'three': 3}] >>> l3 [1, 2, {'four': 4, 'three': 3}] >Just as a recall about value changes by immutable types: > > >>> t='Freude, sch?ner G?tterfunken,...' ; id(t) >6742216 > >>> t='? joie, divine ?tincelle de beaut?...' ; id(t) >10781656 > >The (whole) variable's address changes. What happens when I change x, now? >There are two kinds of changes: I try not to use "variable" in Python, because that word is ambigous. Which is the variable? The name/reference or the actual object/value. When you write t = 'a string' you create a string object which is automatically places somewhere in the memory that Python handles for us, and a name 't' is created in the current scope. The name 't' is bound to the string object containing the text 'a string'. If you then do t = 'another string' you will create another string object, and then rebind 't' to that object. (This will mean that 'a string' will be carbage collected by Python is no other name is bound to it, but that's another story.) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From bvande at po-box.mcgill.ca Fri May 14 19:08:34 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri May 14 19:10:26 2004 Subject: [Tutor] a big thank to all tutors and tutees Message-ID: <40A55172.4010700@po-box.mcgill.ca> Hi all, I just now finished a first real and genuine to-do-some-actual-work program and I wanted to say thanks to those who ask and answer questions on tutor. I doubt I could have done it as easily or at all without what I have learned from the list. Not that you need be, but in case you are interested in the nature of the program: I am a graduate student in philosophy and am working for a professor assembling a 1000'ish page collection of articles for a book. Many people are going to read articles and type up plain text files of index entries with each line being a list of headings and subheadings followed by one or more page references. What I wrote was a program to merge the various files, alphabetize the merged file by heading, merge lines with identical heading strings, sort the page references, and give it book-index formatting where it appears like: A, 67, 78-82 B, 81f C, 89 where B is a subheading of A. Also, the page reference sort needed to preserve a rudimentary markup coding and ignore '-mm' in 'nn-mm'. All in all, no Fields Medal will be awarded, but it feels great to have created a real program to do real work. So, thanks to everyone on the list. Best, Brian vdB From pythontut at pusspaws.net Sat May 15 04:20:25 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat May 15 04:21:04 2004 Subject: [Tutor] Some advice on classes needed ? Message-ID: <40A5D2C9.1020303@pusspaws.net> Good Morning, I need to analyze some data, each set of data will consist of 600 numbers, added to on each sweep of another python program. The data structure will remain at 600, new data pushing oldest data out. After each 'sweep' various statistical functions will need to be applied to this data set of 600 and results returned. Multiply this by 250 sets & there is my problem. I could make a giant matrix 600,250 then program code to sweep the matrix to provide the results. But I have just read about classes :-) If I design a class for one set of data, how do I generate all the instances of classes without 250 generate instances. data1=datastruct() data2=datastruct() ... data250=datastruct() Following on, how can I sweep the 250 data structures instances to get statistical data without manually doing 250 instance calles. What I am asking is, Is it possible to use a for loop ? ie dynamicly generate an instance name to then call ? Hopefully this is an intelegent question - this is the first time I have ever tries OOP ! :-) Dave From roeland.rengelink at chello.nl Sat May 15 06:13:14 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Sat May 15 06:12:33 2004 Subject: [Tutor] tutorial for dbapi 2.0 how to use data In-Reply-To: <40A119E3.8050104@yolo.com> References: <40A119E3.8050104@yolo.com> Message-ID: <40A5ED3A.7020204@chello.nl> John Fabiani wrote: > Hi, > mycur=con.cursor() > mycur.execute("select * from sosord") > mydata=mycur.fetchmany(10) > > The above works and returns data. But know I need to understand how > to view the data. Maybe there is a way to convert the returned list > into a dictionary. A dictionary would allow me to get information by > key (the field name). Anyway, is there some paper or tutorial I can > read on how to view the return data? The returned items of the list mydata already behave as a dictionary (in pyPgSQL). I.e: >>> item = mydata[0] # get the first row from the resultset >>> item.keys() # show the column names ['a', 'b'] >>> item.values() # show the data in the row 0, 123.5 >>> item['a'] # access as dictionary 0 Incidently, the returned object also worksa a list of values: >>> for val item: ... print val ... 0 123.5 >>> print item[1] 123.5 Finally, you can access the values as attributes, e.g.: >>> item.a 0 >>> item.b 123.5 If you want to turn it into a real dictionary, this should work: >>> d = dict(zip(item.keys(), item.values()) Hope this helps, Roeland From alan.gauld at blueyonder.co.uk Sat May 15 07:42:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 15 07:41:46 2004 Subject: [Tutor] a big thank to all tutors and tutees References: <40A55172.4010700@po-box.mcgill.ca> Message-ID: <007a01c43a71$b08c0ba0$6401a8c0@xp> > I just now finished a first real and genuine to-do-some-actual-work > program and Congratulations, there's always a buzz when you move from "interesting novelty" to "real value" programming. > What I wrote was a program to merge the various files, alphabetize the > merged file by heading, merge lines with identical heading strings, sort > the page references, and give it book-index formatting where it appears like: That's pretty impressive. However I wonder whether you have access to either Linux/Unix or Cygwin? If so you probably could have used the publishing tools that come with those to do the indexing etc. It would probably have made the programming much easier I suspect. > All in all, no Fields Medal will be awarded, but it feels great to have > created a real program to do real work. Well done, it's no mean feat and I'm sure it won't be the last. Alan G. From alan.gauld at blueyonder.co.uk Sat May 15 07:50:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 15 07:50:26 2004 Subject: [Tutor] Some advice on classes needed ? References: <40A5D2C9.1020303@pusspaws.net> Message-ID: <007f01c43a72$e01f0ab0$6401a8c0@xp> > If I design a class for one set of data, how do I generate all the > instances of classes without 250 generate instances. > > data1=datastruct() > data2=datastruct() > ... > data250=datastruct() > > What I am asking is, Is it possible to use a for loop ? ie dynamicly > generate an instance name to then call ? You don't need an instance name, you can store them ina list orvdictionary. There is a section at the end of my web tutor topic on OOP that shows how to do this. One thing to consider however is your design, remember that objects own their own dsata arnd are responsible for processing it, so think carefully about how that concept might change the basic way your program functions. Are you going to pass a set of files to each object to extract its own data? Or are you going to going to pass each file in turn to each of the objects? Or are you going to extract the data in bulk and then pass it to the object (so how do you know what data each object needs if the object manages its own data?) Without knowing more about the details its impossible to say which mechanism will work best. But large volume data cruunching can be extremely inefficient if you get the approach wrong. Alan G. From pythontut at pusspaws.net Sat May 15 10:12:04 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat May 15 10:12:14 2004 Subject: [Tutor] Some advice on classes needed ? In-Reply-To: <007f01c43a72$e01f0ab0$6401a8c0@xp> References: <40A5D2C9.1020303@pusspaws.net> <007f01c43a72$e01f0ab0$6401a8c0@xp> Message-ID: <40A62534.8020400@pusspaws.net> Alan Gauld wrote: >>If I design a class for one set of data, how do I generate all the >>instances of classes without 250 generate instances. >> >>data1=datastruct() >>data2=datastruct() >>... >>data250=datastruct() >> >>What I am asking is, Is it possible to use a for loop ? ie dynamicly >>generate an instance name to then call ? >> >> > >You don't need an instance name, you can store them ina list >orvdictionary. >There is a section at the end of my web tutor topic on OOP that shows >how to do this. > > .... can you tell me where I can read this "web tutor topic" ... I think I would find it helpfull Thanks Dave >One thing to consider however is your design, remember that objects >own their own dsata arnd are responsible for processing it, so think >carefully about how that concept might change the basic way your >program functions. Are you going to pass a set of files to each >object to extract its own data? Or are you going to going to pass >each file in turn to each of the objects? Or are you going to >extract the data in bulk and then pass it to the object (so how do >you know what data each object needs if the object manages its own >data?) > >Without knowing more about the details its impossible to say which >mechanism will work best. But large volume data cruunching can be >extremely inefficient if you get the approach wrong. > >Alan G. > > > > > From gew75 at hotmail.com Sat May 15 11:12:37 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sat May 15 11:12:47 2004 Subject: [Tutor] Some advice on classes needed ? References: <40A5D2C9.1020303@pusspaws.net> Message-ID: > [..] > > But I have just read about classes :-) > > If I design a class for one set of data, how do I generate all the > instances of classes without 250 generate instances. > > data1=datastruct() > data2=datastruct() > ... > data250=datastruct() > > Following on, how can I sweep the 250 data structures instances to get > statistical data without manually doing 250 instance calles. > > What I am asking is, Is it possible to use a for loop ? ie dynamicly > generate an instance name to then call ? > What you are asking here is not really a nice thing to do in code. Dynamically creating an instance variable *name* involved the use of eval; which is not a good idea here. I'd suggest something more along the lines of what Alan Gauld stated; use a list or a dictionary. As opposed to simply handing out the solution (where is the fun in that?) here is a little (big?) hint: data = [] for i in range(250): data.append(i) So this is a list of i, from 0 to 250. Noting that unlike most languages python's list object can hold any number of *different* types, one could construct a list-based solution to your problem. Dictionaries are of course alot more fun though. Let's leave that as an exercise... ;). > Hopefully this is an intelegent question - this is the first time I have > ever tries OOP ! :-) > I hope you like it -- it's one of the things python does *really* well. -- Glen From pythontut at pusspaws.net Sat May 15 14:34:51 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat May 15 14:35:38 2004 Subject: [Tutor] Some advice on classes needed ? In-Reply-To: <40A5D2C9.1020303@pusspaws.net> References: <40A5D2C9.1020303@pusspaws.net> Message-ID: <40A662CB.1010300@pusspaws.net> Thanks for all your input, the solutions (sorry hints !) are excellent :-) OOP & loops here I come ... Dave From jsh47 at cam.ac.uk Sat May 15 06:49:23 2004 From: jsh47 at cam.ac.uk (Jonathan Hayward) Date: Sat May 15 16:03:10 2004 Subject: [Tutor] Text numerals? Message-ID: <40A5F5B3.8050103@cam.ac.uk> Is there a function that will return 'one' for 1, 'two' for two, etc.? -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From gew75 at hotmail.com Sat May 15 22:25:09 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sat May 15 22:25:15 2004 Subject: [Tutor] Text numerals? References: <40A5F5B3.8050103@cam.ac.uk> Message-ID: > Is there a function that will return 'one' for 1, 'two' for two, etc.? > I assume you mean 'two' for 2 ;). But no, AFAIK there is no stdlib implementation. This question, although a different isomorphism, was asked recently. The way I code such things is to use a dictionary. Consider these statements: # int y x = 'stringresult' if y == 1: x = 'one' elif y == 2: x = 'two' .. Consider that if you have a dictionary with key:value pairs similar to that data above, you have a half-solution ready to go. The problem of converting full-blown numbers of any length into letters is much harder. Some years ago I remember this being coded in python; if the author has a website, then Google is probably your best bet. But make sure you need that kind of complexity; better to have a solution you understand than one which is too powerful that you don't. It helps when things go wrong ;). -- Glen From isrgish at fastem.com Sun May 16 00:16:23 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun May 16 00:16:27 2004 Subject: [Tutor] Setup.py in program install Message-ID: I find some programs that have a setup.py in them. But wasn't able to figure out how and if it's to be used. If someone can explain it, or point me to where I can find an explaination, I would appreciate it. Thanks All the best Isr From darnold02 at sprynet.com Sun May 16 01:42:15 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun May 16 01:42:24 2004 Subject: [Tutor] Text numerals? In-Reply-To: Message-ID: > Is there a function that will return 'one' for 1, 'two' for two, etc.? > I assume you mean 'two' for 2 ;). But no, AFAIK there is no stdlib implementation. The problem of converting full-blown numbers of any length into letters is much harder. Some years ago I remember this being coded in python; if the author has a website, then Google is probably your best bet. But make sure you need that kind of complexity; better to have a solution you understand than one which is too powerful that you don't. It helps when things go wrong ;). -- Glen my reply: Good advice, but this problem turned out not to be as complex as it first appeared. Really, all you need to do is pad the number to a length that's divisible by 3 and then start processing digits from the left, three at a time. Here's my take on it: littleNumbers = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '10': 'ten', '11': 'eleven', '12': 'twelve', '13': 'thirteen', '14': 'fourteen', '15': 'fifteen', '16': 'sixteen', '17': 'seventeen', '18': 'eighteen', '19': 'nineteen' } tens = {'2': 'twenty', '3': 'thirty', '4': 'forty', '5': 'fifty', '6': 'sixty', '7': 'seventy', '8': 'eighty', '9': 'ninety' } groupings = ['decillion', 'nonillion', 'octillion', 'septillion', 'sextillion', 'quintillion', 'quadrillion', 'trillion', 'billion', 'million', 'thousand', '' ] def process(num): maxDigits = 36 result = [] group = 0 if num < 0: result.append('negative') num = abs(num) num = str(num).zfill(maxDigits) if len(num) > maxDigits: raise 'Number too large' for i in range(0, maxDigits - 1, 3): chunk = num[i:i+3] if chunk != '000': if chunk[0] != '0': result.append(littleNumbers[chunk[0]]) result.append('hundred') if chunk[1] == '1': result.append(littleNumbers[chunk[1:3]]) else: tensString = '' if chunk[1] != '0': if chunk[2] != '0': tensString += tens[chunk[1]] + '-' else: tensString += tens[chunk[1]] if chunk[2] != '0': tensString += littleNumbers[chunk[2]] if tensString: result.append(tensString) if groupings[group]: result.append(groupings[group] + ',') group += 1 if not result: return 'zero' else: result = ' '.join(result) if result.endswith(','): result = result[:-1] return result def main(): while 1: print num = int(raw_input('Enter an integer (0 to quit): ')) print process(num) if num == 0: break if __name__ == '__main__': main() This should handle any integer up to 36 digits long. Here's a sample run: Enter an integer (0 to quit): 10 ten Enter an integer (0 to quit): 243000 two hundred forty-three thousand Enter an integer (0 to quit): 17 seventeen Enter an integer (0 to quit): 232893 two hundred thirty-two thousand, eight hundred ninety-three Enter an integer (0 to quit): -12 negative twelve Enter an integer (0 to quit): -1456 negative one thousand, four hundred fifty-six Enter an integer (0 to quit): 123456789012345678901234567890123456 one hundred twenty-three decillion, four hundred fifty-six nonillion, seven hundred eighty-nine octillion, twelve septillion, three hundred forty-five sextillion, six hundred seventy-eight quintillion, nine hundred one quadrillion, two hundred thirty-four trillion, five hundred sixty-seven billion, eight hundred ninety million, one hundred twenty-three thousand, four hundred fifty-six Enter an integer (0 to quit): 0 zero HTH, Don From dyoo at hkn.eecs.berkeley.edu Sun May 16 04:42:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun May 16 04:42:13 2004 Subject: [Tutor] Text numerals? In-Reply-To: Message-ID: On Sun, 16 May 2004, Don Arnold wrote: > > Is there a function that will return 'one' for 1, 'two' for two, etc.? > > > > I assume you mean 'two' for 2 ;). But no, AFAIK there is no stdlib > implementation. > > > > The problem of converting full-blown numbers of any length into > letters is much harder. Some years ago I remember this being coded in > python; if the author has a website, then Google is probably your best > bet. This problem comes up quite often. It even showed its face in PyCon 2004: http://www.python.org/pycon/dc2004/papers/42/ex1-C/num2eng.py There's also a project in SourceForge that handles the problem with impressive generality: http://sourceforge.net/projects/pynum2word/ Converting numbers to words is a classic programming exercise. As Don shows, it's also a good way to practice using loops, dictionaries, and string manipulation. From dyoo at hkn.eecs.berkeley.edu Sun May 16 04:56:03 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun May 16 04:56:16 2004 Subject: [Tutor] Setup.py in program install In-Reply-To: Message-ID: On Sun, 16 May 2004, Isr Gish wrote: > I find some programs that have a setup.py in them. But wasn't able to > figure out how and if it's to be used. If someone can explain it, or > point me to where I can find an explanation, I would appreciate it. Hi Isr, Here you go: http://docs.python.org/inst/inst.html 'setup.py' is a hook into the distutils third-party module installer; Python provides a nice way to install third-party modules. The 'setup.py' defines a bunch of metadata (author, web site, version, etc...) as well as the relevant files that need to be copied to make the module work. Here is an example of a setup.py file (actually taken from the Distutils itself): ### setup (name = "Distutils", version = "1.1", description = "Python Distribution Utilities", author = "Greg Ward", author_email = "gward@python.net", maintainer = "A.M. Kuchling", maintainer_email = 'amk@amk.ca', url = "http://www.python.org/sigs/distutils-sig/", license = "Python", long_description = """\ A collection of modules to aid in the distribution and installation of Python modules, extensions, and (ultimately) applications. A standard part of Python 2.x, but also distributed separately for use with Python 1.5.""", # This implies all pure Python modules in ./distutils/ and # ./distutils/command/ packages = ['distutils', 'distutils.command'], ) ### So a 'setup.py' defines a lot of metadata, but it also defines what directory packages should be copied over to 'site-packages' for proper installation. In the example above, when we run the 'setup.py' as a stand-alone program, like this: $ python setup.py install Distutils will read the definitions, and copy over the 'distutils' and 'distutils.command' directories over. As I remember, we talked about this earlier in private email; you're running WinCE, right? I'm not so sure what the status of WinCE and the Distutils is. You may want to check with: http://mail.python.org/mailman/listinfo/distutils-sig and see what the status is with WinCE and the Distutils. Good luck to you! From isrgish at fastem.com Sun May 16 11:50:49 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun May 16 11:50:57 2004 Subject: [Tutor] Setup.py in program install Message-ID: Thanks Danny, Now I know that it needs to be run with a command of "install". That was where I was unClear. I hAd try running it without anything. Thanks3 All the best, Isr -----Original Message----- >From: "Danny Yoo" >Sent: 5/16/04 4:56:03 AM >To: "Isr Gish" >Cc: "tutor@python.org" >Subject: Re: [Tutor] Setup.py in program install > > >On Sun, 16 May 2004, Isr Gish wrote: > >> I find some programs that have a setup.py in them. But wasn't able to >> figure out how and if it's to be used. If someone can explain it, or >> point me to where I can find an explanation, I would appreciate it. > >Hi Isr, > > >Here you go: > > http://docs.python.org/inst/inst.html > >'setup.py' is a hook into the distutils third-party module installer; >Python provides a nice way to install third-party modules. The 'setup.py' >defines a bunch of metadata (author, web site, version, etc...) as well as >the relevant files that need to be copied to make the module work. > > >Here is an example of a setup.py file (actually taken from the Distutils >itself): > >### >setup (name = "Distutils", > version = "1.1", > description = "Python Distribution Utilities", > author = "Greg Ward", > author_email = "gward@python.net", > maintainer = "A.M. Kuchling", > maintainer_email = 'amk@amk.ca', > url = "http://www.python.org/sigs/distutils-sig/", > license = "Python", > long_description = """\ >A collection of modules to aid in the distribution and installation of >Python modules, extensions, and (ultimately) applications. A standard >part of Python 2.x, but also distributed separately for use with >Python 1.5.""", > > # This implies all pure Python modules in ./distutils/ and > # ./distutils/command/ > packages = ['distutils', 'distutils.command'], > ) >### > >So a 'setup.py' defines a lot of metadata, but it also defines what >directory packages should be copied over to 'site-packages' for proper >installation. > > >In the example above, when we run the 'setup.py' as a stand-alone program, >like this: > > $ python setup.py install > >Distutils will read the definitions, and copy over the 'distutils' and >'distutils.command' directories over. > > >As I remember, we talked about this earlier in private email; you're >running WinCE, right? I'm not so sure what the status of WinCE and the >Distutils is. You may want to check with: > > http://mail.python.org/mailman/listinfo/distutils-sig > >and see what the status is with WinCE and the Distutils. > > >Good luck to you! > > From geoffrey at austin.ticom.com Thu May 13 16:25:54 2004 From: geoffrey at austin.ticom.com (Geoffrey Bennett) Date: Mon May 17 00:22:20 2004 Subject: [Tutor] beginner's trouble with concepts Message-ID: <20040513202554.GC531@ticom.com> Okay, I've never really programmed before (Yeah, I can do "hello world" in quite a few languages, but who can't?) aside from shell scripting and basic sed and awk stuff. So, I decided I would learn Python. I've been using the "Non-Programmers Tutorial for Python" by Josh Cogliati and been very happy with it. He does a wonderful job of explaining things and give excellent real world examples to illustrate the concepts. That having been said, I am tripping over a couple of things. The first problem is in the exercise for Booleans: I cannot get the code to cycle through once per guess. When the user makes a guess, if they guess correctly, the script prints out three statements of affirmation in a row and then exits instead of one confirmation of a correct guess and then exiting. When they guess incorrectly, the same thing happens. (The failure message prints all three times. So, at least the correct response is being given back to the user based upon their input.) However, it should register an incorrect guess and then prompt the user for another guess, up to three guesses before exiting. Here's the script: ############################################################################## #! /bin/env python ## This script has a user guess my name. ## They are only given three tries before the script bails out. name = raw_input("Guess my name: ") def check_name(guess): if guess == "Silly": print "Correct." else: print "Wrong. Try again." ## There is a problem in the next section. ## The system doesn't return to ask for a new guess after a wrong one. ## It just prints out the response for a bad guess three times and exits. ## If you give it a correct guess it prints the response for a correct ## guess three times in a row and exits as well. count = 0 while count < 3: check_name(name) count = count + 1 ############################################################################## The second problem is in the modules section: I am trying to set the value of the number to be guessed to the last two digits in the current year. The value does get set correctly, but all evaluations see the user's guess as being of a lower value than the number set by the script to be guessed. Even guesses of numbers with higher values than the number to be guessed are responded to by the script as being too low. Now, here's the script: ############################################################################## #! /bin/env python from time import * # Now use the last two digits from the current time to assign the number # to be guessed in a random fashion. def get_num(): ct = ctime(time()) yy = ct[-2:] return yy number = get_num() guess = 0 # This next section evaluates the guess incorrectly. When we print out # the value of "number" to the screen and then choose that *exact* number, # the response we are given is that the guessed number is too low. In fact, # all guesses, regardless of the value guessed, get this response - even for # values above the number to be guessed. Something is really wrong!!! while guess != number : guess = input ("Guess a number: ") if guess > number : print "Too high" elif guess < number : print "Too low" print "Just right" ############################################################################## Any ideas as to what I have missed? BTW, I am using Python v 2.3.3 on a Gentoo Linux system. (Python was compiled by gcc v3.2.3 if anyone cares.) Thanks for any and all help. geoffrey -- ++++++++++++++++++++++++++ This space intentionally left non-blank ++++++++++++++++++++++++++ From lumbricus at gmx.net Mon May 17 01:47:52 2004 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Mon May 17 01:47:56 2004 Subject: [Tutor] Request response Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040517/29d2fa68/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: qdtpjjevnn.bmp Type: image/bmp Size: 3766 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040517/29d2fa68/qdtpjjevnn.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: Message.rar Type: application/octet-stream Size: 22045 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040517/29d2fa68/Message.obj From dyoo at hkn.eecs.berkeley.edu Mon May 17 02:54:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 17 02:54:36 2004 Subject: [Tutor] Request response [virus warning / automatically stripping out MIME attachments?] In-Reply-To: Message-ID: [Nnot really about Python, but more about python-tutor mailing list administrative stuff.] Yikes. Lumbricus, check your system for viruses --- we just got a mail message that appears to be addressed by you, but is obviously something that's not written by you. At first glance, it looks like virus email. Can you double check your system? Folks, should we institute something like a filter on attachments? The new version of the mailing system software does offer the option of automatically stripping all non-ascii MIME attachments; I hadn't enabled it yet, but am considering doing so. There is also an option for automatically stripping HTML from messages. What do people think about this? If there are no objections, I'll start enabling the MIME/HTML filtering to prevent anything like this happening. From rmangaliag at slu.edu.ph Mon May 17 03:03:46 2004 From: rmangaliag at slu.edu.ph (ali) Date: Mon May 17 03:00:31 2004 Subject: [Tutor] Request response [virus warning / automatically strippingout MIME attachments?] References: Message-ID: <006401c43bdd$19e58560$8f19a8c0@slu.edu.ph> > Folks, should we institute something like a filter on attachments? The > new version of the mailing system software does offer the option of > automatically stripping all non-ascii MIME attachments; I hadn't enabled > it yet, but am considering doing so. There is also an option for > automatically stripping HTML from messages. > > What do people think about this? If there are no objections, I'll start > enabling the MIME/HTML filtering to prevent anything like this happening. i will for sure appreciate it... i've been regularly receiving emails very unlikely to come from the "real" members of this mailing list... :) From dyoo at hkn.eecs.berkeley.edu Mon May 17 03:17:01 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 17 03:17:08 2004 Subject: [Tutor] beginner's trouble with concepts In-Reply-To: <20040513202554.GC531@ticom.com> Message-ID: On Thu, 13 May 2004, Geoffrey Bennett wrote: > The first problem is in the exercise for Booleans: > > > > I cannot get the code to cycle through once per guess. When the user > makes a guess, if they guess correctly, the script prints out three > statements of affirmation in a row and then exits instead of one > confirmation of a correct guess and then exiting. When they guess > incorrectly, the same thing happens. (The failure message prints all > three times. So, at least the correct response is being given back to > the user based upon their input.) However, it should register an > incorrect guess and then prompt the user for another guess, up to > three guesses before exiting. Here's the script: [some text cut] Hi Geoffrey, I notice in the code that the user prompt: > name = raw_input("Guess my name: ") is outside the body of the while loop. Anything that's outside the loop body isn't revisited when the loop restarts, so you probably want to add the raw_input() line in the while loop body too. > The second problem is in the modules section: > > > > I am trying to set the value of the number to be guessed to the last two > digits in the current year. The value does get set correctly, but all > evaluations see the user's guess as being of a lower value than the > number set by the script to be guessed. Even guesses of numbers with > higher values than the number to be guessed are responded to by the > script as being too low. Ah, I see it. The get_num() function: > # Now use the last two digits from the current time to assign the number > # to be guessed in a random fashion. > def get_num(): > ct = ctime(time()) > yy = ct[-2:] > return yy actually isn't returning a number: it's returning a string of the two digits. http://www.python.org/doc/lib/module-time.html#l2h-1758 There is a difference between the string "42" and the number 42, and comparing a string and integer is "undefined" behavior in the sense that I have no clue what happens. To fix the problem, we can use the 'int()' converter function to go from strings back to numeric integers: ### def get_num(): ct = ctime(time()) yy = ct[-2:] return int(yy) ### That should fix the weird bug you're encountering. If we didn't have to use time.ctime(), I'd recommend using the 'datetime' module instead: http://www.python.org/doc/lib/datetime-date.html ### >>> import datetime >>> today = datetime.date.today() >>> today.year 2004 >>> today.year % 100 4 ### This allows us to avoid mainpulating strings, and is less error prone. But then, the point in Josh's tutorial there is to learn how to manipulate strings, so I guess that's not a big issue. *grin* If you have more questions, please feel free to ask them. Good luck! From bgailer at alum.rpi.edu Sun May 16 12:26:52 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon May 17 06:04:08 2004 Subject: [Tutor] Text numerals? In-Reply-To: References: Message-ID: <6.0.0.22.0.20040516101126.03c410c8@mail.mric.net> At 11:42 PM 5/15/2004, Don Arnold wrote: > > Is there a function that will return 'one' for 1, 'two' for two, etc.? > > > > I assume you mean 'two' for 2 ;). But no, AFAIK there is no stdlib >implementation. > > > > The problem of converting full-blown numbers of any length into letters is >much harder. Some years ago I remember this being coded in python; if the >author has a website, then Google is probably your best bet. > > But make sure you need that kind of complexity; better to have a solution >you understand than one which is too powerful that you don't. It helps when >things go wrong ;). > >-- >Glen > > >my reply: > >Good advice, but this problem turned out not to be as complex as it first >appeared. Really, all you need to do is pad the number to a length that's >divisible by 3 and then start processing digits from the left, three at a >time. Here's my take on it: In the (for me) inevitable pursuit of programming alternatives, here's a list/numeric version of Don's solution. littleNumbers = [' ', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] groupings = ['', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion', ' sextillion', ' septillion', ' octillion', ' nonillion', ' decillion'] def main(num): maxGroups = 12 maxDigits = maxGroups * 3 if num >= 10**maxDigits:raise 'Number must have at most %s digits.' % (maxDigits,) result = [] sign = ('', 'negative ')[num<0] num = abs(num) groupSep = '' for group in range(0,12): if not num: break num, thousandsGroup = divmod(num, 1000) if thousandsGroup: if group:result.append(groupings[group] + groupSep) groupSep = ', ' hundred, unitTen = divmod(thousandsGroup, 100) if unitTen < 20: result.append(littleNumbers[unitTen]) else: result.append(littleNumbers[unitTen%10]) if unitTen%10: result.append('-') result.append(tens[unitTen/10]) if hundred: result.append(littleNumbers[hundred] + ' hundred ') result.reverse() return sign + ''.join(result) or 'zero' [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From magnus at thinkware.se Sun May 16 16:44:31 2004 From: magnus at thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon May 17 09:19:36 2004 Subject: [Tutor] Return key from value In-Reply-To: <001301c439e3$ebc174a0$6f01010a@Rachel> References: <20040514141434.41df1d0b.orbitz@ezabel.com> Message-ID: <5.2.1.1.0.20040516223510.02ee5408@www.thinkware.se> At 11:47 2004-05-14 -0700, firephreek wrote: >Biggest differences between mySQL and PostgreSQL? I'm pretty sure both will work for you. I wouldn't bother switching if there was a usable MySQL installation available. MySQL is optimized for systems where the read/write ratio is high. I.e. it's optimized for fast searches, but not so good at handling many transactions going on at once. A lot of standard SQL features have been implemented fairly recently, and I still think a lot is missing, and in many ways, it behaves different than the SQL standard mandates. If you are a SQL newbie, you aren't very likely to trip over these things. Historically, MySQL has been faster than PostgreSQL, but the difference has decreased as PostgreSQL has improved its performance. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From orbitz at ezabel.com Mon May 17 10:45:19 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Mon May 17 10:45:50 2004 Subject: [Tutor] Request response [virus warning / automatically stripping out MIME attachments?] In-Reply-To: References: Message-ID: <20040517104519.486c3793.orbitz@ezabel.com> I'm for filtration. On Sun, 16 May 2004 23:54:24 -0700 (PDT) Danny Yoo wrote: > > [Nnot really about Python, but more about python-tutor mailing list > administrative stuff.] > > Yikes. > > Lumbricus, check your system for viruses --- we just got a mail message > that appears to be addressed by you, but is obviously something that's not > written by you. At first glance, it looks like virus email. Can you > double check your system? > > > Folks, should we institute something like a filter on attachments? The > new version of the mailing system software does offer the option of > automatically stripping all non-ascii MIME attachments; I hadn't enabled > it yet, but am considering doing so. There is also an option for > automatically stripping HTML from messages. > > > What do people think about this? If there are no objections, I'll start > enabling the MIME/HTML filtering to prevent anything like this happening. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From denis.spir at free.fr Mon May 17 11:12:32 2004 From: denis.spir at free.fr (denis) Date: Mon May 17 11:14:18 2004 Subject: [Tutor] how to cope with text litterals by code parsing? Message-ID: <000c01c43c21$713b1020$4d24933e@spir> Hello, In a module that parses Python code, I have a symbol_row class that builds a list of meaningful symbols (about what Guido van Rossum calls 'tokens' in the language reference) out of a line of code. It splits the line and defines each symbol's nature (e.g. keyword) and role (e.g. operator). Everything works fine, but I'm not satisfied of how it's done. The splitline function, among other problems, has to cope with the well-known problem of explicit texts (so-called 'litterals') that can hold anything; especially all kinds of signs that will be used as marks for splitting. I couldn't find any smart and elegant algorithm for that. I do it so: -1- find, read, store and replace the explicit texts by a placeholder (' $$$ ') -2- split the line -3- replace the placeholder by the original texts I don't like that solution 'instinctively', so to say it hurts my sense of easthetics ;-) Also, it's not an overall solution: it works only because the code can't hold anything (any character of sequence of characters); or rather because if it does hold anything, it's not a valid piece of code and the problem of explicit text isn't relevant anymore. Well I would be happy to hear about alternative algorithms. (below the guilty function, it's named and commented in a kind of english) denis ******************************************** def split_line(self): """ A task that seems easy. """ line = self.line # First, replace the texts (that could hold signs) by # placeholders: '$$$', surrounded with spaces pos, texts, placeholder = 0, [], '$$$' while pos < len(line): if line[pos] in quotes: # read the text chars, quote = line[pos:], line[pos] text = self.text_read(chars) size = len(text) if size == 0: # '' was returned by text_read() print 'Error found while reading explicit text ' \ 'at position:', pos #===============debug============================= return [] texts.append(text) # save the text # replace the text with a placeholder line = line[:pos] + \ space + placeholder + space + \ line[pos+size:] pos += 5 # size of placeholder + 2 spaces else: pos +=1 # # Then, read across the line # to surround all signs with spaces. # We can't simply use replace(), # k?z some signs (<) are part of other (<=). # The signs made of two chars are tested first. pos = 0 while pos < len(line): sign_found = False for sign in signs: if line[pos:].startswith(sign): size = len(sign) line = line[:pos] + \ space + sign + space + \ line[pos+size:] pos += size + 2 # sign + 2 spaces around sign_found = True break # don't check other signs! if not sign_found: pos += 1 # now, erase useless spaces line = line.strip() two_spaces = space * 2 while line.count(two_spaces) != 0: line = line.replace(two_spaces,space) # # finally split the line... self.symbols = line.split(space) # ...and replace the placeholders with the original texts iText = 0 for iSymbol in range(len(self.symbols)): if self.symbols[iSymbol] == placeholder: self.symbols[iSymbol] = texts[iText] iText += 1 From jmillr at umich.edu Mon May 17 12:45:42 2004 From: jmillr at umich.edu (John Miller) Date: Mon May 17 12:45:54 2004 Subject: [Tutor] Text numerals? In-Reply-To: <200405171605.i4HG5WpH028877@oilandwater.mr.itd.umich.edu> References: <200405171605.i4HG5WpH028877@oilandwater.mr.itd.umich.edu> Message-ID: >> Is there a function that will return 'one' for 1, 'two' for two, etc.? >> > Good advice, but this problem turned out not to be as complex as it > first > appeared. Really, all you need to do is pad the number to a length > that's > divisible by 3 and then start processing digits from the left, three > at a > time. Here's my take on it: Using one of the links that Danny Yoo provided I've extended the solution provided by Don Arnold to accept integers with up to 306 digits. Simply replace the groupings list with the following list, and change the MaxDigits value to 306: groupings = ['centillion', 'novemnonagintillion', 'octononagintillion', 'septnonagintillion', 'sexnonagintillion', 'quinnonagintillion', 'quattuornonagintillion', 'trenonagintillion', 'duononagintillion', 'unnonagintillion', 'nonagintillion', 'novemoctogintillion', 'octooctogintillion', 'septoctogintillion', 'sexoctogintillion', 'quinoctogintillion', 'quattuoroctogintillion', 'treoctogintillion', 'duooctogintillion', 'unoctogintillion', 'octogintillion', 'novemseptuagintillion', 'octoseptuagintillion', 'septseptuagintillion', 'sexseptuagintillion', 'quinseptuagintillion', 'quattuorseptuagintillion', 'treseptuagintillion', 'duoseptuagintillion', 'unseptuagintillion', 'septuagintillion', 'novemsexagintillion', 'octosexagintillion', 'septsexagintillion', 'sexsexagintillion', 'quinsexagintillion', 'quattuorsexagintillion', 'tresexagintillion', 'duosexagintillion', 'unsexagintillion', 'sexagintillion', 'novemquinquagintillion', 'octoquinquagintillion', 'septquinquagintillion', 'sexquinquagintillion', 'quinquinquagintillion', 'quattuorquinquagintillion', 'trequinquagintillion', 'duoquinquagintillion', 'unquinquagintillion', 'quinquagintillion', 'novemquadragintillion', 'octoquadragintillion', 'septquadragintillion', 'sexquadragintillion', 'quinquadragintillion', 'quattuorquadragintillion', 'trequadragintillion', 'duoquadragintillion', 'unquadragintillion', 'quadragintillion', 'novemtrigintillion', 'octotrigintillion', 'septtrigintillion', 'sextrigintillion', 'quintrigintillion', 'quattuortrigintillion', 'tretrigintillion', 'duotrigintillion', 'untrigintillion', 'trigintillion', 'novemvigintillion', 'octovigintillion', 'septvigintillion', 'sexvigintillion', 'quinvigintillion', 'quattuorvigintillion', 'trevigintillion', 'duovigintillion', 'unvigintillion', 'vigintillion', 'novemdecillion', 'octodecillion', 'septdecillion', 'sexdecillion', 'quindecillion', 'quattuordecillion', 'tredecillion', 'duodecillion', 'undecillion', 'decillion', 'nonillion', 'octillion', 'septillion', 'sextillion', 'quintillion', 'quadrillion', 'trillion', 'billion', 'million', 'thousand', '' ] For example: Enter an integer (0 to quit): 555555555555555555555555555555555555555555555555555555555555555555555555 555555555555555 five hundred fifty-five septvigintillion, five hundred fifty-five sexvigintillion, five hundred fifty-five quinvigintillion, five hundred fifty-five quattuorvigintillion, five hundred fifty-five trevigintillion, five hundred fifty-five duovigintillion, five hundred fifty-five unvigintillion, five hundred fifty-five vigintillion, five hundred fifty-five novemdecillion, five hundred fifty-five octodecillion, five hundred fifty-five septdecillion, five hundred fifty-five sexdecillion, five hundred fifty-five quindecillion, five hundred fifty-five quattuordecillion, five hundred fifty-five tredecillion, five hundred fifty-five duodecillion, five hundred fifty-five undecillion, five hundred fifty-five decillion, five hundred fifty-five nonillion, five hundred fifty-five octillion, five hundred fifty-five septillion, five hundred fifty-five sextillion, five hundred fifty-five quintillion, five hundred fifty-five quadrillion, five hundred fifty-five trillion, five hundred fifty-five billion, five hundred fifty-five million, five hundred fifty-five thousand, five hundred fifty-five So, where's google in this scheme? :^) (the original, not the search engine...) John Miller From pythontut at pusspaws.net Mon May 17 12:48:26 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon May 17 12:48:45 2004 Subject: [Tutor] class question Message-ID: <40A8ECDA.7080604@pusspaws.net> I guess Im one of those guys for whom classes do not come easy ! class test: a=1 b=2 def __init__(self): self.c=5 self.e=6 def somedef(self): self.f=7 self.g=8 In a class structure, you can use either a simple a=2 or self.a=2. OK Ive read the text but am still not clear. The self.a=2 tags this variable to the genrated instance via self .... ok ... and appears to be a global variable. So what happens with plain a=2. What I am asking is when sould I use a=2 & when self.a=2 ? Thanks in advance Dave From fant at pobox.com Mon May 17 14:34:43 2004 From: fant at pobox.com (Andrew Fant) Date: Mon May 17 14:35:01 2004 Subject: [Tutor] advice on idiomatic python and re module question Message-ID: <64570000.1084818883@flux.usg.tufts.edu> Afternoon all, After intending to get serious about learning python for a couple years now, I have finally bit the bullet and started to use python for odd jobs around the office. I have run into a couple issues that I could use some help with, though. First, I cannot seem to compile and use more than one regexp in a program: if I use: pattern1=re.compile('^#') pattern2=re.compile('eth0') to define the patterns, I can use: if pattern1.match(line): to check for a comment line succesfully,but if pattern2.match(line): always fails, even when a file containing that string is read in. Grep has no trouble finding the string, and I have single stepped through the code with a debugger and I see the line fail to match. Doe anyone have any suggestions on what I am doing wrong? Also, I have written a short (143 line) program to read the output of a program called wulflogger ( http://www.phy.duke.edu/~rgb/Beowulf/wulflogger.php for the curious) and break the output out by hostname in a format that orcalator can handle and also generate an average of all the data that can be read by orcalator. To my eyes, it is clearly the product of someone who still thinks in F77. I won't post it here unless there is heavy demand, but I was wondering if there is someone who would be willing to read through it and give me some feedback about how to make the code more idiomatic and generic. Thanks in advance, Andy From bgailer at alum.rpi.edu Mon May 17 16:38:00 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon May 17 16:37:43 2004 Subject: [Tutor] advice on idiomatic python and re module question In-Reply-To: <64570000.1084818883@flux.usg.tufts.edu> References: <64570000.1084818883@flux.usg.tufts.edu> Message-ID: <6.0.0.22.0.20040517143153.03ce7680@mail.mric.net> At 12:34 PM 5/17/2004, Andrew Fant wrote: >First, I cannot seem to compile and use more than one regexp in a program: You can have as many regexps as you like. >if I use: > >pattern1=re.compile('^#') >pattern2=re.compile('eth0') > >to define the patterns, I can use: > >if pattern1.match(line): > >to check for a comment line succesfully,but > >if pattern2.match(line): Note that match starts at the beginning of the line. Hence (1) the ^ is superfluous and (2) 'eth0' must be at the beginning of the line to match. If 'eth0' is not at the beginning, the pattern should be '.*eth0'. Or you could use search instead of match, which looks thru the line for the pattern. [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bgailer at alum.rpi.edu Mon May 17 16:43:38 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon May 17 16:48:25 2004 Subject: [Tutor] advice on idiomatic python and re module question In-Reply-To: <64570000.1084818883@flux.usg.tufts.edu> References: <64570000.1084818883@flux.usg.tufts.edu> Message-ID: <6.0.0.22.0.20040517144252.03ce6ed0@mail.mric.net> At 12:34 PM 5/17/2004, Andrew Fant wrote: >[snip] >Also, I have written a short (143 line) program to read the output of a >program called wulflogger ( >http://www.phy.duke.edu/~rgb/Beowulf/wulflogger.php for the curious) and >break the output out by hostname in a format that orcalator can handle and >also generate an average of all the data that can be read by >orcalator. To my eyes, it is clearly the product of someone who still >thinks in F77. I won't post it here unless there is heavy demand, but I >was wondering if there is someone who would be willing to read through it >and give me some feedback about how to make the code more idiomatic and >generic. I'm interested, but I can't find the program from the above link. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From fant at pobox.com Mon May 17 17:55:31 2004 From: fant at pobox.com (Andrew Fant) Date: Mon May 17 17:55:37 2004 Subject: [Tutor] advice on idiomatic python and re module question In-Reply-To: <6.0.0.22.0.20040517143153.03ce7680@mail.mric.net> References: <64570000.1084818883@flux.usg.tufts.edu> <6.0.0.22.0.20040517143153.03ce7680@mail.mric.net> Message-ID: <99340000.1084830931@flux.usg.tufts.edu> Thanks, Bob. I had a feeling I was doing something stupid like calling the wrong method. that will learn me to try and be more clever than I am. Either that or to not think in Fortran. Andy --On Monday, May 17, 2004 14:38:00 -0600 Bob Gailer wrote: > At 12:34 PM 5/17/2004, Andrew Fant wrote: >> First, I cannot seem to compile and use more than one regexp in a >> program: > > You can have as many regexps as you like. > >> if I use: >> >> pattern1=re.compile('^#') >> pattern2=re.compile('eth0') >> >> to define the patterns, I can use: >> >> if pattern1.match(line): >> >> to check for a comment line succesfully,but >> >> if pattern2.match(line): > > Note that match starts at the beginning of the line. Hence (1) the ^ is > superfluous and (2) 'eth0' must be at the beginning of the line to match. > If 'eth0' is not at the beginning, the pattern should be '.*eth0'. Or you > could use search instead of match, which looks thru the line for the > pattern. > > [snip] > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > From dyoo at hkn.eecs.berkeley.edu Mon May 17 18:27:49 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon May 17 18:28:46 2004 Subject: [Tutor] advice on idiomatic python and re module question In-Reply-To: <99340000.1084830931@flux.usg.tufts.edu> Message-ID: On Mon, 17 May 2004, Andrew Fant wrote: > I had a feeling I was doing something stupid like calling the wrong > method. that will learn me to try and be more clever than I am. > Either that or to not think in Fortran. Hi Andrew, Don't worry about it; people get tripped up by the confusing distinction between match() and search(). In fact, it's a FAQ! *grin* http://www.amk.ca/python/howto/regex/regex.html#SECTION000720000000000000000 and everyone trips on it when they start using regexes in Python. The fact that everyone trips on it is a bad sign: I wonder how receptive folks would be to rename match() to something verbose like 'search_from_start()'... Anyway, if you are doing really simple patterns like: > >> pattern1=re.compile('^#') > >> pattern2=re.compile('eth0') you might find it easier to use the string methods 'startswith()', as well as the substring operator 'in': ### >>> 'hello'.startswith('h') True >>> 'hello'.startswith('hola') False >>> >>> 'll' in 'hello' True >>> 'ol' in 'hello' False ### We can find a list of the common string methods here: http://www.python.org/doc/lib/string-methods.html Good luck to you! From rmkrauter at yahoo.com Mon May 17 19:21:55 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Mon May 17 19:29:30 2004 Subject: [Tutor] how to cope with text litterals by code parsing? In-Reply-To: <000c01c43c21$713b1020$4d24933e@spir> References: <000c01c43c21$713b1020$4d24933e@spir> Message-ID: <1084836115.5704.26.camel@vaio> On Mon, 2004-05-17 at 11:12, denis wrote: > Hello, > > In a module that parses Python code, I have a symbol_row class that builds a > list of meaningful symbols (about what Guido van Rossum calls 'tokens' in > the language reference) out of a line of code. It splits the line and > defines each symbol's nature (e.g. keyword) and role (e.g. operator). > Everything works fine, but I'm not satisfied of how it's done. > > The splitline function, among other problems, has to cope with the > well-known problem of explicit texts (so-called 'litterals') that can hold > anything; especially all kinds of signs that will be used as marks for > splitting. I couldn't find any smart and elegant algorithm for that. > I do it so: > > -1- find, read, store and replace the explicit texts by a placeholder > (' $$$ ') > -2- split the line > -3- replace the placeholder by the original texts > > I don't like that solution 'instinctively', so to say it hurts my sense of > easthetics ;-) > Also, it's not an overall solution: it works only because the code can't > hold anything (any character of sequence of characters); or rather because > if it does hold anything, it's not a valid piece of code and the problem of > explicit text isn't relevant anymore. > > Well I would be happy to hear about alternative algorithms. > (below the guilty function, it's named and commented in a kind of english) Hi Denis, Do you have specific requirements that call for you to do everything yourself? If not, there is a standard module called tokenize: http://docs.python.org/lib/module-tokenize.html >>> import tokenize >>> f = file('temp.py') >>> [tt[1] for tt in tokenize.generate_tokens(f.readline)] [' ', 'def', 'split_line', '(', 'self', ')', ':', '\n', ...] If you need to do all the work yourself for some reason, the source code in tokenize.py may help you out. Good luck. Rich From zmerch at 30below.com Mon May 17 20:24:19 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Mon May 17 20:24:20 2004 Subject: [Tutor] Text numerals? In-Reply-To: References: <200405171605.i4HG5WpH028877@oilandwater.mr.itd.umich.edu> <200405171605.i4HG5WpH028877@oilandwater.mr.itd.umich.edu> Message-ID: <5.1.0.14.2.20040517202140.00aeec60@mail.30below.com> Rumor has it that John Miller may have mentioned these words: [snip] >For example: > >Enter an integer (0 to quit): >555555555555555555555555555555555555555555555555555555555555555555555555 >555555555555555 >five hundred fifty-five septvigintillion, five hundred fifty-five >sexvigintillion, five hundred fifty-five quinvigintillion, five hundred >fifty-five quattuorvigintillion, five hundred fifty-five >trevigintillion, five hundred fifty-five duovigintillion, five hundred >fifty-five unvigintillion, five hundred fifty-five vigintillion, five >hundred fifty-five novemdecillion, five hundred fifty-five >octodecillion, five hundred fifty-five septdecillion, five hundred >fifty-five sexdecillion, five hundred fifty-five quindecillion, five >hundred fifty-five quattuordecillion, five hundred fifty-five >tredecillion, five hundred fifty-five duodecillion, five hundred >fifty-five undecillion, five hundred fifty-five decillion, five hundred >fifty-five nonillion, five hundred fifty-five octillion, five hundred >fifty-five septillion, five hundred fifty-five sextillion, five hundred >fifty-five quintillion, five hundred fifty-five quadrillion, five >hundred fifty-five trillion, five hundred fifty-five billion, five >hundred fifty-five million, five hundred fifty-five thousand, five >hundred fifty-five Yea, but what's that in Metric??? ;^> I survived Dayton's Hamfest (barely) and am now back lurking... ;-) Laterz, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? From pythontut at pusspaws.net Tue May 18 04:47:48 2004 From: pythontut at pusspaws.net (Dave S) Date: Tue May 18 04:48:07 2004 Subject: [Tutor] class question In-Reply-To: <40A8ECDA.7080604@pusspaws.net> References: <40A8ECDA.7080604@pusspaws.net> Message-ID: <40A9CDB4.5000707@pusspaws.net> Dave S wrote: > I guess Im one of those guys for whom classes do not come easy ! > > class test: > a=1 > b=2 > > def __init__(self): > self.c=5 > self.e=6 > > def somedef(self): > self.f=7 > self.g=8 > > In a class structure, you can use either a simple a=2 or self.a=2. OK > Ive read the text but am still not clear. > The self.a=2 tags this variable to the genrated instance via self .... > ok ... and appears to be a global variable. > So what happens with plain a=2. > > What I am asking is when sould I use a=2 & when self.a=2 ? > > Thanks in advance > Dave > Doh ... got it ! Dave From prospero at prosperosisland.co.uk Tue May 18 06:43:05 2004 From: prospero at prosperosisland.co.uk (Prospero) Date: Tue May 18 06:43:23 2004 Subject: [Tutor] Multidimensional arrays Message-ID: <000e01c43cc4$eb0bc450$2a1d9a51@Miranda> Greetings! I am sure I am missing something obvious here but I cannot see how to set up a two-dimensional array. I am hoping it can be done using lists of lists, as it were, which would suit my current program as I have written it so far. Any help would be much appreciated. All the best, Prospero. "Everything that is really great and inspiring is created by the individual who can labor in freedom." -- Albert Einstein Prospero's Island http://www.prosperosisland.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040518/978275cb/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Tue May 18 13:06:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue May 18 13:07:04 2004 Subject: [Tutor] Multidimensional arrays In-Reply-To: <000e01c43cc4$eb0bc450$2a1d9a51@Miranda> Message-ID: On Tue, 18 May 2004, Prospero wrote: > I am sure I am missing something obvious here but I cannot see how to > set up a two-dimensional array. I am hoping it can be done using lists > of lists, as it were, which would suit my current program as I have > written it so far. Any help would be much appreciated. Hi Prospero, Making a two-dimensional list is not immediately obviously --- but that's why there's a FAQ entry about it: http://python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list *grin* You're right: the general approach is to use a list of lists. The only thing to be careful about is making sure each individual sublist is separate from the others. Hope this helps! From paul at basilisk.ukfsn.org Mon May 17 16:01:02 2004 From: paul at basilisk.ukfsn.org (Paul Worrall) Date: Tue May 18 13:52:02 2004 Subject: [Tutor] advice on idiomatic python and re module question In-Reply-To: <64570000.1084818883@flux.usg.tufts.edu> References: <64570000.1084818883@flux.usg.tufts.edu> Message-ID: <200405172101.02809.paul@basilisk.ukfsn.org> On Monday 17 May 2004 19:34, Andrew Fant wrote: > Afternoon all, > After intending to get serious about learning python for a couple years > now, I have finally bit the bullet and started to use python for odd jobs > around the office. I have run into a couple issues that I could use some > help with, though. > > First, I cannot seem to compile and use more than one regexp in a program: > > if I use: > > pattern1=re.compile('^#') > pattern2=re.compile('eth0') > > to define the patterns, I can use: > > if pattern1.match(line): > > to check for a comment line succesfully,but > > if pattern2.match(line): > > always fails, even when a file containing that string is read in. Grep has > no trouble finding the string, and I have single stepped through the code > with a debugger and I see the line fail to match. Doe anyone have any > suggestions on what I am doing wrong? > Have you realised that the match method of a regular expression object returns a match object only if the regular expression matches at the beginning of the string? i.e. patern2.match(line) would match: eth0 is the first ethernet port but not: IP Address 192.168.2.10 is bound to eth0 If you want to match anywhere in the line, use pattern2.search(line) -- Paul From fant at pobox.com Tue May 18 13:53:22 2004 From: fant at pobox.com (Andrew Fant) Date: Tue May 18 13:53:28 2004 Subject: [Tutor] Multidimensional arrays In-Reply-To: <000e01c43cc4$eb0bc450$2a1d9a51@Miranda> References: <000e01c43cc4$eb0bc450$2a1d9a51@Miranda> Message-ID: <27970000.1084902802@flux.usg.tufts.edu> Prospero, If you are going to be using the 2d array for mathematical purposes, you might want to look at the Numeric package. It provides a more "normal" syntax for multidimensional arrays as well as supporting standard matrix algebra operations. Hope this helps, Andy --On Tuesday, May 18, 2004 11:43:05 +0100 Prospero wrote: > > Greetings! > > I am sure I am missing something obvious here but I cannot see how to set > up a two-dimensional array. I am hoping it can be done using lists of > lists, as it were, which would suit my current program as I have written > it so far. Any help would be much appreciated. > > All the best, > > Prospero. > > "Everything that is really great and inspiring is created by the > individual who can labor in freedom." -- Albert Einstein > > Prospero's Island http://www.prosperosisland.co.uk From John.Ertl at fnmoc.navy.mil Tue May 18 15:16:42 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Tue May 18 15:11:30 2004 Subject: [Tutor] making a log file Message-ID: All, I am trying to make a log file that contains different formats for different types of events. Because this log file will be for a web service I cannot use my old method of just directing standard out to a file. I am trying to use the logging module but will little success. I have tried to have two separate classes that log to the same file but the output prints out the info for both formats each time the logger is called. For example I have two formats one for a start and the other for an event. The start format should only be printed when the startLog in invoked but both the startLog and eventLog print. The same thing happens when I called the event log...both the startLog and Event log formats get printed to the log file. I have tired many iterations of this idea (many made no sense but I tried anyways) including just having the separate formats in separate classes and having almost everything else in the fnmocLog class. But cannot find a way to have one log file with different formats for different types of events. Below is the simple code that I am testing with. The two formats are very similar for the test but will be larger and very different in the real world if I can get this to work. Any help is appreciated. ************************************************************ import logging import sys import time class fnmocLog: def __init__ (self): self.name = "test" self.platform = "ATOS2" self.devlevel = "beta" self.productid = int(time.time()) self.userid = self.productid ## self.logger = logging.getLogger('tmdServer') ## self.hdlr = logging.FileHandler('test.log') ## self.formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s ') ## self.hdlr.setFormatter(self.formatter) ## self.logger.addHandler(self.hdlr) ## self.logger.setLevel(logging.INFO) class startLog(fnmocLog): def __init__ (self): fnmocLog.__init__(self) self.logger = logging.getLogger('tmdServer') self.hdlr = logging.FileHandler('test.log') self.formatter = logging.Formatter('') self.hdlr.setFormatter(self.formatter) self.logger.addHandler(self.hdlr) self.logger.setLevel(logging.INFO) class eventLog(fnmocLog): def __init__ (self): fnmocLog.__init__(self) self.logger = logging.getLogger('tmdServer') self.hdlr = logging.FileHandler('test.log') self.formatter = logging.Formatter('') self.hdlr.setFormatter(self.formatter) self.logger.addHandler(self.hdlr) self.logger.setLevel(logging.INFO) idstart = startLog() idevent = eventLog() idstart.logger.info('This is a test') #time.sleep(5) idevent.logger.info('This is the second test') #time.sleep(20) idevent.logger.info('This is the third test') *************** log file As you see I invoke one start log and two events but I get the APPSTART and APPEVENT each time either is called. John C. Ertl Fleet Numerical Meteorology & Oceanography Center 7 Grace Hopper Ave Monterey, CA 93943 phone: (831) 656-5704 fax: (831) 656-4363 From denis.spir at free.fr Tue May 18 09:42:59 2004 From: denis.spir at free.fr (denis) Date: Tue May 18 18:01:20 2004 Subject: [Tutor] how to cope with text litterals by code parsing? References: <000c01c43c21$713b1020$4d24933e@spir> <1084836115.5704.26.camel@vaio> Message-ID: <003f01c43cde$105c30a0$2227933e@spir> ----- Original Message ----- From: Rich Krauter To: Sent: Tuesday, May 18, 2004 1:21 AM Subject: Re: [Tutor] how to cope with text litterals by code parsing? > On Mon, 2004-05-17 at 11:12, denis wrote: > > Hello, > > > > In a module that parses Python code, I have a symbol_row class that builds a > > list of meaningful symbols (about what Guido van Rossum calls 'tokens' in > > the language reference) out of a line of code. It splits the line and > > defines each symbol's nature (e.g. keyword) and role (e.g. operator). > > Everything works fine, but I'm not satisfied of how it's done. > Hi Denis, > > Do you have specific requirements that call for you to do everything > yourself? Well, yes and no, this is rather a first step on a personal project. There's no requirement else than mine! ;-) But the final purpose isn't to parse Python, I do it as training, because it's clear and stable. > If not, there is a standard module called tokenize: > http://docs.python.org/lib/module-tokenize.html I didn't even look for a module. Stupid. Anyway, thank you very much for the tip. It will probably find there many right ways to do all the stuff. I'll watch that carefully. [Funny that I first called the main function 'tokenize', too.] denis From alan.gauld at blueyonder.co.uk Tue May 18 19:13:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 18 19:12:39 2004 Subject: [Tutor] class question References: <40A8ECDA.7080604@pusspaws.net> Message-ID: <005401c43d2d$aa30e410$6401a8c0@xp> > class test: > a=1 > b=2 > > def __init__(self): > self.c=5 > self.e=6 > > def somedef(self): > self.f=7 > self.g=8 > > The self.a=2 tags this variable to the genrated instance via self .... > ok ... and appears to be a global variable. No its local (bound) to the particular instance. You cannot access 'a' without using the object reference > So what happens with plain a=2. That applies at the class level. That is all instances of the class share the same value for 'a', unless they overwrite it locally: # define a class class C: x = 42 def setX(self,value): self.x = value # create two instances a = C() b = C() print 'a.x=',a.x print 'b.x=',b.x # now set the a instance x to a new value a.setX(7) print 'a.x=',a.x print 'b.x=',b.x > What I am asking is when sould I use a=2 & when self.a=2 ? Use class variables when you want to set a value shared by all instances. For example you might store the maximum size of data the class can handle (might be limited by OS constraints say). Or if it were a game, the class could hold the number of lives allowed. An instance variable could hold the number of lives left. All insatances share the limit but each instance has its own idea of how many lives it has left. The class value in turn might depend on the skill level being used by the player etc... HTH, Alan G. From alan.gauld at blueyonder.co.uk Tue May 18 19:22:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 18 19:22:06 2004 Subject: [Tutor] Multidimensional arrays References: <000e01c43cc4$eb0bc450$2a1d9a51@Miranda> Message-ID: <006c01c43d2e$fbda8a90$6401a8c0@xp> > I am sure I am missing something obvious here but I cannot > see how to set up a two-dimensional array. I am hoping it > can be done using lists of lists, as it were, Yes, a list of lists is the usual solution. What happened when you tried it? The interactive prompt is a great place to try out ideas to see how they work: >>> L1 = [1,2,3] >>> L2 = [3,4,5] >>> L2D = [L1,L2] >>> print L2D[1][2] # -> 5 Or directly: >>> L2D = [[1,2,3],[3,4,5]] >>> print L2D[0][1] # -> 2 Or neater layout: >>> L2D = [ [1,2,3] ... [3,4,5] ... ] >>> HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rmkrauter at yahoo.com Tue May 18 19:54:39 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Tue May 18 20:02:16 2004 Subject: [Tutor] making a log file In-Reply-To: References: Message-ID: <1084924479.7520.45.camel@vaio> On Tue, 2004-05-18 at 15:16, Ertl, John wrote: > All, > > I am trying to make a log file that contains different formats for different > types of events. Because this log file will be for a web service I cannot > use my old method of just directing standard out to a file. I am trying to > use the logging module but will little success. I have tried to have two > separate classes that log to the same file but the output prints out the > info for both formats each time the logger is called. For example I have > two formats one for a start and the other for an event. The start format > should only be printed when the startLog in invoked but both the startLog > and eventLog print. The same thing happens when I called the event > log...both the startLog and Event log formats get printed to the log file. > > I have tired many iterations of this idea (many made no sense but I tried > anyways) including just having the separate formats in separate classes and > having almost everything else in the fnmocLog class. But cannot find a way > to have one log file with different formats for different types of events. > Below is the simple code that I am testing with. The two formats are very > similar for the test but will be larger and very different in the real world > if I can get this to work. > > Any help is appreciated. > Hi John, I think the trick may be giving different names to different Logger objects. This is what I tried: import logging import sys import time class fnmocLog: def __init__ (self): self.name = "test" self.platform = "ATOS2" self.devlevel = "beta" self.productid = int(time.time()) self.userid = self.productid def _setup_logger(self, fmt='<%(name)s %(asctime)s %(levelname)s %(message)s>'): self.hdlr = logging.FileHandler('%s.log'%self.name) self.logger.setLevel(logging.INFO) # 'name' in fmt refers to name passed to # getLogger, not self.name. self.formatter = logging.Formatter(fmt) self.hdlr.setFormatter(self.formatter) self.logger.addHandler(self.hdlr) class startLog(fnmocLog): def __init__ (self): fnmocLog.__init__(self) self.logger = logging.getLogger('APPSTART') self._setup_logger() class eventLog(fnmocLog): def __init__ (self): fnmocLog.__init__(self) self.logger = logging.getLogger('APPEVENT') self._setup_logger() idstart = startLog() idevent = eventLog() idstart.logger.info('This is a test') idevent.logger.info('This is the second test') idevent.logger.info('This is the third test') I think the example in the docs may be a little misleading - it uses 'myapp' as the name passed to getLogger; I'm guessing that's just because it's a simple example, but I could be wrong. You have more complicated requirements, so you probably want to create different Logger instances by passing different names to getLogger. That way you can control each Logger instance seperately, rather than trying to make one Logger instance do all the work. Good luck. Rich From jfabiani at yolo.com Tue May 18 23:00:39 2004 From: jfabiani at yolo.com (John Fabiani) Date: Tue May 18 23:59:53 2004 Subject: [Tutor] overview of how data is handled Message-ID: <40AACDD7.7060304@yolo.com> Hi, First let me say that the books and all the online tutorials (that I have seen) do not address how to handle data retrieved from a SQL database. They explain how to get the data but not how the data is to be handled after it is retrieved. It appears from what I have read and my experiments that the data needs to be in a dict form. OK I was able to convert the data into a dict. But doing so required many lines of code (two loops). If the program has to convert from list into dict for ten's of thousands of records it is going to be very slow. The handling of data is like nothing I have ever done. It's nothing like Delphi, Java, .Net or VFP. Therefore, I think I wrong in the way I am thinking about how data is to be handled. So can someone provide an over view of how they believe data should be handled in a data centered application - i.e data entry with grids, preparing reports for viewing or printing etc.... Thanks John From orbitz at ezabel.com Wed May 19 00:22:50 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Wed May 19 00:23:28 2004 Subject: [Tutor] overview of how data is handled In-Reply-To: <40AACDD7.7060304@yolo.com> References: <40AACDD7.7060304@yolo.com> Message-ID: <20040519002250.00214524.orbitz@ezabel.com> I am confused about what your question is. dbapi2.0 compliant modules return your object in some sort of list like object, either a tuple or a list. (it is iterable atleast). The DB-API 2.0 document says this about getting a dict object: The database SIG often sees reoccurring questions about the DB API specification. This section covers some of the issues people sometimes have with the specification. Question: How can I construct a dictionary out of the tuples returned by .fetchxxx(): Answer: There are several existing tools available which provide helpers for this task. Most of them use the approach of using the column names defined in the cursor attribute .description as basis for the keys in the row dictionary. Note that the reason for not extending the DB API specification to also support dictionary return values for the .fetchxxx() methods is that this approach has several drawbacks: * Some databases don't support case-sensitive column names or auto-convert them to all lowercase or all uppercase characters. * Columns in the result set which are generated by the query (e.g. using SQL functions) don't map to table column names and databases usually generate names for these columns in a very database specific way. As a result, accessing the columns through dictionary keys varies between databases and makes writing portable code impossible. I didn't bother looking up what these helper tools are but then again I wasn't that interested. Usually you know how many columns your result has so just using the index is not very difficult. On Tue, 18 May 2004 20:00:39 -0700 John Fabiani wrote: > Hi, > > First let me say that the books and all the online tutorials (that I > have seen) do not address how to handle data retrieved from a SQL > database. They explain how to get the data but not how the data is to be > handled after it is retrieved. It appears from what I have read and my > experiments that the data needs to be in a dict form. OK I was able to > convert the data into a dict. But doing so required many lines of code > (two loops). If the program has to convert from list into dict for > ten's of thousands of records it is going to be very slow. > > The handling of data is like nothing I have ever done. It's nothing > like Delphi, Java, .Net or VFP. Therefore, I think I wrong in the way I > am thinking about how data is to be handled. So can someone provide an > over view of how they believe data should be handled in a data centered > application - i.e data entry with grids, preparing reports for viewing > or printing etc.... > > Thanks > John > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed May 19 02:27:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 19 02:28:01 2004 Subject: [Tutor] overview of how data is handled [getting dictionaries from sql cursor / generators] In-Reply-To: <40AACDD7.7060304@yolo.com> Message-ID: On Tue, 18 May 2004, John Fabiani wrote: > The handling of data is like nothing I have ever done. It's nothing > like Delphi, Java, .Net or VFP. Hi John, The approach that the DB API 2.0 takes is similar to Java's JDBC standard. A 'cursor' object in Python behaves like a combination of a Java's 'java.sql.Statement' and 'java.sql.ResultSet'. When we say something in Java like: /*** Java ***/ PreparedStatement stmt = conn.prepareStatement ("select title, abstract from article"); ResultSet rs = stmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); } /******/ then an equivalent translation of this, using Python's API, looks something like this: ### Python cursor = conn.cursor() cursor.execute("select title, abstract from article") for (title, abstract) in cursor.fetchall(): print title print abstract ### The translation isn't exact. I've tried to improve the readability of the Python code, but I think that's perfectly fair. *grin* The examples above use explicit numeric indices to get at a particular column, but you've mentioned that you might want to use a dictionary instead. > OK I was able to convert the data into a dict. But doing so required > many lines of code (two loops). If the program has to convert from list > into dict for ten's of thousands of records it is going to be very slow. Can you show us what your code looks like? And are you sure it's going to be too slow? Python is relatively slow, but at the same time, tens of thousands of records doesn't sound like too much data at all. *grin* I would strongly recommend not to assume that performance is poor until a real performance measurement is taken. Human intuition on what's fast and what's slow can be deceptive. Here's an example that shows how to extract dictionaries from a cursor, assuming that our database doesn't have a native dictionary cursor interface: ### >>> def getDictsFromCursor(cursor): ... while True: ... nextRow = cursor.fetchone() ... if not nextRow: break ... d = {} ... for (i, columnDesc) in enumerate(cursor.description): ... d[columnDesc[0]] = nextRow[i] ... yield d ... >>> cursor.execute("select id, name from pub_term limit 3") 3L >>> for d in getDictsFromCursor(cursor): ... print d ... {'id': 107152L, 'name': "'de novo' GDP-L-fucose biosynthesis"} {'id': 5258L, 'name': "'de novo' IMP biosynthesis"} {'id': 5259L, 'name': "'de novo' protein folding"} ### Hope this helps! From John.Ertl at fnmoc.navy.mil Wed May 19 10:16:07 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Wed May 19 10:11:22 2004 Subject: [Tutor] making a log file Message-ID: You hit the nail on the head. I fell into the simple minded trap of "myapp". Thank you for the code idea, I like how you structured it. John Ertl -----Original Message----- From: Rich Krauter [mailto:rmkrauter@yahoo.com] Sent: Tuesday, May 18, 2004 16:55 To: tutor@python.org Subject: Re: [Tutor] making a log file On Tue, 2004-05-18 at 15:16, Ertl, John wrote: > All, > > I am trying to make a log file that contains different formats for different > types of events. Because this log file will be for a web service I cannot > use my old method of just directing standard out to a file. I am trying to > use the logging module but will little success. I have tried to have two > separate classes that log to the same file but the output prints out the > info for both formats each time the logger is called. For example I have > two formats one for a start and the other for an event. The start format > should only be printed when the startLog in invoked but both the startLog > and eventLog print. The same thing happens when I called the event > log...both the startLog and Event log formats get printed to the log file. > > I have tired many iterations of this idea (many made no sense but I tried > anyways) including just having the separate formats in separate classes and > having almost everything else in the fnmocLog class. But cannot find a way > to have one log file with different formats for different types of events. > Below is the simple code that I am testing with. The two formats are very > similar for the test but will be larger and very different in the real world > if I can get this to work. > > Any help is appreciated. > Hi John, I think the trick may be giving different names to different Logger objects. This is what I tried: import logging import sys import time class fnmocLog: def __init__ (self): self.name = "test" self.platform = "ATOS2" self.devlevel = "beta" self.productid = int(time.time()) self.userid = self.productid def _setup_logger(self, fmt='<%(name)s %(asctime)s %(levelname)s %(message)s>'): self.hdlr = logging.FileHandler('%s.log'%self.name) self.logger.setLevel(logging.INFO) # 'name' in fmt refers to name passed to # getLogger, not self.name. self.formatter = logging.Formatter(fmt) self.hdlr.setFormatter(self.formatter) self.logger.addHandler(self.hdlr) class startLog(fnmocLog): def __init__ (self): fnmocLog.__init__(self) self.logger = logging.getLogger('APPSTART') self._setup_logger() class eventLog(fnmocLog): def __init__ (self): fnmocLog.__init__(self) self.logger = logging.getLogger('APPEVENT') self._setup_logger() idstart = startLog() idevent = eventLog() idstart.logger.info('This is a test') idevent.logger.info('This is the second test') idevent.logger.info('This is the third test') I think the example in the docs may be a little misleading - it uses 'myapp' as the name passed to getLogger; I'm guessing that's just because it's a simple example, but I could be wrong. You have more complicated requirements, so you probably want to create different Logger instances by passing different names to getLogger. That way you can control each Logger instance seperately, rather than trying to make one Logger instance do all the work. Good luck. Rich _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed May 19 13:39:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 19 13:39:52 2004 Subject: [Tutor] overview of how data is handled [getting dictionaries from sql cursor / generators] (fwd) Message-ID: [Forwarding to tutor@python.org: please keep tutor@python.org in CC. It gives other folks the opportunity to help answer your questions.] ---------- Forwarded message ---------- Date: Wed, 19 May 2004 00:37:19 -0700 From: John Fabiani To: Danny Yoo Subject: Re: [Tutor] overview of how data is handled [getting dictionaries from sql cursor / generators] Danny Yoo wrote: >On Tue, 18 May 2004, John Fabiani wrote: > > > >>The handling of data is like nothing I have ever done. It's nothing >>like Delphi, Java, .Net or VFP. >> >> > >Hi John, > > >The approach that the DB API 2.0 takes is similar to Java's JDBC standard. >A 'cursor' object in Python behaves like a combination of a Java's >'java.sql.Statement' and 'java.sql.ResultSet'. > >When we say something in Java like: > >/*** Java ***/ >PreparedStatement stmt = conn.prepareStatement > ("select title, abstract from article"); >ResultSet rs = stmt.executeQuery(); >while (rs.next()) { > System.out.println(rs.getString(1)); > System.out.println(rs.getString(2)); >} >/******/ > >then an equivalent translation of this, using Python's API, looks >something like this: > >### Python >cursor = conn.cursor() >cursor.execute("select title, abstract from article") >for (title, abstract) in cursor.fetchall(): > print title > print abstract >### > >The translation isn't exact. I've tried to improve the readability of the >Python code, but I think that's perfectly fair. *grin* > > >The examples above use explicit numeric indices to get at a particular >column, but you've mentioned that you might want to use a dictionary >instead. > > > >>OK I was able to convert the data into a dict. But doing so required >>many lines of code (two loops). If the program has to convert from list >>into dict for ten's of thousands of records it is going to be very slow. >> >> > >Can you show us what your code looks like? And are you sure it's going to >be too slow? > >Python is relatively slow, but at the same time, tens of thousands of >records doesn't sound like too much data at all. *grin* I would strongly >recommend not to assume that performance is poor until a real performance >measurement is taken. Human intuition on what's fast and what's slow can >be deceptive. > > >Here's an example that shows how to extract dictionaries from a cursor, >assuming that our database doesn't have a native dictionary cursor >interface: > >### > > >>>>def getDictsFromCursor(cursor): >>>> >>>> >... while True: >... nextRow = cursor.fetchone() >... if not nextRow: break >... d = {} >... for (i, columnDesc) in enumerate(cursor.description): >... d[columnDesc[0]] = nextRow[i] >... yield d >... > > >>>>cursor.execute("select id, name from pub_term limit 3") >>>> >>>> >3L > > >>>>for d in getDictsFromCursor(cursor): >>>> >>>> >... print d >... >{'id': 107152L, 'name': "'de novo' GDP-L-fucose biosynthesis"} >{'id': 5258L, 'name': "'de novo' IMP biosynthesis"} >{'id': 5259L, 'name': "'de novo' protein folding"} >### > > >Hope this helps! > > > > my code mylist=[] myrowdata=[] for count in range(0,len(myfields)): mylist.append(myfields[count][0]) for count in range(0,len(mydata[0])): myrowdata.append(mydata[0][count] ) d = dict(zip(mylist,myrowdata)) The above works with only one record at a time. I'm using PyPgSQL and the resultset is a list. mydata=cursor.fetchmany(10) Because the of books I'm reading (O'Rielly) I was expecting a tuple but I got a list. OK but now the routines in the books suggest that I use a dict. So I figured out how to convert the data (mydata in this case) into a dict. But then I realized that the two loops I was going to use (to convert the list into a dict) will take time. I did not test how long. But I also realized that converting has to be wrong. The returned data must be used as a list - not converted and then used. But it appears that's what you are doing in the "getDictsFromCursor" - converting into a dict ( I know to show me). In the java code you are looping thru the resultset. That's all I want to do - at first. Then I'll need some way to loop thru the data based on the field name. Again it looks like I have to create the dict for each record. This just can't be right. Fetchone 1000's of times is also got to be wrong. In the VFP world we have a "SCAN" that loops thru the resultset. I can access the data by field name in VFP. How does one do same thing - loop thru the resultset (could be 1000's) and access the fields by their field name? One nice thing about getting a list is I can change the data in the list (can't in a tuple). so how about something like: replace all extPrice with Qty * price (this is a very simple thing to do in VFP, Delphi or Java.) in the resultset. Then open a connection and save the changed data. What I think has to happen at the moment is each record must be converted to a dict and then after I can change each record based on the key of the dict. This does not sound right - I'm doing something wrong. John From dyoo at hkn.eecs.berkeley.edu Wed May 19 14:47:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed May 19 14:47:13 2004 Subject: [Tutor] overview of how data is handled [getting dictionaries from sql cursor / generators] (fwd) In-Reply-To: Message-ID: > One nice thing about getting a list is I can change the data in the list > (can't in a tuple). so how about something like: replace all extPrice > with Qty * price (this is a very simple thing to do in VFP, Delphi or > Java.) in the resultset. Then open a connection and save the changed > data. Hi John, Ah, ok, this part is different from my assumptions of the problem. I had assumed we were still trying to generate some kind of report file, so that we needed just read-only values. It sounds like you want to make changes to the database. Are you thinking of Java's update* methods in java.sql.ResultSet? If so, then no, I don't think that Python's DB API 2.0 supports doing select-and-update directly through a cursor, but I could be wrong. You may want to ask on the Database SIG group: http://python.org/sigs/db-sig/ > In the java code you are looping thru the resultset. That's all I want > to do - at first. Then I'll need some way to loop thru the data based > on the field name. Again it looks like I have to create the dict for > each record. This just can't be right. Fetchone 1000's of times is also > got to be wrong. Hmmm... I have to disagree here, because I'm not seeing the difference. How is looping through a Java ResultSet conceptually different from calling cursor.fetchone() in Python? In the Java code that was presented earlier, we could just as easily say that in /*** Java ***/ while (rs.next()) { ... } /******/ we're calling 'rs.next()' thousands of times too. The 'test' condition in a loop is not just executed once, but every time at the beginning of each iteration. > In the VFP world we have a "SCAN" that loops thru the resultset. I can > access the data by field name in VFP. How does one do same thing - loop > thru the resultset (could be 1000's) and access the fields by their > field name? Hmmm! I'm not familiar with VFP. Googling... *grin* http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_foxhelp/html/lngscan__endscan.asp Ok, I see how SCAN works. But I still don't see the difference here between the approach we're taking in Python and the approach that Foxpro takes. Let's take the example that they're giving us: ****** Foxpro code CLOSE DATABASES OPEN DATABASE (HOME(2) + 'Data\testdata') USE customer && Opens Customer table CLEAR SCAN FOR UPPER(country) = 'SWEDEN' ? contact, company, city ENDSCAN ****** Here's Python pseudocode for the above, if we pretend to have a MySQLdb database called 'testdata', and a table called 'customer'. (Also, let's pretend we have that getDictsFromCursor() function from our last exchange.): ### conn = MySQLdb.connect(db='testdata') cursor = conn.cursor() cursor.execute("""SELECT * from customer WHERE UPPER(country) = 'SWEDEN'""") for row in getDictsFromCursor(cursor): print row['contact'], row['company'], row['city'] ### There are some issues here we should address. First, the scanning condition in the Foxpro code, SCAN FOR UPPER(country) = 'SWEDEN' can --- and should! --- be defined in the SQL query. So I've put a "WHERE" clause in the SQL that defines that constraint. The following snippet, in contrast: ### conn = MySQLdb.connect(db='testdata') cursor = conn.cursor() cursor.execute("""SELECT * from customer""") for row in getDictsFromCursor(cursor): if row['country'].upper() == 'SWEDEN': print row['contact'], row['company'], row['city'] ### will also work, but it is inefficient because it iterates over all the records in customer. Is this what you were worried about? Foxpro's SCAN function also appears to bind new variables automagically so that we can simply name them within the SCAN block. The equivalent Python code is a little clumsier than the Foxpro code, since I'm accessing the values though that row dictionary. I'm not convinced, though, that Foxpro's rebinding is a good idea. It's convenient, but the names of fields in our database might be easily be keywords in our language. What happens in Foxpro if one of the column names is something like ENDSCAN? Is that possible? That's one motivating reason to package up each result row in a container, like a list or a dictionary. The extra layer of indirection allows us to avoid name-collision issues. I hope this helps! From alan.gauld at blueyonder.co.uk Wed May 19 14:51:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed May 19 14:51:31 2004 Subject: [Tutor] overview of how data is handled References: <40AACDD7.7060304@yolo.com> Message-ID: <002d01c43dd2$4a8d57a0$6401a8c0@xp> > First let me say that the books and all the online tutorials (that I > have seen) do not address how to handle data retrieved from a SQL > database. They explain how to get the data but not how the data is to be > handled after it is retrieved. Thats because you can handle it any way you like! Once its out its all yours. > experiments that the data needs to be in a dict form. Hmm, I wonder. The normal approach is to use a cursor and retrieve the data piece by piece or in small chunks. Are you trying to pull back all the data at once? That will be more problematic (albeit faster if you have enough RAM). But if you allow the database cursor to hold and traverse the query results for you it shouldn't be too hard. This is normal relational database practice, but not normal Windows IDE type practice which disguises the cursor with table views and the like. Python takes a more server like approach (as normally used by COBOL, C, etc). > (two loops). If the program has to convert from list into dict for > ten's of thousands of records it is going to be very slow. Yep, that's why you normally write specific queries and insert the results in a cursor. You can then fetch the data from the cursor. Alternatively write more specific SQL and execute on demand - it depends on where the CPU time gets eaten... > The handling of data is like nothing I have ever done. It's nothing > like Delphi, Java, .Net or VFP. Thats true. I don;t know of any Python environment that mimics the way VB and Delphi present data. But python is far from alone in its approach. > application - i.e data entry with grids, preparing reports for viewing > or printing etc.... Normally to use a grid with N rows you pull N rows outof the cursor and populate the grid. How the population gets done will depend on the grid you use! Preparing reports is more normally done by writing as much as possible in SQL and then iterating line by line over the resultant cursor. Having said all that I haven't used Python's database interface in earnest, my experiences are with COBOL and C! Alan G. From alan.gauld at blueyonder.co.uk Wed May 19 14:57:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed May 19 14:57:27 2004 Subject: [Tutor] overview of how data is handled [getting dictionariesfrom sql cursor / generators] References: Message-ID: <003a01c43dd3$1ed2c5e0$6401a8c0@xp> > On Tue, 18 May 2004, John Fabiani wrote: > > > The handling of data is like nothing I have ever done. It's nothing > > like Delphi, Java, .Net or VFP. > > The approach that the DB API 2.0 takes is similar to Java's JDBC standard. > A 'cursor' object in Python behaves like a combination of a Java's > 'java.sql.Statement' and 'java.sql.ResultSet'. For info to those who may be puzzled by John's question (and apologies if I've got it wrong!) but I think John is referring to the way Delphi, VB and Java IDEs have "live data" controls that allow you to drop the data directly from the database into a table control on the GUI without writing any code (except the SQL, and sometimes not even that!). Once the connection is made you can see the real data in the cells, and modify it by simply updating the cell contents etc. By comparison JDBCs and Python's DBAPI are both fairly primitive tools and therefore seem cumbersome. Again, if I guessed wrong then apologies to all, Alan G. From idiot1 at netzero.net Thu May 20 00:32:46 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Thu May 20 00:33:31 2004 Subject: [Tutor] WTF?!? Message-ID: <40AC34EE.3080204@netzero.net> Ok, we upgraded critter; bigger drives, new(er) mother board, more memory, actually sprouted some hairs on his teenage chest. HOWEVER, we also upgraded to current Python- and FreeBSD. Straightaway we had heacdaches. And we fixed them. Permissions are a little different. ALSO, my page counters stopped working. Here's the old script: #!/usr/local/bin/python # # f1=open("count",'r') count=int(f1.readline()) f1.close() count=count+1 result=str(count) print result f1=open("count",'w') f1.write(result+"\r\n") f1.close the file count stores the page hit count; it is stored in the cgi-bin with the program. Ok, it stopped wortking. FIRST off we check permissions. ok, minor quibbles, fix. Loog now says cannot find file 'count'. ok, we go in and execute from comand line, it works perfect. Hmmm, had something like this before. Turns out that when you run a program via the web server, it is now defaulting to the root dir for that domain name (criter holds several domains, each with it's own seperate directory tree structure including a web cgi-bin). ok, I noticed one site in the box was counting. THE FILE WAS IN THE QRONG PLACE. It was in the root directory for that site. hmmm, put it in the 'right' place, it stops working. 'Default dir' is indeed the root for the website as defined by the domain table in the apache configuration. ok, here is the updated counter: #!/usr/local/bin/python # # f1=open("./cgi-bin/count",'r') count=int(f1.readline()) f1.close() count=count+1 result=str(count) print result f1=open("./cgi-bin/count",'w') f1.write(result+"\r\n") f1.close And it works just peachy. Now, did this arise due to changes in python, or in FreeBSD? So this is the current working version: -- Respectfully, Kirk D Bailey, Pinellas county Florida USA think http://www.tinylist.org/ - $FREE$ Liberating software +-------+ http://www.pinellasintergroupsociety.org/ - NeoPagan | BOX | http://www.listville.net/ - $FREE$ list hosting! +-------+ http://www.howlermonkey.net/ - $FREE$ email Accounts kniht http://www.sacredelectron.org/ - My personal site From roeland.rengelink at chello.nl Thu May 20 05:46:19 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Thu May 20 05:46:03 2004 Subject: [Tutor] overview of how data is handled [getting dictionaries from sql cursor / generators] (fwd) In-Reply-To: References: Message-ID: <40AC7E6B.4020804@chello.nl> Danny Yoo wrote: >[Forwarding to tutor@python.org: please keep tutor@python.org in CC. It >gives other folks the opportunity to help answer your questions.] > > my code >mylist=[] >myrowdata=[] >for count in range(0,len(myfields)): > mylist.append(myfields[count][0]) > >for count in range(0,len(mydata[0])): > myrowdata.append(mydata[0][count] ) > >d = dict(zip(mylist,myrowdata)) >The above works with only one record at a time. > >I'm using PyPgSQL and the resultset is a list. >mydata=cursor.fetchmany(10) > Because the of books I'm reading (O'Rielly) I was expecting a tuple but >I got a list. OK but now the routines in the books suggest that I use >a dict. So I figured out how to convert the data (mydata in this case) >into a dict. But then I realized that the two loops I was going to use >(to convert the list into a dict) will take time. I did not test how >long. But I also realized that converting has to be wrong. The >returned data must be used as a list - not converted and then used. >But it appears that's what you are doing in the "getDictsFromCursor" - >converting into a dict ( I know to show me). > > > It's probably a good idea to stress again that the (list of) objects returned by cursor.fetchone() (cursor.fetchmany()) behave like a dict. It is neither a tuple, nor a list or dict. (It's a PgResultSet object). However, in the context of what you're trying to do, these object are read-only. That is, you can't change them, and even if you transform them into a list (or dict) and change the values, there is no way these values are going to be automagically updated in the the database. You will need additional code for that (see below). >In the java code you are looping thru the resultset. That's all I want >to do - at first. Then I'll need some way to loop thru the data based >on the field name. Again it looks like I have to create the dict for >each record. This just can't be right. Fetchone 1000's of times is >also got to be wrong. In the VFP world we have a "SCAN" that loops >thru the resultset. I can access the data by field name in VFP. How >does one do same thing - loop thru the resultset (could be 1000's) and >access the fields by their field name? > > > If the backend of VFP is an sql database (I wouldn't know) you can assume that VFP is doing something like what I show below under the covers. >One nice thing about getting a list is I can change the data in the list >(can't in a tuple). so how about something like: >replace all extPrice with Qty * price (this is a very simple thing to do >in VFP, Delphi or Java.) in the resultset. Then open a connection and >save the changed data. > > You're not going to be able to do this, even after you have changed the result set from as 'tuple' into a list, to make it editable. The reason that this is not trivial, is that the result set does not know from which row in the database it came, so it's not obvious which row in the database has to be updated once you have changed a row in the result set. And of course, after you have changed an item from the resultset into a list, the list will not know anything whatsoever about any database, making this problem even more difficult. >What I think has to happen at the moment is each record must be >converted to a dict and then after I can change each record based on the >key of the dict. This does not sound right - I'm doing something wrong. >John > > > > > The following code is untested and uses a lot of different python concepts that you may not have encountered yet. But I hope this gives an idea about the kind of work that you have to do to make this work the way you want. class DBRow: """An editable row that remembers from which row in the table it came""" def __init__(self, oid, cols, data): self.oid = oid # row identifier self.cols = cols # column names (a list) self.data = data # row data (a list) self.dirty = 0 # only save when updated def __getitem__(self, key): # used to retrieve a value for one column in this row index = self.cols.index(key) return self.data[index] def __setitem__(self, key, value): # used to set a value for one columns in this row index = self.cols.index(key) self.data[index] = value self.dirty = 1 def save(self, table_name, cursor): if not self.dirty: return terms = [] for col, val in zip(self.cols, self.data) terms.append("%s=%s" % (col, val)) cmnd = "UPDATE %s SET %s WHERE oid=%s" % (table_name, terms, self.oid) cursor.execute(cmnd) class DBTable: """Represent the table as a list of editable DBRows""" def __init__(self, db, table_name, clause=''): self.table_name = table_name self.db = db self.rows = [] # get the data from the db cmnd = "SELECT oid, * FROM %s" % table_name if clause: cmnd = cmnd+" WHERE %s" % clause c = db.cursor() c.execute(cmnd) # find names, except oid colnames = [d[0] for d in c.description[1:]] # transform the resultset in a list of DBRow objects for row in c.fetchall(): oid = row[0] data = row[1:] self.rows.append(DBRow(oid, colnames, data)) def __getitem__(self, index): return self.rows[index] def save(self): c = self.db.cursor() for r in self.rows: r.save(self.table_name, c) c.commit() With this you should be able to do something like: >>> db = PgSQL.connect(...) >>> data = DBTable(db, "mytable", "aaa>42") >>> for row in data: ... row['aaa'] = row['bbb']+3*row['ccc'] >>> data.save() which would change column aaa for all rows where aaa>42 Note that db = PgSQL.connect(...) c = db.cursor() c.execute("UPDATE mytable SET aaa=bbb+3*ccc WHERE aaa>42") c.commit() Is by far the fastest (if not easiest) way to solve this particular problem. Hope this helps, Roeland From pythontut at pusspaws.net Thu May 20 15:10:44 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu May 20 15:10:58 2004 Subject: [Tutor] Is there a better way ? Message-ID: <40AD02B4.4030606@pusspaws.net> A couple of hundred lines of code later ... things are getting easier ... Is there a neater way of saying ... syncerr=False if 'SyncErr' in file: syncerr=True I've got a few of these & they seems a bit of a mess ! Dave PS Why was I scared of OOP - It rocks :-) From kalle at lysator.liu.se Thu May 20 15:22:27 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Thu May 20 15:20:10 2004 Subject: [Tutor] Is there a better way ? In-Reply-To: <40AD02B4.4030606@pusspaws.net> References: <40AD02B4.4030606@pusspaws.net> Message-ID: <20040520192227.GU534@i92.ryd.student.liu.se> [Dave S] > Is there a neater way of saying ... > > syncerr=False > if 'SyncErr' in file: > syncerr=True syncerr = 'SyncErr' in file Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From pythontut at pusspaws.net Thu May 20 16:03:29 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu May 20 16:03:42 2004 Subject: [Tutor] Is there a better way ? In-Reply-To: <20040520192227.GU534@i92.ryd.student.liu.se> References: <40AD02B4.4030606@pusspaws.net> <20040520192227.GU534@i92.ryd.student.liu.se> Message-ID: <40AD0F11.8010101@pusspaws.net> Kalle Svensson wrote: >[Dave S] > > >>Is there a neater way of saying ... >> >>syncerr=False >>if 'SyncErr' in file: >> syncerr=True >> >> > > syncerr = 'SyncErr' in file > >Peace, > Kalle > > Sometimes my own stupidity amazes even me ! :-) Many Thanks Dave From dyoo at hkn.eecs.berkeley.edu Thu May 20 20:59:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu May 20 20:59:30 2004 Subject: [Tutor] WTF?!? In-Reply-To: <40AC34EE.3080204@netzero.net> Message-ID: On Thu, 20 May 2004, Kirk Bailey wrote: > Here's the old script: > #!/usr/local/bin/python > # > # > f1=open("count",'r') > count=int(f1.readline()) > f1.close() > count=count+1 > result=str(count) > print result > f1=open("count",'w') > f1.write(result+"\r\n") > f1.close ^^^^^^^^ Hi Kirk, There's a bug here: you need to call f1.close(), with parentheses. Even methods with no arguments need parentheses to fire off properly. (We may not be seeing this bug only because the code is inadvertantly flushing the file buffer, but we can't depend on our luck to last. *grin*.) > Hmmm, had something like this before. Turns out that when you run a > program via the web server, it is now defaulting to the root dir for > that domain name (criter holds several domains, each with it's own > seperate directory tree structure including a web cgi-bin). Yes --- CGI scripts shouldn't assume where the current working directory is when they are executed. Apache mentions that absolute paths should be used for executable names: http://httpd.apache.org/docs/howto/cgi.html#pathinformation and I think that the same caveat should apply to the names of data files too. The change in behavior probably has nothing to do with Python or FreeBSD, but is more likely due to changes in your web server configuration. I can't find anything in the CGI spec that defines what the current working directory is, I suspect it's "undefined" in the sense that a CGI script should not depend on the current working directory. So instead of changing things to: f1=open("./cgi-bin/count",'r') I'd recommend going one step further, and make it absolutely qualified. If your DocumentRoot is under /var/www, then something like: f1 = open("/var/www/cgi-bin/count", "r") would work. Hope this helps! From pythontut at pusspaws.net Fri May 21 13:27:41 2004 From: pythontut at pusspaws.net (Dave S) Date: Fri May 21 13:28:01 2004 Subject: [Tutor] strange variable problem Message-ID: <40AE3C0D.7060201@pusspaws.net> Please excuse my poor codeing ... but I have a problem. ftseptr is setup as a global variable, value -1, yftseptr is setup as a global variable, value 0 When I execute the calling script I get .... ============================== RESTART ================================ >>> Analizing directory ... 20040429 0 Traceback (most recent call last): File "/home/dave/gg/gg.py", line 72, in -toplevel- gg() File "/home/dave/gg/gg.py", line 62, in gg file2datacore2(stockdir+dir+'/'+file,syncerr) File "/home/dave/gg/gg.py", line 40, in file2datacore2 ggdatacore2.add(datalist[i+1],datalist[i+3],datalist[i+5],datalist[i+6],datalist[i+7],datalist[i+8],datalist[i+9],datalist[i+10],datalist[i+11],datalist[i+12],datalist[i+13],syncerr) File "/home/dave/gg/ggdatacore2.py", line 30, in add print ftseptr UnboundLocalError: local variable 'ftseptr' referenced before assignment >>> Where the 0 after Analizing directory is from yftseptr, but ftseptr causes an exception - no assigned. They were both assigned at the same time. Can anyone help Thanks Dave ------------------------------------------------------------------------------------------------------------- The code causing problems .... import gglogger ftsedata=[] yftsedata=[] ftsedload={} ftseptr=-1 # Pointer into ftsedata list yftseptr=0 for i in range(110): ftsedata.append(ftsedload) yftsedata.append(ftsedload) def add(id,mid,pence,pc,bid,offer,open,high,low,close,volume,syncerr): # Data cookie - is a list # [num consecutive loads,bad data counter,bad cycle counter] print yftseptr # These are test prints where I found the problem ;-) print ftseptr try: if ftseptr==-1: # If ftseptr==-1 get cookie from ftsedata cookie=yftsedata[yftseptr][id][0] else: cookie=ftsedata[ftseptr][id][0] except KeyError: cookie=[0,0,2] # OK no previous id ... start of new record gglogger.log('!!','ggdatacore2','New ftse company '+id) From alan.gauld at blueyonder.co.uk Fri May 21 15:52:56 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri May 21 15:52:42 2004 Subject: [Tutor] Is there a better way ? References: <40AD02B4.4030606@pusspaws.net><20040520192227.GU534@i92.ryd.student.liu.se> <40AD0F11.8010101@pusspaws.net> Message-ID: <001d01c43f6d$367ca4e0$6401a8c0@xp> > >>Is there a neater way of saying ... > >> > > syncerr = 'SyncErr' in file > > > Sometimes my own stupidity amazes even me ! :-) It's not stupidity, until you've seen it that code is far from intuitive to most beginners. Of course, once you see it and think about it it seems obvious! :-) Alan G. From dyoo at hkn.eecs.berkeley.edu Fri May 21 16:32:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri May 21 16:32:38 2004 Subject: [Tutor] strange variable problem In-Reply-To: <40AE3C0D.7060201@pusspaws.net> Message-ID: On Fri, 21 May 2004, Dave S wrote: > Please excuse my poor codeing ... but I have a problem. > > ftseptr is setup as a global variable, value -1, > yftseptr is setup as a global variable, value 0 Hi Dave, Ah! Common gotcha: when using global variables in functions, you may need to declare that the variable is 'global' in nature. For example: ### count = 0 def makeNextName(): global count nextName = "name%s" % count count = count + 1 return nextName ### If the 'global count' declaration in the function is missing, then we'll get the same UnboundLocalError that you're receiving in your program, so I suspect the same thing is happening there. Another example of this is in the Python Programming FAQ, under the title "How do you set a global variable in a fucntion?": http://python.org/doc/faq/programming.html#how-do-you-set-a-global-variable-in-a-function So people do run into this enough that it's a FAQ entry. I get the feeling, sometimes, that globals are awkward in Python to discourage their use. *grin* Hope this helps! From op73418 at mail.telepac.pt Fri May 21 18:06:52 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri May 21 18:03:57 2004 Subject: [Tutor] strange variable problem In-Reply-To: References: <40AE3C0D.7060201@pusspaws.net> Message-ID: Em Fri, 21 May 2004 13:32:30 -0700 (PDT), Danny Yoo atirou este peixe aos pinguins: [text snipped] > >So people do run into this enough that it's a FAQ entry. I get the >feeling, sometimes, that globals are awkward in Python to discourage their >use. *grin* > I think that is only half the story. *grin* Globals are awkward because scope resolution of names follows some very *simple* rules: First notice that the scope of a name is determined at *compile* time - this is important in what follows. 1. If a name is LHS (left-hand-side) of an assignment then it is to be found in the local scope. 2. Names in an expression are found by going from the local scope, then the outer scopes (if any), then the global scope then the builtins. The important rule here is number 1. In a situation like name = 1 def foo(arg): name = name + 1 Since name is the LHS of an assignment it is assumed to be in the local scope. Of course, when *actually running* the code, when executing the expression name + 1 Python sees that there is no name bound in the local scope => you get an error. So, by rule 1 you have to have some way to signal Python's "compiler" (the Translator into Python bytecode) that name is in the outer scope (in this case the module-level one). Thus the need for the global declaration. If you want to preserve the simplicity of rule 1 (and I for one will shoot down everyone who wants to break it :-) you *must* have some special notation to allow *rebinding* of names in outer scopes. Currently rebinding is only allowed in the global scope not in other outer scopes (as defined by functions) but it seems that Guido wants to introduce it except that no good notation has yet been found. I for one favour a new assignment operator, say :=, instead of a declaration like global. With my best regards, G. Rodrigues From blugerz at yahoo.com Fri May 21 21:35:07 2004 From: blugerz at yahoo.com (brian illingworth) Date: Fri May 21 21:35:29 2004 Subject: [Tutor] New to programming-Help Message-ID: <20040522013507.44697.qmail@web41506.mail.yahoo.com> Hi I am new to this group and new to programming. I have had this interest in learning to program because.......well just because. It's just a curiosity that I have. The reason I am starting with Python, well some of the websites I went to recommended Python, so here I am. Ok on to the question. I am currently using the book "Python programming for absolute beginners" by Michael Dawson. The program I am working on is a password program....dont laugh I know it's really simple to some, but I am kinda stuck. The book shows how to code a password program like this: password = raw input("Enter your password:") if password == "secret": print "Access Granted" else: print "Access Denied" raw input("Press the enter key to exit") Ok that is easy enough I understand what is going on here. As the book goes on it also talks about elif, and while loops. At the end of the chapter it gives various challenges that the reader is asked to complete. One of the challenges is to take the password program from above and change it so that the user gets only three attempts to enter the correct password. Well I ain't got it to work yet, I thought I came close, but no cigar. This is what I have so far: #Limiting password atempts to three password = raw input("Enter your Password: ") count = 0 while password != "secret": print password = raw-input("Enter your Password: ") count += 1 if password == "secret": print "Welcome in." elif count > 3: print "Please come back when you remember your Password." else: raw input("Press enter to exit.") Ok, I know I may be way off course here but any help would be greatly appreciated. I dont want to get frustrated and say the heck with it, especially if it is something minor. Thanks in advance. --------------------------------- Do you Yahoo!? Yahoo! Domains - Claim yours for only $14.70/year -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040521/15631749/attachment.html From tomikaze at freemail.hu Fri May 21 21:38:59 2004 From: tomikaze at freemail.hu (=?ISO-8859-2?Q?Moln=E1r_Tam=E1s?=) Date: Fri May 21 21:39:06 2004 Subject: [Tutor] text widget Message-ID: Hola! Could anyone help me if there is a text editor module out in space, which allows stepping to one line from another of a paragraph? Is has one linebreak, so it's actually a line, but users cannot be bothered with this. Maybe the text widget of TKinter can be hacked? I have been playing with some binding modifications and stuff like this for days, but solutions are too slow or likely pixel/monitor dependent. Do I really have to go into C too? Tell me something if you can. thanx ? From janitor at gmail.com Fri May 21 22:17:38 2004 From: janitor at gmail.com (Darshan Gunawardena) Date: Fri May 21 22:17:46 2004 Subject: [Tutor] New to programming-Help In-Reply-To: <20040522013507.44697.qmail@web41506.mail.yahoo.com> References: <20040522013507.44697.qmail@web41506.mail.yahoo.com> Message-ID: <8f4e469604052119172daa682c@mail.gmail.com> I too am new to python. And I'm sure there must be many ways to improve on this code. But for the moment I think it meets your requirements. count = 0 password = 'x' while password != "secret" and count < 3: password = raw_input("Enter your Password: ") if password == "secret": print "Welcome in." else: print "Incorrect Password" count += 1 if count == 3: print "Please come back when you remember your Password." else: raw_input("Press enter to exit.") ----- Original Message ----- From: brian illingworth Date: Fri, 21 May 2004 18:35:07 -0700 (PDT) Subject: [Tutor] New to programming-Help To: tutor@python.org Hi I am new to this group and new to programming. I have had this interest in learning to program because.......well just because. It's just a curiosity that I have. The reason I am starting with Python, well some of the websites I went to recommended Python, so here I am. Ok on to the question. I am currently using the book "Python programming for absolute beginners" by Michael Dawson. The program I am working on is a password program....dont laugh I know it's really simple to some, but I am kinda stuck. The book shows how to code a password program like this: password = raw input("Enter your password:") if password == "secret": print "Access Granted" else: print "Access Denied" raw input("Press the enter key to exit") Ok that is easy enough I understand what is going on here. As the book goes on it also talks about elif, and while loops. At the end of the chapter it gives various challenges that the reader is asked to complete. One of the challenges is to take the password program from above and change it so that the user gets only three attempts to enter the correct password. Well I ain't got it to work yet, I thought I came close, but no cigar. This is what I have so far: #Limiting password atempts to three password = raw input("Enter your Password: ") count = 0 while password != "secret": print password = raw-input("Enter your Password: ") count += 1 if password == "secret": print "Welcome in." elif count > 3: print "Please come back when you remember your Password." else: raw input("Press enter to exit.") Ok, I know I may be way off course here but any help would be greatly appreciated. I dont want to get frustrated and say the heck with it, especially if it is something minor. Thanks in advance. ________________________________ Do you Yahoo!? Yahoo! Domains - Claim yours for only $14.70/year From gew75 at hotmail.com Fri May 21 22:31:51 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Fri May 21 22:31:58 2004 Subject: [Tutor] New to programming-Help References: <20040522013507.44697.qmail@web41506.mail.yahoo.com> Message-ID: Hi Brian, Just before I say anything, please try to send plain text e-mails. Thanks. You haven't provided a traceback, so I don't really know what is wrong with the programs below apart from some basic syntax. The most glaring is that the function raw_input(...) is just one word with an underscore in the middle; this would be causing errors. So, for example, (untested) print 'Welcome to the Miracle Aging salon!' name = raw_input("Please enter your name >> ") print 'Welcome', name+'!' inputOK = false while not inputOK: age = raw_input("Please enter your age >> ") try: age = int(age) if age > 0: inputOK = true else: print "No cheating ;)" except: print "Integral ages only please" inputOK = false while not inputOK: dAge = raw_input("Please enter your *desired* age >> ") try: dAge = int(age) if dAge > 0 and dAge < age: inputOK = true else: print "Sorry, our products only work to provide non-negative ages\n *less* than your current age" except: print "Integral ages only please" for i in range(age-dAge): print "Shaving off 1 year..." print "You are now", age-i-1, "years old!" print "De-aging process complete." print "Congratulations", name, "you are now", dAge, "years old!" This example, which I just concocted, would be a good one to split into functions. You might notice that the two while loops asking for input look very simnilar; they are perfect candidates for turning into functions. Allowing the program to be run multiple times with multiple clients would be another good exercise. Anyway, I'll stop here ;). Feel free to ask any more questions, and apologies for any typos in the above code. -- Glen ----- Original Message ----- From: brian illingworth To: tutor@python.org Sent: Saturday, May 22, 2004 11:35 AM Subject: [Tutor] New to programming-Help Hi I am new to this group and new to programming. I have had this interest in learning to program because.......well just because. It's just a curiosity that I have. The reason I am starting with Python, well some of the websites I went to recommended Python, so here I am. Ok on to the question. I am currently using the book "Python programming for absolute beginners" by Michael Dawson. The program I am working on is a password program....dont laugh I know it's really simple to some, but I am kinda stuck. The book shows how to code a password program like this: password = raw input("Enter your password:") if password == "secret": print "Access Granted" else: print "Access Denied" raw input("Press the enter key to exit") Ok that is easy enough I understand what is going on here. As the book goes on it also talks about elif, and while loops. At the end of the chapter it gives various challenges that the reader is asked to complete. One of the challenges is to take the password program from above and change it so that the user gets only three attempts to enter the correct password. Well I ain't got it to work yet, I thought I came close, but no cigar. This is what I have so far: #Limiting password atempts to three password = raw input("Enter your Password: ") count = 0 while password != "secret": print password = raw-input("Enter your Password: ") count += 1 if password == "secret": print "Welcome in." elif count > 3: print "Please come back when you remember your Password." else: raw input("Press enter to exit.") Ok, I know I may be way off course here but any help would be greatly appreciated. I dont want to get frustrated and say the heck with it, especially if it is something minor. Thanks in advance. Do you Yahoo!? Yahoo! Domains - Claim yours for only $14.70/year _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From gew75 at hotmail.com Fri May 21 22:35:39 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Fri May 21 22:35:47 2004 Subject: [Tutor] text widget References: Message-ID: Hi, I'm not sure about your question. There is an interactive text widget in TKinter. This allows navigation with the arrow keys (IIRC) which is what you're asking? After a quick look at some docs, the following page seems helpful: http://www.pythonware.com/library/tkinter/introduction/text.htm The builtin text widget is quite powerful. -- Glen ----- Original Message ----- From: "Moln?r Tam?s" To: Sent: Saturday, May 22, 2004 11:38 AM Subject: [Tutor] text widget Hola! Could anyone help me if there is a text editor module out in space, which allows stepping to one line from another of a paragraph? Is has one linebreak, so it's actually a line, but users cannot be bothered with this. Maybe the text widget of TKinter can be hacked? I have been playing with some binding modifications and stuff like this for days, but solutions are too slow or likely pixel/monitor dependent. Do I really have to go into C too? Tell me something if you can. thanx ? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sat May 22 03:14:07 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 22 03:13:38 2004 Subject: [Tutor] strange variable problem References: Message-ID: <005d01c43fcc$5f36c640$6401a8c0@xp> > > ftseptr is setup as a global variable, value -1, > > yftseptr is setup as a global variable, value 0 > > Ah! Common gotcha: when using global variables in functions, you may need > to declare that the variable is 'global' in nature. For example: Is that really the problem here? He is not assigning to the variable merely printing it, which shouldn't need the global keyword. However I don't think we have the full story. Looking at the traceback: > Traceback (most recent call last): > File "/home/dave/gg/gg.py", line 72, in -toplevel- > gg() > File "/home/dave/gg/gg.py", line 62, in gg > file2datacore2(stockdir+dir+'/'+file,syncerr) > File "/home/dave/gg/gg.py", line 40, in file2datacore2 > > ggdatacore2.add(datalist[i+1],datalist[i+3],...syncerr) > File "/home/dave/gg/ggdatacore2.py", line 30, in add > print ftseptr > UnboundLocalError: local variable 'ftseptr' referenced before assignment we have calls to gg() and file2datacore2 and then add() for which we have the code. Plus the program seems to be run from a python prompt rather than being executed as a program. If that is the case a lot depends on how the imports are being done because that's when the global variables will be set up. Presumably, for the code to get this far, the module gg does import ggdatacore2 But when is gg imported? Has anything changed between then and the toplevel call to gg()? What happens if you run your program outside the python prompt? Does that change the error in any way? > ### > count = 0 > def makeNextName(): > global count > nextName = "name%s" % count > count = count + 1 > return nextName > ### > > If the 'global count' declaration in the function is missing, then we'll > get the same UnboundLocalError that you're receiving in your program, so I > suspect the same thing is happening there. Yes but in this case the error is because of the assignment which tries to create a local variable. But Dave's code doesn't assign to the variable merely prints it. So it should be OK, unless he hasn't shown us the full code... puzzled, Alan G. From alan.gauld at blueyonder.co.uk Sat May 22 03:21:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 22 03:20:50 2004 Subject: [Tutor] New to programming-Help References: <20040522013507.44697.qmail@web41506.mail.yahoo.com> Message-ID: <006701c43fcd$61929b20$6401a8c0@xp> > As the book goes on it also talks about elif, and while > loops. ... > that the user gets only three attempts to enter the correct > password = raw input("Enter your Password: ") > count = 0 > > while password != "secret": > print password = raw-input("Enter your Password: ") > count += 1 The while loop will repeat *the indented block* until the condition is false. You are only repeating these 2 lines! However there is another problem further down: > if password == "secret": > print "Welcome in." > elif count > 3: > print "Please come back when you remember your Password." > else: > raw input("Press enter to exit.") Even if you move these into the loop you are not exiting the loop after 3 times you only print a message. So your loop test needs to check for two conditions: 1) The password is not "secret" 2) count is less than 3 Finally think about the value of count. You start it at 0 but test for "count > 3" - how many loops will it take for count to be greater than 3? Given that information try modifying your program and see how you get on. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sat May 22 03:25:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 22 03:24:36 2004 Subject: [Tutor] text widget References: Message-ID: <006c01c43fcd$e7893130$6401a8c0@xp> > Could anyone help me if there is a text editor module out in space, > which allows stepping to one line from another of a paragraph? Take a look at the scintilla component, which it the editor used in scite and Pythonwin. I suspect it can do what you want, although I've never used it. But it seems to have lots of functionality. www.scintilla.org Alan G From pythontut at pusspaws.net Sat May 22 04:21:02 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat May 22 04:21:21 2004 Subject: [Tutor] strange variable problem In-Reply-To: <005d01c43fcc$5f36c640$6401a8c0@xp> References: <005d01c43fcc$5f36c640$6401a8c0@xp> Message-ID: <40AF0D6E.1040101@pusspaws.net> Alan Gauld wrote: >>>ftseptr is setup as a global variable, value -1, >>>yftseptr is setup as a global variable, value 0 >>> >>> >>Ah! Common gotcha: when using global variables in functions, you >> >> >may need > > >>to declare that the variable is 'global' in nature. For example: >> >> > >Is that really the problem here? >He is not assigning to the variable merely printing it, >which shouldn't need the global keyword. > >However I don't think we have the full story. >Looking at the traceback: > > > >>Traceback (most recent call last): >> File "/home/dave/gg/gg.py", line 72, in -toplevel- >> gg() >> File "/home/dave/gg/gg.py", line 62, in gg >> file2datacore2(stockdir+dir+'/'+file,syncerr) >> File "/home/dave/gg/gg.py", line 40, in file2datacore2 >> >>ggdatacore2.add(datalist[i+1],datalist[i+3],...syncerr) >> File "/home/dave/gg/ggdatacore2.py", line 30, in add >> print ftseptr >>UnboundLocalError: local variable 'ftseptr' referenced before >> >> >assignment > >we have calls to gg() and file2datacore2 and then add() for > > Yep its part of a larger program .... :-) >which we have the code. Plus the program seems to be run from >a python prompt rather than being executed as a program. > > Its run via IDLE >If that is the case a lot depends on how the imports are being >done because that's when the global variables will be set up. >Presumably, for the code to get this far, the module gg does > >import ggdatacore2 > >But when is gg imported? Has anything changed between then >and the toplevel call to gg()? > >What happens if you run your program outside the python prompt? >Does that change the error in any way? > > > >>### >>count = 0 >>def makeNextName(): >> global count >> nextName = "name%s" % count >> count = count + 1 >> return nextName >>### >> >>If the 'global count' declaration in the function is missing, then >> >> >we'll > > >>get the same UnboundLocalError that you're receiving in your >> >> >program, so I > > >>suspect the same thing is happening there. >> >> > >Yes but in this case the error is because of the assignment which >tries to create a local variable. But Dave's code doesn't assign >to the variable merely prints it. So it should be OK, >unless he hasn't shown us the full code... > >puzzled, > >Alan G. > > I just read your e-mails this morning after staying up to 2:00 Am to fix it ! wish I had downloaded mail earlier :-) The code I pasted to the group was only a section of a larger program calling other scripts, I editied it to what I thought was the problem area rather then send an unwieldy e-mail. From reading you guys emails, and I think I have had a breakthrough .... What confused me whas that I could define 2x global variables at the top of the script, but I could only print one, the other one generated an exception. adding a global inside def add sorted the problem .... def add(id,mid,pence,pc,bid,offer,open,high,low,close,volume,syncerr): global ftseptr,yftseptr # Data cookie - is a list # [num consecutive loads,bad data counter,bad cycle counter] print yftsept # Now works AOK :-) print ftseptr However this did not explain why one variable was OK, the other not ... However further down in def add(...) (err I didn't think this was important :-[ ) I do have a single ftseptr+=1 I guess this is the same as ftseptr=ftseptr+1, an assignment So (wing and prayer thinking here), python scanned my script (at 'compile' time ?), found the ftseptr+=1, treated it as an assignment and therefore local without a global declaration, then tried executing add() found print ftseptr and said .... UnboundLocalError: local variable 'ftseptr' referenced before assignment :-) .... I think so anyhow. Dave PS next time I will paste all the code ... even is it is a bit unwieldy ! From heartlovecrime at yahoo.com Sat May 22 12:19:28 2004 From: heartlovecrime at yahoo.com (Engr Godfrey) Date: Sat May 22 12:19:34 2004 Subject: [Tutor] help (Am New) Message-ID: <20040522161928.73480.qmail@web51509.mail.yahoo.com> dear reader am new to programming i dont even know the meaning of programming. and am interested of beign a programmer and i choice to learn with python can u please tell me where to start from and how to be a perfect programmer and some materials that would help me with my programming. but i already have the software install on my system but dont know how to write a programme i will be greatful if an urgent reply is beign made to this thanks Godfrey please take your time to visit my site here --------------------------------- Do you Yahoo!? Yahoo! Domains - Claim yours for only $14.70/year -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040522/0fae30e3/attachment.html From alan.gauld at blueyonder.co.uk Sat May 22 14:16:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 22 14:16:19 2004 Subject: [Tutor] strange variable problem References: <005d01c43fcc$5f36c640$6401a8c0@xp> <40AF0D6E.1040101@pusspaws.net> Message-ID: <008801c44028$f5d62c60$6401a8c0@xp> > However further down in def add(...) (err I didn't think this was > important :-[ ) I do have a single > ftseptr+=1 > > I guess this is the same as ftseptr=ftseptr+1, an assignment Yep, that'd explain it! > PS next time I will paste all the code ... even is it is a bit unwieldy ! Fragments are OK, but at least check the fragment to check it actually exhibits the same problem! :-) Alan G. From olavi at city.ee Sat May 22 14:22:32 2004 From: olavi at city.ee (olavi@city.ee) Date: Sat May 22 14:22:38 2004 Subject: [Tutor] help (Am New) Message-ID: <20040522182232.3742.qmail@city.ee> Hei, Welcome to the programmers world :), you made a good coice, choosing python your first programming language. Best site, to understand, what language python is, is http://python.org/topics/learn/ . Good luck with discovering python & programming with python :) Olavi Ivask Engr Godfrey wrote: > dear reader > am new to programming > i dont even know the meaning of programming. > and am interested of beign a programmer > and i choice to learn with python > can u please tell me where to start from and how to be a perfect programmer and some materials that would help me with my programming. > but i already have the software install on my system but dont know how to write a programme > > i will be greatful if an urgent reply is beign made to this > thanks > > Godfrey From prospero at prosperosisland.co.uk Sat May 22 20:38:25 2004 From: prospero at prosperosisland.co.uk (Prospero) Date: Sat May 22 20:38:36 2004 Subject: [Tutor] Odd problem Message-ID: <002b01c4405e$4456a8d0$e5f22ad9@Miranda> Greetings! Firstly, much thanks to those who responded to my last question. That enabled me to complete a program in Python that was going to take weeks to run in the language I had been using before. As far as I can tell from test runs it should complete in about two and a half hours in the Python version, which is obviously much better for me. Now for the weird bit. Every time I try to run the thing it gets partway through and then my computer overheats and dies. (I am working on a laptop which is slightly temperamental but not usually that bad.) The best it has managed so far is about a fifth of the full task but there is no consistency to when it dies in terms of the percentage completed. I therefore need to either slow the program down so that the machine can handle it or cut the task into chunks, of which the latter strikes me as the more practical approach. To do that I need it to save six integer values to a text file at the end of each run and then take those values as the starting point for the next run. I cannot find anything in the Python documentation about how to read integers from a text file into a list. I assume there is a logical opposite to str() but have not seen it as yet. Any help would be much appreciated. All the best, Prospero. "Everything that is really great and inspiring is created by the individual who can labor in freedom." -- Albert Einstein Prospero's Island http://www.prosperosisland.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040523/8d53b411/attachment.html From lumbricus at gmx.net Sat May 22 22:29:49 2004 From: lumbricus at gmx.net (Joerg Woelke) Date: Sat May 22 22:37:21 2004 Subject: [Tutor] Odd problem In-Reply-To: <002b01c4405e$4456a8d0$e5f22ad9@Miranda> References: <002b01c4405e$4456a8d0$e5f22ad9@Miranda> Message-ID: <20040523022949.GA1371@linux.local> On Sun, May 23, 2004 at 01:38:25AM +0100, Prospero wrote: > Greetings! [ snip ] > I cannot find anything in the Python documentation about how to read integers from a text file into a list. I assume there is a logical opposite to str() but have not seen it as yet. Any help would be much appreciated. >>> s="666" >>> i=int(s) >>> type(i) > All the best, > > Prospero. HTH and Re, J"o! -- memento mori From pythontut at pusspaws.net Sun May 23 05:32:25 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun May 23 05:32:48 2004 Subject: [Tutor] strange variable problem In-Reply-To: <008801c44028$f5d62c60$6401a8c0@xp> References: <005d01c43fcc$5f36c640$6401a8c0@xp> <40AF0D6E.1040101@pusspaws.net> <008801c44028$f5d62c60$6401a8c0@xp> Message-ID: <40B06FA8.5010103@pusspaws.net> Alan Gauld wrote: >>However further down in def add(...) (err I didn't think this was >>important :-[ ) I do have a single >>ftseptr+=1 >> >>I guess this is the same as ftseptr=ftseptr+1, an assignment >> >> > >Yep, that'd explain it! > > > >>PS next time I will paste all the code ... even is it is a bit >> >> >unwieldy ! > >Fragments are OK, but at least check the fragment to check it actually >exhibits the same problem! :-) > >Alan G. > > > Thats a roger, will double check it :-) Dave From pythontut at pusspaws.net Sun May 23 05:49:19 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun May 23 05:49:33 2004 Subject: [Tutor] OT How to approach problem ? Message-ID: <40B0739F.4070502@pusspaws.net> This is probarbly a Python style question ... Having written a program to track the ftse250, I have two large lists of dictionaries forming 2 x 'fluid' matries. To access this data I have various defs which all use common pointers into the matries. As a result I have lots of 'global' statements for each def to share these pointers (Cheers guys, you made it possible ;-) ) OK this works, but apparently globals are to be avoided. (Ahh ... Harp back to Basic + FORTH ....) The only other way I can see is to define a class, and use self.pointer instead of global pointers .... Since there would only be one instance of this class this seems a strange way to approach it. I guess what I am asking is ... How would an experiensed Python programmer approach it ? Dave From missive at hotmail.com Sun May 23 10:42:55 2004 From: missive at hotmail.com (Lee Harr) Date: Sun May 23 10:43:17 2004 Subject: [Tutor] Re: Odd problem Message-ID: >[...] I need it to save six integer >values to a text file at the end of each run and then take those values >as the starting point for the next run. http://python.org/doc/current/lib/module-shelve.html _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From blugerz at yahoo.com Sun May 23 13:27:57 2004 From: blugerz at yahoo.com (brian illingworth) Date: Sun May 23 13:28:03 2004 Subject: [Tutor] Thanks-finally got it to work Message-ID: <20040523172757.52389.qmail@web41504.mail.yahoo.com> Thanks for everyones help I finally got it to work: #Limiting password atempts to three count = 1 password = "" while not password and count < 3: password = raw_input("Please enter your Password: ") count += 1 if password == "secret": print "Welcome in." elif raw_input("Please enter your Password: "): count += 1 else: count == 3 print "Try again later when you remember your password." raw_input("Press enter to exit.") It may not be the perfect way, but it is finally doing what I want it to. Time to move on to the next one, and I am sure I will have more questions. __________________________________ Do you Yahoo!? Yahoo! Domains – Claim yours for only $14.70/year http://smallbusiness.promotions.yahoo.com/offer From chriscasey at ev1.net Sun May 23 17:13:21 2004 From: chriscasey at ev1.net (Chris Casey) Date: Sun May 23 17:06:13 2004 Subject: [Tutor] pg or pgdb? Message-ID: <200405231613.21716.chriscasey@ev1.net> I'm trying to teach myself how to use Python with Postgresql with what came with SuSE 9.0 (I believe pygresql). I've found a little documentation on the pg module, at least enough to get started. I noticed that there is also a pgdb module, but haven't found much documentation on it. Are there major differences between the two, & any reasons I should use one over the other? Chris From alan.gauld at blueyonder.co.uk Sun May 23 18:20:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun May 23 18:19:32 2004 Subject: [Tutor] Odd problem References: <002b01c4405e$4456a8d0$e5f22ad9@Miranda> Message-ID: <00b301c44114$26730500$6401a8c0@xp> > I cannot find anything in the Python documentation about how to > read integers from a text file into a list. I assume there is a > logical opposite to str() but have not seen it as yet. Yes, try int() :-) Really, it is that simple... The >>> prompt is a great place to try out ideas, in Python, often the intuitive approach just works, it's always worth a try... Alan G. From alan.gauld at blueyonder.co.uk Sun May 23 18:27:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun May 23 18:26:08 2004 Subject: [Tutor] OT How to approach problem ? References: <40B0739F.4070502@pusspaws.net> Message-ID: <00bc01c44115$11e5fba0$6401a8c0@xp> > Having written a program to track the ftse250, I have two large lists of > dictionaries forming 2 x 'fluid' matries. To access this data I have > various defs which all use common pointers into the matries. Probably twoi clases or maybe just two instances of one class - since they are both lists of dictionaries they presumably share common behaviour? > OK this works, but apparently globals are to be avoided. In principle yes, but... > The only other way I can see is to define a class, and use self.pointer > instead of global pointers .... Since there would only be > one instance of this class this seems a strange way to approach it. One instance of a class is just hiding global variables. Might still be better because who knows when you find a need for multiple instances (maybe even in another program 9in the future...). But generally a single instance is just wallpaper over globals. The other normal approach is to pass the pointers in as parameters of the functions. This might mean a lot of parameters but intelligent use of default values can often make it manageable and make the functions much more reusable. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sun May 23 18:30:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun May 23 18:29:41 2004 Subject: [Tutor] help (Am New) References: <20040522182232.3742.qmail@city.ee> Message-ID: <00c301c44115$93871a40$6401a8c0@xp> > Best site, to understand, what language python is, is http://python.org/topics/learn/ . > And for a non-programmer even more specifically try: http://www.python.org/topics/learn/non-prog.html And being biased I think my tutorial is pretty good :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From cybersamurai at terra.com.br Sun May 23 23:55:10 2004 From: cybersamurai at terra.com.br (Luiz Siqueira) Date: Sun May 23 23:48:06 2004 Subject: [Tutor] some questions about dcom server, SOAP WSDL and Internet Explorer Message-ID: <40B1721E.9040300@terra.com.br> I have some questions: 1 Some one have information about some implementation of dcom server for Python? 2 Some one know a easy way to build WSDL for a Python SOAPpy server? 3 I need take control of Internet Explorer on Windows 95 or hight: A - Have some way to send HTML, XML direct to IE trough COM or some like that? B - Have some easy way to send messages from javascript inside of IE for a python application using HTTP or some like that? C - Some one know some small HTTP server implementation in Python? For me HTTP server look like a possible solution, but need to be little for be possible make a little and easy installation for end users. sorry about my english From janitor at gmail.com Mon May 24 02:02:05 2004 From: janitor at gmail.com (Darshan Gunawardena) Date: Mon May 24 02:02:13 2004 Subject: [Tutor] some questions about dcom server, SOAP WSDL and Internet Explorer In-Reply-To: <40B1721E.9040300@terra.com.br> References: <40B1721E.9040300@terra.com.br> Message-ID: <8f4e4696040523230265f1a524@mail.gmail.com> For 3.c maybe you can look at www.zope.org On Mon, 24 May 2004 00:55:10 -0300, Luiz Siqueira wrote: > > I have some questions: > > 1 Some one have information about some implementation of dcom server for > Python? > > 2 Some one know a easy way to build WSDL for a Python SOAPpy server? > > 3 I need take control of Internet Explorer on Windows 95 or hight: > > A - Have some way to send HTML, XML direct to IE trough COM or some > like that? > B - Have some easy way to send messages from javascript inside of IE > for a python application using HTTP or some like that? > C - Some one know some small HTTP server implementation in Python? > For me HTTP server look like a possible solution, but need to be little > for be possible make a little and easy installation for end users. > > sorry about my english > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythontut at pusspaws.net Mon May 24 03:47:42 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon May 24 03:47:58 2004 Subject: [Tutor] OT How to approach problem ? In-Reply-To: <00bc01c44115$11e5fba0$6401a8c0@xp> References: <40B0739F.4070502@pusspaws.net> <00bc01c44115$11e5fba0$6401a8c0@xp> Message-ID: <40B1A89E.1050600@pusspaws.net> Alan Gauld wrote: >>Having written a program to track the ftse250, I have two large >> >> >lists of > > >>dictionaries forming 2 x 'fluid' matries. To access this data I have >>various defs which all use common pointers into the matries. >> >> > >Probably twoi clases or maybe just two instances of one class >- since they are both lists of dictionaries they presumably >share common behaviour? > > The second matrix is a deep copy of the first at the end of a trading day so stock information for two days is retained. Statistical info is only generated & stored in the first matrix, then copied. > > >>OK this works, but apparently globals are to be avoided. >> >> > >In principle yes, but... > > > >>The only other way I can see is to define a class, and use >> >> >self.pointer > > >>instead of global pointers .... Since there would only be >>one instance of this class this seems a strange way to approach it. >> >> > >One instance of a class is just hiding global variables. Might still >be >better because who knows when you find a need for multiple instances >(maybe even in another program 9in the future...). But generally a >single instance is just wallpaper over globals. > > ... this confirms something I suspected. Turning it into a one instance class would work but seems a bit fruitless ... >The other normal approach is to pass the pointers in as parameters of >the functions. This might mean a lot of parameters but intelligent >use of default values can often make it manageable and make the >functions much more reusable. > > I was concerned about speed, I would be passing a lot of data through another layer of def. Scanning the matrix via another function which would be called 110*250*12=330,000 times a throw. I guess the only way to find out the time penalty is to code it & time it :-) I appreciate your help, Although I 'bodged' it with globals It is good to see other alternatives. Cheers Dave >HTH, > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > > > > From martin at hardcoder.dk Mon May 24 04:43:01 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Mon May 24 04:44:59 2004 Subject: [Tutor] Creating an object with a string Message-ID: <40B1B595.6080901@hardcoder.dk> I am parsing an XML file, and based on certain tags, i want to create certain objects. During the parsing i generate a string, with which i determine what type of object I want to create. The simple way is to have som if statements to determine it, but I was wondering if there is not a more "smart" method. I also do lot of PHP programming, where it is possible to do: In that way I am able to with very few lines, to create an object based on a string. Is there any way of doing something similar in Python? regards Martin Hjort Eriksen From roeland.rengelink at chello.nl Mon May 24 05:07:40 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Mon May 24 05:09:30 2004 Subject: [Tutor] Creating an object with a string In-Reply-To: <40B1B595.6080901@hardcoder.dk> References: <40B1B595.6080901@hardcoder.dk> Message-ID: <40B1BB5C.6080501@chello.nl> Martin Hjort Eriksen wrote: > I am parsing an XML file, and based on certain tags, i want to create > certain objects. During the parsing i generate a string, with which i > determine what type of object I want to create. The simple way is to > have som if statements to determine it, but I was wondering if there > is not a more "smart" method. I also do lot of PHP programming, where > it is possible to do: > > $object = "ClassToCreate"; > > $newObject = new $object(); > > ?> > > In that way I am able to with very few lines, to create an object > based on a string. Is there any way of doing something similar in Python? > The canonical way to do this with Python is to create a dictionary that maps strings to classes. E.g: class A: ... class B: ... cls_map = {'A': A, 'B':B} def create_class(a_string): return cls_map[a_string]() If your strings match the class names then you could use eval() instance = eval(a_string+"()") Hope this helps, Roeland From martin at hardcoder.dk Mon May 24 05:26:53 2004 From: martin at hardcoder.dk (Martin Hjort Eriksen) Date: Mon May 24 05:28:55 2004 Subject: [Tutor] Creating an object with a string In-Reply-To: <40B1BB5C.6080501@chello.nl> References: <40B1B595.6080901@hardcoder.dk> <40B1BB5C.6080501@chello.nl> Message-ID: <40B1BFDD.8080300@hardcoder.dk> > The canonical way to do this with Python is to create a dictionary > that maps strings to classes. E.g: > > class A: > ... > > class B: > ... > > cls_map = {'A': A, 'B':B} > > def create_class(a_string): > return cls_map[a_string]() > > If your strings match the class names then you could use eval() > > instance = eval(a_string+"()") > > Hope this helps, > > Roeland > This helped...thank you very much... A second question in the same area, again the start point is PHP, where you have variable variables. I have also looked through the Python litterature, and cannot find anything that helps. The problem is, as I instantiate the objects, I will put them in an dictionary, where I have 4 dictionaries, one for each type of class. Since I have mulitple instances if the classes, I have added copy to the above code that Roeland sent. Based on that string I want to insert it into the correct dictionary, without using if many if sentences. PHP example again: From riccardo at reflab.it Mon May 24 10:26:44 2004 From: riccardo at reflab.it (Riccardo Lemmi) Date: Mon May 24 10:27:09 2004 Subject: [Tutor] Re: Creating an object with a string References: <40B1B595.6080901@hardcoder.dk> Message-ID: Martin Hjort Eriksen wrote: > I am parsing an XML file, and based on certain tags, i want to create > certain objects. During the parsing i generate a string, with which i > determine what type of object I want to create. The simple way is to > have som if statements to determine it, but I was wondering if there is > not a more "smart" method. I also do lot of PHP programming, where it is > possible to do: > > $object = "ClassToCreate"; > > $newObject = new $object(); > > ?> > > In that way I am able to with very few lines, to create an object based > on a string. Is there any way of doing something similar in Python? > > regards > > Martin Hjort Eriksen > >From shell: >>> class ClassToCreate: ... pass ... >>> newObject = globals()['ClassToCreate']() >>> newObject <__main__.ClassToCreate instance at 0x4029e98c> >>> If you use a module, for example: >>> import UserDict >>> ClassToCreate = getattr(UserDict,'UserDict') >>> x=ClassToCreate() >>> x {} >>> -- Riccardo Lemmi From christian at treesforlife.org Mon May 24 10:50:21 2004 From: christian at treesforlife.org (Christian Junker) Date: Mon May 24 11:00:32 2004 Subject: [Tutor] stdout Question Message-ID: Hello everybody, I am new to Python so please forgive me for any mistakes I do in the next few lines. My OS is Win2000, and my Python version is 2.3.3 with the Win Addon from Mark Hammond, whose IDE I use (PythonWin). What I simply want to do is print out a bold text/ or making the first character in the text bold. And I am having big problems how to do that and can't seem to find anything that could help me. I would appreciate any help. Christian From alan.gauld at blueyonder.co.uk Mon May 24 12:51:12 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon May 24 12:50:04 2004 Subject: [Tutor] Thanks-finally got it to work References: <20040523172757.52389.qmail@web41504.mail.yahoo.com> Message-ID: <00eb01c441af$524e1e30$6401a8c0@xp> > Thanks for everyones help I finally got it to work: Are you sure? What this does is tries 3 times to get a password - any password not just the right one. > #Limiting password atempts to three > > count = 1 > password = "" > > while not password and count < 3: > password = raw_input("Please enter your Password: > ") > count += 1 > > if password == "secret": > print "Welcome in." > > elif raw_input("Please enter your Password: "): > count += 1 And incrementing count here has no effect whatsoever because you are now outside the while loop. > else: > count == 3 And this line just evaluates to a boolean value but is not used. > print "Try again later when you remember your > password." > > raw_input("Press enter to exit.") > > It may not be the perfect way, but it is finally doing > what I want it to. You may be right, but I wonder if you have actually tested it fully. For example try these scenarios and see if they do what you expect: 1) Run the program and hit return with no password everytime. 2) Run the program but using the wrong value the first time. 3) Run the program and use the wrong value twice 4) Run the program and use the wrong value three times 5) Run the program and use the wrong value four times(!) 6) Run the program and use the right value first time. If they all do what you expect, congratulations, it's just your interpretation of the requirements were different to mine. If not its time to pull the thinking cap back on. :-) Alan G. From alan.gauld at blueyonder.co.uk Mon May 24 12:54:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon May 24 12:53:15 2004 Subject: [Tutor] some questions about dcom server, SOAP WSDL and Internet Explorer References: <40B1721E.9040300@terra.com.br> <8f4e4696040523230265f1a524@mail.gmail.com> Message-ID: <00fa01c441af$c4e01ac0$6401a8c0@xp> > For 3.c maybe you can look at www.zope.org Zope is probably too big, but there is a small sample server ships with Python in the library someplace. Check out the various http, web type modules. There is a very basic one, and one that supports CGI I think. Alan G From alan.gauld at blueyonder.co.uk Mon May 24 12:58:02 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon May 24 12:56:52 2004 Subject: [Tutor] OT How to approach problem ? References: <40B0739F.4070502@pusspaws.net> <00bc01c44115$11e5fba0$6401a8c0@xp> <40B1A89E.1050600@pusspaws.net> Message-ID: <010101c441b0$46d3c630$6401a8c0@xp> > >The other normal approach is to pass the pointers in as parameters of > > > I was concerned about speed, I would be passing a lot of data through > another layer of def. Because Python only passes references to the objects there is very little overhead in passing parameters, the real overhead is the actual function call itself. Adding parameters makes the code more reusable and safer and carries very little overhead. > I guess the only way to find out the time penalty is to code it & time > it :-) This is always a good idea when thinking about performance... Alan G. From alan.gauld at blueyonder.co.uk Mon May 24 13:01:59 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon May 24 13:00:51 2004 Subject: [Tutor] Creating an object with a string References: <40B1B595.6080901@hardcoder.dk> Message-ID: <010601c441b0$d3d27090$6401a8c0@xp> > I am parsing an XML file, and based on certain tags, i want to create > certain objects. Sounds exactly like SAX to me. I assume you are using the standard parsers and not trying to craft something by habd based on regexs or somesuch? SAX is an event based parser so you simply create a function that you associate with each XML tag you are interested in. When the parser hits that tag type it calls your function. > $object = "ClassToCreate"; > > $newObject = new $object(); You could do something like that with eval() but using eval() and exec() should really be a last resort, better to use the power of the tools IMHO. Alan G. From alan.gauld at blueyonder.co.uk Mon May 24 13:16:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon May 24 13:15:15 2004 Subject: [Tutor] stdout Question References: Message-ID: <011101c441b2$d8a9fe60$6401a8c0@xp> > My OS is Win2000, and my Python version is 2.3.3 with the Win Addon from > Mark Hammond, whose IDE I use (PythonWin). So far so good. > What I simply want to do is print out a bold text/ or making the first > character in the text bold. That depends entirely on where you print it. Since your subject line says stdout I'll assume that's what you mean. Stdout is a file, it is not a display device. Normally the stdout file is redirected to a terminal screen, in your case a Command Prompt (or DOS Box). Basically the DOS BOx displays whatever the stdout file contains so if you want to display Bold characters you need to insert the ANSI control characters to enable/disable bold display. ANSI control codes consist of the escape character followed by a character, for example to clear the screen: >>> # chr(27) is the ESC code, [2J is the clear screen combination >>> print chr(27)+'[2J' This used to be a common technique on PCs before Windows came along. Its messy but works. Here is a web page with the various codes: http://www.bluesock.org/~willg/dev/ansi.html For it to work you will also need to ensure that ANSI.SYS is loaded since it is ANSI.SYS that controls how DOS displays things, it has nothing to do with Python. In general if I want fancy formatting I opt to use a GUI like Tkinter and its Text widget which allows me to do text formatting more easily or if its for printouts I use HTML and generate an intermediate file. HTH, Alan G. From alan.gauld at blueyonder.co.uk Mon May 24 13:20:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon May 24 13:19:48 2004 Subject: [Tutor] some questions about dcom server, SOAP WSDL and Internet Explorer References: <40B1721E.9040300@terra.com.br> Message-ID: <011601c441b3$7a1d79c0$6401a8c0@xp> > 1 Some one have information about some implementation of dcom server for > Python? Look at Mark Hammond's winall package (or the ActiveState version of Python) Also Marks book Python Programming on Win32 looks like it will be essential reading for you... > 2 Some one know a easy way to build WSDL for a Python SOAPpy server? There is some web documentation around on writing SOAP with Python, try a Google search. > 3 I need take control of Internet Explorer on Windows 95 or hight: > > A - Have some way to send HTML, XML direct to IE trough COM or some > like that? Winall to the rescue here too > B - Have some easy way to send messages from javascript inside of IE > for a python application using HTTP or some like that? You can go yto a URL using Javascript, whether thats enough depends on what you need to do. In general its a bad idea to try that kind of thing since the browser is liely to be restricted for security reasons. Which is why you can't open local files etc from Javascript in a browser. > C - Some one know some small HTTP server implementation in Python? > For me HTTP server look like a possible solution, but need to be little > for be possible make a little and easy installation for end users. The http server might do, or the cgi server, both are quite small by todays standards. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From blugerz at yahoo.com Tue May 25 01:45:45 2004 From: blugerz at yahoo.com (brian illingworth) Date: Tue May 25 01:45:51 2004 Subject: [Tutor] Oh boy!! Message-ID: <20040525054545.86153.qmail@web41502.mail.yahoo.com> 1) Run the program and hit return with no password everytime. -Okay, that works 2) Run the program but using the wrong value the first time. -That works too 3) Run the program and use the wrong value twice -Ok, no working so good here 4) Run the program and use the wrong value three times -Or here 5) Run the program and use the wrong value four times -or here 6) Run the program and use the right value first time. -This works Oh boy, now I forgot where I put my thinking cap! __________________________________ Do you Yahoo!? Friends. Fun. Try the all-new Yahoo! Messenger. http://messenger.yahoo.com/ From pythontut at pusspaws.net Tue May 25 05:39:52 2004 From: pythontut at pusspaws.net (Dave S) Date: Tue May 25 05:40:11 2004 Subject: [Tutor] IDLE problems, recommend a good IDE ? Message-ID: <40B31468.4020409@pusspaws.net> Ive been learning on IDLE, which has been great but I have had occasional stability problems, which are a bit disconcerting. It just locked up X on my gentoo system :-( Anyhow Im back now - Thanks to alt-sysreq-r I didn't have to re-boot. Can anybody recomend a good python IDE, Something functional without too many gizmos ! Im running Gentoo 1.4 though I am happy to compile from source if needbe. Dave From cybersamurai at terra.com.br Tue May 25 06:38:00 2004 From: cybersamurai at terra.com.br (Luiz Siqueira) Date: Tue May 25 06:30:52 2004 Subject: [Tutor] Another option for bobo/zobject/zpublicher? Message-ID: <40B32208.9000704@terra.com.br> Some one know another project with the same idea of "bobo"? I need get a call from a browser using HTTP and send this direct to some object. I can implement that, but if this exist I prefer join to project. Thanks for some help From jsh47 at cam.ac.uk Tue May 25 11:02:07 2004 From: jsh47 at cam.ac.uk (Jonathan Hayward) Date: Tue May 25 11:02:48 2004 Subject: [Tutor] CGI oddity Message-ID: <40B35FEF.1000004@cam.ac.uk> http://JonathansCorner.com/etc/datamine/datamine0_0b.tgz There is a daemon server and a thin web client which queries the server. If, in the server, I change configuration_class.get_action_method() to return "post" instead of "get" (so we have """
"""), queries frequently hang. I'd like to have the forms use "post" so I don't have to worry about data size. The thin client pickles and dumps cgi.FieldStorage() to a socket, which is then read and deserialized by multitasking_manager.handle_oracle_query() in the third line or so, in the server. Can anyone offer a suggestion that will fix or circumvent the hanging if I use the "post" method? -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From John.Ertl at fnmoc.navy.mil Tue May 25 12:12:13 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Tue May 25 12:08:20 2004 Subject: [Tutor] IDLE problem Message-ID: All, I have been given a virtual system to play with which also means I have to load all things myself. I think I have all the needed stuff loaded but when I try to run idle I get: ** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** I have checked and tk and Tkinter are there. I read some vague reference to needing to say yes to loading Tk when python is loaded but I was not asked (or could I find any reference in the config files) about loading Tk. I am not a system admin type so I probably missed something. Any ideas are appreciated. John Ertl From alan.gauld at blueyonder.co.uk Tue May 25 13:27:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 25 13:27:31 2004 Subject: [Tutor] Another option for bobo/zobject/zpublicher? References: <40B32208.9000704@terra.com.br> Message-ID: <014c01c4427d$9ed23ce0$6401a8c0@xp> > Some one know another project with the same idea of "bobo"? Well Bobo became Zope which works as you describe. I asume you looked at Zope? Alan G From acidrex at earthlink.net Tue May 25 14:25:42 2004 From: acidrex at earthlink.net (acidblue) Date: Tue May 25 14:25:49 2004 Subject: [Tutor] Using datetime module Message-ID: <002601c44285$b219dee0$0a4ffea9@amdbox> I'm trying to add dates together using datetime module. I want usr's to enter a date and add a number of days to it. Example: import datetime usrDate= input("Enter the date:") T= input("Enter how many days:") print datetime.date.today() + datetime.timedelta(days=T) Obviosly the 'datetime.date.today()' only works for today's date What I what is this: Psuedo code: usrDate + datetime.timedelta(days=T) Am I using the right module? Syntax? Arguments? From pythonTutor at venix.com Tue May 25 15:18:03 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue May 25 15:18:09 2004 Subject: [Tutor] clearing traceback after exeption is handled Message-ID: <1085512683.2098.79.camel@laptop.venix.com> When possible, I have my Python programs send an email when there is a failure or problem during execution. The email routine ALWAYS calls traceback.print_exc. Today I got an email with a "stale" traceback from an exception that had been handled along with information about the real problem. I started researching the traceback before I realized it was not relevant. It took me a while to find out how to clear an exception after handling it, so I thought it was worth posting the information. In Python 2.3, the sys module now has a function exc_clear that will clear all information relating to the last or current exception for the current thread. It is mostly of use to prevent logging and reporting of exceptions that have already been handled. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From alan.gauld at blueyonder.co.uk Tue May 25 16:50:49 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue May 25 16:50:21 2004 Subject: [Tutor] OT: Help required Message-ID: <015401c44299$f61a6150$6401a8c0@xp> I think this is OT, but someone emailed me from my web tutor but I don't know which language or what they are saying. I've tried the BabelFish translator for Spanish, Portugese, Italian and drawn blanks with all 3. If anyone here can translate, please reply to me directly. Thanks, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ------------ message follows ------------ hola a mi me intereza saver programar en python y me gustaria poder bajar este programa para poder practicar me podrias decir como? From jb at riseup.net Tue May 25 17:34:20 2004 From: jb at riseup.net (jb) Date: Tue May 25 17:34:56 2004 Subject: [Tutor] OT: Help required In-Reply-To: <015401c44299$f61a6150$6401a8c0@xp> References: <015401c44299$f61a6150$6401a8c0@xp> Message-ID: <20040525213420.GA5505@tsoupi.fl.sakeos.net> On Tue, May 25, 2004 at 09:50:49PM +0100, Alan Gauld wrote: > I think this is OT, but someone emailed me from my web > tutor but I don't know which language or what they are > saying. I've tried the BabelFish translator for Spanish, > Portugese, Italian and drawn blanks with all 3. > > If anyone here can translate, please reply to me directly. > > Thanks, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > ------------ message follows ------------ > hola a mi me intereza saver programar en python y me > gustaria poder bajar este programa para poder practicar > me podrias decir como? > here's a translation, (cc'ing to the list so that you dont receive thousand of them). hi, i'm interested in knowing how to program in python and i'd like to download this software to practice. can you tell me how to do that ? later' jb From op73418 at mail.telepac.pt Tue May 25 18:07:53 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue May 25 18:04:56 2004 Subject: [Tutor] OT: Help required In-Reply-To: <015401c44299$f61a6150$6401a8c0@xp> References: <015401c44299$f61a6150$6401a8c0@xp> Message-ID: Em Tue, 25 May 2004 21:50:49 +0100, "Alan Gauld" atirou este peixe aos pinguins: >I think this is OT, but someone emailed me from my web >tutor but I don't know which language or what they are >saying. I've tried the BabelFish translator for Spanish, >Portugese, Italian and drawn blanks with all 3. > >If anyone here can translate, please reply to me directly. > >Thanks, > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > >------------ message follows ------------ >hola a mi me intereza saver programar en python y me >gustaria poder bajar este programa para poder practicar >me podrias decir como? > Spanish. A (rough) translation, follows: Hello I'm interesting in learning how to program in Python and I would like to download this program so I can practice, could you tell me how? With my best regards, G. Rodrigues From darnold02 at sprynet.com Tue May 25 22:12:15 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Tue May 25 22:12:13 2004 Subject: [Tutor] Using datetime module In-Reply-To: <002601c44285$b219dee0$0a4ffea9@amdbox> Message-ID: A datetime.date object can be set to a given date by passing in the year, month, and day as parameters when you create it. So, you could do something like this: import datetime usrDate= raw_input("Enter the date (yyyy/mm/dd format): ") T = int(raw_input("Enter how many days: ")) offset = datetime.timedelta(days=T) yyyy = int(usrDate[0:4]) mm = int(usrDate[5:7]) dd = int(usrDate[8:]) usrDateObj = datetime.date(year=yyyy,month=mm,day=dd) print '%s + %d days = %s' % (usrDateObj, T, usrDateObj + offset) [-----begin script run-----] Enter the date (yyyy/mm/dd format): 2004/01/01 Enter how many days: 59 2004-01-01 + 59 days = 2004-02-29 [-----end script run-----] HTH, Don -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of acidblue Sent: Tuesday, May 25, 2004 1:26 PM To: tutor@python.org Subject: [Tutor] Using datetime module I'm trying to add dates together using datetime module. I want usr's to enter a date and add a number of days to it. Example: import datetime usrDate= input("Enter the date:") T= input("Enter how many days:") print datetime.date.today() + datetime.timedelta(days=T) Obviosly the 'datetime.date.today()' only works for today's date What I what is this: Psuedo code: usrDate + datetime.timedelta(days=T) Am I using the right module? Syntax? Arguments? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kkurnia at bigw.com.au Tue May 25 22:28:02 2004 From: kkurnia at bigw.com.au (Kurt Kurniawan) Date: Tue May 25 22:24:36 2004 Subject: [Tutor] Another option for bobo/zobject/zpublicher? Message-ID: There is a cool project called TWISTED MATRIX. It has a lot of networking framework including HTTP server. Probably you can try that. http://twistedmatrix.com/ Message: 9 Date: Tue, 25 May 2004 07:38:00 -0300 From: Luiz Siqueira Subject: [Tutor] Another option for bobo/zobject/zpublicher? To: tutor@python.org Message-ID: <40B32208.9000704@terra.com.br> Content-Type: text/plain; charset=us-ascii; format=flowed Some one know another project with the same idea of "bobo"? I need get a call from a browser using HTTP and send this direct to some object. I can implement that, but if this exist I prefer join to project. Thanks for some help Kurt Kurniawan CAUTION: This message may contain confidential information intended only for the use of the addressee named above. If you are not the intended recipient of this message, any use or disclosure of this message is prohibited. If you received this message in error please notify email Administrators immediately. You must obtain all necessary intellectual property clearances before doing anything other than displaying this message on your monitor. There is no intellectual property licence. Any views expressed in this message are those of the individual sender and may not necessarily reflect the views of BIG W Discount Stores. From rantek at pacific.net.sg Wed May 26 02:29:38 2004 From: rantek at pacific.net.sg (William Rance) Date: Wed May 26 02:33:09 2004 Subject: [Tutor] Programming Style Message-ID: <000101c442ea$f4cbe480$e24518d2@pcmaster> A Pure Mathematician(PM) and an Applied Mathematician(AM) were put in separate rooms and located 20ft from an Apple.They were informed that to reach the apple they had to jump 10ft, followed by another jump of half thedistance (5ft) followed by subsequent jumps each of which would be half the distance of preceding jump. The PM quickly calculated that no matter how may jumps he made he could never land at the apple, consequently he did not attempt the jumps. The AM however immediately started jumping, as he calculated that after 5 to6 jumps he would land close enough to grab the apple. Happy coding to all. Bill From op73418 at mail.telepac.pt Wed May 26 07:01:28 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed May 26 06:58:32 2004 Subject: [Tutor] Programming Style In-Reply-To: <000101c442ea$f4cbe480$e24518d2@pcmaster> References: <000101c442ea$f4cbe480$e24518d2@pcmaster> Message-ID: Em Wed, 26 May 2004 14:29:38 +0800, "William Rance" atirou este peixe aos pinguins: >A Pure Mathematician(PM) and an Applied Mathematician(AM) were put in >separate rooms and located 20ft from an Apple.They were informed that to >reach the apple they had to jump 10ft, followed by another jump of half >thedistance (5ft) followed by subsequent jumps each of which would be half >the >distance of preceding jump. >The PM quickly calculated that no matter how may jumps he made he could >never land at the apple, consequently he did not attempt the jumps. >The AM however immediately started jumping, as he calculated that after 5 >to6 jumps he would land close enough to grab the apple. > Actually you're wrong on the motivations: The PM knows a geometric series when he sees one, so he proved on paper that after an infinite amount jumps (and an infinite amount of time) he would have jumped a distance of *exactly* 10*(1/(1-1/2)) = 20 20ft that is, which means he would land *exactly* on top of the apple. Being satisfied with this result (which he reached after a few seconds) he delivered a paper (on LaTeX) to the examiners, posted a copy to the arxiv, and sent another one to the Board of Advances in Mathematics, and then went on to do more interesting things than be a guinea pig to *mutter obscenities against the examiners*. By God! he didn't even liked apples! With my best regards, G. Rodrigues P.S: He thought about slicing off the arms of the AM, but he wouldn't be so cruel and destroy the pleasure of such simpleton minds, now would he ;-) From tim at johnsons-web.com Wed May 26 11:48:32 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed May 26 11:43:53 2004 Subject: [Tutor] IDLE problems, recommend a good IDE ? In-Reply-To: <40B31468.4020409@pusspaws.net> References: <40B31468.4020409@pusspaws.net> Message-ID: <20040526154831.GI23820@johnsons-web.com> * Dave S [040525 01:56]: > Ive been learning on IDLE, which has been great but I have had > occasional stability problems, which are a bit > disconcerting. It just locked up X on my gentoo system :-( Anyhow Im > back now - Hi Dave: Before you 'switch', are you absolutley certain that there aren't system problems causing your IDLE problems? I use gvim (graphical Vi Much Improved) and vim extensively for python programming. There are extensive python plugins for vim that make it a very nice IDE. You can in fact, compile the python interpreter directly into vim so that you can modify or 'drive' your 'python IDE' using python code. There there is GNU Emacs and Xemacs. Unlike vim, these are modeless editors with complex key mappings and are 'driven' by LISP. So some level of LISP skill would help. Both lineages have both rabid fans and those who hate'm. I like them both and couldn't do without them as a programmer. JMTCW tj > Thanks to alt-sysreq-r I didn't have to re-boot. > > Can anybody recomend a good python IDE, Something functional without too > many gizmos ! P.S. : From your statement above, you want something simple? Simple is easy to learn are hard to make really productive IMHO. > Im running Gentoo 1.4 though I am happy to compile from source if needbe. > > Dave > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From fant at pobox.com Wed May 26 12:08:58 2004 From: fant at pobox.com (Andrew Fant) Date: Wed May 26 12:09:09 2004 Subject: [Tutor] IDLE problems, recommend a good IDE ? In-Reply-To: <20040526154831.GI23820@johnsons-web.com> References: <40B31468.4020409@pusspaws.net> <20040526154831.GI23820@johnsons-web.com> Message-ID: <88330000.1085587738@flux.usg.tufts.edu> --On Wednesday, May 26, 2004 07:48:32 -0800 Tim Johnson wrote: > * Dave S [040525 01:56]: >> Ive been learning on IDLE, which has been great but I have had >> occasional stability problems, which are a bit >> disconcerting. It just locked up X on my gentoo system :-( Anyhow Im >> back now - > Dave: Good to see more gentoo-types coming out of the woodwork. I'd check my optimizations settings in make.conf and steer away from excessive compiler flags, just as generic advice. If you are depending on -f flags instead of the -O and -march/-mcpu options, wierd things can happen. As far as IDEs go, I never got into idle myself. boa-constructor is in portage, but it is a rather heavyweight tool for developing larger apps (particularly gui tools with WxPython). I've played with it a little, but it is almost certainly overkill for those of us, including myself, who are still learning. I'm doing all my coding lately in Komodo. It's not free, but Activestate sells the educational/hobbiest version for about 30 dollars. The key bindings are a little annoying, and I am working on setting them to be more emacsish, but aside from that, it works very nicely. It also has a nice graphical source debugger built in which has saved my rear several times lately. If you use komodo as a professional developer, you are supposed to by their pro version which is more expensive, but also includes a graphical gui builder and support for tcl/tk (the educational version supports perl, python, and php fully, with syntax highlighting for many other languages). Installation went fine on my gentoo systems, and it hasn't had caused me any problems yet. Andy From cybersamurai at terra.com.br Wed May 26 13:49:23 2004 From: cybersamurai at terra.com.br (cybersamurai) Date: Wed May 26 13:49:28 2004 Subject: [Tutor] get a list of all IPs on a lan Message-ID: Some one know how to get a list of all IPs on a lan? From fant at pobox.com Wed May 26 13:55:18 2004 From: fant at pobox.com (Andrew Fant) Date: Wed May 26 13:55:23 2004 Subject: [Tutor] get a list of all IPs on a lan In-Reply-To: References: Message-ID: <107270000.1085594118@flux.usg.tufts.edu> --On Wednesday, May 26, 2004 14:49:23 -0300 cybersamurai wrote: > Some one know how to get a list of all IPs on a lan? Ping the broadcast address and see who answers? Andy From orbitz at ezabel.com Wed May 26 13:57:09 2004 From: orbitz at ezabel.com (orbitz@ezabel.com) Date: Wed May 26 13:57:38 2004 Subject: [Tutor] get a list of all IPs on a lan In-Reply-To: References: Message-ID: <20040526135709.40ca47eb.orbitz@ezabel.com> I'm not sure how this relates to python at all, but google for ICMP. On Wed, 26 May 2004 14:49:23 -0300 "cybersamurai" wrote: > Some one know how to get a list of all IPs on a lan? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Wed May 26 14:19:22 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed May 26 14:18:39 2004 Subject: [Tutor] Re: Tutor Digest, Vol 3, Issue 38 References: Message-ID: <003b01c4434d$f862bde0$6401a8c0@xp> Thanks for all the translations, much appreciated. Alan G. ----- Original Message ----- From: To: Sent: Wednesday, May 26, 2004 5:04 PM Subject: Tutor Digest, Vol 3, Issue 38 > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > ---------------------------------------------------------------------- ---------- > Today's Topics: > > 1. IDLE problem (Ertl, John) > 2. Re: Another option for bobo/zobject/zpublicher? (Alan Gauld) > 3. Using datetime module (acidblue) > 4. clearing traceback after exeption is handled (Lloyd Kvam) > 5. OT: Help required (Alan Gauld) > 6. Re: OT: Help required (jb) > 7. Re: OT: Help required (Gon?alo Rodrigues) > 8. RE: Using datetime module (Don Arnold) > 9. Another option for bobo/zobject/zpublicher? (Kurt Kurniawan) > 10. Programming Style (William Rance) > 11. Re: Programming Style (Gon?alo Rodrigues) > 12. Re: IDLE problems, recommend a good IDE ? (Tim Johnson) > ---------------------------------------------------------------------- ---------- > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythontut at pusspaws.net Wed May 26 15:38:59 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed May 26 15:39:13 2004 Subject: [Tutor] IDLE problems, recommend a good IDE ? In-Reply-To: <20040526154831.GI23820@johnsons-web.com> References: <40B31468.4020409@pusspaws.net> <20040526154831.GI23820@johnsons-web.com> Message-ID: <40B4F253.2080102@pusspaws.net> Tim Johnson wrote: >* Dave S [040525 01:56]: > > >>Ive been learning on IDLE, which has been great but I have had >>occasional stability problems, which are a bit >>disconcerting. It just locked up X on my gentoo system :-( Anyhow Im >>back now - >> >> > > Hi Dave: Before you 'switch', are you absolutley certain that > there aren't system problems causing your IDLE problems? > > > I think they are - my system is rock solid (thats torn it ;-) ). When using IDLE, IDLE has suddenly crashed disappearing off my X screen. The latest & most serious event being a total X lockup when trying to open a file via IDLE. > I use gvim (graphical Vi Much Improved) and vim extensively for > python programming. There are extensive python plugins for > vim that make it a very nice IDE. > > You can in fact, compile the python interpreter directly into vim so > that you can modify or 'drive' your 'python IDE' using python code. > > > That sounds interesting .... I never knew VIM could be configured to become more Python friendly .. I thought syntax highlighting was the limit. I have experience of VIM in the past but struggled. Where can I find out about this ... VIM site ? > There there is GNU Emacs and Xemacs. Unlike vim, these are modeless > editors with complex key mappings and are 'driven' by LISP. So > some level of LISP skill would help. > > Never got on with emacs ... its a personal choice thing ... > Both lineages have both rabid fans and those who hate'm. I like > them both and couldn't do without them as a programmer. > > JMTCW > tj > > > >>Thanks to alt-sysreq-r I didn't have to re-boot. >> >>Can anybody recomend a good python IDE, Something functional without too >>many gizmos ! >> >> > > P.S. : > From your statement above, you want something simple? Simple is > easy to learn are hard to make really productive IMHO. > > Im also looking at eric3, I was put off by the number of 'gizmos' but some of them gizmos seem usefull ! (Breakpoints & the like) > > > >>Im running Gentoo 1.4 though I am happy to compile from source if needbe. >> >>Dave >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > > > From pythontut at pusspaws.net Wed May 26 16:00:13 2004 From: pythontut at pusspaws.net (Dave S) Date: Wed May 26 16:00:32 2004 Subject: [Tutor] IDLE problems, recommend a good IDE ? In-Reply-To: <88330000.1085587738@flux.usg.tufts.edu> References: <40B31468.4020409@pusspaws.net> <20040526154831.GI23820@johnsons-web.com> <88330000.1085587738@flux.usg.tufts.edu> Message-ID: <40B4F74D.3030903@pusspaws.net> Andrew Fant wrote: > > --On Wednesday, May 26, 2004 07:48:32 -0800 Tim Johnson > wrote: > >> * Dave S [040525 01:56]: >> >>> Ive been learning on IDLE, which has been great but I have had >>> occasional stability problems, which are a bit >>> disconcerting. It just locked up X on my gentoo system :-( Anyhow Im >>> back now - >> >> > > Dave: > Good to see more gentoo-types coming out of the woodwork. I'd check my > optimizations settings in make.conf and steer away from excessive > compiler flags, just as generic advice. If you are depending on -f > flags instead of the -O and -march/-mcpu options, wierd things can > happen. I think I am OK there ... System has been rock solid up till now. > > As far as IDEs go, I never got into idle myself. boa-constructor is in > portage, but it is a rather heavyweight tool for developing larger > apps (particularly gui tools with WxPython). I've played with it a > little, but it is almost certainly overkill for those of us, including > myself, who are still learning. I'm doing all my coding lately in > Komodo. It's not free, but Activestate sells the educational/hobbiest > version for about 30 dollars. The key bindings are a little annoying, > and I am working on setting them to be more emacsish, but aside from > that, it works very nicely. It also has a nice graphical source > debugger built in which has saved my rear several times lately. Im learning about de-buggers .. tried the eric3 one & liked it > If you use komodo as a professional developer, you are supposed to by > their pro version which is more expensive, but also includes a > graphical gui builder and support for tcl/tk (the educational version > supports perl, python, and php fully, with syntax highlighting for > many other languages). Installation went fine on my gentoo systems, > and it hasn't had caused me any problems yet. Ill take a look at Komodo ... OT Gentoo rocks ! > > Andy > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From tim at johnsons-web.com Wed May 26 17:20:15 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Wed May 26 17:15:31 2004 Subject: [Tutor] IDLE problems, recommend a good IDE ? In-Reply-To: <40B4F253.2080102@pusspaws.net> References: <40B31468.4020409@pusspaws.net> <20040526154831.GI23820@johnsons-web.com> <40B4F253.2080102@pusspaws.net> Message-ID: <20040526212015.GK23820@johnsons-web.com> * Dave S [040526 11:50]: > Tim Johnson wrote: > > >* Dave S [040525 01:56]: > > I use gvim (graphical Vi Much Improved) and vim extensively for > > python programming. There are extensive python plugins for > > vim that make it a very nice IDE. > > > > You can in fact, compile the python interpreter directly into vim so > > that you can modify or 'drive' your 'python IDE' using python code. > > > That sounds interesting .... I never knew VIM could be configured to > become more Python friendly .. I Oh you can get it as friendly as you want it to! http://www.vim.org/ For python related plugins: In case your mail clients wraps: Between this line and the asterisks is a one line URL http://www.vim.org/scripts/script_search_results.php?keywords=python+&script_type=&order_by=rating&direction=descending&search=search ******************************************************** > thought syntax highlighting was the limit. I have experience of VIM in > the past but struggled. VIM can drive you nuts with the modal editing approach. I recently did an LPI cert session on editors and I have a vim "cheat sheet". If you're interested email me OTL and I will provide it to you. (there are many vim cheat sheets, though) - and - The vim ML is *very* helpful. > Where can I find out about this ... VIM site ? > Never got on with emacs ... its a personal choice thing ... I don't blame you, and the online help that I have found for either GNU or X emacs is not as good as either this ML or the vim one. > > > Im also looking at eric3, I was put off by the number of 'gizmos' but > some of them gizmos seem usefull ! > (Breakpoints & the like) I've used pythonwin (windows only) and it has nice, intuitive object browser services. I don't know if anyone has done any thing so sophisitcated for vim, although it has nice taglist features. (X)emacs has an OO-browser plugin that will accomodate python, but I haven't used it. tim -- Tim Johnson http://www.alaska-internet-solutions.com From david at graniteweb.com Wed May 26 17:21:43 2004 From: david at graniteweb.com (David Rock) Date: Wed May 26 17:21:45 2004 Subject: [Tutor] get a list of all IPs on a lan In-Reply-To: <107270000.1085594118@flux.usg.tufts.edu> References: <107270000.1085594118@flux.usg.tufts.edu> Message-ID: <20040526212143.GC4072@wdfs.graniteweb.com> * Andrew Fant [2004-05-26 13:55]: > --On Wednesday, May 26, 2004 14:49:23 -0300 cybersamurai > wrote: > > >Some one know how to get a list of all IPs on a lan? > > > Ping the broadcast address and see who answers? That's cool. Learn something new every day ;-) -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040526/d80a3553/attachment.bin From lbblair at adaptisinc.com Wed May 26 17:53:43 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Wed May 26 17:55:45 2004 Subject: [Tutor] sendmail Message-ID: Being new to Python is there a module for sending e-mail. I have browsed through a bunch of the modules but just don't recognize it if it is there. Thanks Larry __________________________________ Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s) and may contain information that is confidential privileged and/or exempt from disclosure under applicable law. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. From lbblair at adaptisinc.com Wed May 26 18:01:11 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Wed May 26 18:04:42 2004 Subject: [Tutor] sendmail Message-ID: Sorry for the dumb question. About 30 seconds later I saw the "email" module. Larry -----Original Message----- From: Larry Blair Sent: Wednesday, May 26, 2004 2:54 PM To: 'Tutor@python.org' Subject: [Tutor] sendmail Being new to Python is there a module for sending e-mail. I have browsed through a bunch of the modules but just don't recognize it if it is there. Thanks Larry __________________________________ Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s) and may contain information that is confidential privileged and/or exempt from disclosure under applicable law. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor __________________________________ Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s) and may contain information that is confidential privileged and/or exempt from disclosure under applicable law. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. From alan.gauld at blueyonder.co.uk Wed May 26 19:08:59 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed May 26 19:09:01 2004 Subject: [Tutor] sendmail References: Message-ID: <006c01c44376$6dd8e770$6401a8c0@xp> > Sorry for the dumb question. About 30 seconds later I saw the "email" > module. :-) There are also smtp, pop and mime modules for getting deeper into it. And I think there's an IMAP module too but can't reember if its a standard library one. Alan G. From bjmartin98 at pennswoods.net Thu May 27 00:54:47 2004 From: bjmartin98 at pennswoods.net (Billie Martin) Date: Wed May 26 22:02:04 2004 Subject: [Tutor] Please remove me Message-ID: <004b01c443a6$be138940$3f5ea30c@mark> Unsubscribe me please. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040526/fcda065e/attachment.html From lsloan at umich.edu Thu May 27 11:24:30 2004 From: lsloan at umich.edu (Lance E Sloan) Date: Thu May 27 11:24:38 2004 Subject: [Tutor] reading Excel CSVs? In-Reply-To: <5.2.1.1.0.20040514094453.02124ea8@www.thinkware.se> References: <1084454216.5059.11.camel@laptop.venix.com> <2147483647.1084437266@[192.168.2.201]> <2147483647.1084437851@[192.168.2.201]> <1084454216.5059.11.camel@laptop.venix.com> <5.2.1.1.0.20040514094453.02124ea8@www.thinkware.se> Message-ID: <2147483647.1085657070@blue-four.us.itd.umich.edu> --On Friday, May 14, 2004 10:21 AM +0200 Magnus Lyck? wrote: > I think csv [the module] is confused by the fact that there is no > line feed character in line endings on the Mac. > > Unix uses \n, WinDOS uses \r\n and Mac uses \r. > > I'd try opening the files with file("true-csv.csv", "rU") > Note capital U. This is the universal line ending mode. See > file function in Library reference section 2.1. Thank you very much. That did the trick. I've not dealt with non-Unix files much. I'm using Mac OS X, which uses Unix line endings for the most part. So this file produced by Excel for MOSX is a bit of an oddity. Maybe the programmers at MS didn't realize the CSV-producing part might need to be changed for MOSX. Or maybe there's a line-ending option in Excel. Anyway, using "U" mode, I don't need to worry about it, right? ;) -- Lance E Sloan, Systems Research Programmer III U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://www.itcs.umich.edu/wats/ - "Putting U on the Web" From nouda at freemail.nl Thu May 27 11:17:38 2004 From: nouda at freemail.nl (nouda) Date: Thu May 27 11:24:54 2004 Subject: [Tutor] Re: get a list of all IPs on a lan In-Reply-To: <20040526220506.6BC458C408D@box-05.freemail.nl> Message-ID: On Wed, 26 May 2004 14:49:23 -0300 "cybersamurai" wrote: > Some one know how to get a list of all IPs on a lan? Learn how to use a ip scanning device. For windows something like superscan or something like that. For Unix or Linux I should use Nmap. But that has nothing to do with Python, it isn't even written in it... <_< Noud Aldenhoven ps. I hope I send this mail to the right place! From gaedol at softhome.net Thu May 27 13:26:15 2004 From: gaedol at softhome.net (Marco) Date: Thu May 27 13:35:00 2004 Subject: [Tutor] get a list of all IPs on a lan In-Reply-To: <107270000.1085594118@flux.usg.tufts.edu> References: <107270000.1085594118@flux.usg.tufts.edu> Message-ID: <20040527192615.78e11130.gaedol@softhome.net> On Wed, 26 May 2004 13:55:18 -0400 Andrew Fant wrote: > Ping the broadcast address and see who answers? Not "everybody" answers to broadcasts, usually even "lightly" firewalled machines avoid answering to some ICMP types. my 2 cents, marco PS Sorry Andrew will receive two of this message cause i hit the wrong buttons.. i was in a hurry! excuse me, Andrew -- Telefono, s.m.: Un'invenzione diabolica che annulla alcuni dei vantaggi del tenere una persona antipatica a debita distanza. -- Ambrose Bierce From steegness at hotmail.com Thu May 27 15:13:20 2004 From: steegness at hotmail.com (steegness) Date: Thu May 27 15:13:23 2004 Subject: [Tutor] sendmail References: Message-ID: You might be interested in this little piece I crafted as well. I the low-level nature of the email-related modules started to get to me, so I wrote this to help me out. (and now, to help everyone out) http://www.uselesspython.com/users/ssteeg/Samples/SimpleMessage.py Sean ----- Original Message ----- From: To: Sent: Thursday, May 27, 2004 12:03 PM Subject: Tutor Digest, Vol 3, Issue 40 > Message: 1 > Date: Thu, 27 May 2004 00:08:59 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] sendmail > To: "Larry Blair" , > Message-ID: <006c01c44376$6dd8e770$6401a8c0@xp> > Content-Type: text/plain; charset="iso-8859-1" > > > > Sorry for the dumb question. About 30 seconds later I saw the > "email" > > module. > > :-) > > There are also smtp, pop and mime modules for getting deeper into it. > And I think there's an IMAP module too but can't reember if its a > standard library one. > > Alan G. From bobhe at telkomsa.net Thu May 27 15:36:24 2004 From: bobhe at telkomsa.net (Bob Heasman) Date: Thu May 27 15:36:06 2004 Subject: [Tutor] Question about stdin/stdout Message-ID: <40B64338.6040301@telkomsa.net> Hi, I have just started programming with Python using the book and disk supplied by Michael Dawson, and am rather overawed at the questions and answers that I have seen. I am a Radio Amateur and I have a need for a program that will, when the program sees one of a few call signs, it will send an instruction to the parallel port to make one of the pins go high. I will have a series of relays which will operate and rotate my beam towards that particular station. Now I have devised a means of getting the "password" program to recognise the following line and activate the appropriate command, as follows:.... #! /usr/bin/python # Password # Demonstrates the if structure # Antenna direction changer # Bob Heasman 25/04/04 ******************************* print "\tWelcome to System Security Inc." print "_where security is our middle name" password = raw_input("\n\nEnter your password: ") if password == "[PTCPACTOR - 19 - UA6ADV-0]": print "Activate pin 1" if password == "F3KT": print "Activate pin 2" raw_input ("\n\nPress the Enter key to exit.") ************************************* This works well as far as it goes, but it is reliant on having stdin and stdout being the keyboard and the screen. I have read through the book and see that he goes on to demonstrate how to write games which rely on exactly the same stdin/stdout. I realise that "Activate pin 1" won't work, but I can sort that out. I just want to know about stdin/stdout. What I want to do is get the program to read a screen display (or I can get Linux to save this display to a file using the "tail -f" command) or file, and when it recognises the line with the call sign "UA6ADV" (or one of the other call signs) it will then send a cmd to the parallel port, ttyS0, to make one of the pins go high. So this uses a file as "stdin", and "stdout" is a pin on the parallel port.Can someone give me some pointers as to how to do this, or if necessary, point me to a book or a web site where I can find this info. I suppose I could wade through the book in the hope that I find something to do this, but I really would like to get this program working asap, and going through the book will take me forever. I have been a bit verbose I am afraid, but I thought rather do that then be confusing by leaving out info. Thanks....Bob From acidrex at earthlink.net Thu May 27 17:33:16 2004 From: acidrex at earthlink.net (acidblue) Date: Thu May 27 17:33:28 2004 Subject: [Tutor] How to save user data? Message-ID: <000d01c44432$3a149ee0$0a4ffea9@amdbox> I have a textctrl box for usr input, do I use raw_input and assign a variable in order to save the information? Using wxPython2.4 Python 2.3 My code thus far: from wxPython.wx import * from wxPython.lib.maskededit import Field, wxMaskedTextCtrl from wxPython.lib.maskededit import autoformats import datetime def create(parent): return Blue49(parent) [wxID_BLUE49, wxID_BLUE49FLOWERTIMEBOX, wxID_BLUE49PANEL1, wxID_BLUE49STARTDATEBOX, wxID_BLUE49STARTSEEDSTEXTBOX, wxID_BLUE49STATICTEXT1, ] = map(lambda _init_ctrls: wxNewId(), range(6)) class Blue49(wxFrame): def _init_ctrls(self, prnt): # generated method, don't edit wxFrame.__init__(self, id=wxID_BLUE49, name='Blue49', parent=prnt, pos=wxPoint(168, 148), size=wxSize(600, 427), style=wxDEFAULT_FRAME_STYLE, title='Blue49') self.SetClientSize(wxSize(592, 393)) self.panel1 = wxPanel(id=wxID_BLUE49PANEL1, name='panel1', parent=self, pos=wxPoint(0, 0), size=wxSize(592, 393), style=wxTAB_TRAVERSAL) self.StartDateBox = wxMaskedTextCtrl(id=wxID_BLUE49STARTDATEBOX, name='StartDateBox', parent=self.panel1, pos=wxPoint(192, 48), size=wxSize(79, 21), style=0, value=' / / ') self.StartDateBox.SetMask('XX/XX/XXXX') self.StartDateBox.SetAutoformat('') self.StartDateBox.SetDatestyle('MDY') self.StartDateBox.SetFormatcodes('') self.StartDateBox.SetDescription('') self.StartDateBox.SetExcludeChars('') self.StartDateBox.SetValidRegex('') self.StartSeedsTextbox = wxStaticText(id=wxID_BLUE49STARTSEEDSTEXTBOX, label='Enter a date for starting seeds', name='StartSeedsTextbox', parent=self.panel1, pos=wxPoint(40, 56), size=wxSize(141, 13), style=0) self.FlowerTimebox = wxMaskedTextCtrl(id=wxID_BLUE49FLOWERTIMEBOX, name='FlowerTimebox', parent=self.panel1, pos=wxPoint(248, 80), size=wxSize(24, 21), style=0, value='') self.FlowerTimebox.SetMask('XX') self.FlowerTimebox.SetAutoformat('') self.FlowerTimebox.SetDatestyle('MDY') self.FlowerTimebox.SetFormatcodes('') self.FlowerTimebox.SetDescription('') self.FlowerTimebox.SetExcludeChars('') self.FlowerTimebox.SetValidRegex('') self.staticText1 = wxStaticText(id=wxID_BLUE49STATICTEXT1, label='Enter days for flower period.(max-99)', name='staticText1', parent=self.panel1, pos=wxPoint(40, 88), size=wxSize(171, 13), style=0) def __init__(self, parent): self._init_ctrls(parent) From learn2prog at indyamail.net Thu May 27 17:35:21 2004 From: learn2prog at indyamail.net (Lauzon, Michael) Date: Thu May 27 17:35:42 2004 Subject: [Tutor] Just Testing Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040527/26222d83/attachment.html From missive at hotmail.com Thu May 27 18:04:49 2004 From: missive at hotmail.com (Lee Harr) Date: Thu May 27 18:05:04 2004 Subject: [Tutor] Re: Question about stdin/stdout Message-ID: >I realise that "Activate pin 1" won't work, but I can sort that out. I >just want to know about stdin/stdout. > >What I want to do is get the program to read a screen display (or I can >get Linux to save this display to a file using the "tail -f" command) or >file, and when it recognises the line with the call sign "UA6ADV" (or >one of the other call signs) it will then send a cmd to the parallel >port, ttyS0, to make one of the pins go high. You may want to look here: http://pyserial.sourceforge.net/ http://pyserial.sourceforge.net/pyparallel.html In answer to your questions about stdin/stdout... Essentially, they are just files like any other files... >>>import sys >>>sys.stdin ', mode 'r' at 0x8132020> >>>sys.stdout ', mode 'w' at 0x8132060> >>>f = file('atempfile', 'w') >>>f The magic thing is that print is hooked up automatically to stdout, but you can rearrange that if you really want to... >>>f.write('some test text') >>>f.write('some test text with newline\n') >>>print 'testing print' testing print >>>sys.stdout = f >>>print 'testing print' >>>print 'testing print' >>>print 'testing print' >>>[...here I exited the interpreter] 17:56 >more atempfile some test textsome test text with newline testing print testing print testing print Most likely though, you would want to just open a new file and write to it, rather than redirecting stdout. _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From project5 at redrival.net Fri May 28 02:36:15 2004 From: project5 at redrival.net (Andrei) Date: Fri May 28 02:36:29 2004 Subject: [Tutor] Re: How to save user data? References: <000d01c44432$3a149ee0$0a4ffea9@amdbox> Message-ID: acidblue earthlink.net> writes: > I have a textctrl box for usr input, do I use raw_input and assign a > variable in order to save the information? > Using wxPython2.4 You don't use raw_input if you use wxPython. raw_input is for command line (console) applications, while the whole point of wxPython is *not* to have a console application :). You should use some kind of wxTextCtrl and use its GetValue method to get the user's input in that text control. E.g.: username = MyTextCtrl.GetValue() You can then do with that input whatever you like, including saving it. Yours, Andrei From allyn. at tardigrade.net Fri May 28 03:03:38 2004 From: allyn. at tardigrade.net (Allyn Weaks) Date: Fri May 28 03:03:24 2004 Subject: [Tutor] get a list of all IPs on a lan In-Reply-To: <20040527192615.78e11130.gaedol@softhome.net> References: <107270000.1085594118@flux.usg.tufts.edu> <20040527192615.78e11130.gaedol@softhome.net> Message-ID: On 27/5/2004, Marco wrote: >> Ping the broadcast address and see who answers? > >Not "everybody" answers to broadcasts, usually even "lightly" >firewalled machines avoid answering to some ICMP types. On unix, if you have root access and can turn on promiscuous mode, and if you aren't isolated behind a switch, install the excellent arpwatch. It watches all traffic across the network card, collects pairs of IP vs MAC address and logs it. On a complex enough network, it's worth analyzing the log with a python script... -- Allyn Weaks allyn@tardigrade.net Seattle, WA Sunset zone 5 Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/ "To announce that there must be no criticism of the president, or that we are to stand by the president, right or wrong, is not only unpatriotic and servile, but is morally treasonable to the American public." -- Theodore Roosevelt From dr_mirror at freemail.hu Fri May 28 20:14:06 2004 From: dr_mirror at freemail.hu (Mirror Three) Date: Fri May 28 20:14:16 2004 Subject: [Tutor] gui tks and encodings Message-ID: hi there, so i am finally out of the tunnel, meant rewriting the gui of my first app in python from tkinter to wxpython.. thanks for the hands you gave on my problem with textcontrols, i started to look after scintilla, and then through some links i took a longer look at this wxwidgets stuff. i can say now that it is better than tkinter, i did not even need scintilla.. i like tkinter, because it is unique, and implements cross-platformity not like deciding what to rely on, but like shi**ing on standards. but being the 'official' gui toolkit of python, i think it should manage to solve some basic problems, like navigation on wrapped text.. (not mentioning you cannot move the insertion cursor from program.. or am i wrong?) something else. i installed the unicode version of wxpython on my windows me, because i felt small when the download page reminded me i am not a native english speaker. :) somebody mentioned on some page, that it needs some hackjob on windows excluding 9x or so, but i have not spotted any problems yet. but could anyone tell me if i really need this? i only know about unicode that it deals with multibyte characters, and that is not much of my taste. my app shows now a little chaos with this charset and encoding stuff, i have just finished to rewrite a mail header decoder directly for pop3. it decodes using the iso-8859-2 charset, because that is what i need. the result is normal string wich i put in a listctrl and it works without mentioning unicode in that part of the program. but on the other hand a listbox suffered from getting some hungarian style characters in its item labels, and works with u'...'. have any experience? thanks tm From alan.gauld at blueyonder.co.uk Sat May 29 18:42:21 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat May 29 18:41:44 2004 Subject: [Tutor] gui tks and encodings References: Message-ID: <003a01c445ce$3424c120$6401a8c0@xp> > the 'official' gui toolkit of python, i think it should manage to solve some > basic problems, like navigation on wrapped text.. (not mentioning you > cannot move the insertion cursor from program.. or am i wrong?) I'm not sure what you tried but moving the insertion point is pretty easy - once you know that Tk calls the insertion point the "insert mark". There is a method: myWidget.mark_set('insert', index) Where index is the usual Tk style index, typically a line.char pair. You can also use a mark plus modifier so for example: >>> tk = Tk() >>> t = Text() >>> t.pack() >>> def move5(): ... t.mark_set("insert","insert + 5 chars") ... >>> b = Button(tk,text="move 5",command=move5) >>> b.pack() >>> tk.mainloop() Creates a Text widget and button which moves the insert cursor 5 characters forward. (Note the use of strings in mark_set()! - A Tk feature) The other mark of note is "current" which tracks the mouse position. If the user clicks the mouse in the text the values of "current" and "insert" will become the same. You can of course create your own named marks too and jump to them etc. None of this is exactly clear in the Tkinter docs I must say, but the pages do explain it a little. http://www.pythonware.com/library/tkinter/introduction/x7883-concepts.htm But I dsid have to experiment a bit to get the example above working - even after reading the help! However it should be obvious that Tkinters Text editing capabilities are very much present since IDLE is itself built using it! :-) Alan G. From game at gameweave.com Sat May 29 23:30:57 2004 From: game at gameweave.com (K J) Date: Sat May 29 23:27:58 2004 Subject: [Tutor] Hello new to python and the mailing list, need some help Message-ID: <000801c445f6$8628d1f0$30e57218@nonet55l04ooq3> Hello, I am new to python and need a little help. I am trying to write to a file but wich i can the only problem that I have is that Each raw_input I want to write to a seperate line so that it will print on the screen like this: Kevin 27 Male right now it just prints to the screen like this: Kevin27Male here is the code that I did: NAME = raw_input("What is your name? ") AGE = raw_input ("What is your age? ") SEX = raw_input ("What is your sex? ") player = open("name.plr", 'w') player.write (NAME) player.write (AGE) player.write (SEX) player.close() player = open("name.plr", 'r') line = player.readline() player.close() print line Thanks for any help Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040529/5efe916f/attachment.html From gew75 at hotmail.com Sun May 30 01:24:48 2004 From: gew75 at hotmail.com (Glen Wheeler) Date: Sun May 30 01:24:54 2004 Subject: [Tutor] Hello new to python and the mailing list, need some help References: <000801c445f6$8628d1f0$30e57218@nonet55l04ooq3> Message-ID: Hi Kevin, Escape codes are special characters used in strings to represent things which we find hard to put into simple letters. For example, the escape code for a newline is `\n'. So, print '\n' will actually print *two* blank lines. There is a little inconsistency with Python's file handling in that the print command will automatically add a newline after any output, but a file.write(..) will not. As a further hint, string concatenation is formed with the `+' operator. So that d = 'dog' c = 'cat' s = c+d print s // 'catdog' Now, I'm sure you can figure out how to get newlines into your file :). Glen ----- Original Message ----- From: K J To: tutor@python.org Sent: Sunday, May 30, 2004 1:30 PM Subject: [Tutor] Hello new to python and the mailing list, need some help Hello, I am new to python and need a little help. I am trying to write to a file but wich i can the only problem that I have is that Each raw_input I want to write to a seperate line so that it will print on the screen like this: Kevin 27 Male right now it just prints to the screen like this: Kevin27Male here is the code that I did: NAME = raw_input("What is your name? ") AGE = raw_input ("What is your age? ") SEX = raw_input ("What is your sex? ") player = open("name.plr", 'w') player.write (NAME) player.write (AGE) player.write (SEX) player.close() player = open("name.plr", 'r') line = player.readline() player.close() print line Thanks for any help Kevin _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From gaedol at softhome.net Sun May 30 06:58:26 2004 From: gaedol at softhome.net (Marco) Date: Sun May 30 07:07:07 2004 Subject: [Tutor] Peaks detection Message-ID: <20040530125826.24eae0c9.gaedol@softhome.net> Hey all, i am tryin to write in python a peak detection algorithm to use on spectra taken from a data analyser in a lab. The spectrum comes in a text file with 2 columns, one with the channel number and the other one with number of counts for that channel. Making the calibration to the energy is not a problem, except for the fact that the algorithm _should_ recognize the peaks of the spectrum (those that have a fair gaussian form) and notate the centroid of the gaussian. The problem is: i can't find an algorithm except for a labview "procedure" on the net. Once found the "how" implementing it in python shouldn't be that hard :) so the question is: Anyone has a source for an algorithm of that kind? Any suggestion? thank you all, marco -- "Caro, ho un... anticipo sul ciclo!" From darnold02 at sprynet.com Sun May 30 09:23:37 2004 From: darnold02 at sprynet.com (Don Arnold) Date: Sun May 30 09:23:55 2004 Subject: [Tutor] Hello new to python and the mailing list, need some help In-Reply-To: Message-ID: Or, you could use the decorated form of print to write directly to the file: >>> outfile = open('c:/temp2/stuff','w') >>> print >> outfile, 'John Smith' >>> print >> outfile, '23' >>> print >> outfile, 'Male' >>> outfile.close() >>> Contents of outfile: John Smith 23 Male HTH, Don -----Original Message----- From: tutor-bounces+darnold02=sprynet.com@python.org [mailto:tutor-bounces+darnold02=sprynet.com@python.org] On Behalf Of Glen Wheeler Sent: Sunday, May 30, 2004 12:25 AM To: K J; tutor@python.org Subject: Re: [Tutor] Hello new to python and the mailing list, need some help Hi Kevin, Escape codes are special characters used in strings to represent things which we find hard to put into simple letters. For example, the escape code for a newline is `\n'. So, print '\n' will actually print *two* blank lines. There is a little inconsistency with Python's file handling in that the print command will automatically add a newline after any output, but a file.write(..) will not. As a further hint, string concatenation is formed with the `+' operator. So that d = 'dog' c = 'cat' s = c+d print s // 'catdog' Now, I'm sure you can figure out how to get newlines into your file :). Glen ----- Original Message ----- From: K J To: tutor@python.org Sent: Sunday, May 30, 2004 1:30 PM Subject: [Tutor] Hello new to python and the mailing list, need some help Hello, I am new to python and need a little help. I am trying to write to a file but wich i can the only problem that I have is that Each raw_input I want to write to a seperate line so that it will print on the screen like this: Kevin 27 Male right now it just prints to the screen like this: Kevin27Male here is the code that I did: NAME = raw_input("What is your name? ") AGE = raw_input ("What is your age? ") SEX = raw_input ("What is your sex? ") player = open("name.plr", 'w') player.write (NAME) player.write (AGE) player.write (SEX) player.close() player = open("name.plr", 'r') line = player.readline() player.close() print line Thanks for any help Kevin _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sun May 30 12:49:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun May 30 12:49:01 2004 Subject: [Tutor] Hello new to python and the mailing list, need some help References: <000801c445f6$8628d1f0$30e57218@nonet55l04ooq3> Message-ID: <005101c44666$216210e0$6401a8c0@xp> Hi Kevin, welcome to Python. There are several points to mke, only one of which actually resolves your problem :-) > ...I want to write to a seperate line so that it will > print on the screen like this: > here is the code that I did: > NAME = raw_input("What is your name? ") > AGE = raw_input ("What is your age? ") > SEX = raw_input ("What is your sex? ") First, by convention all uppercase letters are usually reserved for fixed values or constants. Its just a convention but a pretty well respected one. A mnore normal convention for variable names is to keep then lower case and capitalize any secondary words within the name., like this: aLongName It doesn't change how the code works but makes it easier for other people to read your code. > player = open("name.plr", 'w') > player.write (NAME) You are writing the data but the data has no newline at the end. You need to add it. Unfortunately python files have a readline() method but no writeline() - for reasons which have always puzzled me! To add the newline we use the character sequence: '\n' so to write to the file you need to do: player.write(NAME+'\n') > player = open("name.plr", 'r') > line = player.readline() > player.close() This will only read one line of input, if you need to read the others you will either have to add multiple lines like the above or use a loop - which you may not have come across yet in whatever tutor you are following! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 From game at gameweave.com Sun May 30 14:12:51 2004 From: game at gameweave.com (K J) Date: Sun May 30 14:09:50 2004 Subject: [Tutor] Re: Hello new to python and the mailing list, need some help Message-ID: <002f01c44671$b8b51360$30e57218@nonet55l04ooq3> Thank you to all that help me on that. I got it to write seperate lines with out useing any loops. Thanks for telling my about the upper case thing I did not know that. Here is the code I made: name = raw_input("What is your name? ") age = raw_input ("What is your age? ") sex = raw_input ("What is your sex? ") player = open("name.plr", 'w') player.write (name+'\n') player.write (age+'\n') player.write (sex+'\n') player.close() player = open("name.plr", 'r') line_a = player.readline() line_b = player.readline() line_c = player.readline() player.close() print line_a print line_b print line_c The output is like this Kevin 27 Male Is there a way to bring the lines closer to gether? Sorry for all the questions I still have not had time to go buy a Python book, I have only been reading what I can on the internet and most of the tutorials don't explain this stuff. Thanks again, Kevin ----- Original Message ----- From: "Alan Gauld" To: "K J" ; Sent: Sunday, May 30, 2004 12:49 PM Subject: Re: [Tutor] Hello new to python and the mailing list, need some help > Hi Kevin, welcome to Python. > > There are several points to mke, only one of which > actually resolves your problem :-) > > > ...I want to write to a seperate line so that it will > > print on the screen like this: > > > here is the code that I did: > > NAME = raw_input("What is your name? ") > > AGE = raw_input ("What is your age? ") > > SEX = raw_input ("What is your sex? ") > > First, by convention all uppercase letters are usually > reserved for fixed values or constants. Its just a convention > but a pretty well respected one. A mnore normal convention > for variable names is to keep then lower case and capitalize > any secondary words within the name., like this: > > aLongName > > It doesn't change how the code works but makes it easier > for other people to read your code. > > > player = open("name.plr", 'w') > > player.write (NAME) > > You are writing the data but the data has no newline at the end. > You need to add it. Unfortunately python files have a readline() > method but no writeline() - for reasons which have always puzzled me! > > To add the newline we use the character sequence: > > '\n' > > so to write to the file you need to do: > > player.write(NAME+'\n') > > > player = open("name.plr", 'r') > > line = player.readline() > > player.close() > > This will only read one line of input, if you need to read the > others you will either have to add multiple lines like the above > or use a loop - which you may not have come across yet in whatever > tutor you are following! > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040530/7c4abef2/attachment.html From nick at javacat.f2s.com Sun May 30 14:46:56 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun May 30 14:47:04 2004 Subject: [Tutor] Re: Hello new to python and the mailing list, need some help In-Reply-To: <002f01c44671$b8b51360$30e57218@nonet55l04ooq3> Message-ID: Hi Kevin, you can stop python appending its own newline with a comma, ie print line_a, print line_b, etc. Hope that helps Nick -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of K J Sent: 30 May 2004 19:13 To: tutor@python.org Subject: [Tutor] Re: Hello new to python and the mailing list, need some help Thank you to all that help me on that. I got it to write seperate lines with out useing any loops. Thanks for telling my about the upper case thing I did not know that. Here is the code I made: name = raw_input("What is your name? ") age = raw_input ("What is your age? ") sex = raw_input ("What is your sex? ") player = open("name.plr", 'w') player.write (name+'\n') player.write (age+'\n') player.write (sex+'\n') player.close() player = open("name.plr", 'r') line_a = player.readline() line_b = player.readline() line_c = player.readline() player.close() print line_a print line_b print line_c The output is like this Kevin 27 Male Is there a way to bring the lines closer to gether? Sorry for all the questions I still have not had time to go buy a Python book, I have only been reading what I can on the internet and most of the tutorials don't explain this stuff. Thanks again, Kevin ----- Original Message ----- From: "Alan Gauld" To: "K J" ; Sent: Sunday, May 30, 2004 12:49 PM Subject: Re: [Tutor] Hello new to python and the mailing list, need some help > Hi Kevin, welcome to Python. > > There are several points to mke, only one of which > actually resolves your problem :-) > > > ...I want to write to a seperate line so that it will > > print on the screen like this: > > > here is the code that I did: > > NAME = raw_input("What is your name? ") > > AGE = raw_input ("What is your age? ") > > SEX = raw_input ("What is your sex? ") > > First, by convention all uppercase letters are usually > reserved for fixed values or constants. Its just a convention > but a pretty well respected one. A mnore normal convention > for variable names is to keep then lower case and capitalize > any secondary words within the name., like this: > > aLongName > > It doesn't change how the code works but makes it easier > for other people to read your code. > > > player = open("name.plr", 'w') > > player.write (NAME) > > You are writing the data but the data has no newline at the end. > You need to add it. Unfortunately python files have a readline() > method but no writeline() - for reasons which have always puzzled me! > > To add the newline we use the character sequence: > > '\n' > > so to write to the file you need to do: > > player.write(NAME+'\n') > > > player = open("name.plr", 'r') > > line = player.readline() > > player.close() > > This will only read one line of input, if you need to read the > others you will either have to add multiple lines like the above > or use a loop - which you may not have come across yet in whatever > tutor you are following! > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040530/57c8dfa0/attachment.html From game at gameweave.com Sun May 30 15:31:27 2004 From: game at gameweave.com (K J) Date: Sun May 30 15:28:28 2004 Subject: [Tutor] Re: Hello new to python and the mailing list, need some help References: Message-ID: <001a01c4467c$b41c7770$30e57218@nonet55l04ooq3> Ya that helped alot! thanks. I see that I can also put the 3 print lines in to one ie: print line_a, line_b, line_c and it outputs the same thing. I must say this is the funnest programming language that I have ever had the pleasure of teaching my self. Kevin ----- Original Message ----- From: Nick Lunt To: K J ; tutor@python.org Sent: Sunday, May 30, 2004 2:46 PM Subject: RE: [Tutor] Re: Hello new to python and the mailing list, need some help Hi Kevin, you can stop python appending its own newline with a comma, ie print line_a, print line_b, etc. Hope that helps Nick -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of K J Sent: 30 May 2004 19:13 To: tutor@python.org Subject: [Tutor] Re: Hello new to python and the mailing list, need some help Thank you to all that help me on that. I got it to write seperate lines with out useing any loops. Thanks for telling my about the upper case thing I did not know that. Here is the code I made: name = raw_input("What is your name? ") age = raw_input ("What is your age? ") sex = raw_input ("What is your sex? ") player = open("name.plr", 'w') player.write (name+'\n') player.write (age+'\n') player.write (sex+'\n') player.close() player = open("name.plr", 'r') line_a = player.readline() line_b = player.readline() line_c = player.readline() player.close() print line_a print line_b print line_c The output is like this Kevin 27 Male Is there a way to bring the lines closer to gether? Sorry for all the questions I still have not had time to go buy a Python book, I have only been reading what I can on the internet and most of the tutorials don't explain this stuff. Thanks again, Kevin ----- Original Message ----- From: "Alan Gauld" To: "K J" ; Sent: Sunday, May 30, 2004 12:49 PM Subject: Re: [Tutor] Hello new to python and the mailing list, need some help > Hi Kevin, welcome to Python. > > There are several points to mke, only one of which > actually resolves your problem :-) > > > ...I want to write to a seperate line so that it will > > print on the screen like this: > > > here is the code that I did: > > NAME = raw_input("What is your name? ") > > AGE = raw_input ("What is your age? ") > > SEX = raw_input ("What is your sex? ") > > First, by convention all uppercase letters are usually > reserved for fixed values or constants. Its just a convention > but a pretty well respected one. A mnore normal convention > for variable names is to keep then lower case and capitalize > any secondary words within the name., like this: > > aLongName > > It doesn't change how the code works but makes it easier > for other people to read your code. > > > player = open("name.plr", 'w') > > player.write (NAME) > > You are writing the data but the data has no newline at the end. > You need to add it. Unfortunately python files have a readline() > method but no writeline() - for reasons which have always puzzled me! > > To add the newline we use the character sequence: > > '\n' > > so to write to the file you need to do: > > player.write(NAME+'\n') > > > player = open("name.plr", 'r') > > line = player.readline() > > player.close() > > This will only read one line of input, if you need to read the > others you will either have to add multiple lines like the above > or use a loop - which you may not have come across yet in whatever > tutor you are following! > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld/tutor2 > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040530/8d3335cf/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Sun May 30 20:07:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun May 30 20:07:08 2004 Subject: [Tutor] Peaks detection In-Reply-To: <20040530125826.24eae0c9.gaedol@softhome.net> Message-ID: On Sun, 30 May 2004, Marco wrote: > i am tryin to write in python a peak detection algorithm to use on > spectra taken from a data analyser in a lab. The spectrum comes in a > text file with 2 columns, one with the channel number and the other one [text cut] > so the question is: > Anyone has a source for an algorithm of that kind? Any suggestion? Hi Marco, This is a highly domain-specialized question. Consequently, I'm not sure if any of us are qualified to help on this. Your question has very little to do with Python, and more to do with computational algorithms. You may want to try the folks at SciPy: http://www.scipy.org/ and see if anyone there can point you toward relevant resources. I'm sorry that we can't be of more help on this question. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Sun May 30 20:10:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun May 30 20:10:58 2004 Subject: [Tutor] Re: How to save user data? In-Reply-To: Message-ID: On Fri, 28 May 2004, Andrei wrote: > acidblue earthlink.net> writes: > > > I have a textctrl box for usr input, do I use raw_input and assign a > > variable in order to save the information? > > Using wxPython2.4 > > You don't use raw_input if you use wxPython. raw_input is for command line > (console) applications, while the whole point of wxPython is *not* to have a > console application :). You should use some kind of wxTextCtrl and use its > GetValue method to get the user's input in that text control. E.g.: > > username = MyTextCtrl.GetValue() > > You can then do with that input whatever you like, including saving it. Hi Acidblue, You can save certain values in your program by using something like the 'shelve' library: http://www.python.org/doc/lib/module-shelve.html If you have more questions, please feel free to ask. Good luck! From dyoo at hkn.eecs.berkeley.edu Sun May 30 20:21:11 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun May 30 20:21:27 2004 Subject: [Tutor] Question about stdin/stdout In-Reply-To: <40B64338.6040301@telkomsa.net> Message-ID: On Thu, 27 May 2004, Bob Heasman wrote: > I have just started programming with Python using the book and disk > supplied by Michael Dawson, and am rather overawed at the questions and > answers that I have seen. Hi Bob, Don't be overawed. *grin* If there's stuff that goes over your head, just skip it. And if you're finding that there are too many messages coming from the list, you can turn on "digest mode" on your mailing list settings from: http://mail.python.org/mailman/listinfo/tutor Near the bottom, there's a form there where you can edit certain options for your mailing list subscription --- this includes turning on digest mode, to bundle messages from the list into chunks. > get Linux to save this display to a file using the "tail -f" command) or > file, and when it recognises the line with the call sign "UA6ADV" (or > one of the other call signs) it will then send a cmd to the parallel > port, ttyS0, to make one of the pins go high. It will probably be easy to deal with stdin. Here's a small sample program that takes stdin, and UPPERCASES every line it can read from the standard input: ### import sys for line in sys.stdin: sys.stdout.write(line.upper()) ### > So this uses a file as "stdin", and "stdout" is a pin on the parallel > port.Can someone give me some pointers as to how to do this, or if > necessary, point me to a book or a web site where I can find this info. It sounds that, given some line of text, you'll want to look for a specific pattern. If the pattern isn't too complex, you can use a substring check with the 'in' operator: ### >>> 'go' in 'chess was invented, but go was discovered' True >>> 'othello' in 'chess was invented, but go was discovered' False ### If the pattern you're looking for is a little more complex, then the "regular expression" library may be of more help. There's a good HOWTO on regular expressions here: http://www.amk.ca/python/howto/regex/ Finally, I'm guessing that you've had some programming experience; you might then want to do a quick tour through the standard tutorial at: http://python.org/doc/tut to brush up on Python's feature set. Good luck to you! From roeland.rengelink at chello.nl Mon May 31 04:21:34 2004 From: roeland.rengelink at chello.nl (Roeland Rengelink) Date: Mon May 31 04:19:58 2004 Subject: [Tutor] Peaks detection In-Reply-To: <20040530125826.24eae0c9.gaedol@softhome.net> References: <20040530125826.24eae0c9.gaedol@softhome.net> Message-ID: <40BAEB0E.8080608@chello.nl> Marco wrote: >Hey all, >i am tryin to write in python a peak detection algorithm to use on spectra taken from a data analyser in a lab. >The spectrum comes in a text file with 2 columns, one with the channel number and the other one with number of counts for that channel. >Making the calibration to the energy is not a problem, except for the fact that the algorithm _should_ recognize the peaks of the spectrum (those that have a fair gaussian form) and notate the centroid of the gaussian. > >The problem is: i can't find an algorithm except for a labview "procedure" on the net. >Once found the "how" implementing it in python shouldn't be that hard :) > > >so the question is: >Anyone has a source for an algorithm of that kind? Any suggestion? > > Hi Marco, I'm only going to give you an outline of the solution, because this problem is a lot easier to solve in theory than in practice (code is untested). Lets't define two functions: def is_local_maximum(counts, current_channel): """Return True if counts in current_channel are larger than in neighbouring channels""" if (counts[current_channel] > counts[current_channel-1] and counts[current_channel] > counts[current_channel+1]): return True else: return False def measure_peak(counts, channels, max_channel, width) """Return the mean (centroid) and stddev of a peak at max_channel""" mean = 0.0 stdev = 0.0 total_counts = 0.0 for i in range(max_channel-width, max_channel+width): total_counts += counts[i] mean += counts[i]*channels[i] mean = mean/total_counts for i in range(max_channel-width, max_channel+width): stdev += counts[i]*(channels[i]-mean)**2 stdev = math.sqrt(stdev/total_counts) return mean, stdev To analyze the dataset we are going to assume that you know the background signal and the rms of the background signal (measuring them is left as an exercise) def analyze(counts, channels, background, background_rms, min_sigma, window_width): minimum_signal = background+background_rms*min_sigma for i in range(window_width, len(channels)-window_width): if counts[i] < minimum_signal: # Ignore noise continue if is_local_maximum(counts, i): mean, stdev = measure_peak(counts, channels, i, window_width) print "Detected peak", counts[i], mean, stdev Now for the caveats: - I assume that there is going to be only one peak within the window around a given maximum - I assume that the peaks are properly sampled (channel_width < width_of_peak/2) - I assume that the window width >> width of the peak - I assume that the total signal within the window is dominated by the peak - I assume that the background is flat and the rms of the background is constant These assumptions are generally not (all) true in practice Hope this help, Roeland From mlist at asesoft.ro Mon May 31 06:15:59 2004 From: mlist at asesoft.ro (MailingList) Date: Mon May 31 06:23:46 2004 Subject: [Tutor] (no subject) Message-ID: <080b01c446f8$44b0d5d0$7560a8c0@asesoft.intl> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040531/f333d540/attachment.html From kim.branson at csiro.au Mon May 31 06:38:20 2004 From: kim.branson at csiro.au (Kim Branson) Date: Mon May 31 06:38:34 2004 Subject: [Tutor] object question Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi all, i'm having a go at using classes. below is my attempt (a long time ago i posted a question to this list and received a great reply from Karl suggesting an object based approach, i filed it away to understand at a later date :) This object sets up some dictionaries, and these are then filled with the update method. This changes to the appropriate directory at reads in a results file. this file looks like: PK= 5.38 Qual= 1.58 PMF= -75.04 PMF_rb= -75.04 SMoG= -85.09 SMoG_H= - - -8.51 ChemScore= -29.01 Clash= 0.00 Int= 0.00 DockNRG= -13.07 AutoDock= -15.71 my problem is in the matching done in the update method. the assignment of m=self.score_lines.search(line) does not produce a object with and prints as None. I've tested with the test code i've attached. I think its a scope issue as it seems to work when its not in the object? Can someone explain this to me. cheers Kim - - -----begin test code---- import re, string, os path = os.getcwd() results_path= path + "/dock" os.chdir("%s" % results_path) data =open("results_summary", 'r') data= data.readlines() score_lines =re.compile("""PK= (?P.*) Qual= (?P.*) PMF= (?P.*)\ PMF_rb= (?P.*) SMoG= (?P.*) SMoG_H= (?P.*) ChemScore= (?P.*)\ Clash= (?P.*) Int= (?P.*) DockNRG= (?P.*) AutoDock= (?P.*)""") for line in data: #print line m=score_lines.search(line) #print type(m) print m.group("score") print m for grp, val in m.groupdict().items(): print grp,val - - ---- end test code--- */ ***********Begin Code****** */ import string, os, re #we get the data from the SCORER outout class scorer_values: score_lines =re.compile("""PK= (?P.*) Qual= (?P.*) PMF= (?P.*)\ PMF_rb= (?P.*) SMoG= (?P.*) SMoG_H= (?P.*) ChemScore= (?P.*)\ Clash= (?P.*) Int= (?P.*) DockNRG= (?P.*) AutoDock= (?P.*)""") def __init__(self): self.counter=0; #make the dictionaries self.tables=dict([(name,{}) for name in ["score","qual","pmf","pmf_rb","smog","smog_h",\ "chemscore","clash","int","docknrg","autodock"]]) #def __str__(self): #s = [] #for key in self.tables: #s.append(key + '\n') #s.append("-" * len(key) + '\n') #items =self.tables[key].items() #items.sort() #for key, val in items: #s.append(str(key) + '->' + val + "\n") #return ''.join(s) def _pull(self,program="dock"): os.chdir("%s"% program) self.results=open("results_summary", 'r') return self.results.readlines() def update(self,program="dock"): for line in (self._pull(program)): m=self.score_lines.search(line) print type(m) print m if m: for grp,val in m.groupdict().items(): tables=self.tables[grp] tables[self.counter]=val print self.tables self.counter += 1 dock_values=scorer_values() dock_values.update("dock") print dock_values Kim Branson Diffraction and Theory CSIRO Health Sciences and Nutrition 343 Royal Parade, Parkville Melbourne Ph +613 9662 7136 kim.branson@csiro.au Kim Branson Diffraction and Theory CSIRO Health Sciences and Nutrition 343 Royal Parade, Parkville Melbourne Ph +613 9662 7136 kim.branson@csiro.au -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) iD8DBQFAuwsjer2hmGbHcokRAvszAJ9Ws1Vcbc43OKDodbJjam03By+GHwCffdjV F4VKwwXqeFkQVkS+fmzO1Ro= =q1TV -----END PGP SIGNATURE----- From MBussell at aol.com Mon May 31 11:42:10 2004 From: MBussell at aol.com (MBussell@aol.com) Date: Mon May 31 11:42:27 2004 Subject: [Tutor] Time help Message-ID: <103.471bf71d.2decac52@aol.com> I am playing with the Time Module, and was attempt to write a script which would tell me when a specific time was reached. I am using the integer number of seconds since the epoch. This is what I have: def test(): now = 1086017720.0 current = time.time() print current while now<>current: current = time.time() print current print "now is acheived!" The problem is the count continues past the specific time. Thanks, MB -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040531/e533745a/attachment.html From pythonTutor at venix.com Mon May 31 12:07:06 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon May 31 12:07:14 2004 Subject: [Tutor] Time help In-Reply-To: <103.471bf71d.2decac52@aol.com> References: <103.471bf71d.2decac52@aol.com> Message-ID: <1086019626.2097.40.camel@laptop.venix.com> Your loop requires that you catch an EXACT match to your desired time. On a system that does not round to the second, this is quite unlikely to happen. You could round current, but I'd recommend changing the while test to be: while now > current The loop will exit when current reaches or exceeds now. On Mon, 2004-05-31 at 11:42, MBussell@aol.com wrote: > I am playing with the Time Module, and was attempt to write a script > which would tell me when a specific time was reached. > > I am using the integer number of seconds since the epoch. This is > what I have: > > def test(): > now = 1086017720.0 > current = time.time() > print current > while now<>current: > current = time.time() > print current > print "now is acheived!" > > The problem is the count continues past the specific time. > > Thanks, > MB > > ______________________________________________________________________ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From tomikaze at enternet.hu Mon May 31 17:14:35 2004 From: tomikaze at enternet.hu (tomikaze@enternet.hu) Date: Tue Jun 1 15:56:47 2004 Subject: [Tutor] gui tks and encodings Message-ID: <200405312114.i4VLEZ7l033048@smtp.enternet.hu> ok you are right, i have finally found a few lines about mark_set and the insertion point being a mark on the page too, that Glen told me. it seems like reading the modul thirtyfour times is not enough in some special cases. :) but could you tell me why do i always get 0, 0, 0, 0 for print text_widget.bbox('insert') ? text_widget.update_idletasks() is done before.. do i use it the wrong way? thanks tm From tommusgrove__ at hotmail.com Mon May 31 19:47:54 2004 From: tommusgrove__ at hotmail.com (Tom Musgrove) Date: Tue Jun 1 15:56:52 2004 Subject: [Tutor] list comprehension question Message-ID: Hi, I'm writing some code that takes two meshes, an original, and an altered mesh. Finds the added and deleted edges/vertices. And then modifiys a list of targets that were applied to the original mesh and modifies them to have the same behavior on the altered mesh. (Ie the targets are mesh deformations for specified vertices, but the new mesh might have new vertices that need to be interpolated, or vertices that have been deleted, or moved, etc.) I have two lists of keys that I have from creating edge dictionaries for the altered and original mesh, then using list comprehension to find the unique edges. giving, for instance, the following. ListAUniqueEdges = {(1,5), (2,6), (3,7), (8,9)} ListBUniqueEdges = {(2,7), (3,5), (1,6), (10,11)} I need to create two dictionaries from the above, showing how the edges from lista relate to those in listb and vice versa, ie the resulting Dict would be DictA = {(1,5): {(1,6), (3,5)}, (2,6): {(2,7), (1,6)}, (3,7): {(3,5), (2,7)}, (8,9):{}} is there some elegant way to do this, I think it should be doable via list comprehension, but for some reason I can't think of the solution right now, and the power of google isn't helping... Thanks, Tom M. _________________________________________________________________ Best Restaurant Giveaway Ever! Vote for your favorites for a chance to win $1 million! http://local.msn.com/special/giveaway.asp