From syrinx at simplecom.net Sat Nov 1 00:53:58 2003 From: syrinx at simplecom.net (Scott) Date: Sat Nov 1 00:55:09 2003 Subject: [Tutor] broken pipe Message-ID: <20031031235358.2e55bd5d.syrinx@simplecom.net> I've been working on an internet app, off and on, for quite some time, and the socket module keeps throwing error/"broken pipe" exceptions. What exactly do these mean? Also, less frequently, I see "connection reset by peer." What do I do about that? Thanks. From pythontutor at venix.com Sat Nov 1 10:15:06 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Nov 1 10:15:12 2003 Subject: [Tutor] broken pipe In-Reply-To: <20031031235358.2e55bd5d.syrinx@simplecom.net> References: <20031031235358.2e55bd5d.syrinx@simplecom.net> Message-ID: <3FA3CDFA.6070505@venix.com> "connection reset by peer" means that the computer sent a reset signal that it was closing the connection. This is a simple one-step termination. The "normal" termination involves sending a FIN from each end to the other end and getting an acknowledgement back. You might find it useful to run a program like tcpdump to monitor the traffic to help with debugging. tcpdump is included with most linux distributions. Scott wrote: > I've been working on an internet app, off and on, for quite some time, > and the socket module keeps throwing error/"broken pipe" exceptions. > What exactly do these mean? Also, less frequently, I see "connection > reset by peer." What do I do about that? Thanks. > > > > _______________________________________________ > 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 alan.gauld at blueyonder.co.uk Sat Nov 1 12:48:14 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Nov 1 12:47:31 2003 Subject: [Tutor] Re: test if file is not ascii References: <20031031061006.GA18340@localhost.localdomain> <20031031191935.GA13823@localhost.localdomain> Message-ID: <007801c3a0a0$52fbc8b0$6401a8c0@xp> > for letter in line: > char = ord(letter) > if char < 20: It should be possible to write a regex for all the letters below ASCII 20. Checking if the regex exists in the line is almost certainly faster than checking each character using Python. Something like: regex = "[" for n in range(20): regex = regex+chr(n) regex = regex+"]" re.compile(regex) > sys.stderr.write('File contains illegal characters.\n') > return 101 It might be nicer to raise an exception. Certainly more Pythonic. Alan G. From alan.gauld at blueyonder.co.uk Sat Nov 1 12:50:21 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Nov 1 12:49:38 2003 Subject: [Tutor] Re: test if file is not ascii References: <20031031061006.GA18340@localhost.localdomain> <5.1.0.14.2.20031031142641.029d28a8@mail.30below.com> Message-ID: <007d01c3a0a0$9ee47650$6401a8c0@xp> > ... have you tried a regular expression? Great minds think alike... > bb = 'this is the search string that I want to see is in it...' > if re.search('[\x00-\x19]',bb): But for some reason I didn't think a range would work - I don't know why!?! > However, I don't know off the top of my head how to specify special > characters in regexps... What I listed might work, It seems to in the short test I did. Alan G From littledanehren at yahoo.com Sat Nov 1 14:12:48 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Nov 1 14:12:53 2003 Subject: [Tutor] New-style classes Message-ID: <20031101191248.63175.qmail@web41808.mail.yahoo.com> I have heard about new-style classes, and I'm afraid I'm using old-style classes (since I'm learning from a book made for 2.0). Could somebody please explain what new-style classes are and their benefit over old-style classes? Daniel Ehrenberg __________________________________ Do you Yahoo!? Exclusive Video Premiere - Britney Spears http://launch.yahoo.com/promos/britneyspears/ From pythontutor at venix.com Sat Nov 1 14:45:57 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Nov 1 14:46:02 2003 Subject: [Tutor] New-style classes In-Reply-To: <20031101191248.63175.qmail@web41808.mail.yahoo.com> References: <20031101191248.63175.qmail@web41808.mail.yahoo.com> Message-ID: <3FA40D75.9030201@venix.com> http://www.python.org/doc/2.2.1/whatsnew/ What's New in Python 2.2 http://www.python.org/2.2/descrintro.html Unifying types and classes in Python 2.2 The first link is by amk (just in case he's not watching the list). The second is by GvR and will probably make more sense after reading the section of amk's document dealing with the new classes. Daniel Ehrenberg wrote: > I have heard about new-style classes, and I'm afraid > I'm using old-style classes (since I'm learning from a > book made for 2.0). Could somebody please explain what > new-style classes are and their benefit over old-style > classes? > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > Exclusive Video Premiere - Britney Spears > http://launch.yahoo.com/promos/britneyspears/ > > _______________________________________________ > 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 pythontutor at venix.com Sat Nov 1 14:55:08 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Nov 1 14:55:12 2003 Subject: [Tutor] New-style classes In-Reply-To: <3FA40D75.9030201@venix.com> References: <20031101191248.63175.qmail@web41808.mail.yahoo.com> <3FA40D75.9030201@venix.com> Message-ID: <3FA40F9C.3020802@venix.com> One more comment. A "classic" class has a base class defined as: class Base: A newstyle class has a base of object class Base(object): or one of the other built in types (e.g. dict or list). I have not encountered any cases where code was broken my switching to the new style classes. Lloyd Kvam wrote: > http://www.python.org/doc/2.2.1/whatsnew/ > What's New in Python 2.2 > > http://www.python.org/2.2/descrintro.html > Unifying types and classes in Python 2.2 > > The first link is by amk (just in case he's not watching the list). > The second is by GvR and will probably make more sense after reading > the section of amk's document dealing with the new classes. > > > Daniel Ehrenberg wrote: > >> I have heard about new-style classes, and I'm afraid >> I'm using old-style classes (since I'm learning from a >> book made for 2.0). Could somebody please explain what >> new-style classes are and their benefit over old-style >> classes? >> Daniel Ehrenberg >> >> __________________________________ >> Do you Yahoo!? >> Exclusive Video Premiere - Britney Spears >> http://launch.yahoo.com/promos/britneyspears/ >> >> _______________________________________________ >> 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 dyoo at hkn.eecs.berkeley.edu Sat Nov 1 21:14:15 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Nov 1 21:14:24 2003 Subject: [Tutor] ANN: BayPIGies meeting for Thursday, November 13, 2003 Message-ID: Hi everyone, Here's the monthly announcement for the upcoming BayPIGgies Bay Area Python Users Group. Our speaker for this month may be familiar to a few of you. *grin* --- When: Thursday, November 13, 2003 Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: What's new in Python? Not your usual list of new features Speaker: Guido van Rossum Python is an OO programming language that is usable for pedestrian tasks typically called "scripting", as well as for the construction of highly advanced class libraries. The latest versions, Python 2.2 and 2.3, have added significant power to Python's competence in the latter area, primarily through the introduction of two new concepts: iterators (a generalization of for loops) and descriptors (a generalization of customizable attributes). In this talk I will present the principles and some examples of these additions, and show how they are useful for lowly scripting tasks as well as for advanced class library authors. I encourage audience participation and will be available for questions afterwards. For driving directions to Carnegie, as well as information about BayPIGgies, please visit: http://www.baypiggies.net From tim.ronning at start.no Sun Nov 2 10:43:22 2003 From: tim.ronning at start.no (Tim Ronning) Date: Sun Nov 2 08:43:38 2003 Subject: [Tutor] Newbie append puzzle Message-ID: Hi you all The following code is a part of my first thumbeling steps into the world of Python. It's a simple mp3 player. - - - - Cut - - - - - - - - - - - - - elif choice == '3': # Add to an existing list def append(mp3): app = open("playlist","a") app.write(mp3) app.close() newmp3 = raw_input("New mp3: ") append(newmp3) elif choice == '4': # Make an int. list, deletes, makes a new playlist, and copies itself to playlist def makeaList(s): anothermp3 = string.split(s) return anothermp3 playlist = open("playlist","r") mp3list = [] for line in playlist.readlines(): mp3list = mp3list + makeaList(line) playlist.close() delnr = int(raw_input("Which number? ")) del mp3list[delnr] listlen = len(mp3list) def append(mp3): app = open("playlist.new","a") app.write(mp3) app.close() n = 0 while n < listlen: append(mp3list[n]) n = n + 1 - - - - - Cut - - - - - - - - - - - - - The problem: The append() function under choice "3" appends the raw_input on a new line in the playlist file. Simple ascii. This is correct. The append() function under choice "4" appends all the list items on one single line without spaces, this is not what I want. I want them on separate lines. I have a feeling the answer is embarasing simple and probably steering me right in the face, but somehow I don't see it. Anyone? Best regards Tim Ronning -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From tim.ronning at start.no Sun Nov 2 12:01:29 2003 From: tim.ronning at start.no (Tim Ronning) Date: Sun Nov 2 10:01:44 2003 Subject: [Tutor] Newbie append puzzle In-Reply-To: References: Message-ID: BTW. My Opera mail reader/writer is messing up indentation somehow. Let's try this. elif choice == '3': def append(mp3): app = open("playlist","a") app.write(mp3) app.close() newmp3 = raw_input("New mp3: ") append(newmp3) elif choice == '4': def makeaList(s): anothermp3 = string.split(s) return anothermp3 playlist = open("playlist","r") mp3list = [] for line in playlist.readlines(): mp3list = mp3list + makeaList(line) playlist.close() delnr = int(raw_input("Which number? ")) del mp3list[delnr] listlen = len(mp3list) def append(mp3): app = open("playlist.new","a") app.write(mp3) app.close() n = 0 while n < listlen: append(mp3list[n]) n = n + 1 The problem: The append() function under choice "3" appends the raw_input on a new line in the playlist file. Simple ascii. This is correct. The append() function under choice "4" appends all the list items on one single line without spaces, this is not what I want. I want them on separate lines. I have a feeling the answer is embarasing simple and probably steering me right in the face, but somehow I don't see it. Anyone? Best regards Tim Ronning From mwagman at charter.net Sun Nov 2 10:03:29 2003 From: mwagman at charter.net (Mike Wagman) Date: Sun Nov 2 10:04:03 2003 Subject: [Tutor] Sound and Python Message-ID: <1067785409.2561.2.camel@24-159-248-140.jvl.wi.charter.com> Can anyone point me to some tutorials on putting sound in python programs. Mike From Janssen at rz.uni-frankfurt.de Sun Nov 2 10:15:06 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sun Nov 2 10:15:15 2003 Subject: [Tutor] Re: test if file is not ascii In-Reply-To: <5.1.0.14.2.20031031142641.029d28a8@mail.30below.com> References: <20031031061006.GA18340@localhost.localdomain> <5.1.0.14.2.20031031142641.029d28a8@mail.30below.com> Message-ID: On Fri, 31 Oct 2003, Roger Merchberger wrote: > Checking each individual char [as you noticed] is insane... > > ... have you tried a regular expression? > > Something like: > =-=-=-=-=-=-=-= > > import re > > bb = 'this is the search string that I want to see is in it...' > if re.search('[\x00-\x19]',bb): > print "Yes it's in there" > else: > Print "No, it's not in there" I've tested the range-definition, and it works. But are newlines also invalid within rtf (or better exclude \n - \x0A and \r - \x0B)? Note that you can make the error Message more helpful: mt = re.search('[\x00-\x19]',bb) if mt: print "illegal character (ascii-num: %s) on position %s" \ % (ord(mt.group()), mt.start()) determining the line-number (if rtf-source has lines ;-) could be: line_num = len( re.findall(os.linesep, bb[:mt.start()]) ) +1 Michael From Janssen at rz.uni-frankfurt.de Sun Nov 2 10:27:50 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Sun Nov 2 10:27:59 2003 Subject: [Tutor] Newbie append puzzle In-Reply-To: References: Message-ID: On Sun, 2 Nov 2003, Tim Ronning wrote: > BTW. My Opera mail reader/writer is messing up indentation somehow. [you got probably a tab-problem. code below mixes tabs and spaces] > Let's try this. > > elif choice == '3': > > def append(mp3): > app = open("playlist","a") > app.write(mp3) > app.close() > newmp3 = raw_input("New mp3: ") > append(newmp3) > > elif choice == '4': > > def makeaList(s): > anothermp3 = string.split(s) > return anothermp3 > > playlist = open("playlist","r") > mp3list = [] > for line in playlist.readlines(): > mp3list = mp3list + makeaList(line) > > playlist.close() > delnr = int(raw_input("Which number? ")) > del mp3list[delnr] > listlen = len(mp3list) > > def append(mp3): > app = open("playlist.new","a") > app.write(mp3) > app.close() > n = 0 > while n < listlen: > append(mp3list[n]) > n = n + 1 > > The problem: The append() function under choice "3" appends the raw_input > on a new line in the playlist file. Simple ascii. This is correct. The > append() function under choice "4" appends all the list items on one single > line without spaces, certainly choice "4" "mp3" strings manage somehow to get rid of their newlines. The newline was originally delivered by "raw_input". Hint: string.split splits per default by any kind of whitespace.... Best (instead of making shure that your code never tries to "append" a string, that doesn't end in newline) is to rewrite your "append" function, so that it test itself if the "mp3" string ends with a newline. I assume, you want to write that bit yourself (Feel free to ask on tutor if you can't get it right - or post your solution)? Note: now where you need to enhance your "append" function it becomes even more sensible to define it only once: Just define it before any if-clause and you won't have to do every bugfix twice. Hey, welcome at tutor and python :-) Michael > this is not what I want. I want them on separate > lines. I have a feeling the answer is embarasing simple and probably > steering me right in the face, but somehow I don't see it. Anyone? > Best regards > Tim Ronning > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tim.ronning at start.no Sun Nov 2 14:18:54 2003 From: tim.ronning at start.no (Tim Ronning) Date: Sun Nov 2 12:19:10 2003 Subject: [Tutor] Newbie append puzzle In-Reply-To: References: Message-ID: P? Sun, 2 Nov 2003 16:27:50 +0100 (CET), skrev Michael Janssen : > > certainly choice "4" "mp3" strings manage somehow to get rid of their > newlines. The newline was originally delivered by "raw_input". Hint: > string.split splits per default by any kind of whitespace.... > > Best (instead of making shure that your code never tries to "append" a > string, that doesn't end in newline) is to rewrite your "append" > function, so that it test itself if the "mp3" string ends with a > newline. I assume, you want to write that bit yourself (Feel free to > ask on tutor if you can't get it right - or post your solution)? > > Note: now where you need to enhance your "append" function it becomes > even more sensible to define it only once: Just define it before any > if-clause and you won't have to do every bugfix twice. > > Hey, welcome at tutor and python :-) > > > Michael Thanks for your answer Michael. I have re-done a couple of things incl. the append function. Not shure if this is what you had in mind though. How do you test for "\n" in a string ? Anyway the following code works, but I greatly appriciate input on smarter ways to do things. Thats what learning is all about, -learning to do smart things! MP3 Player in 100 lines! #!/usr/bin/env python ######################################## ## DSPmP ## ## Dead.Simple.Python.mp3.Player ## ## ## ## Author: Tim Ronning ## ## Version: 0.0.2 ## ## Date: 02.11.03 ## ## ## ######################################## import sys, ao, mad, string, os choice = '1' while choice != '5': print """ ************************ * DSPmP * ************************ * 1)....Play List * * 2)....Show List * * 3)....Add MP3's * * 4)....Remove MP3's * * 5)....Quit * ************************ ************************ """ choice = raw_input("Choice: ") def makeaList(s): anothermp3 = string.split(s) return anothermp3 def append(mp3): if choice == "3": app = open("playlist","a") app.write(mp3) app.close() else: app = open("playlist.new","a") app.write(mp3 + "\n") app.close if choice == '1': playlist = open("playlist","r") mp3list = [] for line in playlist.readlines(): mp3list = mp3list + makeaList(line) playlist.close() print mp3list items = len(mp3list) j=0 while j < items: tune = mp3list[j] mf = mad.MadFile(tune) dev = ao.AudioDevice('alsa09', rate=mf.samplerate()) while 1: buf = mf.read() if buf is None: break dev.play(buf, len(buf)) j = j + 1 elif choice == '2': playlist = open("playlist","r") for line in playlist.readlines(): print line playlist.close() elif choice == '3': newmp3 = raw_input("New mp3: ") append(newmp3) elif choice == '4': playlist = open("playlist","r") mp3list = [] for line in playlist.readlines(): mp3list = mp3list + makeaList(line) playlist.close() delnr = int(raw_input("Which number? ")) del mp3list[delnr] listlen = len(mp3list) n = 0 while n < listlen: append(mp3list[n]) n = n + 1 os.system("mv -f playlist.new playlist") else: sys.exit() - - - - -END CODE - - - - - Best regards -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From alan.gauld at blueyonder.co.uk Sun Nov 2 13:44:54 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 2 13:44:44 2003 Subject: [Tutor] New-style classes References: <20031101191248.63175.qmail@web41808.mail.yahoo.com> Message-ID: <001f01c3a171$687b3ff0$6401a8c0@xp> > I have heard about new-style classes, and I'm afraid > I'm using old-style classes Don't be afraid, old style classes are still what most of us use! > Could somebody please explain what > new-style classes are and their benefit over old-style Simply put new style classes turn every type in Python into a class. This means that you can now sub class the standard types like int, float ot string. I believe there are a few exeptions - you can't (yet) subclass a function. In practice thee are very few occasions when you will need new style classes, but its nice to know that if you do, you can... But its definitely in the "advanced topics" category, you can get into serious complexity when you statrt subtyping the basic types in any language. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From glingl at aon.at Sun Nov 2 13:54:52 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Nov 2 13:56:47 2003 Subject: [Tutor] New-style classes In-Reply-To: <001f01c3a171$687b3ff0$6401a8c0@xp> References: <20031101191248.63175.qmail@web41808.mail.yahoo.com> <001f01c3a171$687b3ff0$6401a8c0@xp> Message-ID: <3FA552FC.1020201@aon.at> >This means that you can now sub class the >standard types like int, float ot string. I believe there >are a few exeptions - you can't (yet) subclass a >function. > ---- i. e. the ?? Does this "(yet)" express some sort of hope - or a certain knowledge about future developments of Python? Gregor From op73418 at mail.telepac.pt Sun Nov 2 14:09:45 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Nov 2 14:08:15 2003 Subject: [Tutor] New-style classes In-Reply-To: <20031101191248.63175.qmail@web41808.mail.yahoo.com> References: <20031101191248.63175.qmail@web41808.mail.yahoo.com> Message-ID: On Sat, 1 Nov 2003 11:12:48 -0800 (PST), you wrote: >I have heard about new-style classes, and I'm afraid >I'm using old-style classes (since I'm learning from a >book made for 2.0). Could somebody please explain what >new-style classes are and their benefit over old-style >classes? For most of the programming problems there is no difference in using either old-style or new-style classes. Lloyd Kvam has already posted some references. Let me add a few things -- this is all advanced stuff so I'll be short and cryptic :-) - There are some notable differences, between old-style and new-style classes. One has to do with special __*__ name lookup. Consider the following example: >>> #An old style class >>> class Test: ... pass ... >>> a = Test() >>> def it(self): ... yield None ... >>> import types >>> print types.MethodType.__doc__ instancemethod(function, instance, class) Create an instance method object. >>> #Sticking an __iter__ iterator method on the *instance* itself. >>> a.__iter__ = types.MethodType(it, a, a.__class__) >>> iter(a) >>> for elem in a: ... print elem ... None >>> #A new-style class >>> class TestNew(object): ... pass ... >>> b = TestNew() >>> #Sticking an __iter__ iterator method on the *instance* itself. >>> b.__iter__ = types.MethodType(it, b, b.__class__) >>> iter(b) Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence >>> I'll leave you to ponder on what's happening here. - One other difference has to do with how Python linearizes the graph of super classes of a given class. For new-style classes the C3 order is used (from 2.3 onward) - there is an article somewhere in the net by S. Pedroni I believe explaining this. But only with some contrived inheritance graphs you'd notice the difference :-) - There are some distinct advantages in using new-style classes. Besides being able to subclass (almost all) builtin types you can use features like super, properties and metaclasses. All advanced stuff, as I said. With my best regards, G. Rodrigues From arkamir at softhome.net Sun Nov 2 15:42:16 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Sun Nov 2 15:42:35 2003 Subject: [Tutor] weird error messge Message-ID: <1067805736.7021.8.camel@quercus> Hey can anyone help me. Whenever i run this script i get an error i cant make anything of. Can someone explain it to me?? import MySQLdb import re import compare import numberofpages import display db = MySQLdb.connect(host='localhost', user='conrad', passwd='mysql4conrad', db='cgi') cursor = db.cursor() def retrieve_posts(forum, thread, end_post): giventemplate = 'posttemplate' inputtemplate = open(giventemplate, 'r') posttemplate = inputtemplate.read() inputtemplate.close() start_post = end_post - 20 cursor.execute('''select names, dates, subjects, posts, positions from %s where threads = \'%s\' and positions > \'%s\' and positions < \'%s\'''' % (forum, thread, start_post, end_post)) postsinfo = cursor.fetchall() #if i do postsinfo.sort() or #postsinfo.sort(compare.compare) # it makes postsinfo = none postsinfo = list(postsinfo) posts = posttemplate subsitutes = ['NAME', 'DATE', 'SUBJECT', 'POST'] hello = [] for post in postsinfo: posts = re.sub('', post[1], posts) posts = re.sub('', post[2], posts) posts = re.sub('', post[3], posts) posts = re.sub('', post[4], posts) hello.append(posts) posts = posttemplate print hello the error message is: traceback (most recent call last): File "", line 1, in ? File "retrieveposts.py", line 32, in retrieve_posts posts = re.sub('', post[1], posts) File "/usr/lib/python2.2/sre.py", line 143, in sub return _compile(pattern, 0).sub(repl, string, count) File "/usr/lib/python2.2/sre.py", line 229, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat Traceback (most recent call last): File "", line 1, in ? File "retrieveposts.py", line 32, in retrieve_posts posts = re.sub('', post[1], posts) File "/usr/lib/python2.2/sre.py", line 143, in sub return _compile(pattern, 0).sub(repl, string, count) File "/usr/lib/python2.2/sre.py", line 229, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat this is posttemplate: '
\n\t
\n\t\t\t\t\t
\n\t\t\t\t\t \n\t\t\t\t\t
\n\t\t\t\t\t

Posted on:

\n\t
\n\t
\n\t\t\t \n\t
\n\t
\n\t\t\t
\t\n\t\t\t
\n\t\t\t\n\t\t\t
\n\t\t\t
\n\t\t\ t
\n\t\t\t
\n\t\t\t
\n\t\t\t
\t\n\t
\n
\n' THanks a lot, Conrad Koziol From littledanehren at yahoo.com Sun Nov 2 15:55:00 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Nov 2 15:55:06 2003 Subject: [Tutor] Newbie append puzzle In-Reply-To: Message-ID: <20031102205500.13315.qmail@web41808.mail.yahoo.com> > Thanks for your answer Michael. > I have re-done a couple of things incl. the append > function. Not shure if > this is what you had in mind though. How do you test > for "\n" in a string ? > Anyway the following code works, but I greatly > appriciate input on smarter > ways to do things. Thats what learning is all about, > -learning to do smart > things! > > MP3 Player in 100 lines! > > #!/usr/bin/env python > ######################################## > ## DSPmP ## > ## Dead.Simple.Python.mp3.Player ## > ## ## > ## Author: Tim Ronning ## > ## Version: 0.0.2 ## > ## Date: 02.11.03 ## > ## ## > ######################################## > > import sys, ao, mad, string, os > > choice = '1' > > while choice != '5': > print """ > ************************ > * DSPmP * > ************************ > * 1)....Play List * > * 2)....Show List * > * 3)....Add MP3's * > * 4)....Remove MP3's * > * 5)....Quit * > ************************ > ************************ > """ > choice = raw_input("Choice: ") > def makeaList(s): > anothermp3 = string.split(s) > return anothermp3 > def append(mp3): > if choice == "3": > app = open("playlist","a") > app.write(mp3) > app.close() > else: > app = open("playlist.new","a") > app.write(mp3 + "\n") > app.close > if choice == '1': > playlist = open("playlist","r") > mp3list = [] > for line in playlist.readlines(): > mp3list = mp3list + makeaList(line) > > playlist.close() > print mp3list > items = len(mp3list) > j=0 > while j < items: > tune = mp3list[j] > mf = mad.MadFile(tune) > dev = ao.AudioDevice('alsa09', > rate=mf.samplerate()) > while 1: > buf = mf.read() > if buf is None: > break > dev.play(buf, len(buf)) > j = j + 1 > > elif choice == '2': > playlist = open("playlist","r") > for line in playlist.readlines(): > print line > playlist.close() > > elif choice == '3': > newmp3 = raw_input("New mp3: ") > append(newmp3) > > elif choice == '4': > playlist = open("playlist","r") > mp3list = [] > for line in playlist.readlines(): > mp3list = mp3list + makeaList(line) > > playlist.close() > delnr = int(raw_input("Which number? ")) > del mp3list[delnr] > listlen = len(mp3list) > n = 0 > while n < listlen: > append(mp3list[n]) > n = n + 1 > os.system("mv -f playlist.new playlist") > > else: > sys.exit() > > - - - - -END CODE - - - - - > > Best regards Your program uses the string module, which is obsolete. Most of the string methods have been replaced with methods on the string type, acting as an object. Here's the part where you used the string module: > def makeaList(s): > anothermp3 = string.split(s) > return anothermp3 Using the builtin string methods, you would instead write: > def makeaList(s): > anothermp3 = s.split() > return anothermp3 but I would probably impliment it like this: > makeaList = lambda s: s.split() and I'd define it outside of the while loop. If you define it inside of the loop, it is defined over and over again, slowing the program. I don't think the filenames you used will work as you intended. When you were making a new playlist, you opened the file playlist.new (playlist is the name and new is the file extention, not a new playlist). When you're reading the playlist, you open a file named playlist with no file extention. These files are in the directory where the script is run. If you open a file that doesn't exist, the file is automatically created. I would open something like playlist.dsp whether or not the playlist exists. What are the ao and mad modules that you're using? They're not builtin so I can't use your mp3 player. Where could I find those modules? Daniel Ehrenberg __________________________________ Do you Yahoo!? Exclusive Video Premiere - Britney Spears http://launch.yahoo.com/promos/britneyspears/ From phthenry at earthlink.net Sun Nov 2 17:21:41 2003 From: phthenry at earthlink.net (Paul Tremblay) Date: Sun Nov 2 17:21:40 2003 Subject: [Tutor] Re: test if file is not ascii In-Reply-To: References: <20031031061006.GA18340@localhost.localdomain> <5.1.0.14.2.20031031142641.029d28a8@mail.30below.com> Message-ID: <20031102222141.GA26191@localhost.localdomain> On Sun, Nov 02, 2003 at 04:15:06PM +0100, Michael Janssen wrote: > > I've tested the range-definition, and it works. But are newlines also > invalid within rtf (or better exclude \n - \x0A and \r - \x0B)? Right. They are allowed. So I came up with this solution: illegal_regx = re.compile( '\x00|\x01|\x02|\x03|\x04|\x05|\x06|\x07|\x08|\x0B|\x0E|\x0F|\x10|\x11|\x12|\x13') line = 1 read_obj = open(self.__file, 'r') write_obj = open(self.__write_to, 'w') while line: line = read_obj.read(1000) line = line.replace ('\r', '\n') line = re.sub(illegal_regx, '', line) write_obj.write(line ) I believe that \x09 is a tab.I think that \x0B is actually a vertical tab. I do need to replace \r with \n. I do this with: line = line.replace('\r', '\n') Doing a quick test: print ' the \\r is "%s"'% ord('\r') I get number "13". So that means that '\r' is equal to \x0D. \x0C seems to be eqaul to " ". But my unicode charts say it is a file separator, so I should probably add \x0C to my regualar expression. > > Note that you can make the error Message more helpful: > > mt = re.search('[\x00-\x19]',bb) > if mt: > print "illegal character (ascii-num: %s) on position %s" \ > % (ord(mt.group()), mt.start()) Note that I've just substituted illegal control charcters, which don't add any info to the file, but somehow creep in. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From dyoo at hkn.eecs.berkeley.edu Sun Nov 2 17:55:57 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 2 17:56:03 2003 Subject: [Tutor] weird error messge In-Reply-To: <1067805736.7021.8.camel@quercus> Message-ID: > Hey can anyone help me. Whenever i run this script i get an error i cant > make anything of. Can someone explain it to me?? Hi Conrad, The error message: > traceback (most recent call last): > File "", line 1, in ? > File "retrieveposts.py", line 32, in retrieve_posts > posts = re.sub('', post[1], posts) > File "/usr/lib/python2.2/sre.py", line 143, in sub > return _compile(pattern, 0).sub(repl, string, count) > File "/usr/lib/python2.2/sre.py", line 229, in _compile > raise error, v # invalid expression > sre_constants.error: multiple repeat is important: the system is saying that the regular expression is using an illegal "multiple repeat" thing that it has no idea how to handle. What it's really trying to say is that '*' is a regular expression metacharacter. For example, a* represents any number of "a" characters. But what does something like: a** mean? To repeat it more? It turns out that this isn't legal as a regular expression pattern: ### >>> re.compile('a**') Traceback (most recent call last): File "", line 1, in ? File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre.py", line 179, in compile return _compile(pattern, flags) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre.py", line 229, in _compile raise error, v # invalid expression sre_constants.error: multiple repeat ### So that explains the error message. How do we fix things? Looking back, it appears like we want to match for the literal character sequence: '' but we need to teach the regex engine not to treat stars as special! To fix the regular expression, we need to "escape" those stars so that they're treated as literal characters instead of metacharacters. And the function re.escape() does this for us: ### >>> s = '' >>> import re >>> re.escape(s) '\\<\\!\\-\\-\\*\\*\\*INSERT\\ NAME\\ HERE\\*\\*\\*\\-\\-\\>' >>> print re.escape(s) \<\!\-\-\*\*\*INSERT\ NAME\ HERE\*\*\*\-\-\> ### It does look ugly, but that's ok, since only the regex engine will be seeing it. Notice that re.escape() puts backslashes right before each star --- that's the way we can protect characters from being interpreted as metacharacters. Please feel free to ask more questions on thes tuff that doesn't make sense yet. Hope this helps! From alan.gauld at blueyonder.co.uk Sun Nov 2 18:53:22 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 2 18:53:07 2003 Subject: [Tutor] New-style classes References: <20031101191248.63175.qmail@web41808.mail.yahoo.com> <001f01c3a171$687b3ff0$6401a8c0@xp> <3FA552FC.1020201@aon.at> Message-ID: <002801c3a19c$7fa9cb30$6401a8c0@xp> > >are a few exeptions - you can't (yet) subclass a > >function. > > > Does this "(yet)" express some sort of hope I wouldn't say its a hope, more of a dread :-) I fear that Python is heading down the C++ route of adding every requested feature and losing the very thing that makes it so appealingto me...its simplicity > - or a certain knowledge about future developments > of Python? I have no knowledge of those at all! Alan G. From dyoo at hkn.eecs.berkeley.edu Mon Nov 3 02:42:11 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 3 02:42:17 2003 Subject: [Tutor] Sound and Python In-Reply-To: <1067785409.2561.2.camel@24-159-248-140.jvl.wi.charter.com> Message-ID: On Sun, 2 Nov 2003, Mike Wagman wrote: > Can anyone point me to some tutorials on putting sound in python > programs. Hi Mike, I've heard that the 'pygame' module has a good sound module; you can find out more from its web site: http://pygame.org It's been a while since I've played with pygame, but it seemed to be a really nice toolkit for doing multimedia stuff. I think it might even be as easy as: ### import pygame pygame.init() sound = pygame.mixer.Sound("SomeWaveFile.wav") sound.play() ### but then, I haven't tested this code out at all yet... *grin* I just did a Google search, and on the edu-sig list, Dethe Elza gave a great overview of the projects out there that deal with sound in Python: http://mail.python.org/pipermail/edu-sig/2001-December/001898.html I hope this helps. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Nov 3 03:26:26 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 3 03:26:30 2003 Subject: [Tutor] Importing from classes or functions In-Reply-To: Message-ID: > > > >>> class sinnum(int): > > > ... def __getattr__(self, attr): > > > ... def f(*args): > > > ... return apply(getattr(__builtins__, > > > attr), > > > ... (self,) + args) > > > ... return f > > > ### > > > > > Would you mind explaining that code? I can't understand it, and it > > doesn't seem to work if you're using namespaces. Hi Daniel, Before we start: can you point out which parts are completely unfamiliar in the example? There has to be something there that looks sorta familiar. *grin* But there is a lot of advanced stuff in that example, and I don't want to tackle it all at once. So this message is going to be a bit long again, but this time, I'll try to not jump so far. For the moment, let's talk about __getattr__(). __getattr__ is a special method --- it's the one we can write to make a sinnum() appear to know how to do certain things, even if we haven't explicitely written methods for them. It might help if we simplify the example a little: ### import math class Test(int): def __getattr__(self, attr): print "Python's asking me to look for", attr return 42 ### Whenever we ask for an attribute out of a Test instance, Python will be forced to resort to Test.__getattr__(), since there's no other attributes defined in there: ### >>> t = Test() >>> t.tea Python's asking me to look for tea 42 >>> t.answer() Python's asking me to look for answer Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable ### The important thing to see is that the function "methods" of an object are also looked up as attributes. So when we say: t.answer() Python first grabs the value of 't.answer': ### >>> t.answer Python's asking me to look for answer 42 ### and then tries to execute it as if it were a function: ### >>> 42() Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable ### That's not going to work: if we want something like: t.sin() t.cos() t.floor() to work, then we can't just return some number like 42. Instead, we need to give back a function. ### >>> import math >>> math.sin ### Let's modify the example again and try to get it to return the 'sin' function: ### import math class Test(int): def __getattr__(self, attr): return math.sin ### Let's see how this works now: ### >>> t2 = Test(1) >>> t2.sin >>> t2.sin(3.1415) 9.2653589660490258e-05 ### Almost there, but not quite! We want to be able to say: t2.sin() and have the system magically call: math.sin(t2) We can make this work if with a little bit of magic: ### import math class Test(int): def __getattr__(self, attr): def dynamic_function(): return math.sin(self) return dynamic_function ### The magic is not that magical: we're dynamically creating a new function "dynamic_function", whose sole purpose in life is to call math.sin() on self. Let's see if this works: ### >>> t3 = Test(.5) >>> t3.sin() 0.0 ### Hmmm... well, the syntax is working, but the answer is wrong. *grin* Oh! That's because we've inheriting from 'int' --- we really should be using float to avoid truncation. ### import math class Test(float): def __getattr__(self, attr): def dynamic_function(): return math.sin(self) return dynamic_function ### Here it is in action: ### >>> t4 = Test(0.5) >>> t4.sin() 0.47942553860420301 ### This still isn't quite right though, since this version of the class ALWAYS returns something that sin()s, regardless of what kind of function we're asking it to do: ### >>> t4.cos() 0.47942553860420301 >>> >>> >>> t4.fangoriously() 0.47942553860420301 >>> t4.gelatinous() 0.47942553860420301 >>> t4.linebacker() 0.47942553860420301 ### so it still needs some work. Please feel free to ask questions on any of this! Good luck to you. From tim.ronning at start.no Mon Nov 3 06:48:06 2003 From: tim.ronning at start.no (Tim Ronning) Date: Mon Nov 3 04:48:25 2003 Subject: [Tutor] Newbie append puzzle In-Reply-To: <20031102205500.13315.qmail@web41808.mail.yahoo.com> References: <20031102205500.13315.qmail@web41808.mail.yahoo.com> Message-ID: P? Sun, 2 Nov 2003 12:55:00 -0800 (PST), skrev Daniel Ehrenberg : >> else: >> sys.exit() >> >> - - - - -END CODE - - - - - >> >> Best regards > > Your program uses the string module, which is > obsolete. Most of the string methods have been > replaced with methods on the string type, acting as an > object. Here's the part where you used the string > module: > >> def makeaList(s): >> anothermp3 = string.split(s) >> return anothermp3 > > Using the builtin string methods, you would instead > write: > >> def makeaList(s): >> anothermp3 = s.split() >> return anothermp3 > > but I would probably impliment it like this: > >> makeaList = lambda s: s.split() > > and I'd define it outside of the while loop. If you > define it inside of the loop, it is defined over and > over again, slowing the program. > > I don't think the filenames you used will work as you > intended. When you were making a new playlist, you > opened the file playlist.new (playlist is the name and > new is the file extention, not a new playlist). When > you're reading the playlist, you open a file named > playlist with no file extention. These files are in > the directory where the script is run. If you open a > file that doesn't exist, the file is automatically > created. I would open something like playlist.dsp > whether or not the playlist exists. > > What are the ao and mad modules that you're using? > They're not builtin so I can't use your mp3 player. > Where could I find those modules? > > Daniel Ehrenberg Thanks for valuable input Danliel. Didn't know that the string module was obsolete. I only have an older book on Python so this kind of input is gold for me. I'm planning on getting "Learning Python 2.ed." from O'Reilly when it hits the market sometimes in december. I'm using the libMad mp3 decoder for this player. It uses a bit more resources but it produces a cleaner sound than the mpeg123 decoder. Here are the links: libMad decoder: http://www.underbit.com/products/mad/ pyMad wrapper module: http://spacepants.org/src/pymad/ ao module: http://www.andrewchatham.com/pyogg/ Best regards Tim Ronning -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From jim_938 at hotmail.com Mon Nov 3 07:15:58 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Mon Nov 3 07:16:03 2003 Subject: [Tutor] string to int or float Message-ID: Hello, I want to convert a list of strings to list of integers: e.g. List = ['207','-308','-8.0','6'] and i want it like this list = [207, -308, -8.0, 6] i am trying to do it with int and float functions But i dont know how i can check whether the string will be for float function or int function. for i in range(len(list)): t = int(list[i]) But this will give error when it will encounter '-8.0' as it should be submitted to float() Is there any pythonic way to check whether i should use int or float. Thanks in advance. Regards, J+ _________________________________________________________________ Nutrition is in! Junk food is out! http://server1.msn.co.in/features/fabmall/ Be a part of the microwave revolution. From op73418 at mail.telepac.pt Mon Nov 3 07:43:55 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Nov 3 07:42:30 2003 Subject: [Tutor] string to int or float In-Reply-To: References: Message-ID: <44jcqv87ehld8rqocjtrs76a0eohiiquj4@4ax.com> On Mon, 03 Nov 2003 17:45:58 +0530, you wrote: >Hello, > >I want to convert a list of strings to list of integers: > >e.g. > >List = ['207','-308','-8.0','6'] > >and i want it like this > >list = [207, -308, -8.0, 6] > >i am trying to do it with int and float functions >But i dont know how i can check whether the string will be for float >function or int function. > >for i in range(len(list)): > t = int(list[i]) > >But this will give error when it will encounter '-8.0' as it should be >submitted to float() > > >Is there any pythonic way to check whether i should use int or float. > The key is the Python interpreter: >>> int("-0.1") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): -0.1 OK, int raises ValueError on an invalid string. Then we can use the try, except block to catch the exception and try float. Something like: >>> def convertStr(s): ... """Convert string to either int or float.""" ... try: ... ret = int(s) ... except ValueError: ... #Try float. ... ret = float(s) ... return ret ... Now let us test it >>> convertStr("1") 1 >>> convertStr("0.1") 0.10000000000000001 >>> convertStr("") Traceback (most recent call last): File "", line 1, in ? File "", line 7, in convertStr ValueError: empty string for float() >>> OK, it's working as we want it. Now, the rest is up to you :-) With my best regards, G. Rodrigues From jim_938 at hotmail.com Mon Nov 3 08:26:39 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Mon Nov 3 08:26:44 2003 Subject: [Tutor] string to int or float Message-ID: Yes that worked for me. Thanks a lot for your suggestions. Really this list is of great help as it is having helpful persons around. Thanks again to everyone for their suggestions. >From: Gon蓷lo Rodrigues >To: tutor@python.org >Subject: Re: [Tutor] string to int or float >Date: Mon, 03 Nov 2003 12:43:55 +0000 > >On Mon, 03 Nov 2003 17:45:58 +0530, you wrote: > > >Hello, > > > >I want to convert a list of strings to list of integers: > > > >e.g. > > > >List = ['207','-308','-8.0','6'] > > > >and i want it like this > > > >list = [207, -308, -8.0, 6] > > > >i am trying to do it with int and float functions > >But i dont know how i can check whether the string will be for float > >function or int function. > > > >for i in range(len(list)): > > t = int(list[i]) > > > >But this will give error when it will encounter '-8.0' as it should be > >submitted to float() > > > > > >Is there any pythonic way to check whether i should use int or float. > > > >The key is the Python interpreter: > > >>> int("-0.1") >Traceback (most recent call last): > File "", line 1, in ? >ValueError: invalid literal for int(): -0.1 > >OK, int raises ValueError on an invalid string. Then we can use the >try, except block to catch the exception and try float. Something >like: > > >>> def convertStr(s): >... """Convert string to either int or float.""" >... try: >... ret = int(s) >... except ValueError: >... #Try float. >... ret = float(s) >... return ret >... > >Now let us test it > > >>> convertStr("1") >1 > >>> convertStr("0.1") >0.10000000000000001 > >>> convertStr("") >Traceback (most recent call last): > File "", line 1, in ? > File "", line 7, in convertStr >ValueError: empty string for float() > >>> > >OK, it's working as we want it. > >Now, the rest is up to you :-) > >With my best regards, >G. Rodrigues > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Discover digital jadoo! Enter this contest. http://server1.msn.co.in/sp03/mediacenter/index.asp Win cool prizes! From pythontutor at venix.com Mon Nov 3 09:43:53 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Nov 3 09:43:58 2003 Subject: [Tutor] socket programming Message-ID: <3FA669A9.3050907@venix.com> There have been some socket oriented questions lately. I just saw a notice about a socket programming tutorial by David Mertz on the IBM developerworks web site: http://www-106.ibm.com/developerworks/linux/edu/l-dw-linux-sock-i.html?S_TACT=103AMW61&S_CMP=GR&ca=dgr-lnxw16SocketP1 Programming Linux sockets, Part 1 There is a requirement to register in order to view the tutorial. I've found Mertz's columns to be helpful. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From glingl at aon.at Mon Nov 3 10:09:31 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Nov 3 10:11:28 2003 Subject: [Tutor] string to int or float In-Reply-To: References: Message-ID: <3FA66FAB.6010204@aon.at> Jimmy verma schrieb: > > Yes that worked for me. Thanks a lot for your suggestions. > > Really this list is of great help as it is having helpful persons around. May I, just for fun, supplay another funny solution to your problem: >>> def str2num(s): return "." in s and float(s) or int(s) >>> map(str2num, ['207','-308','-8.0','6','.5']) [207, -308, -8.0, 6, 0.5] This one uses the so called "short-circuit-evaluation" (am I right?) of logical operations. That means, that operands of logical expressions are evaluated only if necessary and then the value of the last evaluated operand is returned. In the case above: If "." is s is True, then float(s) is (successfully) evaluated and retured, otherwise the second operand of the or, i. e. int(s) has to be evaluated (as the first one is False) and the result of this evaluation is returned. Alas! I remember that zeros count as False in Python, so >>> str2num('0.') Traceback (most recent call last): File "", line 1, in -toplevel- str2num('0.') File "", line 2, in str2num return "." in s and float(s) or int(s) ValueError: invalid literal for int(): 0. >>> The conjunction remains false and the second part ot the or doesn't work. So there must not be a floatingpoint zero in your list. Except... ... hmm, there was somewhere, somewhen, somehow a wokaround (I'd bet this came from a German mailing list), ah..., I remember: >>> def str2num(s): return ("." in s and [float(s)] or [int(s)])[0] >>> map(str2num, ['207','-308','-8.0','6','.5', '0.0']) [207, -308, -8.0, 6, 0.5, 0.0] >>> (A list that contains a zero is True! So we construct one and use its first element. 8-) ) Regards, Gregor From abli at freemail.hu Mon Nov 3 12:47:38 2003 From: abli at freemail.hu (Abel Daniel) Date: Mon Nov 3 12:47:17 2003 Subject: [Tutor] function algebra, explained (was: Re: function algebra) References: <20031101044241.91603.qmail@web41806.mail.yahoo.com> Message-ID: Daniel Ehrenberg writes: > I'm sorry, but being a beginner, as many are on this > list, I can't understand that. Would you mind > explaining it or pointing me to a website explaining > something similar? Let's start from the first version: class Fun: def __init__(self, func): self.func=func def __call__(self, *a, **kw): return self.func(*a, **kw) def __add__(self, other): def f(*a, **kw): return self.func(*a, **kw) + other(*a, **kw) return Fun(f) The __call__ method will be called when a Fun instance is called, so ( after sin=Fun(math.sin) ) "sin(42)" is the same as "sin.__call__(42)". The __add__ method will be called when two Fun instances are added, so "sin + sin" is transformed into sin.__add__(sin). (There is other magic going on, it might be transformed into something else. We'll see more about this a bit later.) So instances of Fun can be called, and they can be added. Now we'll continue by adding other operations. http://python.org/doc/current/ref/numeric-types.html contains a long list of them. To support "sin * sin" we need a __mul__ method. We could simply add it by copying the __add__ method, like this: def __mul__(self, other): def f(*a, **kw): return self.func(*a, **kw) * other(*a, **kw) return Fun(f) However, wwe would have to make almost the same method for every similar "magic method". That's "comb code" (see http://bigasterisk.com/wikis/essays/CombCode) and I wanted to avoid it. (If for no better reasons then because it's unimaginative and not fun.) Instead of writing that many similar methods, we will make a more general solution. The 'template' which is the same in these methods is: def some-name(self, other): def f(*a, **kw): return self.func(*a, **kw) some-operator other(*a, **kw) #(1) return Fun(f) In each case we would substitute the appropriate thing in the place of 'some-name' and 'some-operator'. (Like __add__ and +, for example.) This can be done by hand when writing the code, but we would like to do it during runtime in the program. However, the line marked with (1) would cause a error. Here, we would like to replace 'some-operator' with the contents of a variable. We could do this by generating code with something like exec() or eval(). (Making a string and passing that to one of these.) But such 'generating code from a string' is awfully dangerous when done wrong, using some other alternative is usually much better. In this case, there is a suitable alternative, so we'll use that instead.[1] The idea is to first replace self.func(*a, **kw) some-operator other(*a, **kw) with self.func(*a, **kw).some-name( other(*a, **kw) ) Then we can replace self.func(*a, **kw).some-name with getattr(self.func(*a, **kw), some-name) getting getattr(self.func(*a, **kw), name)(other(*a, **kw)) which is just what we need. Putting it together, we get a 'method generator' which will generate the appropriate method from a name: def method_generator(self, name): def ff(other): def f(*a, **kw): return getattr(self.func(*a, **kw), name)(other(*a, **kw)) return Fun(f) return ff Okay, this three-times nested 'def' looks really intimidating. The easy way of grokking it is to find out what the innermost def does ('creates a function which takes such and such arguments and returns such and such') and then handle that part as a black box. Then go from inside out: take the second-innermost def and so on. The idea is that stepping 'outwards' means going to a higher abstraction level. A function in an inner level is just a variable in an outer level. Trying to describe method_generator as 'a function that returns a function that returns an object, which, when called returns a number' might be precise, but it's not really useful. Calling it 'a function that returns something we can pass on to get numerical operations supported' might be more helpful. Ignorance is bliss. :) Another complicating thing here is the use of variables. Normally the body of a function only works with thing that are either 'global' (for example they come from an imported module or such) or are passed in as variables. Here, however, we have a function created with: def f(*a, **kw): return getattr(self.func(*a, **kw), name)(other(*a, **kw)) In this case, 'name', 'other' and 'self' are variables, that are neither 'global', nor passed in as variables. They come from the scope where f is defined. Here, we are using the lexically-scopedness of the language. ( For more examples, see http://mail.python.org/pipermail/tutor/2003-June/023187.html ) So now we can generate all these magic methods simply from the name. But we don't want to generate them, we want to use them. Make them the methods of the class and get them called when we want to divide two Fun instances. That can be achieved in different ways. I choose a getattr hack, for no real reason. Simply that was the first idea I had. Now I think different approach is better, see [3]. __getattr__ is a magic method too. It is used for attribute access, just as __call__ is used for calling. A.B will be A.__getattr__(B). (There are many details I ommit here. See http://python.org/doc/current/ref/attribute-access.html) So the idea is that "A + B" get transformed into "A.__add__(B)" which becomes "A.__getattr__('__add__')(B)". ( As A.__add__ is turned into A.__getattr__('__add__') .) All we have to do in __getattr__ is check if the requested attribute is a numerical-operation-handling-magic-method and return the result of method_generator: operators=['__add__', '__mul__', ...etc... ] def __getattr__(self, name): if name in operators: return self.method_generator(name) raise AttributeError # follow __getattr__'s docs This will work fine for all the binary operators. But some operators are unary (like __neg__ which handles negation) and some have an optional third argument (actually only one, __pow__). method_generator in it's current form can only handle the binary operators. To support unary and ternary operators, we would have to add a new method_generator, and extra checking in __getattr__. Following the spirit of this posting, we should create a new method that creates the necessary method_generator methods on-the-fly. We would call it n_ary_method_generator_generator, and it would be a function, that would return a function, that would return a function... Oh well, I don't hate comb-code _that_ much. So we'll rename method_generator to binary_operation and make the methods unary_operation and ternary_operation which differ only in one line. In the case of ternary_operation there is an extra trick in that the third arg is optional, so we can't make ff take two args, it needs to take arbitrary number of args (which in practice will be one or two), hence the use of *args. Now we have only two methods left to explain. (Which have not much to do with the ones discussing sofar.) compose is pretty simple, if you understood the first version of Fun, you'll understand compose, too. As for __coerce__, it's for handling "f = Fun(math.sin) + 5". Adding a number to a function usually doesn't make much sense, but we can say that in this case we aren't adding a number, we are adding the constant 5 function, in which case f(x) should be "math.sin(x)+5". Doing numerical operations with different types is pretty every-day, so there is a special mechanism to handle it. The idea is that __coerce__ is called before doing the operation, thus giving the programmer a chance to convert the object to something else. In our case, we have to make something callable, so we simply bundle it up in a lambda. That's it. Pretty simple, isn't it? :) -- Abel Daniel [1] As it turns out, this alternative isn't so 'suitable' after all. Although "a+b" gets transformed into "a.__add__(b)", that doesn't mean that the two are equivalent. For example: >>> 5 + 12j (5+12j) >>> (5).__add__(12j) NotImplemented Here we get an error because complex numbers and ints can't be added. The int must be turned into a complex number first. (Which means converting 5 to (5+0j) in this case.) This is done during coercion when doing "5 + 12j", but by calling __add__ we skip this step. This means that my (second) Fun() class will break when doing operations on two functions that return different type of numbers. For example: >>> (Fun(int) + Fun(math.sin))(1.0) NotImplemented Adding to the breakage, the order of adding matters: >>> (Fun(math.sin) + Fun(int))(1.0) 1.8414709848078965 (In this case, a float's __add__ method is called, which can handle ints. In the previous case and int's __add__ method was called, which can't handle floats.) Generating code from a string looks really attractive now... (At least I don't know how to do it in some other way.) [3] In the version detailed above, __getattr__ creates a new method for every numerical operation. That's not really what we had in mind when we started by trying to avoid comb-code. A better method would be the following: (only for binary operations, putting ternary and unary back is trivial) binary_operators ['__add__', ...etc... ] class Fun: def __init__(self, func): self.func=func def __call__(self, *a, **kw): return self.func(*a, **kw) # __coerce__ and compose don't change def binary_operation( name ): def ff(self, other): def f(*a, **kw): return getattr(self.func(*a, **kw), name)(other(*a, **kw)) return Fun(f) return ff for i in binary_operators: setattr(Fun, i, binary_operation(i)) # (2) The changes: binary_operation is not a method of Fun any more, ff in binary_operation is a bit different, __getattr__ is gone, and there is a strange loop at the end. The idea is that at the end of Fun's definition we have a class that's missing all the magic __add__ and similar methods. We'll attach these methods in that for loop. After that loop, there won't be any tricks. No __getattr__, no method generation, nothing. The class will behave as if we had written every magic method by hand, like in the first version we wrote __add__ by hand. Let's take a look at that loop. For every item in the list, it will first create a function by calling binary_operation. This function takes two args, self and other. Then it makes this function into an attribute of the Fun class. I have to note that the above might be wrong. All the examples I found on the net that does such 'add a new method to an existing class at runtime' trick uses new.instancemethod. I don't know why that would be needed, as ommiting it works fine for me, but there might be a reason for it. If it _is_ needed, the line marked with (2) above should be replaced with: setattr(Fun, i, new.instancemethod(binary_operation(i), None, Fun)) (And an 'import new' should be added.) From klappnase at freenet.de Mon Nov 3 13:26:25 2003 From: klappnase at freenet.de (Michael Lange) Date: Mon Nov 3 13:26:29 2003 Subject: [Tutor] Sound and Python In-Reply-To: References: <1067785409.2561.2.camel@24-159-248-140.jvl.wi.charter.com> Message-ID: <20031103192625.5f46b387.klappnase@freenet.de> On Sun, 2 Nov 2003 23:42:11 -0800 (PST) Danny Yoo wrote: > > > On Sun, 2 Nov 2003, Mike Wagman wrote: > > > Can anyone point me to some tutorials on putting sound in python > > programs. > > Hi Mike, > > > I've heard that the 'pygame' module has a good sound module; you can find > out more from its web site: > > http://pygame.org > > It's been a while since I've played with pygame, but it seemed to be a > really nice toolkit for doing multimedia stuff. I think it might even be > as easy as: > > ### > import pygame > pygame.init() > sound = pygame.mixer.Sound("SomeWaveFile.wav") > sound.play() > ### > Another nice sound module is tkSnack : www.speech.kth.se/snack Snack handles wav, mp3 and a lot of other formats, the usage is pretty easy, comparable to the pygame example above. Cheers Michael From alan.gauld at blueyonder.co.uk Mon Nov 3 14:40:14 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Nov 3 14:39:47 2003 Subject: [Tutor] string to int or float References: Message-ID: <003101c3a242$4d5e9010$6401a8c0@xp> > List = ['207','-308','-8.0','6'] > > and i want it like this > > list = [207, -308, -8.0, 6] Depending on whether you trust your source of raw data this might be one place where I'd use eval(): list = map(eval,List) But if the strings are potentially unsecure then I'd use one of the other methods suggested already. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Karthic.Raghavan at logicacmg.com Tue Nov 4 05:19:48 2003 From: Karthic.Raghavan at logicacmg.com (Raghavan, Karthic) Date: Tue Nov 4 05:20:16 2003 Subject: [Tutor] signalrestart Message-ID: Hello, I encountered a piece of code which is given below signal.signalrestart(signal.SIGUSR1, UsrHandler) where UsrHandler is a function I searched the library references but I couldnot find the Signalrestart function. I found signal function which sets a function handler to the corresponding signal. The above said signalrestart also seems to be like that but i couldn't find any reference for it. Could you please let me know whether signalrestart function is available in signal module and if it is available please explain me what it does. Thanks in Advance, Karthic This e-mail and any attachment is for authorised use by the intended recipient(s) only. It may contain proprietary material, confidential information and/or be subject to legal privilege. It should not be copied, disclosed to, retained or used by, any other party. If you are not an intended recipient then please promptly delete this e-mail and any attachment and all copies and inform the sender. Thank you. LogicaCMG global sponsors, Gartner Symposium, Cannes, 4th -7th November 2003 http://symposium.gartner.com/story.php.id.3323.s.5.html Please note that LogicaCMG does not have control over content from,or availability of, this website -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031104/5eff609e/attachment.html From tim.ronning at start.no Tue Nov 4 14:51:35 2003 From: tim.ronning at start.no (Tim Ronning) Date: Tue Nov 4 12:51:55 2003 Subject: [Tutor] Interactive control with keys Message-ID: Greetings all I continue my mp3 player learning project. I'm at a stage where I would like to add interactive controll like "stop", "next" and "previous" assigned to keys "S", "N" and "P" I have no clue on how to implement this except that I think it have to be placed or called from somewere within the play function. It would be great if someone could give me a hint on how to start. Not the solution but some hints to get me digging. I include the full source as is right now. Best regards Tim R #!/usr/bin/env python ############################################ ## DSPmP ## ## Dead.Simple.Python.mp3.Player ## ## ## ## Author: Tim Ronning ## ## tim.ronning@pasecurity.org ## ## License: GPL ## ## Platform: POSIX ## ## Version: 0.0.3 ## ## Date: 03.11.03 ## ## Req. libraries: ## ## - libao ## ## - libmad ## ## Req. wrappers: ## ## - pyao ## ## - pymad ## ## ## ############################################ import sys, ao, mad, os # Global configuration # global_aod = "alsa09" # valid ; alsa05 / alsa09 / oss global_plist = "playlist" # your choice for playlist file os.system("clear") def makeaList(s): anothermp3 = s.split() return anothermp3 def append(mp3): if choice == "3": app = open(global_plist,"a") app.write(mp3 + "\n") app.close() else: app = open("playlist.new","a") app.write(mp3 + "\n") app.close def play(t): # plays a file and returns key data about mp3 mf = mad.MadFile(t) os.system("clear") if mf.layer() == mad.LAYER_I: print "MPEG Layer I" elif mf.layer() == mad.LAYER_II: print "MPEG Layer II" elif mf.layer() == mad.LAYER_III: print "MPEG Layer III" else: print "unexpected layer value" if mf.mode() == mad.MODE_SINGLE_CHANNEL: print "single channel" elif mf.mode() == mad.MODE_DUAL_CHANNEL: print "dual channel" elif mf.mode() == mad.MODE_JOINT_STEREO: print "joint (MS/intensity) stereo" elif mf.mode() == mad.MODE_STEREO: print "normal L/R stereo" else: print "unexpected mode value" if mf.emphasis() == mad.EMPHASIS_NONE: print "no emphasis" elif mf.emphasis() == mad.EMPHASIS_50_15_US: print "50/15us emphasis" elif mf.emphasis() == mad.EMPHASIS_CCITT_J_17: print "CCITT J.17 emphasis" else: print "unexpected emphasis value" print "bitrate %lu bps" % mf.bitrate() print "samplerate %d Hz" % mf.samplerate() millis = mf.total_time() secs = millis / 1000 print "total time %d ms (%dm%2ds)" % (millis, secs / 60, secs % 60) print "Now playing: %s" % (t) dev = ao.AudioDevice(global_aod, rate=mf.samplerate()) while 1: buf = mf.read() if buf is None: break dev.play(buf, len(buf)) choice = '1' while choice != '6': print """ ************************ * DSPmP * ************************ * 1)....Play List * * 2)....Play Directory * * 3)....Show List * * 4)....Add MP3's * * 5)....Remove MP3's * * 6)....Quit * ************************ ************************ """ choice = raw_input("Choice: ") if choice == '1': playlist = open(global_plist,"r") mp3list = [] for line in playlist.readlines(): mp3list = mp3list + makeaList(line) playlist.close() items = len(mp3list) j=0 while j < items: tune = mp3list[j] play(tune) # calls function play with arg. tune j = j + 1 elif choice == '2': dirpath = raw_input("Directory: ") raw_list = os.listdir(dirpath) # makes a list of an entire directory os.chdir(dirpath) items = len(raw_list) j=0 while j < items: tune = raw_list[j] play(tune) j = j + 1 elif choice == '3': os.system("clear") playlist = open(global_plist,"r") for line in playlist.readlines(): print line playlist.close() elif choice == '4': newmp3 = raw_input("New mp3: ") append(newmp3) os.system("clear") elif choice == '5': playlist = open(global_plist,"r") mp3list = [] for line in playlist.readlines(): mp3list = mp3list + makeaList(line) playlist.close() delnr = int(raw_input("Which number? ")) del mp3list[delnr] listlen = len(mp3list) n = 0 while n < listlen: append(mp3list[n]) n = n + 1 os.system("mv -f playlist.new playlist") os.system("clear") else: sys.exit() -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From learning.python at dbmail.dk Tue Nov 4 15:41:18 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Tue Nov 4 15:41:31 2003 Subject: Fw: [Tutor] Interactive control with keys Message-ID: <000f01c3a314$0000ed40$954c73d5@BAERBAR> Just forwarding my reply to the tutor list, as I forgot to hit 'reply all'. > Hi Tim > Although I myself is only learning to program and not familiar ein python > enough to tell you how to do it, I would presume you would need to do this > using a graphical user interface (GUI), as non-gui programs will just look > through your code until it gets to the end (or a sys.exit) and because of > that the program would stall at some > > playnext = raw_input("pres 's' to skip") > > So my tip would be to look into Tkinter or similiar and try to create some > kind of GUI. > > Regards > Ole J. > ----- Original Message ----- > From: "Tim Ronning" > To: > Sent: Tuesday, November 04, 2003 8:51 PM > Subject: [Tutor] Interactive control with keys > > > > Greetings all > > > > I continue my mp3 player learning project. I'm at a stage where I would > > like to add interactive controll like "stop", "next" and "previous" > > assigned to keys "S", "N" and "P" I have no clue on how to implement this > > except that I think it have to be placed or called from somewere within > the > > play function. It would be great if someone could give me a hint on how to > > start. Not the solution but some hints to get me digging. > > > > I include the full source as is right now. > > > > Best regards > > Tim R > > > > #!/usr/bin/env python > > ############################################ > > ## DSPmP ## > > ## Dead.Simple.Python.mp3.Player ## > > ## ## > > ## Author: Tim Ronning ## > > ## tim.ronning@pasecurity.org ## > > ## License: GPL ## > > ## Platform: POSIX ## > > ## Version: 0.0.3 ## > > ## Date: 03.11.03 ## > > ## Req. libraries: ## > > ## - libao ## > > ## - libmad ## > > ## Req. wrappers: ## > > ## - pyao ## > > ## - pymad ## > > ## ## > > ############################################ > > > > import sys, ao, mad, os > > > > # Global configuration # > > global_aod = "alsa09" # valid ; alsa05 / alsa09 / oss > > global_plist = "playlist" # your choice for playlist file > > > > os.system("clear") > > > > def makeaList(s): > > anothermp3 = s.split() > > return anothermp3 > > def append(mp3): > > if choice == "3": > > app = open(global_plist,"a") > > app.write(mp3 + "\n") > > app.close() > > else: > > app = open("playlist.new","a") > > app.write(mp3 + "\n") > > app.close > > > > def play(t): # plays a file and returns key data about > > mp3 > > mf = mad.MadFile(t) > > os.system("clear") > > if mf.layer() == mad.LAYER_I: > > print "MPEG Layer I" > > elif mf.layer() == mad.LAYER_II: > > print "MPEG Layer II" > > elif mf.layer() == mad.LAYER_III: > > print "MPEG Layer III" > > else: > > print "unexpected layer value" > > if mf.mode() == mad.MODE_SINGLE_CHANNEL: > > print "single channel" > > elif mf.mode() == mad.MODE_DUAL_CHANNEL: > > print "dual channel" > > elif mf.mode() == mad.MODE_JOINT_STEREO: > > print "joint (MS/intensity) stereo" > > elif mf.mode() == mad.MODE_STEREO: > > print "normal L/R stereo" > > else: > > print "unexpected mode value" > > if mf.emphasis() == mad.EMPHASIS_NONE: > > print "no emphasis" > > elif mf.emphasis() == mad.EMPHASIS_50_15_US: > > print "50/15us emphasis" > > elif mf.emphasis() == mad.EMPHASIS_CCITT_J_17: > > print "CCITT J.17 emphasis" > > else: > > print "unexpected emphasis value" > > print "bitrate %lu bps" % mf.bitrate() > > print "samplerate %d Hz" % mf.samplerate() > > millis = mf.total_time() > > secs = millis / 1000 > > print "total time %d ms (%dm%2ds)" % (millis, secs / 60, secs % 60) > > print "Now playing: %s" % (t) > > dev = ao.AudioDevice(global_aod, rate=mf.samplerate()) > > while 1: > > buf = mf.read() > > if buf is None: > > break > > dev.play(buf, len(buf)) > > > > choice = '1' > > > > while choice != '6': > > print """ > > ************************ > > * DSPmP * > > ************************ > > * 1)....Play List * > > * 2)....Play Directory * > > * 3)....Show List * > > * 4)....Add MP3's * > > * 5)....Remove MP3's * > > * 6)....Quit * > > ************************ > > ************************ > > """ > > choice = raw_input("Choice: ") > > if choice == '1': > > playlist = open(global_plist,"r") > > mp3list = [] > > for line in playlist.readlines(): > > mp3list = mp3list + makeaList(line) > > playlist.close() > > items = len(mp3list) > > j=0 > > while j < items: > > tune = mp3list[j] > > play(tune) # calls function play with arg. tune > > j = j + 1 > > > > elif choice == '2': > > dirpath = raw_input("Directory: ") > > raw_list = os.listdir(dirpath) # makes a list of an entire > > directory > > os.chdir(dirpath) > > items = len(raw_list) > > j=0 > > while j < items: > > tune = raw_list[j] > > play(tune) > > j = j + 1 > > > > elif choice == '3': > > os.system("clear") > > playlist = open(global_plist,"r") > > for line in playlist.readlines(): > > print line > > playlist.close() > > > > elif choice == '4': > > newmp3 = raw_input("New mp3: ") > > append(newmp3) > > os.system("clear") > > > > elif choice == '5': > > playlist = open(global_plist,"r") > > mp3list = [] > > for line in playlist.readlines(): > > mp3list = mp3list + makeaList(line) > > playlist.close() > > delnr = int(raw_input("Which number? ")) > > del mp3list[delnr] > > listlen = len(mp3list) > > n = 0 > > while n < listlen: > > append(mp3list[n]) > > n = n + 1 > > os.system("mv -f playlist.new playlist") > > os.system("clear") > > > > else: > > sys.exit() > > > > > > -- > > Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From arkamir at softhome.net Tue Nov 4 18:43:36 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Nov 4 18:44:14 2003 Subject: [Tutor] Weird error message Message-ID: <1067989415.5396.1.camel@quercus> Hey thanks for the tip Danny but it still doesnt work. This is the last bit of the code posts = posttemplate subsitutes = ['NAME', 'DATE', 'SUBJECT', 'POST'] list_of_posts = [] content1 = re.escape('') content2 = re.escape('') content3 = re.escape('') content4 = re.escape('') for post in postsinfo: for value in range(4): posts = re.sub(content1, post[1], posts) posts = re.sub(content2, post[2], posts) posts = re.sub(content3, post[3], posts) posts = re.sub(content4, post[4], posts) list_of_posts.append(posts) posts = posttemplate I still get this error though: Traceback (most recent call last): File "", line 1, in ? File "retrieveposts.py", line 44, in retrieve_posts posts = re.sub(content1, post[1], posts) File "/usr/lib/python2.2/sre.py", line 143, in sub return _compile(pattern, 0).sub(repl, string, count) File "/usr/lib/python2.2/sre.py", line 257, in _subx template = _compile_repl(template, pattern) File "/usr/lib/python2.2/sre.py", line 242, in _compile_repl p = sre_parse.parse_template(repl, pattern) File "/usr/lib/python2.2/sre_parse.py", line 644, in parse_template s = Tokenizer(source) File "/usr/lib/python2.2/sre_parse.py", line 186, in __init__ self.__next() File "/usr/lib/python2.2/sre_parse.py", line 188, in __next if self.index >= len(self.string): TypeError: len() of unsized object This the the templatefile which posts equals:


Posted on:









When I use this code I also get the same error, Except this code is a lot prettier so I'd prefer to use this :). Another problem with this code is I cant get it to replace the %s in expression with the data. I think it has to do with it not finding the regular expression. Any help is greatly appreciated. posts = posttemplate subsitutes = ['NAME', 'DATE', 'SUBJECT', 'POST'] list_of_posts = [] expression = '' for post in postsinfo: for value in range(4): posts = re.sub((expression, post[value], posts) % subsitutes[value]) list_of_posts.append(posts) posts = posttemplate Thanks a lot, Conrad Koziol From dyoo at hkn.eecs.berkeley.edu Tue Nov 4 19:42:14 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 4 19:42:23 2003 Subject: [Tutor] Weird error message In-Reply-To: <1067989415.5396.1.camel@quercus> Message-ID: On Tue, 4 Nov 2003, Conrad Koziol wrote: > Hey thanks for the tip Danny but it still doesnt work. This is the last > bit of the code > > posts = posttemplate > subsitutes = ['NAME', 'DATE', 'SUBJECT', 'POST'] > list_of_posts = [] > content1 = re.escape('') > content2 = re.escape('') > content3 = re.escape('') > content4 = re.escape('') > > for post in postsinfo: > for value in range(4): > posts = re.sub(content1, post[1], posts) > posts = re.sub(content2, post[2], posts) > posts = re.sub(content3, post[3], posts) > posts = re.sub(content4, post[4], posts) Hi Conrad, What is post[1], post[2], post[3], and post[4]? If any of these is 'None', we can get a similar "len() of unsized object" error message: ### >>> re.sub('', None, "hello") Traceback (most recent call last): File "", line 1, in ? File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre.py", line 143, in sub return _compile(pattern, 0).sub(repl, string, count) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre.py", line 257, in _subx template = _compile_repl(template, pattern) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre.py", line 242, in _compile_repl p = sre_parse.parse_template(repl, pattern) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre_parse.py", line 645, in parse_template s = Tokenizer(source) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre_parse.py", line 186, in __init__ self.__next() File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/sre_parse.py", line 188, in __next if self.index >= len(self.string): TypeError: len() of unsized object ### I'd recommend looking more closely at what the program is sending to re.sub(), since it's possible that post[1] contains something other than what you're expecting. Also, I'm not quite sure I understand the reason for the inner loop: > for post in postsinfo: > for value in range(4): > posts = re.sub(content1, post[1], posts) > posts = re.sub(content2, post[2], posts) > posts = re.sub(content3, post[3], posts) > posts = re.sub(content4, post[4], posts) > list_of_posts.append(posts) > posts = posttemplate The code doesn't do anything with the 'value' of the loop, so that raises my suspicion. *grin* Furthermore, each post ends up getting appended four times. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue Nov 4 19:51:08 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 4 19:51:12 2003 Subject: [Tutor] weird error messge In-Reply-To: <1067805736.7021.8.camel@quercus> Message-ID: Hi Conrad, Looking back at an older post: On Sun, 2 Nov 2003, Conrad Koziol wrote: > cursor.execute('''select names, dates, subjects, posts, positions from > %s where threads = \'%s\' and positions > \'%s\' and positions < > \'%s\'''' % (forum, thread, start_post, end_post)) > postsinfo = cursor.fetchall() [some text cut] > for post in postsinfo: > posts = re.sub('', post[1], posts) > posts = re.sub('', post[2], posts) > posts = re.sub('', post[3], posts) > posts = re.sub('', post[4], posts) Warning: Python's lists are indexed starting at 0, not 1. So you may need to change this to refer to 'post[0]', 'post[1]', 'post[2]', and 'post[3]'. Hope this helps! From missive at hotmail.com Tue Nov 4 20:56:29 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Nov 4 20:56:35 2003 Subject: [Tutor] Re: signalrestart Message-ID: >I encountered a piece of code which is given below >signal.signalrestart(signal.SIGUSR1, UsrHandler) > >where UsrHandler is a function > >I searched the library references but I couldnot find the Signalrestart >function. > What do the other references to signal look like in this program? Is it... import signal or from some_package import signal or import signal def foobar(baz): pass signal.signalrestart = foobar I do not see signalrestart in the python signal module in 2.1 2.2 or 2.3, so it's either an older release, or they are pulling that function from somewhere else. _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From glingl at aon.at Wed Nov 5 06:32:49 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Nov 5 06:35:01 2003 Subject: [Tutor] anagrams Message-ID: <3FA8DFE1.3050300@aon.at> Hi! Triggered by a remark on the DailyPythonUrl I looked for the Kata - Site and found an interesting little problem: finding anagrams among the words in a textfile. KataSix http://pragprog.com/pragdave/Practices/Kata/KataSix.rdoc,v The author tells us of a 25-line Ruby-Solution with a performance of 1.5 secs on his 1 Ghz PPC. (The wordfile can be found on his website) I found a Python Solution, which needs 0.75 secs on my 2.3 GHz PC, but it certainly is not optimal. (Maybe someone here likes to find a better one?) Another problem remains for me: My script finds 2531 groups of anagrams with 5683 words alltogether, whereas the above mentioned solution has only 2,530 sets of anagrams (and a total of 5,680 words). So I suspect, that my solution contains a bug, but I couldn't find it (until now). Here the code: """KataSix: Find groups of anagrams in a wordlist http://pragprog.com/pragdave/Practices/Kata/KataSix.rdoc,v Solution making heavy use of Tim Peters marvelous sort - implementation """ # get wordlist wordlist = open("wordlist.txt").read().split() # convert words to lists of characters, remember index in wordlist listlist = [(list(word.lower()),i) for (i,word) in enumerate(wordlist)] # first sort each characterlist, then the list of characterlists for item in listlist: item[0].sort() listlist.sort() # now anagrams form groups of consecutive characterlists - extract them: lenwl = len(wordlist) i, anagramgroups = 0, [] while i < lenwl: anagramlist = [wordlist[listlist[i][1]]] j = i+1 while j < lenwl and listlist[j][0] == listlist[i][0]: anagramlist.append(wordlist[listlist[j][1]]) j = j+1 if len(anagramlist) > 1: anagramgroups.append(anagramlist) i = j # Output results: print "anagram groups:", len(anagramgroups) print "words:", sum([len(g) for g in anagramgroups]) ############### Remarks, comments, amendments? Gregor From Janssen at rz.uni-frankfurt.de Wed Nov 5 08:07:42 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Wed Nov 5 08:07:58 2003 Subject: [Tutor] Newbie append puzzle In-Reply-To: References: Message-ID: On Sun, 2 Nov 2003, Tim Ronning wrote: > I have re-done a couple of things incl. the append function. Not shure if > this is what you had in mind though. How do you test for "\n" in a string ? > Anyway the following code works, but I greatly appriciate input on smarter > ways to do things. Thats what learning is all about, -learning to do smart > things! > def append(mp3): > if choice == "3": > app = open("playlist","a") > app.write(mp3) > app.close() > else: > app = open("playlist.new","a") > app.write(mp3 + "\n") > app.close yes, you're right, this solution is somewhat unsmart: since "append" uses a big deal of knowledge of how the rest of the script works, you will often need to reflects changes in the core part of your script within "append". Many errors and hard maintance might be a result. It's better to make the "append" function tough enough that it doesn't need to know which choise was made and if the choice preserve the newline. This brings me back to your question: How to test for "\n". You can test for any character on any position in a string via slices (check the library reference for this: http://www.python.org/doc/current/lib/typesseq.html or the tutorial: http://www.python.org/doc/current/tut/node5.html (somewhere down the side): if "test"[1] == "e": print "yes" if mp3[-1] != "\n": mp3 = mp3 + "\n" or even better use the stringsmethod endswith: if not mp3.endswith("\n"): mp3 = mp3 + "\n" i would take for "append" (with an optional parameter playlist): def append(mp3, playlist="playlist"): if not mp3.endswith("\n"): mp3 = mp3 + "\n" app = open(playlist,"a") app.write(mp3) app.close() this way you get, with a little luck, functions once-defined-working-ever. Helps much to concentrate on new-to-write functionality. Michael From eur at fiwihex.nl Wed Nov 5 08:26:05 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Wed Nov 5 08:27:03 2003 Subject: [Tutor] [newbie] output formatting Message-ID: Hi I'm fairly new to Python (3 days) and I have trouble formatting my output: > for i in range(1, number_of_boards+1): > for j in range(1,5): > print '%2.1f' % T[i][j], > if i % 3 == 0: > print '\n', > time.sleep(5) produces: >20.0 19.6 20.0 20.2 9.8 9.8 9.8 9.8 20.0 19.6 20.0 32.8 >18.2 18.2 18.8 19.0 18.4 18.2 19.8 18.8 18.8 18.4 19.0 19.4 >20.0 20.0 20.0 20.2 9.8 9.8 9.8 9.8 20.0 19.6 20.0 32.8 >18.2 18.2 18.8 19.0 18.4 18.0 19.6 18.8 18.8 18.4 19.0 19.4 >20.0 20.0 20.0 20.2 9.8 9.8 9.8 9.8 20.0 19.6 20.0 32.8 Now I would like the 9.8 printed either as 09.8 or with an extra leading space. Googling for "leading zero", "print output", etc in comp.lang.python gave me several warnings about leading zeroes for octal numbers. The tutor section of the manual is too short, the reference too academic (and I can't find the print statement in the refererence section) The FAQ mubles about "0": >0 The conversion will be zero padded for numeric values. but it doesn't work: >print '%02.2f, %02.2F'% (T1, T2) >3.14, 3.14 Life is hard for Python newbies :-( PS. I'm used to: >for i = 1 to 10 do is it really true that I should do >for i in range(1,10+1) ?? PPS. Is there a Python (or maybe Perl (!)) prog that prints the 'call stack' of a Python program? I need to analyse other peoples programs, that's why I need it. -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From glingl at aon.at Wed Nov 5 09:14:38 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Nov 5 09:18:19 2003 Subject: [Tutor] [newbie] output formatting In-Reply-To: References: Message-ID: <3FA905CE.5030103@aon.at> Eur van Andel schrieb: > ... > >>0 The conversion will be zero padded for numeric values. >> >> > >but it doesn't work: > > > >>print '%02.2f, %02.2F'% (T1, T2) >>3.14, 3.14 >> >> >>> from math import pi >>> print '%06.2f, %06.2F'% (pi,pi) 003.14, 003.14 >>> print '%6.2f, %6.2F'% (pi,pi) 3.14, 3.14 >>> >Life is hard for Python newbies :-( > > Not really, as there ist the Tutor - List ;-) Gregor P.S.: Perhaps you additionally will like http://rgruet.free.fr/PQR2.3.html a Python Quick Reference. From mhansen at cso.atmel.com Wed Nov 5 09:49:42 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed Nov 5 09:49:48 2003 Subject: [Tutor] Weird error message In-Reply-To: References: Message-ID: <3FA90E06.9090805@cso.atmel.com> If you need a HTML template, you might look at htmltmpl at http://htmltmpl.sourceforge.net/. It the same templating syntax as Perl's HTML::Template. However, if you want to brew your own templating system as a learning exercise, then never mind. Although it might be worth looking at to see how it's implemented. Mike > Subject: > [Tutor] Weird error message > From: > Conrad Koziol > Date: > Tue, 04 Nov 2003 15:43:36 -0800 > To: > tutor@python.org > > >Hey thanks for the tip Danny but it still doesnt work. This is the last >bit of the code > > posts = posttemplate > subsitutes = ['NAME', 'DATE', 'SUBJECT', 'POST'] > list_of_posts = [] > content1 = re.escape('') > content2 = re.escape('') > content3 = re.escape('') > content4 = re.escape('') > > for post in postsinfo: > for value in range(4): > posts = re.sub(content1, post[1], posts) > posts = re.sub(content2, post[2], posts) > posts = re.sub(content3, post[3], posts) > posts = re.sub(content4, post[4], posts) > > list_of_posts.append(posts) > posts = posttemplate > >I still get this error though: > > >Traceback (most recent call last): > File "", line 1, in ? > File "retrieveposts.py", line 44, in retrieve_posts > posts = re.sub(content1, post[1], posts) > File "/usr/lib/python2.2/sre.py", line 143, in sub > return _compile(pattern, 0).sub(repl, string, count) > File "/usr/lib/python2.2/sre.py", line 257, in _subx > template = _compile_repl(template, pattern) > File "/usr/lib/python2.2/sre.py", line 242, in _compile_repl > p = sre_parse.parse_template(repl, pattern) > File "/usr/lib/python2.2/sre_parse.py", line 644, in parse_template > s = Tokenizer(source) > File "/usr/lib/python2.2/sre_parse.py", line 186, in __init__ > self.__next() > File "/usr/lib/python2.2/sre_parse.py", line 188, in __next > if self.index >= len(self.string): >TypeError: len() of unsized object > >This the the templatefile which posts equals: > >
>
>
> >
>

Posted on:

>
>
> > >
>
>
>
> > >
>
>
>
>
>
>
>
> >When I use this code I also get the same error, Except this code is a >lot prettier so I'd prefer to use this :). Another problem with this >code is I cant get it to replace the %s in expression with the data. I >think >it has to do with it not finding the regular expression. Any help is >greatly appreciated. > > posts = posttemplate > subsitutes = ['NAME', 'DATE', 'SUBJECT', 'POST'] > list_of_posts = [] > expression = '' > > for post in postsinfo: > for value in range(4): > > posts = re.sub((expression, post[value], posts) % subsitutes[value]) > > list_of_posts.append(posts) > posts = posttemplate > >Thanks a lot, > > Conrad Koziol > > > From project5 at redrival.net Wed Nov 5 09:54:22 2003 From: project5 at redrival.net (Andrei) Date: Wed Nov 5 09:56:44 2003 Subject: [Tutor] Re: [newbie] output formatting References: Message-ID: <1wlvxakd1uhlu$.4px9do8o1968.dlg@40tude.net> Eur van Andel wrote on Wed, 05 Nov 2003 14:26:05 +0100: Hi, > Now I would like the 9.8 printed either as 09.8 or with an extra leading space. Well, you're using the wrong numbers in your formatting: >>> "%0.2f" % 3.14 '3.14' # no padding, 2 decimals >>> "%02.2f" % 3.14 '3.14' # no padding, since the string is longer than 2 chars >>> "%05.2f '03.14' # padded with 0 up to 5 chars >>> "%5.2f" % 3.14 ' 3.14' # padded with spaces, total length = 5 >>> "%010.2f" % 3.14 '0000003.14'# padded with 0, total length = 10 >>> "%010.3f" % 3.14 '000003.140' # 10 long, 3 decimals, 0-padded It's like this: "%xy.zf" x can be either 0 (the string will be 0-padded if necessary), or absent (padded with spaces if necessary). y determines the minimum total length of the resulting string (including decimals and the dot). z determines the number of decimals after the dot. > Life is hard for Python newbies :-( It's probably covered in more detail in one of the tutorials. > PS. I'm used to: > >>for i = 1 to 10 do > is it really true that I should do > >>for i in range(1,10+1) Depends on your needs. If you just want to do something ten times, you'd probably say: for i in range(10): and be done with it. If necessary, you could add 1 to i inside the string if you need which loop this is. But generally speaking, it's wiser to count from 0 than from 1, otherwise you'll run into trouble when accessing lists, strings, and the likes because you'll need to keep converting back and forth. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From shobhan.challa at cybernetsoft.com Wed Nov 5 08:58:10 2003 From: shobhan.challa at cybernetsoft.com (Shobhan Challa) Date: Wed Nov 5 12:47:13 2003 Subject: [Tutor] jpg to doc conversion Message-ID: <1068040698.4740.4.camel@shobs.cybernetsoft.com> Hi Fellow Pythoners, Im new to python, I have an idea about converting jpg/jpeg image files into doc files. The jpg files contain text and the text should be converted into doc format. Im looking for ideas about how to go about it. Does anyone has any idea of any Open Source application which can do this..?? Suggestions/comments are welcome. Fellow Pythoner. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031105/aef84f04/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Nov 5 12:55:43 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 5 12:55:49 2003 Subject: [Tutor] [newbie] output formatting [using traceback to print call stacks] In-Reply-To: Message-ID: > PPS. Is there a Python (or maybe Perl (!)) prog that prints the 'call > stack' of a Python program? I need to analyse other peoples programs, > that's why I need it. Hello! Yes; the 'traceback' module has functions that allow us to see the call stack: http://www.python.org/doc/lib/module-traceback.html The function traceback.print_stack() should do the trick: ### >>> def foo(): ... bar() ... >>> def bar(): ... baz() ... >>> def baz(): ... traceback.print_stack() ... >>> foo() File "", line 1, in ? File "", line 2, in foo File "", line 2, in bar File "", line 2, in baz ### Hope this helps! From tpc at csua.berkeley.edu Wed Nov 5 12:58:04 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Nov 5 12:58:16 2003 Subject: [Tutor] Re: [mod_python] invalid literal for float int or long solved ! In-Reply-To: <20031027144335.Q39378@onyx.ispol.com> Message-ID: <20031105095630.H73580-100000@localhost.name> the former is correct, I assumed it was the latter but was proven wrong when I reverted to my earlier MySQL SELECT statement (i.e., WHERE) and switched the url and title and it worked just fine. On Mon, 27 Oct 2003, Gregory (Grisha) Trubetskoy wrote: > > The first one is "url, title", the second is "title, url" - was that the > problem, or was it the WHERE instead of INNER JOIN (which are same thing > IIRC). > > Grisha > > > On Mon, 27 Oct 2003 tpc@csua.berkeley.edu wrote: > > > > > fingers crossed, here's hoping the bug doesn't rear its creepy head again, > > can't really say wherefore the bug but I found a workaround, I changed the > > basic MySQL statement below: > > > > SELECT url, title FROM URLs, URLs_WITH_MATCHES WHERE URLs.id = > > URLs_WITH_MATCHES.url_id; > > > > to: > > > > SELECT title, url from URLs INNER JOIN URLs_WITH_MATCHES ON URLs.id = > > URLs_WITH_MATCHES.url_id; > > > > and voila ! I am a complete idiot. > > > > _______________________________________________ > > Mod_python mailing list > > Mod_python@modpython.org > > http://mailman.modpython.org/mailman/listinfo/mod_python > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From nas-pytut at python.ca Wed Nov 5 13:01:11 2003 From: nas-pytut at python.ca (Neil Schemenauer) Date: Wed Nov 5 12:59:28 2003 Subject: [Tutor] binary_read? In-Reply-To: <3F9DC7F4.9090207@utoronto.ca> References: <3F9DC7F4.9090207@utoronto.ca> Message-ID: <20031105180110.GB19352@mems-exchange.org> On Mon, Oct 27, 2003 at 08:35:48PM -0500, Karshi F.Hasanov wrote: > I am trying to read a binary file using python's "read" method. > Here how it starts file: > '@\xe0\x00\x00\x00\x00f\x00\x00326112\x0010/17/103\x0022:20 What exactly is in this binary file? I suspect you may want the 'struct' module. Neil From nas-pytut at python.ca Wed Nov 5 13:02:54 2003 From: nas-pytut at python.ca (Neil Schemenauer) Date: Wed Nov 5 13:01:12 2003 Subject: [Tutor] Coin toss program In-Reply-To: References: Message-ID: <20031105180253.GC19352@mems-exchange.org> On Wed, Oct 29, 2003 at 01:02:17PM -0500, LONG, SPENCER wrote: > I'm having difficulty writing code for the following end of chapter > exercise: > > "Write a program that flips a coin 100 times and then tells you the number > of heads and tails." > > Can anyone forward to this Newbie the code for how this is accomplished? So > far I have code that flips the coin once (using a random number generator), > which results in either a heads or tails. But again, it's a single flip of > the coin. Could you post the code you have? To do something 100 times I would use a for loop, eg.: for i in range(100): print "Hello world" HTH, Neil From dyoo at hkn.eecs.berkeley.edu Wed Nov 5 13:00:41 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 5 13:03:55 2003 Subject: [Tutor] Coin toss program In-Reply-To: Message-ID: On Wed, 29 Oct 2003, LONG, SPENCER wrote: > "Write a program that flips a coin 100 times and then tells you the > number of heads and tails." > > Can anyone forward to this Newbie the code for how this is accomplished? > So far I have code that flips the coin once (using a random number > generator), which results in either a heads or tails. But again, it's a > single flip of the coin. Hi Spencer, Well, one way to do this is to write one hundred lines of code flips. *grin* But this is probably not a good way to approach the problem. Have you read about using loops yet? Here are two links to tutorials that talk about loops: http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm http://www.ibiblio.org/obp/thinkCSpy/chap06.htm There are other tutorials at: http://www.python.org/topics/learn/non-prog.html that should have more examples of loops --- as soon as you get them, you can solve that coin-flipping program in a couple of lines (instead of one hundred.) Good luck! From sigurd at 12move.de Wed Nov 5 13:37:08 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Nov 5 13:41:30 2003 Subject: [Tutor] Problem with variables In-Reply-To: <000801c399ed$366ae5a0$3a229f18@docnova477ccv3> (docnova@charter.net's message of "Fri, 24 Oct 2003 01:10:51 -0400") References: <000801c399ed$366ae5a0$3a229f18@docnova477ccv3> Message-ID: On 24 Oct 2003, docnova <- docnova@charter.net wrote: > There are several problems that I need to figure out how to address. The first > (and biggest) is the inuput of the users name. In numerology the one of the > core numbers is acheived by adding each letter of the users full name > together. As of now the only solution is for the user to enter the name as > such "J+O+H+N+S+M+I+T+H". > The ideal scenario would be for "John Smith" to be translated into > "J+O+H+N+S+M+I+T+H" > How would I make this action possible? > Here is the source i have so far: > #This program will give a complete numerology rating :) > #Each letter represents a number. Each letter is given its proper value. > a=1; A=1 > b=2; B=2 > c=3; C=3 [...] > y=1; Y=1 > z=7; Z=7 Remeber: characters in Python have to be enclosed in either single or double quotes. > print "Welcome" > print "This program will give you a complete numerology rating :)" > name = raw_input("Please enter your full name (first, middle, last): ") > print "Hello there", name +"." For all these tasks where you have to do the same action again and again it can be good to work with a list. So first you'd have to transform the string from raw_input into a list. That's easy: simply use the function `list'. Then you'd have to walk through that list and find the the value for each character and finally sum these values up. To have a mapping between your characters and their values you could use a dictionary. That's a special kind of table (hash table) where you can use eg. characters as keys to store and later retrieve values. So let's start (the following solution is only a raw sketch but should give you a hint how to solve your problem). table = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5, 'f' : 8, 'g' : 3, 'h' : 5, 'i' : 1, 'j' : 1, 'k' : 2, 'l' : 3, 'm' : 4, 'n' : 5, 'o' : 7, 'p' : 8, 'q' : 1, 'r' : 2, 's' : 3, 't' : 4, 'u' : 6, 'v' : 6, 'w' : 6, 'x' : 6, 'y' : 1, 'z' : 7} # here we have the dictionary; as the case doesn't matter we only use # lower case letters print "Welcome" print "This program will give you a complete numerology rating :)" name = raw_input("Please enter your full name (first, middle, last): ") print "Hello there", name +"." # here we convert our string to a list of chars name = list(name) # now we iterate through the list and sum up the values; we convert each # char to lowercase # the following can (and should IMO) be written as a function. But as we # use it here only once and it's very simple it's also ok like that. # We use here try ... except because the spaces are also converted to list # members summ = 0 for char in name: try: summ += table[char.lower()] except KeyError: pass print sum Karl -- Please do *not* send copies of replies to me. I read the list From abli at freemail.hu Wed Nov 5 14:45:41 2003 From: abli at freemail.hu (Abel Daniel) Date: Wed Nov 5 14:44:56 2003 Subject: [Tutor] Re: jpg to doc conversion In-Reply-To: <1068040698.4740.4.camel@shobs.cybernetsoft.com> (Shobhan Challa's message of "05 Nov 2003 19:28:10 +0530") References: <1068040698.4740.4.camel@shobs.cybernetsoft.com> Message-ID: Shobhan Challa writes: > Im new to python, I have an idea about converting jpg/jpeg image files > into doc files. The jpg files contain text and the text should be > converted into doc format. > Im looking for ideas about how to go about it. Does anyone has any idea of > any Open Source application which can do this..?? The problem is that jpeg files are pictures, and they don't contain the text itself, but an image of the text. Turning that back into the text is awfully hard. You should be looking for OCR (optical character recognition) software. Try googling for "ocr gpl" or something like that. -- Abel Daniel From ATrautman at perryjudds.com Wed Nov 5 15:03:31 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Wed Nov 5 15:03:38 2003 Subject: FW: [Tutor] jpg to doc conversion Message-ID: <06738462136C054B8F8872D69DA140DB01C08B3C@corp-exch-1.pjinet.com> Shobhan, The other posting is absolutely correct for most JPEG's. However, there is space in some JPEG formats for internal comments. This is sometimes used as a digital watermark in high end imaging and printing. It would not be visible to a normal JPEG viewer. It is very unusual but if you suffer the JPEG standard you might be able to extract his information. My opinion is that it would be a very painful procedure for a beginner. If you want to work with images and learn Python. http://www.pythonware.com/products/pil/ is an easy graphics handler to learn with. HTH, Alan Hi Fellow Pythoners, Im new to python, I have an idea about converting jpg/jpeg image files into doc files. The jpg files contain text and the text should be converted into doc format. Im looking for ideas about how to go about it. Does anyone has any idea of any Open Source application which can do this..?? Suggestions/comments are welcome. Fellow Pythoner. From alan.gauld at blueyonder.co.uk Wed Nov 5 15:29:50 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 5 15:29:23 2003 Subject: [Tutor] Interactive control with keys References: Message-ID: <003901c3a3db$904ac390$6401a8c0@xp> > I continue my mp3 player learning project. I'm at a stage where I would > like to add interactive controll like "stop", "next" and "previous" > assigned to keys "S", "N" and "P" I have no clue on how to implement this > except that I think it have to be placed or called from somewere within the > play function. It would be great if someone could give me a hint on how to > start. Not the solution but some hints to get me digging. Check out the event driven programming page on my web tutor which shows a simple example of reading key presses both in command terminal mode and using Tkinter. The terminal code is in QBASIC but similar code can be written in Python using the getch() function found within the curses(*nix) or mvcrt(windoze) modules. 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 Wed Nov 5 15:36:52 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 5 15:36:23 2003 Subject: [Tutor] [newbie] output formatting References: Message-ID: <004e01c3a3dc$8bca9d30$6401a8c0@xp> > Now I would like the 9.8 printed either as 09.8 or with an extra leading space. > ... > but it doesn't work: > > >print '%02.2f, %02.2F'% (T1, T2) > >3.14, 3.14 > > Life is hard for Python newbies :-( The first format figure 02 gives the *ytotal* length of the printed number, the second .2 gives how many digits after the point. THus 2.2 implies 2 characters with 2 digits after the point. But .2 is already 3 characters so Python will always ignore the first 02. You need at least 5 characters 2+'.'+2 so you want: '05.2f' > >for i = 1 to 10 do > > is it really true that I should do > > >for i in range(1,10+1) Yes, because Python's "for" is really a "Foreach", and so it needs a sequence of items. range() generates such a sequence. Try my tutor, which explains all of the above and more! :-) 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 Wed Nov 5 15:43:06 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 5 15:42:36 2003 Subject: [Tutor] [newbie] output formatting [using traceback to printcall stacks] References: Message-ID: <006501c3a3dd$6a5151c0$6401a8c0@xp> > > PPS. Is there a Python (or maybe Perl (!)) prog that prints the 'call > > stack' of a Python program? I need to analyse other peoples programs, > > that's why I need it. > > Hello! > > > Yes; the 'traceback' module has functions that allow us to see the call > stack: And the pdb debugger (or the one in IDLE or Pythonwin IDE's) will let you do this too. http://www.python.org/doc/current/lib/module-pdb.html 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 Wed Nov 5 15:46:25 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 5 15:45:56 2003 Subject: [Tutor] jpg to doc conversion References: <1068040698.4740.4.camel@shobs.cybernetsoft.com> Message-ID: <006f01c3a3dd$e1713ae0$6401a8c0@xp> > Im new to python, I have an idea about converting jpg/jpeg image files > into doc files. The jpg files contain text and the text should be > converted into doc format. You mean the jpg files are images of text - eg from a scanner? And you want to perform a kind of OCR function on them to convert it to text, but in a Doc format (I assume you mean Microsoft Word .doc and not any other proprietary format called .doc - there are several!) Before we all start jumping in with ideas can you confirm that's what you mean please? Alan G. From sigurd at 12move.de Wed Nov 5 16:59:38 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Nov 5 17:02:46 2003 Subject: [Tutor] anagrams In-Reply-To: <3FA8DFE1.3050300@aon.at> (Gregor Lingl's message of "Wed, 05 Nov 2003 12:32:49 +0100") References: <3FA8DFE1.3050300@aon.at> Message-ID: On 5 Nov 2003, Gregor Lingl <- glingl@aon.at wrote: > Triggered by a remark on the DailyPythonUrl I looked for the Is that a newsletter? > Kata - Site and found an interesting little problem: finding > anagrams among the words in a textfile. [...] > I found a Python Solution, which needs 0.75 secs on my 2.3 GHz PC, > but it certainly is not optimal. (Maybe someone here likes to find > a better one?) Don't know if mine one is better; on my PC it's 30% faster than your solution. > Another problem remains for me: My script finds 2531 groups > of anagrams with 5683 words alltogether, whereas the above > mentioned solution has only 2,530 sets of anagrams (and a total of > 5,680 words). So I suspect, that my solution contains a bug, but > I couldn't find it (until now). My solution finds the same values as yours one. Perhaps the bug is in the Ruby code? [Code] f = open("wordlist.txt") d = {} for word in f: k, v = list(word.lower()), word k.sort() k = ''.join(k) if k in d: d[k].append(v) else: d[k] = [v] f.close() ang = [x for x in d.itervalues() if len(x) > 1] print len(ang) print sum([len(x) for x in ang]) Karl -- Please do *not* send copies of replies to me. I read the list From littledanehren at yahoo.com Wed Nov 5 17:34:17 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Nov 5 17:34:24 2003 Subject: [Tutor] anagrams In-Reply-To: Message-ID: <20031105223417.96469.qmail@web41807.mail.yahoo.com> > f = open("wordlist.txt") > > d = {} > for word in f: > k, v = list(word.lower()), word > k.sort() > k = ''.join(k) > if k in d: > d[k].append(v) > else: > d[k] = [v] > > f.close() > > ang = [x for x in d.itervalues() if len(x) > 1] > > print len(ang) > print sum([len(x) for x in ang]) For some reason, when I iterated over a file, it gave me lines, not words. Is this what it is supposed to do, or could there be something wrong with how I have Python configured? Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From sigurd at 12move.de Wed Nov 5 18:08:59 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Nov 5 18:11:57 2003 Subject: [Tutor] anagrams In-Reply-To: (Karl =?iso-8859-1?q?Pfl=E4sterer's?= message of "Wed, 05 Nov 2003 22:59:38 +0100") References: <3FA8DFE1.3050300@aon.at> Message-ID: On 5 Nov 2003, Karl Pfl?sterer <- sigurd@12move.de wrote: > Don't know if mine one is better; on my PC it's 30% faster than your > solution. Here is another solution. It uses iterators instead of building a list. With the small number of anagram groups it's a bit slower but it would be interesting to see it with really a lot og groups. from itertools import * f = open("wordlist.txt") d = {} for word in f: k, v = list(word.lower()), word k.sort() k = ''.join(k) if k in d: d[k].append(v) else: d[k] = [v] f.close() ang = izip(ifilter(lambda tup: tup[0] > 1, imap(lambda i: (len(i), i), d.itervalues())), count(1)) s = 0 for k, v in ang: s += k[0] print v, s Karl -- Please do *not* send copies of replies to me. I read the list From glingl at aon.at Wed Nov 5 18:25:34 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Nov 5 18:27:29 2003 Subject: [Tutor] anagrams In-Reply-To: References: <3FA8DFE1.3050300@aon.at> Message-ID: <3FA986EE.2010706@aon.at> Hi Karl! Karl Pfl?sterer schrieb: >On 5 Nov 2003, Gregor Lingl <- glingl@aon.at wrote: > > > >>Triggered by a remark on the DailyPythonUrl I looked for the >> >> > >Is that a newsletter? > > This is part of the pythonware website. It records new developments in the world of Python. Have a look at it here: http://www.pythonware.com/daily/ (There is also a link to it from the homepage of www.python.org "Other items of interest", third link from the bottom. Thanks for your code (both solutions). I'll study them tomorrow evening. It's now half past midnight here (in Vienna) and I have to get up early in the morning. Talk to you later Regards, Gregor (P. S.: You seem to be from Deutschland? Right? From where?) > > >>Kata - Site and found an interesting little problem: finding >>anagrams among the words in a textfile. >> >> > >[...] > > >>I found a Python Solution, which needs 0.75 secs on my 2.3 GHz PC, >>but it certainly is not optimal. (Maybe someone here likes to find >>a better one?) >> >> > >Don't know if mine one is better; on my PC it's 30% faster than your >solution. > > > >>Another problem remains for me: My script finds 2531 groups >>of anagrams with 5683 words alltogether, whereas the above >>mentioned solution has only 2,530 sets of anagrams (and a total of >>5,680 words). So I suspect, that my solution contains a bug, but >>I couldn't find it (until now). >> >> > >My solution finds the same values as yours one. Perhaps the bug is in >the Ruby code? > >[Code] > >f = open("wordlist.txt") > >d = {} >for word in f: > k, v = list(word.lower()), word > k.sort() > k = ''.join(k) > if k in d: > d[k].append(v) > else: > d[k] = [v] > >f.close() > >ang = [x for x in d.itervalues() if len(x) > 1] > >print len(ang) >print sum([len(x) for x in ang]) > > > > Karl > > From klappnase at freenet.de Wed Nov 5 18:30:14 2003 From: klappnase at freenet.de (Michael Lange) Date: Wed Nov 5 18:30:22 2003 Subject: [Tutor] newbie question on sys.path.append() Message-ID: <20031106003014.17761e67.klappnase@freenet.de> Hello, as the program I am working on grows, I would like to store some of the modules that are imported in the main program file in a separate subdirectory and add the subdirectory to sys.path. I used sys.path.append() for this at the very beginning of this file, like: #!/usr/bin/env python from Tkinter import * import tkMessageBox, tkSnack, sys, os, fileinput, Tix sys.path.append(os.path.join(sys.path[0], 'widgets')) so I can import the modules I stored in the "widgets" subdirectory. I am not sure now if this might cause problems, maybe there is a more proper way to import those modules. Any help on this would be very appreciated. Thanks in advance Michael From dyoo at hkn.eecs.berkeley.edu Wed Nov 5 18:32:09 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 5 18:32:15 2003 Subject: [Tutor] anagrams In-Reply-To: Message-ID: On Thu, 6 Nov 2003, Karl [iso-8859-1] Pfl=E4sterer wrote: > On 5 Nov 2003, Karl Pfl=E4sterer <- sigurd@12move.de wrote: > > > Don't know if mine one is better; on my PC it's 30% faster than your > > solution. Time to jump in as well! *grin* ### def main(): for anagrams in find_anagrams(open("wordlist.txt").readlines()): if len(anagrams) > 1: print '\t'.join(anagrams) def anagram_signature(word): """Finds the anagram "signature" of a word.""" letters =3D list(word.lower().strip()) letters.sort() return ''.join(letters) def find_anagrams(words): """Returns a partitioning of words into equivalence classes, based on a word's anagram signature.""" d =3D {} for word in words: d.setdefault(anagram_signature(word), []).append(word.strip()) return d.values() if __name__ =3D=3D '__main__': main() ### From op73418 at mail.telepac.pt Wed Nov 5 17:47:35 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 5 18:41:32 2003 Subject: [Tutor] anagrams In-Reply-To: <20031105223417.96469.qmail@web41807.mail.yahoo.com> References: <20031105223417.96469.qmail@web41807.mail.yahoo.com> Message-ID: On Wed, 5 Nov 2003 14:34:17 -0800 (PST), you wrote: [text snipped] > >For some reason, when I iterated over a file, it gave >me lines, not words. Is this what it is supposed to >do, or could there be something wrong with how I have >Python configured? > It's correct, the iterator over a file gives lines not words. But it's very simple to have an iterator over words. Untested: def iterword(f): """Iterate over the words of a file. Args: a file object. """ for line in f: #Split the line in words. words = line.split() for word in words: yield word In splitting the line in words I have used the simplest possible device: the string method split that splits a string on whitespace. More sophisticated (and correct) ways of splitting a line in words can be achieved with the re module, for example. With my best regards, G. Rodrigues From Karthic.Raghavan at logicacmg.com Thu Nov 6 01:12:22 2003 From: Karthic.Raghavan at logicacmg.com (Raghavan, Karthic) Date: Thu Nov 6 01:12:35 2003 Subject: [Tutor] RE: Tutor Digest, Vol 4, Issue 6 Message-ID: Hello Lee Harr, First of all thanks for ur reply. I have just given u few lines of the code below -------------------- import os import time import string import syslog import signal import sys from types import * import pdb InternalError = "InternalError" __db_instance = None def UsrHandler(sig, frame): global __db_instance try: if sig == signal.SIGUSR1: __db_instance.IncDebugLvl() signal.signalrestart(signal.SIGUSR1, self.UsrHandler) ------------------------ I think the version is 1.5.2 . But even in that version if i see the library reference there is no function called signal restart. Can you makeout anything from the above piece of code. Is the signal is imported from pdb package or not??? If yes how could i look into the fuction definition(code) of signalrestart. Thanking you in advance, Kind Regards, Karthic 6. Re: signalrestart (Lee Harr) Message: 6 Date: Wed, 05 Nov 2003 01:56:29 +0000 From: "Lee Harr" Subject: [Tutor] Re: signalrestart To: tutor@python.org Message-ID: Content-Type: text/plain; format=flowed >I encountered a piece of code which is given below >signal.signalrestart(signal.SIGUSR1, UsrHandler) > >where UsrHandler is a function > >I searched the library references but I couldnot find the Signalrestart >function. > What do the other references to signal look like in this program? Is it... import signal or from some_package import signal or import signal def foobar(baz): pass signal.signalrestart = foobar I do not see signalrestart in the python signal module in 2.1 2.2 or 2.3, so it's either an older release, or they are pulling that function from somewhere else. This e-mail and any attachment is for authorised use by the intended recipient(s) only. It may contain proprietary material, confidential information and/or be subject to legal privilege. It should not be copied, disclosed to, retained or used by, any other party. If you are not an intended recipient then please promptly delete this e-mail and any attachment and all copies and inform the sender. Thank you. LogicaCMG global sponsors, Gartner Symposium, Cannes, 4th -7th November 2003 http://symposium.gartner.com/story.php.id.3323.s.5.html Please note that LogicaCMG does not have control over content from,or availability of, this website From phthenry at earthlink.net Thu Nov 6 03:26:46 2003 From: phthenry at earthlink.net (Paul Tremblay) Date: Thu Nov 6 03:26:34 2003 Subject: [Tutor] where to put configuration files: Solution! Message-ID: <20031106082646.GC2985@localhost.localdomain> A while back, I started a thread on where to put configuration files. There seemed to be no good solution. Jeff Shannon summed up the problem when he wrote "The problem is that there is no good cross-platform way to store configuration files... It does seem to me that a transparent cross-platform config manager, a la wxConfig, would be a very useful addition to the Python standard library." Since wxConfig does not exist, I have come up with a satisfactory solution. Others might find this solution useful, so I posted it below. PROBLEM ======= Your script must read certain data files yet cannot know where to put them so that all users on any system will have access to them. A seeming solution is to put the files in the same file as the modules. But you cannot use this method if you use disutils to install your package. disutils will not put data files in the same locaton as the packages or the script. SOLUTION ======== Write a configuration utility that determines the location of the data files and writes a module to give the script access to this location. The configuration script might look like this: #!/usr/bin/env python """ Get the desired location of a the data files, and write a module to give access to this location Write a one line file of the location of the target files. """ import os, sys def do_location(): """ The target is the first system argument. Use the target to write a simple script to access the location. """ target = sys.argv[1] the_dir = os.path.join(target, 'data_dir') # write the module write_obj = open('module_name/configuration_dir.py', 'w') write_obj = open(the_dir, 'w') write_obj.write( 'def get_dir():\n' ' return "%s"' % the_dir) write_obj.close() # write the data_location file write_obj = open('data_location', 'w') write_obj.write(target) write_obj.close() if __name__ == '__main__': do_location() *** Once the user runs python configure.py, two new files will be created. The first, a modlue, looks like this: def get_dir() return "/path/data_dir" This simple two-line module is located within the package of your other modules, so it will get put in the right place. The second file created by configure.py is a one line file called "data_location". It has one line--the location of the data files. If the user choose "/etc," it would look like this: /etc Your setup.py file will look like this: import sys, os from distutils.core import setup from distutils.core import setup data__file_exists = os.path.isfile('data_location') if not data_file_exists: sys.stderr.write('Please run python configure.py first\n') sys.exit(1) read_obj = open('data_location', 'r') lines = read_obj.readlines() read_obj.close() data_location = lines[0] data_location = os.path.join(data_location, 'data_dir') setup(name="module_name", version= '.4' , description="Perform a certain function", author="First Last", author_email="myemail@provider.net", license = 'GNU GPL', url = "http://module_name.sourceforge.net/", packages=['package_name'], scripts=['scripts/script_name'], data_files = [ (data_location, ['data/configure.txt']), ) *** The user types: python setup build python setup install All the scripts, modules and data files get put in the right place. Now your main script can have access to the data files, no matter where they are. For example, you main script might look like this: #!/usr/bin/env python import module_name.configuration_dir data_dir = module_name.configuration_dir.get_dir() Any files you need will be located within data_dir. For example, if you needed to read a configuration file, you might write: config_file = os.path.join(data_dir, 'configuration.txt') read_obj = open(config_file, 'r') This solution works as long as your script has multiple modules located within a package called "module_name." If your script consisted of only one module, or just the executable itself, you would have to tinker with this solution--though I wouldn't think too much. For example, if your script consited of just one file, you could still write the get_directory module and store it in the same directory as the script. Make sure you tell setup.py to see this new two-line module as a module that needs to be installed. And of course, since the two-line module would reside in the same directory as any other module, give it a unique name. That is, instead of calling it "configuration_dir.py," call it "my_module_name_configuration.py." In addition, you probably want to make your configuration.py file perform a lot more functions. For example, it should check that the target is a valid directory, and that the user can install to this directory. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From project5 at redrival.net Thu Nov 6 10:26:45 2003 From: project5 at redrival.net (Andrei) Date: Thu Nov 6 10:53:07 2003 Subject: [Tutor] Re: newbie References: Message-ID: RoT wrote on Thu, 06 Nov 2003 23:03:39 +0800: Hi, > Hi, I have been studying python for a month or so now and have written a few > small apps the main being a ~300 line application. I am finding as I work > through things that I am coding in a procedural way, and then going back > over the code and recoding parts into an OO model. Is this a normal > progression, or should I be trying to force myself into an initial OO My non-guru opinion is that some small things lend themselves better to procedural solutions than OOP ones, even if it were just because it requires less typing. Big programs however are better as OOP than procedural. Exactly where the boundary is, depends on the application. FWIW, when I first started Python I started a smallish program as procedural and ended up OOP-ing it, so I think it's pretty normal :). > model, my brain just doesn't seem to think like that, and I have work > through a procedural method to actually solve the problem. Do experienced > programmers find this sometimes also? You'll get used to it and the translation will then no longer be necessary. You might find it helps if you think about your program's desing on paper first. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From karl.fast at pobox.com Thu Nov 6 10:53:32 2003 From: karl.fast at pobox.com (Karl Fast) Date: Thu Nov 6 10:54:13 2003 Subject: [Tutor] newbie In-Reply-To: ; from RoT@245T.com on Thu, Nov 06, 2003 at 11:03:39PM +0800 References: Message-ID: <20031106095332.B13125@signal.lights.com> > I am coding in a procedural way, and then going back over the code > and recoding parts into an OO model. Is this a normal... I found something similar, at first. I was never formally taught OO, and my programming experience was mainly fortran, pascal, perl, IDL, and assembler....the whole OO thing was a mind twister. But increasingly it feels more natural, and python made the transition reasonably painless. Several factors helped me make the jump: a big-ish project, a GUI interface using wxPython, and several weeks of uninterrupted time to work on it. The GUI bit was both the most frustrating and the most helpful (wxPython is big, but is easier if you think OOP). The project was (is!) a custom web spider. I'd used perl for similar programs and my conception of the problem was a long-running batch job. I thought about it in a procedural way (instantiating objects from perl modules, but never creating my own classes). I started doing things procedurally, but the GUI bit slowly helped me understand the OO paradigm and forced me to begin making my own classes. I rewrote my procedural code into some classes, making it much easier to fit it into the wxPython framework. I still think procedurally, but I no longer hesitate to create my own classes. Lots left to learn, but in three weeks I've come a long ways. I couldn't have come this far in C++ or Java. Yesterday I was asked to quickly whip up a small robot for a related project. I immediately subclassed some classes I made for the other project, imported a few more, and in a few hours the basic shell was all done. Up with OO and code reuse! --karl From jsoons at juilliard.edu Thu Nov 6 11:13:43 2003 From: jsoons at juilliard.edu (Jonathan Soons) Date: Thu Nov 6 11:13:49 2003 Subject: [Tutor] unprintable characters from MSWord Message-ID: <33E101AC5AFF78419F466954A9685420BCF1A2@mailbox.juilliard.edu> I have to parse text that seems to be cut and pasted from a word document into a web form. It looks like this: ^II shouldM-^Rnt attempt any of the great solosM-^WWagnerM-^Rs Tristan. (From the `cat -tev` output). I am guessing it is from a word processor. How can I find out what these characters are and convert them to ascii equivalents? Thank you jon soons From sigurd at 12move.de Thu Nov 6 11:11:33 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Nov 6 11:13:57 2003 Subject: [Tutor] anagrams In-Reply-To: <3FA986EE.2010706@aon.at> (Gregor Lingl's message of "Thu, 06 Nov 2003 00:25:34 +0100") References: <3FA8DFE1.3050300@aon.at> <3FA986EE.2010706@aon.at> Message-ID: On 6 Nov 2003, Gregor Lingl <- glingl@aon.at wrote: > Karl Pfl?sterer schrieb: >>Is that a newsletter? > This is part of the pythonware website. It records new developments in the > world of Python. Have a look at it here: > http://www.pythonware.com/daily/ Thanks. I look often at the site but for some reason I don't know I never read that. > (There is also a link to it from the homepage of www.python.org > "Other items of interest", third link from the bottom. [...] > (P. S.: You seem to be from Deutschland? Right? From where?) Right. From Weinheim (a town near Heidelberg). Unfortunately no Pythonistas seem to be in that region. But we have Usenet and mailinglists. Karl -- Please do *not* send copies of replies to me. I read the list From mikef at formostpkg.com Thu Nov 6 12:52:36 2003 From: mikef at formostpkg.com (Mike Faire) Date: Thu Nov 6 12:52:49 2003 Subject: [Tutor] How do I save the output of the rotor module? Message-ID: <3FAA8A64.1080804@formostpkg.com> Hi everyone! I wrote a simple script to get acquainted with the rotor module. Encrypting and decrypting was simple enough. However, once I save the encrypted list to a file, it will not decrypt correctly beyond the first newline. Here is the code: #!/usr/bin/env python import rotor contents = ["This is a line of text\n", "including newlines\n", "for rotor testing."] print contents # shows a list of three strings encon = [] rt = rotor.newrotor('606') for item in contents: encon.append(rt.encrypt(item)) print encon # at this point, print encon shows a list of three strings, encrypted fh = open('text.txt', 'w') fh.writelines(encon) # write to a file fh.close() fh = open('text.txt', 'r') incoming = fh.readlines() # read from a file fh.close() print incoming # after writing the strings to disk and then reading them back in # again, print incoming shows a list comprised of one large string after = [] for item in incoming: after.append(rt.decrypt(item)) print after # the one large string will only decrypt correctly as far as the # first newline Do I need to use pickle for that list? If they are strings, why does it matter that they happen to contain representations of binary data? TIA Mike From inkedmn at inkedmn.homelinux.org Thu Nov 6 16:16:09 2003 From: inkedmn at inkedmn.homelinux.org (Brett Kelly) Date: Thu Nov 6 16:16:16 2003 Subject: [Tutor] newbie In-Reply-To: <20031106095332.B13125@signal.lights.com> References: <20031106095332.B13125@signal.lights.com> Message-ID: <20031106211609.GA18444@inkedmn.homelinux.org> Care to link us to this app? i'm curious to see a good-sized example of wxPython... :) Sometime around Thu, Nov 06, 2003 at 09:53:32AM -0600, Karl Fast said: > > > I am coding in a procedural way, and then going back over the code > > and recoding parts into an OO model. Is this a normal... > > I found something similar, at first. I was never formally taught OO, > and my programming experience was mainly fortran, pascal, perl, IDL, > and assembler....the whole OO thing was a mind twister. But > increasingly it feels more natural, and python made the transition > reasonably painless. > > Several factors helped me make the jump: a big-ish project, a GUI > interface using wxPython, and several weeks of uninterrupted time to > work on it. The GUI bit was both the most frustrating and the most > helpful (wxPython is big, but is easier if you think OOP). > > The project was (is!) a custom web spider. I'd used perl for similar > programs and my conception of the problem was a long-running batch > job. I thought about it in a procedural way (instantiating objects > from perl modules, but never creating my own classes). > > I started doing things procedurally, but the GUI bit slowly helped > me understand the OO paradigm and forced me to begin making my own > classes. I rewrote my procedural code into some classes, making it > much easier to fit it into the wxPython framework. > > I still think procedurally, but I no longer hesitate to create my > own classes. Lots left to learn, but in three weeks I've come a long > ways. I couldn't have come this far in C++ or Java. > > Yesterday I was asked to quickly whip up a small robot for a related > project. I immediately subclassed some classes I made for the other > project, imported a few more, and in a few hours the basic shell was > all done. Up with OO and code reuse! > > > --karl > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Brett Kelly inkedmn@inkedmn.homelinux.org This message has been digitally autographed using GnuPG. GnuPG Key fingerprint: 5ED0 CB0C A6B7 5C1F 3750 1364 0DB3 D265 A01F 904A Vim - this ain't your daddy's text editor http://www.vim.org -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20031106/9e10bdda/attachment.bin From alan.gauld at blueyonder.co.uk Thu Nov 6 17:05:15 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Nov 6 17:05:05 2003 Subject: [Tutor] newbie References: Message-ID: <002901c3a4b2$0f3ce990$6401a8c0@xp> > through things that I am coding in a procedural way, and then going back > over the code and recoding parts into an OO model. Is this a normal > progression, Yes if you learned to program in a procedural language first or if you ever studied math or science. All of these encourage a style of mental analysis based on functional decomposition. If on the other hand your background is in organisational taxonomies - librarianship, office admin, history etc then you will likely find adopting OO thinking a natural progression. > my brain just doesn't seem to think like that, and I have work > through a procedural method to actually solve the problem. > Do experienced programmers find this sometimes also? In the early days of OOP popularity(~1988-93) a lot of industry research went into this. They figured an experienced procedural programmer took from 6 months to two years to completely migrate to OO. I think I took about 4-6 months personally but I started on OOP while at college and still learning procedural techniques. My wn experience of mentoring C programmers into C++ and Lisp Flavors was an average of about 6-9 months to really lose the procedural mindset. Some studies with teaching Librarians (practiced taxonomists) OOP showed that they picked up programming significantly faster than control groups learning traditional techniques. However, studies with children, starting with Alan Kay and Smalltalk have consistently shown that they learn OOP very easily and so its actually a natural way to think for most folks, its just that some of us get trained out of it at school! Persist and it will eventually be the most natural way to do it. In fact I now have to force myself to think in procedural terms for those rare cases where procedural is obviously the better technique. (And that quite often includes here on tutor where beginners usually prefer a procedural solution) HTH, Alan G. From project5 at redrival.net Thu Nov 6 17:07:11 2003 From: project5 at redrival.net (Andrei) Date: Thu Nov 6 17:09:30 2003 Subject: [Tutor] Re: newbie References: <20031106095332.B13125@signal.lights.com> <20031106211609.GA18444@inkedmn.homelinux.org> Message-ID: <1b0h3uhpkcdki$.mmcu3to6gv2k$.dlg@40tude.net> Brett Kelly wrote on Thu, 6 Nov 2003 13:16:09 -0800: > Care to link us to this app? i'm curious to see a good-sized example of > wxPython... :) Boa is sizable :). And the wxPython demo (well, it's modular, but the end result is quite big). Of course there's also Spe, wxGlade, Cornice and let's not forget the upcoming Chandler PIM which will probably end up being huge. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From arkamir at softhome.net Thu Nov 6 18:33:19 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Thu Nov 6 18:33:32 2003 Subject: [Tutor] Weird error message In-Reply-To: References: Message-ID: <1068161599.5395.4.camel@quercus> Hey Danny thanks for the tips but it still doesn't work. :( I've deduced from the error messages it has too do something with the date time object of x[1]. I was hoping you guys could supply me with an answer. This is the code in question: import MySQLdb import re import compare import numberofpages import display import time db = MySQLdb.connect(host='localhost', user='conrad', passwd='mysqlinsecret', db='cgi') cursor = db.cursor() #import retrieveposts #retrieveposts.retrieve_posts('general', 'Hello, World', 20) def retrieve_posts(forum, thread, end_post): giventemplate = 'posttemplate' inputtemplate = open(giventemplate, 'r') posttemplate = inputtemplate.read() inputtemplate.close() start_post = end_post - 20 cursor.execute('''select names, dates, subjects, posts, positions from %s where threads = \'%s\' and positions > \'%s\' and positions < \'%s\'''' % (forum, thread, start_post, end_post)) postsinfo = cursor.fetchall() postsinfo = list(postsinfo) postsinfo.sort(compare.compare) posts = posttemplate subsitutes = ['NAME', 'DATE', 'SUBJECT', 'POST'] list_of_posts = [] # 1111111 expression = '' content1 = re.escape('') content2 = re.escape('') content3 = re.escape('') content4 = re.escape('') for post in postsinfo: #change it from a datetime object repr(post[1]) for value in range(4): # 1111111 posts = re.sub((expression, post[value], posts) % subsitutes[value]) posts = re.sub(content1, post[0], posts) #this is where the error occurs posts = re.sub(content2, post[1], posts) posts = re.sub(content3, post[2], posts) posts = re.sub(content4, post[3], posts) print posts list_of_posts.append(posts) posts = posttemplate This is posttemplate:


Posted on:









This is the error message: >>> import retrieveposts >>> retrieveposts.retrieve_posts('general', 'Hello, World', 20) Traceback (most recent call last): File "", line 1, in ? File "retrieveposts.py", line 45, in retrieve_posts posts = re.sub(content2, post[1], posts) File "/usr/lib/python2.2/sre.py", line 143, in sub return _compile(pattern, 0).sub(repl, string, count) File "/usr/lib/python2.2/sre.py", line 257, in _subx template = _compile_repl(template, pattern) File "/usr/lib/python2.2/sre.py", line 242, in _compile_repl p = sre_parse.parse_template(repl, pattern) File "/usr/lib/python2.2/sre_parse.py", line 644, in parse_template s = Tokenizer(source) File "/usr/lib/python2.2/sre_parse.py", line 186, in __init__ self.__next() File "/usr/lib/python2.2/sre_parse.py", line 188, in __next if self.index >= len(self.string): TypeError: len() of unsized object >>> Thanks for the help Conrad From littledanehren at yahoo.com Thu Nov 6 20:05:49 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Nov 6 20:05:56 2003 Subject: [Tutor] newbie In-Reply-To: Message-ID: <20031107010549.82321.qmail@web41802.mail.yahoo.com> > Hi, I have been studying python for a month or so > now and have written a few > small apps the main being a ~300 line application. > I am finding as I work > through things that I am coding in a procedural way, > and then going back > over the code and recoding parts into an OO model. > Is this a normal > progression, or should I be trying to force myself > into an initial OO > model, my brain just doesn't seem to think like > that, and I have work > through a procedural method to actually solve the > problem. Do experienced > programmers find this sometimes also? No, that's completely normal. Before I learned Python, I was using TI-83 calculator basic. It is the most imperitive programming language short of assembly. When I learned Python, I really hated that you couldn't use the GOTO command, and I was mistified at the for loops. It took me a while to learn the programming style of Python, but now I can write semi-useful, object-oriented programs. Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From glingl at aon.at Thu Nov 6 20:38:20 2003 From: glingl at aon.at (Gregor Lingl) Date: Thu Nov 6 20:40:05 2003 Subject: [Tutor] How do I save the output of the rotor module? In-Reply-To: <3FAA8A64.1080804@formostpkg.com> References: <3FAA8A64.1080804@formostpkg.com> Message-ID: <3FAAF78C.1050601@aon.at> Mike Faire schrieb: > > Hi everyone! > > I wrote a simple script to get acquainted with the rotor module. > However...it will not decrypt correctly beyond the first newline. > > Here is the code: > > #!/usr/bin/env python > > import rotor > > contents = ["This is a line of text\n", "including newlines\n", "for > rotor testing."] > ... > fh = open('text.txt', 'r') > incoming = fh.readlines() # read from a file > fh.close() > print incoming > > # after writing the strings to disk and then reading them back in > # again, print incoming shows a list comprised of one large string Hi, Mike! I think readlines() cannot decompose the encrypted file into lines, because those newline-characters also get encrypted. Maybe the encryption-decryption process doesn't work because at every call of encrypt, the rotor object is reset to its initial state (see docs). In your example this happens three times during encryption but only once for decryption ... ? You can avoid this by using the encryptmore method for encrypting (which doesn't reset the rotor object. Another way to accomplish correct decryption is using strings: import rotor contents = "This is a line of text\nincluding newlines\nfor rotor testing." print contents # shows a list of three strings rt = rotor.newrotor('606') encon=rt.encrypt(contents) print encon # at this point, print encon shows a list of three strings, encrypted fh = open('text.txt', 'w') fh.write(encon) # write to a file fh.close() fh = open('text.txt', 'r') incoming = fh.read() # read from a file fh.close() print incoming # after writing the strings to disk and then reading them back in # again, print incoming shows a list comprised of one large string after = rt.decrypt(incoming) print after # the one large string will decrypt correctly HTH, Gregor From dyoo at hkn.eecs.berkeley.edu Thu Nov 6 21:23:01 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 6 21:23:19 2003 Subject: [Tutor] Weird error message In-Reply-To: <1068161599.5395.4.camel@quercus> Message-ID: On Thu, 6 Nov 2003, Conrad Koziol wrote: > Hey Danny thanks for the tips but it still doesn't work. :( > I've deduced from the error messages it has too do something with the > date time object of x[1]. Hi Conrad, In the statements: ### posts = re.sub(content1, post[0], posts) posts = re.sub(content2, post[1], posts) posts = re.sub(content3, post[2], posts) posts = re.sub(content4, post[3], posts) ### the code works only if post[0], post[1], post[2] and post[3] represent non-NULL strings: re.sub only deals with strings, and will choke if given anything else. (I'm lying: re.sub() can take in a function as a second argument, but let's ignore that for the moment. *grin*) Since post[1] is a DateType object, the code needs to do something before passing it to re.sub(). Something like: ### posts = re.sub(content1, str(post[0]), posts) posts = re.sub(content2, str(post[1]), posts) posts = re.sub(content3, str(post[2]), posts) posts = re.sub(content4, str(post[3]), posts) ### should behave a little more reliably. From dyoo at hkn.eecs.berkeley.edu Thu Nov 6 21:48:30 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 6 21:48:34 2003 Subject: [Tutor] How do I save the output of the rotor module? In-Reply-To: <3FAA8A64.1080804@formostpkg.com> Message-ID: On Thu, 6 Nov 2003, Mike Faire wrote: > I wrote a simple script to get acquainted with the rotor module. > Encrypting and decrypting was simple enough. However, once I save the > encrypted list to a file, it will not decrypt correctly beyond the first > newline. Hi Mike, 'rotor' provides no guarantee that r.encrypt(a + b) is the same as r.encrypt(a) + r.encrypt(b) Let me check something... ### >>> r = rotor.newrotor("606") >>> r.encrypt("hello") + r.encrypt("world") '~\xe5k\t&\n\x17@\t\x08' >>> >>> >>> r = rotor.newrotor("606") >>> r.encrypt("helloworld") '~\xe5k\t&\x85\xe0>^\\' ### So that's one issue we need to be aware of. Another is that newlines themselves will be encoded! ### >>> r.encrypt("\n\n\n") '*\x86O' ### These two facts interact in a funny way: since you're doing the encoding, line by line: > rt = rotor.newrotor('606') > for item in contents: > encon.append(rt.encrypt(item)) > print encon is very likely that the encoded file won't have the same number of newlines as the original input. This, combined with the knowledge that: r.encrypt(a) + r.encrypt(b) != r.encrypt(a + b) should be enough to see that we're in trouble as soon as we try decoding the string. *grin* Does this make sense so far? From dyoo at hkn.eecs.berkeley.edu Thu Nov 6 22:04:06 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 6 22:04:12 2003 Subject: [Tutor] How do I save the output of the rotor module? In-Reply-To: Message-ID: On Thu, 6 Nov 2003, Danny Yoo wrote: > These two facts interact in a funny way: since you're doing the encoding, > line by line: > > > rt = rotor.newrotor('606') > > for item in contents: > > encon.append(rt.encrypt(item)) > > print encon > > is very likely that the encoded file won't have the same number of > newlines as the original input. > > > This, combined with the knowledge that: > > r.encrypt(a) + r.encrypt(b) != r.encrypt(a + b) > > should be enough to see that we're in trouble as soon as we try decoding > the string. *grin* > > > Does this make sense so far? Hi Mike, I pressed "Send" too quickly! *grin* I mean to talk about two ways to solve the problem. One way to avoid the issue with rotor's behavior is to encode and decode the whole thing at once instead of in parts. So instead of: ### contents = ["This is a line of text\n", "including newlines\n", "for rotor testing."] print contents # shows a list of three strings encon = [] rt = rotor.newrotor('606') for item in contents: encon.append(rt.encrypt(item)) print encon ### We can do this: ### contents = ["This is a line of text\n", "including newlines\n", "for rotor testing."] text = ''.join(contents) rt = rotor.newrotor('606') encon = rt.encrypt(text) ### What we end up with is a single string that we can write to disk. When we read from disk, we again read the whole file as a single string: ### fh = open('text.txt', 'r') incoming = fh.read() # read from a file fh.close() print incoming ### and call decrypt() on that single string. But the simpler approach is to use rotor's rotor.encryptmore() and rotor.decryptmore() methods instead: ### >>> import rotor >>> rt = rotor.newrotor("foo") >>> rt.encryptmore("hello") + rt.encryptmore("world") 'F\x14\xf5\x12\xdb\xec%\xf8\x92\xb6' >>> >>> >>> rt = rotor.newrotor("foo") >>> rt.encryptmore("helloworld") 'F\x14\xf5\x12\xdb\xec%\xf8\x92\xb6' ### encryptmore() and decryptmore() preserve the property that rt.encryptmore(a + b) and rt.encryptmore(a) + rt.encryptmore(b) are equivalent, so if you just use these methods instead, you should get good results. But when decrypting, be sure to reset the rotor to the initial state, so that the gears are in the right positions... *grin* Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Nov 6 22:25:57 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 6 22:26:02 2003 Subject: [Tutor] unprintable characters from MSWord In-Reply-To: <33E101AC5AFF78419F466954A9685420BCF1A2@mailbox.juilliard.edu> Message-ID: On Thu, 6 Nov 2003, Jonathan Soons wrote: > I have to parse text that seems to be cut and pasted from a word > document into a web form. It looks like this: > > ^II shouldM-^Rnt attempt any of the great solosM-^WWagnerM-^Rs Tristan. > > (From the `cat -tev` output). > I am guessing it is from a word processor. > How can I find out what these characters are and convert them to ascii > equivalents? Hi Jonathan, Hmmm... I'm not sure what '^I' means, but I'm guessing that 'M-' could be the start of some escape character. ### >>> ord("'") 39 >>> ord("R") 82 >>> 82 - 39 43 ### Hmmm... If we assume that 'M-^R' is really meant to be "'", and if we're lucky enough that the encoding is similar to ASCII, then perhaps something like this might work: ### >>> chr(ord('W') - 43) ',' >>> chr(ord('R') - 43) "'" >>> def decodeEscape(ch): ... return chr(ord(ch) - 43) ... >>> decodeEscape('R') "'" ### It's possible that > ^II shouldM-^Rnt attempt any of the great solosM-^WWagnerM-^Rs Tristan. could translate to: ^II shouldn't attempt any of the great solos,Wagner's Tristan. But this is just a real wild guess here. *grin* We need more data. What is the word processor that you're cutting and pasting from? And do you have more samples of text, as well as the proper translations for us to test against? Talk to you later! From missive at hotmail.com Thu Nov 6 22:42:24 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Nov 6 22:42:30 2003 Subject: [Tutor] Re: newbie question on sys.path.append() Message-ID: as the program I am working on grows, I would like to store some of the modules that are imported >in the main program file in a separate subdirectory and add the >subdirectory to sys.path. >I used sys.path.append() for this at the very beginning of this file, >like: > >#!/usr/bin/env python >from Tkinter import * >import tkMessageBox, tkSnack, sys, os, fileinput, Tix >sys.path.append(os.path.join(sys.path[0], 'widgets')) > >so I can import the modules I stored in the "widgets" subdirectory. > >I am not sure now if this might cause problems, maybe there is a more >proper way to import those >modules. > Make your subdirectory a package by adding a file called __init__.py Like this: #foo/bar.py x = 5 #baz.py from foo import bar print bar.x $python baz.py Traceback (most recent call last): File "baz.py", line 1, in ? from foo import bar ImportError: No module named foo $touch foo/__init__.py $python baz.py 5 _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From res0p1ia at verizon.net Thu Nov 6 23:48:39 2003 From: res0p1ia at verizon.net (Mike Faire) Date: Thu Nov 6 23:48:52 2003 Subject: [Tutor] How do I save the output of the rotor module? In-Reply-To: References: Message-ID: <200311062048.39554.res0p1ia@verizon.net> I hit the wrong "reply" button and sent my initial response to Danny, here it is for the list to see. On Thursday 06 November 2003 19:04, Danny Yoo wrote: > On Thu, 6 Nov 2003, Danny Yoo wrote: > > > > r.encrypt(a) + r.encrypt(b) != r.encrypt(a + b) > > > > should be enough to see that we're in trouble as soon as we try decoding > > the string. *grin* > > > > > > Does this make sense so far? > Wow! of course! I imagined that since writelines() read in a list of strings, I could process that list of strings, write it to disk and it would come back as another list of strings. Since the encrypted output of rotor is "binary" data, all structure is lost. I was completely missing the fact that r.encrypt(a) + r.encrypt(b) was happening at all. > > But the simpler approach is to use rotor's rotor.encryptmore() and > rotor.decryptmore() methods instead: > > ### > > >>> import rotor > >>> rt = rotor.newrotor("foo") > >>> rt.encryptmore("hello") + rt.encryptmore("world") > > 'F\x14\xf5\x12\xdb\xec%\xf8\x92\xb6' > > >>> rt = rotor.newrotor("foo") > >>> rt.encryptmore("helloworld") > > 'F\x14\xf5\x12\xdb\xec%\xf8\x92\xb6' > ### > > > encryptmore() and decryptmore() preserve the property that > > rt.encryptmore(a + b) > > and > > rt.encryptmore(a) + rt.encryptmore(b) > > are equivalent, so if you just use these methods instead, you should get > good results. But when decrypting, be sure to reset the rotor to the > initial state, so that the gears are in the right positions... *grin* > > > > Hope this helps! > > Very slick! This list has the *stellar* tutors! Thanks Danny and Gregor (who touched on the similiar points). The code now decrypts successfully. Although it leaves the file in the form of one large string instead of a list of strings. The split() method returns it to a list of strings but *removes* the \n's. I could loop through the list and append newlines to each string. Can split() be instructed to perform the split without removing the newlines? import rotor contents = ["This is a line of text\n", " including newlines\n", " for rotor testing."] print contents # shows a list of three strings encon = [] rt = rotor.newrotor('606') for item in contents: encon.append(rt.encryptmore(item)) print encon # at this point, print encon shows a list of three strings, encrypted fh = open('text.txt', 'w') fh.writelines(encon) # write to a file fh.close() fh = open('text.txt', 'r') incoming = fh.readlines() # read from a file fh.close() print incoming # now the string is identical rt = rotor.newrotor('606') # reset the wheels to their starting positions after = [] for item in incoming: after.append(rt.decryptmore(item)) after = after[0].split('\n') # restore the "list of strings" form of the file fh = open('text.txt', 'w') fh.writelines(after) fh.close() Mike From tim.ronning at start.no Fri Nov 7 08:55:09 2003 From: tim.ronning at start.no (Tim Ronning) Date: Fri Nov 7 06:55:37 2003 Subject: [Tutor] Newbie append puzzle In-Reply-To: References: Message-ID: P? Wed, 5 Nov 2003 14:07:42 +0100 (CET), skrev Michael Janssen : > if mp3[-1] != "\n": > mp3 = mp3 + "\n" > > > or even better use the stringsmethod endswith: > > if not mp3.endswith("\n"): > mp3 = mp3 + "\n" > > i would take for "append" (with an optional parameter playlist): > > def append(mp3, playlist="playlist"): > if not mp3.endswith("\n"): > mp3 = mp3 + "\n" > app = open(playlist,"a") > app.write(mp3) > app.close() > > this way you get, with a little luck, functions > once-defined-working-ever. Helps much to concentrate on new-to-write > functionality. > > Michael > Ofcourse. Some years back I did learn Pascal and then some C (most of it gone now I'm afraid) and I think I have some small problems realizing how "obvious" Python can be at times. The "if not mp3.endswith("\n")" is a brilliant example of that. It sounds like something you could throw out in a conversation with the wife during dinner! I need to "beam" my mind to a higher level I think! Thanks again Michael Best regards Tim R -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From tim.ronning at start.no Fri Nov 7 10:21:59 2003 From: tim.ronning at start.no (Tim Ronning) Date: Fri Nov 7 08:22:28 2003 Subject: [Tutor] More OOP Message-ID: To follow up the OOP thread. I have followed the discussion on how to "think" OO and I question if I'm doing the right thing not to dive into GUI making to much this early in my learning ladder. Whould it simply be better, from a OO perspective, to plan and design my learning projects out of a GUI base. Forcing me to produce object chuncks instead. After all my real-life projects are and will be GUI based. Tutorials, intro. books, etc. do take a console approach but it shouldn't be to difficult to apply knowledge from this kind of sources into a GUI/OO approach. It's basically the same knowledge, just grouped and applied somewhat differently. Also learning your favourite GUI toolkit is a big task and will take it's time. I currently, on a non project basis, play with Tkinter, PyQt/QT and pyFLTK/FLTK and learning properly one of these environments is a big task itself. Specially QT, it's massive! So, what do you think? Should one go GUI right away and try to translate console focused learning sources into an OO/GUI environment for ones learning projects? Best regards Tim R -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From littledanehren at yahoo.com Fri Nov 7 09:33:06 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Fri Nov 7 09:33:13 2003 Subject: [Tutor] More OOP In-Reply-To: Message-ID: <20031107143306.40409.qmail@web41812.mail.yahoo.com> > To follow up the OOP thread. > > I have followed the discussion on how to "think" OO > and I question if I'm > doing the right thing not to dive into GUI making to > much this early in my > learning ladder. Whould it simply be better, from a > OO perspective, to plan > and design my learning projects out of a GUI base. > Forcing me to produce > object chuncks instead. After all my real-life > projects are and will be GUI > based. Tutorials, intro. books, etc. do take a > console approach but it > shouldn't be to difficult to apply knowledge from > this kind of sources into > a GUI/OO approach. It's basically the same > knowledge, just grouped and > applied somewhat differently. Also learning your > favourite GUI toolkit is a > big task and will take it's time. I currently, on a > non project basis, play > with Tkinter, PyQt/QT and pyFLTK/FLTK and learning > properly one of these > environments is a big task itself. Specially QT, > it's massive! > > So, what do you think? Should one go GUI right away > and try to translate > console focused learning sources into an OO/GUI > environment for ones > learning projects? > > Best regards > Tim R It's always good to program in a somewhat object-oriented manner, but there's no special need (that I can see) for programming in a more object-oriented fashion just because you're using a GUI. Isn't it still possible to program procedurally (except for GUI itself) when using a GUI? Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From tim.ronning at start.no Fri Nov 7 12:36:37 2003 From: tim.ronning at start.no (Tim Ronning) Date: Fri Nov 7 10:36:56 2003 Subject: [Tutor] More OOP In-Reply-To: <20031107143306.40409.qmail@web41812.mail.yahoo.com> References: <20031107143306.40409.qmail@web41812.mail.yahoo.com> Message-ID: P? Fri, 7 Nov 2003 06:33:06 -0800 (PST), skrev Daniel Ehrenberg : >> So, what do you think? Should one go GUI right away >> and try to translate console focused learning sources into an OO/GUI >> environment for ones learning projects? >> >> Best regards >> Tim R > > It's always good to program in a somewhat > object-oriented manner, but there's no special need > (that I can see) for programming in a more > object-oriented fashion just because you're using a > GUI. Isn't it still possible to program procedurally > (except for GUI itself) when using a GUI? > > Daniel Ehrenberg > Probably, but I'm not yet skilled enough to answer actually. As a novice I got to ask this when one hear statements like "GUI development forced coding into a more OO way" This was implied in an earlier post, but I can't find right now. The quote is therefor probably not per word correct, rather what I read. Bottom line, I think my question is something like this: Is it advisable to take on a special approach to coding structures when one are dealing with a GUI app. Regards Tim R. -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From karl.fast at pobox.com Fri Nov 7 10:41:15 2003 From: karl.fast at pobox.com (Karl Fast) Date: Fri Nov 7 10:41:47 2003 Subject: [Tutor] More OOP In-Reply-To: ; from tim.ronning@start.no on Fri, Nov 07, 2003 at 04:21:59PM +0100 References: Message-ID: <20031107094115.B10715@signal.lights.com> > I question if I'm doing the right thing not to dive into GUI making > to much this early in my learning ladder. This is the story about how GUI programming helped me learn the basics of OOP (I posted a real short version yesterday). For my project, where I learned python and everything, I was asked to create a simple GUI. No CLI, I was told. And I need to be able to pause, continue, and cancel the spider. I did *not* start with the GUI. I starting by writing the code as a basic commnand line spider (like I'd done in Perl in a previous project). It was rudimentary, but it worked. I just needed to get a feel for the language. My code was wholly procedural. I avoid classes. My thinking was "hmmm, it's probably a bad idea to learn python, oop, wxPython + gui programming + event driven programming, and COM all in one go." (COM was for reading/writing directly to Excel) So my initial focus was python and COM-to-excel for data storage. Since I had written a spider in perl this was largely a matter of translation. This was a good exercise, not too difficult, and exposed me to a lot of standard modules in python. The COM bit was completely new to me. It was also confusing. I got the COM piece working thanks to (a) a small example in Learning Python and (b) examples I dug up googling. Now I had a basic spider in python that would read/write data to excel. It didn't have all the features I needed, but it worked, I understood it, and if I saw some python I could understand most of it. I felt sufficiently confident in my python skills to move on. So I moved on to creating a basic GUI. Again, I kept it real simple. I used wxGlade to create my GUI code (I considered Boa, PythonCard, and wxDesigner too). Then I started wiring it together. I followed examples in the wxPython wiki. I read the sections on OOP and classes in my books (Learning Python and Core Python Programming). I began experimenting. It was frustrating at times, but I kept plugging away. Slowly, the learning curve flattened. The GUI stuff was OO-heavy. No way to avoid it. And when I wired my other code in I got something that worked, but it didn't feel right. It felt ugly and as I kept adding things, it was getting uglier. It worked, but gawd...what a mess. I began rewriting my procedural code as classes. The GUI stuff wasn't forcing me down this road, but it sure made this road more appealing. My previous code, the procedural stuff, worked fine. It instantiated objects from other modules, of course, but I had never found a compelling need to step outside my procedural comfort zone and write my own classes. Building a wxPython-based GUI changed all that. Suddenly it was worthing switching my mindset from a procedural worldview to an OOP one. Suddently OOP was the path of least resistance. A complete switch. Yes, OOP would have made previous projects easier, but when I added in the cost of learning how to do this new math, the answer was always the same: you gotta get this done, you know how to do it procedurally, so just get it done and move on. Yet here was a situation where when the equation was giving me a different answer. For me, learning wxPython (Tkinter would have been the same) has been an excellent way to learn how to write my own classes. Of course there are piles of things I don't know and many aspects of OOP that elude me. But I can see the value of it now. I don't hesitate to create a new class. The other day I began working with threads and right off I subclassed the threading module. It was easy and felt natural. A few weeks ago I would have been comfortable instantiating a threading object, but that's about all. The idea of subclassing would have given me pause. No more. I feel like one of those weight loss ads: "I learned OOP in 21 days, and you can too. Just switch to Python, build a little GUI, eat a little sushi, and voila!" --karl From karl.fast at pobox.com Fri Nov 7 10:53:11 2003 From: karl.fast at pobox.com (Karl Fast) Date: Fri Nov 7 10:53:41 2003 Subject: [Tutor] newbie In-Reply-To: <20031106211609.GA18444@inkedmn.homelinux.org>; from inkedmn@inkedmn.homelinux.org on Thu, Nov 06, 2003 at 01:16:09PM -0800 References: <20031106095332.B13125@signal.lights.com> <20031106211609.GA18444@inkedmn.homelinux.org> Message-ID: <20031107095311.C10715@signal.lights.com> > Care to link us to this app? i'm curious to see a good-sized example of > wxPython... :) I can't right now, and am not sure I'll be able to. I will if I'm allowed to. However, I can shared several sources of good information and examples, including full working apps: * The wxPython Wiki http://wiki.wxpython.org/ There are some good starter tutorials here with sample code. Not as complete as I'd like and sometimes hard to find your way around, but this is one of the most important resources you'll find. * the wxGlade tutorial http://wxglade.sourceforge.net/tutorial.php There are several tools for making wxPython coding easier. Boa and Pythoncard are frameworks/IDEs. I tried them, but for various reasons decided not to use them. wxGlade and wxDesigner are GUI code generators, not IDEs: you lay out the interface, it generates the code, and you use this to build your GUI. I chose wxGlade, used the tutorial, studied the code, and then began learning how to build an application around that. * Cornice http://web.tiscali.it/no-redirect-tiscali/agriggio/cornice.html This is a cross-platform image browser written in wxPython and partially built with wxGlade. The source code for this has been extremely helpful. Other good examples of wxPython apps built with wxGlade can be found here. I looked at many of these: http://wxglade.sourceforge.net/apps.php Hope this helps. --karl From karl.fast at pobox.com Fri Nov 7 11:14:01 2003 From: karl.fast at pobox.com (Karl Fast) Date: Fri Nov 7 11:14:33 2003 Subject: [Tutor] newbie In-Reply-To: <002901c3a4b2$0f3ce990$6401a8c0@xp>; from alan.gauld@blueyonder.co.uk on Thu, Nov 06, 2003 at 10:05:15PM -0000 References: <002901c3a4b2$0f3ce990$6401a8c0@xp> Message-ID: <20031107101401.D10715@signal.lights.com> > Some studies with teaching Librarians (practiced taxonomists) OOP > showed that they picked up programming significantly faster than > control groups learning traditional techniques. I'd be interested in reading these studies. As a librarian I'm skeptical. My undergrad degree is engineering physics. I learned fortran, pascal, IDL and lots of assembler. All procedural. But I also have a masters in library & information science. I've spent most of my life working with physicists, computer scientists, and librarians. Most library students I know came from english and history and things like that. For them, math and computers are scary. I teach them labs and getting them to understand relative URIs is a big challenge (a few can't even copy files from the hard drive to a floppy disk) Most of them don't understand basic programming concepts, let alone objects. I'm curious about these studies. For example, in one of my classes the prof took an hour to introduce IF-THEN-ELSE. This was a completely new concept to most students. They were big-time lost. It was a basic database class (took it for an easy credit). The last two weeks covered wiring databases to the web using Cold Fusion. Basic concepts like variables, data types, and flow control were big conceptual leaps for these students. I know that Kay had success teaching smalltalk to kids, but my experience with librarians makes me skeptical about teaching them OOP. So I'm *real* curious about these studies. --karl From dyoo at hkn.eecs.berkeley.edu Fri Nov 7 13:04:29 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 7 13:04:37 2003 Subject: [Tutor] How do I save the output of the rotor module? In-Reply-To: <200311062048.39554.res0p1ia@verizon.net> Message-ID: > The code now decrypts successfully. Although it leaves the file in the > form of one large string instead of a list of strings. The split() > method returns it to a list of strings but *removes* the \n's. I could > loop through the list and append newlines to each string. Can split() be > instructed to perform the split without removing the newlines? Hi Mike, split() can't, but splitlines() can. ### >>> s = "hello world\nthis is a test\n" >>> s.split() ['hello', 'world', 'this', 'is', 'a', 'test'] >>> s.splitlines() ['hello world', 'this is a test'] >>> s.splitlines(True) ['hello world\n', 'this is a test\n'] ### splitlines() can take in an optional 'keepends' parameter: if we send it a true value, then it'll keep the newlines. We can find out more about the string methods in the Library Reference: http://www.python.org/doc/lib/string-methods.html I hope this helps! From dyoo at hkn.eecs.berkeley.edu Fri Nov 7 13:14:37 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 7 13:14:43 2003 Subject: [Tutor] unprintable characters from MSWord (fwd) Message-ID: Hi Jonathan, I'm forwarding this to Python-Tutor, so that the others there might be able to help. In general, we try to keep the conversation on list just in case one of us gets hit by a bus or something... *grin* ---------- Forwarded message ---------- Date: Fri, 7 Nov 2003 09:52:17 -0500 From: Jonathan Soons To: Danny Yoo Subject: RE: [Tutor] unprintable characters from MSWord Here's what I'd like to do: -- Make a dictionary of character substitutions. -- Find all the octal values of the characters in the line. -- Substitute. There is no need to guess what these codes are. I just want to find them and substitute. (I have no knowledge of what word processors people are using when they visit the web form.) Thanks for the ord() tip. I will try: for i in range(0, len (string)-1) : print ord(string[i]) Then I will have the integer values. Then put these in a dictionary = {BadChar:asciiChar, ...:..., }. Then BadCharTuple = keys(dictionary) for char in BadCharTuple : goodtxt = origtxt.replace(BadChar, dictionary[BadChar] I will know if this works later today. But tell me if it is obviously flawed. Thank you jon soons -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Thursday, November 06, 2003 10:26 PM To: Jonathan Soons Cc: Tutor Subject: Re: [Tutor] unprintable characters from MSWord On Thu, 6 Nov 2003, Jonathan Soons wrote: > I have to parse text that seems to be cut and pasted from a word > document into a web form. It looks like this: > > ^II shouldM-^Rnt attempt any of the great solosM-^WWagnerM-^Rs Tristan. > > (From the `cat -tev` output). > I am guessing it is from a word processor. > How can I find out what these characters are and convert them to ascii > equivalents? Hi Jonathan, Hmmm... I'm not sure what '^I' means, but I'm guessing that 'M-' could be the start of some escape character. ### >>> ord("'") 39 >>> ord("R") 82 >>> 82 - 39 43 ### Hmmm... If we assume that 'M-^R' is really meant to be "'", and if we're lucky enough that the encoding is similar to ASCII, then perhaps something like this might work: ### >>> chr(ord('W') - 43) ',' >>> chr(ord('R') - 43) "'" >>> def decodeEscape(ch): ... return chr(ord(ch) - 43) ... >>> decodeEscape('R') "'" ### It's possible that > ^II shouldM-^Rnt attempt any of the great solosM-^WWagnerM-^Rs Tristan. could translate to: ^II shouldn't attempt any of the great solos,Wagner's Tristan. But this is just a real wild guess here. *grin* We need more data. What is the word processor that you're cutting and pasting from? And do you have more samples of text, as well as the proper translations for us to test against? Talk to you later! From alan.gauld at blueyonder.co.uk Fri Nov 7 14:22:45 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Nov 7 14:22:18 2003 Subject: [Tutor] More OOP References: Message-ID: <003501c3a564$85aa50b0$6401a8c0@xp> > So, what do you think? Should one go GUI right away and try to translate > console focused learning sources into an OO/GUI environment for ones > learning projects? If you have programnmed GUIs in other languages there is no great hardship in adopting a GUI based approach. But If GUI is new then you are adding significant complexity to your learning curve. Its easy to get confused over whether sometghing is wrong because of the GUI, using OO or the basic language. Personally I advise learning the language first then move to a GUI. Well structured programs should be relatively easy to port, badly structured programs should be rewritten to understand how to do it better in the future! Alan G. From alan.gauld at blueyonder.co.uk Fri Nov 7 14:42:43 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Nov 7 14:42:16 2003 Subject: [Tutor] More OOP References: <20031107143306.40409.qmail@web41812.mail.yahoo.com> Message-ID: <003e01c3a567$501b3240$6401a8c0@xp> > Bottom line, I think my question is something like this: Is it advisable > to take on a special approach to coding structures when one are dealing > with a GUI app. Its not necessary but there is a natural synergy between GUI widgets and objects. Also many GUI toolkits are implemented as object frameworks so you have to use objects anyway, you might as well make your code fit in. But with Tkinter for example its pefectly possible to use a procedural approach and for small programs thats fine, once you get to beigger GUI programs procedural code quickly becomes complex. Alan G. From scott_list at mischko.com Fri Nov 7 14:45:16 2003 From: scott_list at mischko.com (Scott Chapman) Date: Fri Nov 7 14:45:21 2003 Subject: [Tutor] How to convert or make Python module docs into one HTML file? Message-ID: <200311071145.16291.scott_list@mischko.com> Hi! I have python modules such as Draco and Mod_Python which follow the python documenting standard. I want these to be one big file rather than tons of small ones. The big file should have links working correctly from a top table of contents. I need this to print the docs and not waste so much paper on partially filled pages. Anyone know how to do this? I know -zero- about tex but I think it's probably not too tough to do? Scott From scott_list at mischko.com Fri Nov 7 14:55:22 2003 From: scott_list at mischko.com (Scott Chapman) Date: Fri Nov 7 14:55:35 2003 Subject: [Tutor] Can I hook a "file" to a python script? Message-ID: <200311071155.22408.scott_list@mischko.com> Hi! I'd like a "file" on the Linux box to actually be the input and output of a Python script. Anything written to the file would be sent to a database and anything read from the file would come from the database. I know how to do the database end of this but I'm not sure if a script can be hooked to a "file" transparently. The script would probably have to be run as a daemon. I doubt there's enough magic in the Linux world to make it so that a read/write would actually launch the script. That'd be Ok. Scott From alan.gauld at blueyonder.co.uk Fri Nov 7 14:56:40 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Nov 7 14:56:14 2003 Subject: [Tutor] newbie References: <002901c3a4b2$0f3ce990$6401a8c0@xp> <20031107101401.D10715@signal.lights.com> Message-ID: <004701c3a569$42997c10$6401a8c0@xp> > I'd be interested in reading these studies. As a librarian I'm > skeptical. OK, the studies were published (as a summary article of course) in HOOT(I think, maybe JOOP) back in the early 1990's - I'd guess 1992? > and librarians. Most library students I know came from english and > history and things like that. Hmm, Librarians in the UK are university graduates, often with a masters degree in the subject. Are we talking about the same thing? They all get taught programming and computers as part of the degree course. > For example, in one of my classes the prof took an hour to introduce > IF-THEN-ELSE. This was a completely new concept to most students. Exactly but with OOP you very rarely see an If/Then/Else branch... OK thats an obvious exageration but polymorphism does away with a lot of it, and the studies worked on that principle. They started them playing with objects not algorithms. Send a message to an object and watch it dance. The object knows what do do according to its type. Objects of relate types behave in similar ways etc... So the teaching was focused on teaching objects from the outside in rather than the traditional CS approach of teaching you how to build a class then instantiate it(huh?) and finally use it... Actually writing methods was about the last thing they showed them. > an easy credit). The last two weeks covered wiring databases to the > web using Cold Fusion. Basic concepts like variables, data types, > and flow control were big conceptual leaps for these students. Absolutely and most of these are irrelevant in a pure OO world. Objects are objects and they pass messages. No need to worry about types, operators etc. > I know that Kay had success teaching smalltalk to kids, but my > experience with librarians makes me skeptical about teaching them > OOP. So I'm *real* curious about these studies. FWIW There are other studies (but I don't know if they were published) that showed that bankers learnt programming via OOP faster than traditional style too. This was late '90s when many finance houses ditched their spreadsheets for vertical Smalltalk modelling tools. Alan G. PS I may still have a paper copy of the Librarians article, if so I'll try to find it over the weekend. From john at duartedailey.org Fri Nov 7 17:33:56 2003 From: john at duartedailey.org (John Duarte) Date: Fri Nov 7 17:33:42 2003 Subject: [Tutor] OOP source code?? Message-ID: <200311071433.56843.john@duartedailey.org> I have been enjoying the 'More OOP' thread. Can someone point out some python source code that does a good job of illustrating "How it should be done"? I have been struggling with trying to design an estimating system for a manufacturing process. I know that this is the perfect task for the OOP approach, but the path to design enlightenment is eluding me. I don't want anybody to "do my homework for me", but the simplified examples I have encountered have not prepared me for tackling my problem. So, I am looking for some "real world" source that illustrates how OOP can be used to provide solutions. Thanks, John From missive at hotmail.com Fri Nov 7 18:52:22 2003 From: missive at hotmail.com (Lee Harr) Date: Fri Nov 7 18:52:26 2003 Subject: [Tutor] Re: Can I hook a "file" to a python script? Message-ID: >I'd like a "file" on the Linux box to actually be the input and output >of a Python script. Anything written to the file would be sent to a >database and anything read from the file would come from the database. >I know how to do the database end of this but I'm not sure if a script >can be hooked to a "file" transparently. The script would probably >have to be run as a daemon. I doubt there's enough magic in the Linux >world to make it so that a read/write would actually launch the script. > Doubt not :o) You could create a kernel module which does something special when a particular device node is accessed, for instance. Maybe what you are looking for is a socket? In BSD, there is also the kqueue interface (and py-kqueue of course) There are interfaces which have been around for a while, and are very well thought out. (files, devices, sockets, etc) and it is likely that if you are trying to do something so far outside of the box that linux does not have the special magic that you need... well... that does not sound encouraging. Of course, maybe you are inventing a new and better interface. It sounds interesting, anyhow. _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From karl.fast at pobox.com Fri Nov 7 20:44:10 2003 From: karl.fast at pobox.com (Karl Fast) Date: Fri Nov 7 20:44:42 2003 Subject: [Tutor] newbie In-Reply-To: <004701c3a569$42997c10$6401a8c0@xp>; from alan.gauld@blueyonder.co.uk on Fri, Nov 07, 2003 at 07:56:40PM -0000 References: <002901c3a4b2$0f3ce990$6401a8c0@xp> <20031107101401.D10715@signal.lights.com> <004701c3a569$42997c10$6401a8c0@xp> Message-ID: <20031107194410.F10715@signal.lights.com> > OK, the studies were published (as a summary article of course) > in HOOT(I think, maybe JOOP) back in the early 1990's Thanks. I will look for them. > Hmm, Librarians in the UK are university graduates, often with a > masters degree in the subject. Are we talking about the same thing? Yes. It is a master's level program. You must have a previous degree. Most of the students have backgrounds in humanities and social sciences. Out of 100+ students each year we're lucky to get more than five with a technical background: math, engineering, sciences, computers, etc. > They all get taught programming and computers as part of the degree > course. Not necessarily. It depends on the school. Most places grant a masters in library and information science (LIS). One of your standard essays in the first term is writing a paper about the distinctions between library science and information science (an old joke has it that information science is library science as practiced by men; librarianship is dominated by women). Some LIS schools are L-heavy, others are I-heavy. You have some that are L-only, and others that are I-only. My university is much more L-focused. We produce professional librarians. A handful of them enter with programming skills. None of them leave. There is one introduction to programming class here (VB). It's usually offered once a year. Perhaps 10 people take it. Nobody leaves here capable of doing programming work as their main job. Anybody who does could code before they started. That's not the case everywhere. There are some schools (Berkeley, for one) where it's critical. Other programs offer multiple streams, like Michigan which has an HCI stream. So the answer is, it depends. I wouldn't count on it unless the student came from one of maybe ten schools (there are about 60 accredited schools in the US & Canada). --karl From zmerch at 30below.com Sat Nov 8 09:58:04 2003 From: zmerch at 30below.com (Roger Merchberger) Date: Sat Nov 8 10:01:38 2003 Subject: [Tutor] Re: Can I hook a "file" to a python script? In-Reply-To: Message-ID: <5.1.0.14.2.20031108094157.01d59608@mail.30below.com> Rumor has it that Lee Harr may have mentioned these words: >>I'd like a "file" on the Linux box to actually be the input and output >>of a Python script. Anything written to the file would be sent to a >>database and anything read from the file would come from the database. >>I know how to do the database end of this but I'm not sure if a script >>can be hooked to a "file" transparently. Okay... no problem... >> The script would probably have to be run as a daemon. Probably, yes... >> I doubt there's enough magic in the Linux >>world to make it so that a read/write would actually launch the script. ...You are actually quite incorrect with that statement, for a couple of reasons: 1) If the script is a daemon, it's running *all the time* so you won't need to 'launch' it every time... 2) There *is* more than enough magic in *nix (Linux, Unix, Xenix, etc... ;-) to allow you to do this: it's called a named pipe. Do you know how to redirect stdin & stdout from the command line? bash# mycommand.py < inputfile.txt | nextcommand.py > outputfile.txt This runs mycommand.py, but takes all input from inputfile.txt instead of from the keyboard or standard input. The center character is a "Pipe" character - it pipes the output from mycommand.py directly to the standard input of nextcommand.py which does it's magic, but instead of the output going to the screen or terminal window, it's sent to outputfile.txt. (If you wanted to append the data to the file, instead of overwrite the file every time, use the two > signs, like this: nextcommand.py >> outputfile.txt ) So, you want to set up a named pipe (or FIFO), and tell your daemon to take input from that. Then the daemon will sit there, and wait... and when you send data to the named pipe, it will automatically be sent to the waiting daemon, which will "do it's magic" when the data arrives. 1 Caveat - I've used them *Very* rarely, so I'm no exspurt on them, but here's a few links that can help... http://www.linuxvalley.it/encyclopedia/ldp/manpage/man4/fifo.4.php http://www.linuxjournal.com/article.php?sid=2156 Googling for '''linux named pipe tutorial''' may well render other good help sites... ;-) Hope this helps, 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 bgailer at alum.rpi.edu Sat Nov 8 10:13:47 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Nov 8 10:16:11 2003 Subject: [Tutor] OOP source code?? In-Reply-To: <200311071433.56843.john@duartedailey.org> References: <200311071433.56843.john@duartedailey.org> Message-ID: <6.0.0.22.0.20031108081055.0310c5a8@66.28.54.253> At 03:33 PM 11/7/2003, John Duarte wrote: >I have been enjoying the 'More OOP' thread. > >Can someone point out some python source code that does a good job of >illustrating "How it should be done"? > >I have been struggling with trying to design an estimating system for a >manufacturing process. I know that this is the perfect task for the OOP >approach, but the path to design enlightenment is eluding me. I have some experience in manufacturing process estimating systems. The work was done first in Excel, then Access. No OOP was used. I'd be interested to hear some more detail of what you are tackling; perhaps I could give you some pointers. (but wait...Python doesn't have pointers) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.537 / Virus Database: 332 - Release Date: 11/6/2003 From project5 at redrival.net Sat Nov 8 10:48:22 2003 From: project5 at redrival.net (Andrei) Date: Sat Nov 8 10:50:46 2003 Subject: [Tutor] Re: OOP source code?? References: <200311071433.56843.john@duartedailey.org> Message-ID: John Duarte wrote on Fri, 7 Nov 2003 14:33:56 -0800: > Can someone point out some python source code that does a good job of > illustrating "How it should be done"? There's a lot of OOP Python code out there (in the Python libs too), so it's hard to point out anything specific. Here's an example which I think clearly illustrates OOP and inheritance at a very simple level: http://mail.python.org/pipermail/tutor/2001-March/004010.html > I don't want anybody to "do my homework for me", but the simplified examples I > have encountered have not prepared me for tackling my problem. So, I am > looking for some "real world" source that illustrates how OOP can be used to > provide solutions. Hm... I think it's best to start small really. If you don't understand OOP, staring at the Zope codebase won't be a lot of help I presume. IMO you'd be better off coding something small and simple instead. If the example with polygons is too small, try extending it and make a CAD-like storage system which can store all kinds of different shapes and calculate areas, circumferences, etc. You'd need a point class, a polygon class (with all kinds of subclasses), etc. Or a Jukebox-like application (for ease of use without actually having it produce sound) which can manage Collections of different types of Songs (MP3, OGG, MIDI) and play random Songs from all Collections, or random songs witin a Collection. The Jukebox itself could be a Collection of Collections. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Sat Nov 8 12:15:13 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Nov 8 12:14:35 2003 Subject: [Tutor] newbie References: <002901c3a4b2$0f3ce990$6401a8c0@xp><20031107101401.D10715@signal.lights.com><004701c3a569$42997c10$6401a8c0@xp> <20031107194410.F10715@signal.lights.com> Message-ID: <002201c3a61b$e033ba00$6401a8c0@xp> > librarians. A handful of them enter with programming skills. None of > them leave. There is one introduction to programming class here > (VB). It's usually offered once a year. Perhaps 10 people take it. > Nobody leaves here capable of doing programming work as their main > job. Anybody who does could code before they started. Interesting. I'm currently working on a project where two of the team (both women :-) studied as Librarians but became so interested in the computing side that after finishing the course they signed up for a 1 yeear Masters IT course and ae now full time software engineers... Albeit both primarily focussed on Business Analysis type roles, but both capable of whipping up a database or programmng a web app with no problem. The fact that the IT industry pays better helped too of course! :-) Still looking for the article BTW. Alan G. From ptwaugh at earthlink.net Sat Nov 8 19:15:42 2003 From: ptwaugh at earthlink.net (P.T. Waugh MA) Date: Sat Nov 8 19:18:14 2003 Subject: [Tutor] RE: REG in XP vs Win2000 Message-ID: <5.2.1.1.2.20031108161400.00acf168@pop.earthlink.net> I use this code: def get_regkey_value(key, subkey): h = win32api.RegOpenKeyEx(key, subkey , 0 , win32con.KEY_READ ) return win32api.RegQueryValueEx( h, "" )[0].split('.exe')[0] FS9_PATH = get_regkey_value(win32con.HKEY_CLASSES_ROOT, FS9_PATH_KEY)[:-3] to find Microsoft FS9 in Windows. However, it does not seem to work in XP. Is there a better and more effective way to find the FS9's install directory? Thanks for the ideas. Patrick From mrmrmr50 at yahoo.com Sat Nov 8 20:18:08 2003 From: mrmrmr50 at yahoo.com (mike re-v) Date: Sat Nov 8 20:18:14 2003 Subject: [Tutor] python sound and repeat using snack Message-ID: <20031109011808.49620.qmail@web21208.mail.yahoo.com> I'd like to get the following code to repeat Now it is playing both instances at the same time the range variable print then I hear the sound What I expected the code to do is play each 4x in sequence. Any ideas? #!/usr/bin/python from Tkinter import * root = Tk() import tkSnack tkSnack.initializeSnack(root) mysound = tkSnack.Sound() mysound1 = tkSnack.Sound() mysound.read('/home/re-v/clm/lion2.wav') mysound1.read('/home/re-v/clm/crow2.wav') a = [1,2,3,4] for x in a: print x mysound.play() b = [1,2,3,4] for y in b: print y mysound1.play() root.mainloop() __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From mrmrmr50 at yahoo.com Sat Nov 8 20:35:33 2003 From: mrmrmr50 at yahoo.com (mike re-v) Date: Sat Nov 8 20:35:38 2003 Subject: [Tutor] answer found thanks Message-ID: <20031109013533.43892.qmail@web21207.mail.yahoo.com> I was able to come up with the answer looking at the archive. it involves using the blocking command with play ie; mysound.play(blocking= 'yes') thanks re-v __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From dyoo at hkn.eecs.berkeley.edu Sat Nov 8 21:00:09 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Nov 8 21:00:18 2003 Subject: [Tutor] 4 begginers questions ... (fwd) Message-ID: Hi David, I will forward this message to the Python-Tutor mailing list. Instead of emailing Alan or the 'tutor-owner@python.org' address directly, you may want to send your messages on the Tutor mailing list. There are a lot of experts and learners on the list, so it's a great place to ask questions. To subscribe to Python-Tutor, see: http://mail.python.org/mailman/listinfo/tutor Good luck to you! ---------- Forwarded message ---------- Date: Sun, 9 Nov 2003 00:59:57 +0100 From: Tadey To: tutor-owner@python.org Subject: 4 begginers questions ... Hello ... I am newbie at programming, and though I have allready send this mail to Alan Gauld (and also to Kirby Urner - the webmaster on python.org - and got his answer), I think there would be good to ask this "begginer" questions also here: 1.) I was puting in some wrong values, and python start to calculating endlessly, so I would like to know, if it is possible, how to force python to stop executing my instructions in that cases (without quiting program) ?? ************************************************************************ 2.) And second, after error message, is python continuing from last line, or do I need to retype all from the begging of current program (I suppose exept variables, which were set previous) ************************************************************************ 3.) In your (Alan Gauld) tutorial in part "Conversing with the user" it says: >>> print raw_input("Type something: ") As you see raw_input simply displays the given prompt and captures whatever the user types in response. Print then displays that response. We could instead assign it to a variable: resp = raw_input("What's your name? ") print "Hi, %s, nice to meet you" % resp So, the question is (though not so important, I couldn't live without knowing the answer): Answer on that promt is displayed right after "prompt" line, so what do you mean with ... "Print then displays that response." ... ... it looks like that, in all cases it displays promt: >>> raw_input("What's your name?") What's your name? David # when I hit return here after David it display response automaticly ... 'David' >>> resp = raw_input("What's your name?") What's your name? David # right after this line wich display promt and response to that promt - so what is then with ... 'David' >>> print raw_input("What's your name?") What's your name? David # "Print then displays that response." (it's impossible to print response afterwards) 'David' ... so actually there is no need (and impossible though) to use print command again to display that response, (the response is displayed automaticly, right after second "promt/response" line) so response is "captured" only if we set the answer to variable (like in second case) ... ************************************************************************ 4.) Different between : >>> a = "dav" >>> print a # type print a and hit return ... 'dav' # dav is displayed inside ' ' sign >>> a = "dav" >>> a # type a and hit return in this case ... dav # dav is displayed without ' ' signs Thanks for this great tutorial, please don't be mad, I am begginer ... David from Slovenija From ptwaugh at earthlink.net Sun Nov 9 00:03:47 2003 From: ptwaugh at earthlink.net (P.T. Waugh MA) Date: Sun Nov 9 00:06:19 2003 Subject: [Tutor] how to determine windows version Message-ID: <5.2.1.1.2.20031108210232.00ad1bc0@pop.earthlink.net> Hi all, Can't figure out how to determine the windows version my code is running on. I need to tell so I can determine where in the registry to look for the location of a program. Thanks, Patrick From tbrauch at mindless.com Sun Nov 9 00:16:38 2003 From: tbrauch at mindless.com (Timothy M. Brauch) Date: Sun Nov 9 00:16:42 2003 Subject: [Tutor] how to determine windows version References: <5.2.1.1.2.20031108210232.00ad1bc0@pop.earthlink.net> Message-ID: <004901c3a680$a77e8fe0$6600a8c0@winxp> From: "P.T. Waugh MA" > Hi all, > > Can't figure out how to determine the windows version my code is running > on. I need to tell so I can determine where in the registry to look for > the location of a program. > > Thanks, > > Patrick Using my Windows XP pro machine, I tried this.... >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'exitfunc', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', 'winver'] Hmm, a few of those look promising. Let's see what they do. >>> sys.platform Not too helpful. >>> sys.version '2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)]' Ah, that tells me about Python. >>> sys.version_info (2, 3, 2, 'final', 0) About Python in a tuple. >>> sys.winver '2.3' Looks like that just again tells me about Python. >>> sys.getwindowsversion Maybe this is what we need, but it's not a string; it's a function. Let's check the __doc__ >>> sys.getwindowsversion.__doc__ 'getwindowsversion()\n\nReturn information about the running version of Windows.\nThe result is a tuple of (major, minor, build, platform, text)\nAll elements are numbers, except text which is a string.\nPlatform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n' Yes, that seems like what we will need. >>> sys.getwindowsversion() (5, 1, 2600, 2, 'Service Pack 1') So I am using Windows 5.1.2600, which is NT/2000/XP based with Service Pack 1. It all checks out. Remember, dir(module) and __doc__ can be your friends. If you can't remember what modules there are, try looking at http://www.python.org/doc/current/modindex.html - Tim --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.536 / Virus Database: 331 - Release Date: 11/04/2003 From ptwaugh at earthlink.net Sun Nov 9 00:18:19 2003 From: ptwaugh at earthlink.net (P.T. Waugh MA) Date: Sun Nov 9 00:20:51 2003 Subject: [Tutor] how to determine windows version In-Reply-To: <004901c3a680$a77e8fe0$6600a8c0@winxp> References: <5.2.1.1.2.20031108210232.00ad1bc0@pop.earthlink.net> Message-ID: <5.2.1.1.2.20031108211734.00aeabf0@pop.earthlink.net> Tim, thanks for showing me how to 'fish' =) Patrick At 12:16 AM 11/9/2003 -0500, you wrote: >From: "P.T. Waugh MA" > > Hi all, > > > > Can't figure out how to determine the windows version my code is running > > on. I need to tell so I can determine where in the registry to look for > > the location of a program. > > > > Thanks, > > > > Patrick > >Using my Windows XP pro machine, I tried this.... > > >>> import sys > >>> dir(sys) >['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', >'__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', >'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', >'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info', >'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', >'executable', 'exit', 'exitfunc', 'getcheckinterval', 'getdefaultencoding', >'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', >'getwindowsversion', 'hexversion', 'maxint', 'maxunicode', 'meta_path', >'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', >'prefix', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', >'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions', >'winver'] > >Hmm, a few of those look promising. Let's see what they do. > > >>> sys.platform > >Not too helpful. > > >>> sys.version >'2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)]' > >Ah, that tells me about Python. > > >>> sys.version_info >(2, 3, 2, 'final', 0) > >About Python in a tuple. > > >>> sys.winver >'2.3' > >Looks like that just again tells me about Python. > > >>> sys.getwindowsversion > > >Maybe this is what we need, but it's not a string; it's a function. Let's >check the __doc__ > > >>> sys.getwindowsversion.__doc__ >'getwindowsversion()\n\nReturn information about the running version of >Windows.\nThe result is a tuple of (major, minor, build, platform, >text)\nAll elements are numbers, except text which is a string.\nPlatform >may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n' > >Yes, that seems like what we will need. > > >>> sys.getwindowsversion() >(5, 1, 2600, 2, 'Service Pack 1') > >So I am using Windows 5.1.2600, which is NT/2000/XP based with Service Pack >1. It all checks out. > >Remember, dir(module) and __doc__ can be your friends. If you can't >remember what modules there are, try looking at >http://www.python.org/doc/current/modindex.html > > - Tim > > > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.536 / Virus Database: 331 - Release Date: 11/04/2003 From missive at hotmail.com Sun Nov 9 09:48:53 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Nov 9 09:48:59 2003 Subject: [Tutor] Re: 4 begginers questions ... (fwd) Message-ID: >1.) I was puting in some wrong values, and python start to calculating >endlessly, so I would like to know, if it is possible, how to force python >to stop executing my instructions in that cases (without quiting program) >?? > Are you typing at the interactive interpreter? (the >>> prompt?) Try ctrl-c >2.) And second, after error message, is python continuing from last line, >or do I need to retype all from the begging of current program (I suppose >exept variables, which were set previous) > If your program is starting to get complex enough that you are concerned about "typing it again" you should be saving it in a file and running it, rather than just typing it at the interactive interpreter prompt. If you expect you might get an error, you can plan for it: for denominator in range(-10, 10): try: quotient = 10.0 / denominator print '10 / %s = %s' % (denominator, quotient) except ZeroDivisionError: print 'cannot divide by zero' >3.) In your (Alan Gauld) tutorial in part "Conversing with the user" it >says: > >>>>print raw_input("Type something: ") > >As you see raw_input simply displays the given prompt and captures whatever >the user types in response. Print then displays that response. We could >instead assign it to a variable: > >resp = raw_input("What's your name? ") >print "Hi, %s, nice to meet you" % resp > >>>>resp = raw_input("What's your name?") >What's your name? David # right after this line wich display promt >and response to that promt - so what is then with ... 'David' > Isn't that the part that you typed? If it did not show that, you would not be able to see what you were typing. >... so actually there is no need (and impossible though) to use print >command again to display that response, (the response is displayed >automaticly, right after second "promt/response" line) so response is >"captured" only if we set the answer to variable (like in second case) ... > Right. This actually relates to your next question. Some functions return a value. What happens to that value is slightly different depending on whether you are typing at the interactive interpreter, or running a program from a file. >4.) Different between : > >>>>a = "dav" >>>>print a # type print a and hit return ... >'dav' # dav is displayed inside ' ' sign > >>>>a = "dav" >>>>a # type a and hit return in this case ... >dav # dav is displayed without ' ' signs > The interactive interpreter will show you what a name is attached to if you just type it in and hit enter: >>>a 'dav' however, if you did the same thing in a program, you would never see that output: #save this as showa.py a = 'dav' print 'this is a' a print 'this is print a' print a # now run that program and you will see: $python showa.py this is a this is print a dav _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From littledanehren at yahoo.com Sun Nov 9 11:30:32 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Nov 9 11:30:42 2003 Subject: [Tutor] code blocks and output streams Message-ID: <20031109163032.83573.qmail@web41813.mail.yahoo.com> I am trying to create a program that can have php-like embedding of Python in html files. First, I want to start out with a program that can take an html file with python code inside tags (ie something like print 'hi'). In trying to do this, I found two problems: executing complex code blocks (eg ones that must have some indentation) and creating a new output stream to direct things that are printed to. All I know about how to do this is that the exec keyword should be used to execute things and that I should change sys.stdout to change the output stream. Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From glingl at aon.at Sun Nov 9 12:24:19 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Nov 9 12:26:16 2003 Subject: [Tutor] anagrams In-Reply-To: References: Message-ID: <3FAE7843.9040709@aon.at> Danny Yoo schrieb: >... >Time to jump in as well! *grin* > Thanks for your and Karls contributions to the anagram - problem! They were both very instructive for me (except that I still have to think about this itertools-spiced one ... which also is very fast.) Karl's first solution is the fastest and Danny's - I can't help, I have to say so - is, as often, the clearest, best explained and most beautiful one. (Both of them apply similar ideas) Many on this list contribute very fine, use- and helpful postings, but Danny is certainly not only a gifted Python tutor but also a marvelous tutoring tutor. Regards, Gregor > >### >def main(): > for anagrams in find_anagrams(open("wordlist.txt").readlines()): > if len(anagrams) > 1: > print '\t'.join(anagrams) > > >def anagram_signature(word): > """Finds the anagram "signature" of a word.""" > letters = list(word.lower().strip()) > letters.sort() > return ''.join(letters) > > >def find_anagrams(words): > """Returns a partitioning of words into equivalence classes, based on > a word's anagram signature.""" > d = {} > for word in words: > d.setdefault(anagram_signature(word), []).append(word.strip()) > return d.values() > > >if __name__ == '__main__': > main() >### > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From jsoons at juilliard.edu Sun Nov 9 17:07:37 2003 From: jsoons at juilliard.edu (Jonathan Soons) Date: Sun Nov 9 17:07:43 2003 Subject: [Tutor] unicode() bug? Message-ID: <33E101AC5AFF78419F466954A96854202F5A9B@mailbox.juilliard.edu> the following program fails: #!/usr/local/bin/python f = open("text.txt", "r") txt = f.read() f.close() output = open("unifile", "w") output.write(unicode(txt, "iso-8859-1", "ignore")) output.close() so does the following: #!/usr/local/bin/python f = open("text.txt", "r") txt = f.read() f.close() output = open("unifile", "w") for i in range(len(txt)-1): try: output.write(unichr(txt[i])) except: print "bad character, but I'll keep going" output.close() The error is: UnicodeError: ASCII encoding error: ordinal not in range(128) The "ignore" seems to do nothing! If I wanted it to stop on errors I would have used "strict". How can I convert a string to unicode and skip any iffy characters? Thank you. From amk at amk.ca Sun Nov 9 17:45:41 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sun Nov 9 17:46:07 2003 Subject: [Tutor] unicode() bug? In-Reply-To: <33E101AC5AFF78419F466954A96854202F5A9B@mailbox.juilliard.edu> References: <33E101AC5AFF78419F466954A96854202F5A9B@mailbox.juilliard.edu> Message-ID: <20031109224541.GA22680@rogue.amk.ca> On Sun, Nov 09, 2003 at 05:07:37PM -0500, Jonathan Soons wrote: > output.write(unicode(txt, "iso-8859-1", "ignore")) unicode() returns a Unicode string, but the write() method wants an 8-bit string. You could see this by breaking this into two expressions: u = unicode(...) output.write(u) The conversion to Unicode is ignoring errors as you expect, but write() doesn't know what encoding to use for writing out the Unicode string. So, convert it to 8-bit via some encoding and be explicit: u = unicode(...) output.write(u.encode('iso-8859-1')) See http://effbot.org/zone/unicode-objects.htm for some additional notes. --amk From alan.gauld at blueyonder.co.uk Sun Nov 9 18:38:30 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 9 18:37:27 2003 Subject: [Tutor] 4 begginers questions ... (fwd) References: Message-ID: <002701c3a71a$94f924d0$6401a8c0@xp> FWIW I sent a mail directly from my tutorial mail address to David before seeing this one on tutor. But I'm sure answers from the group will help fill in the gaps I undoubtedly left uncovered. Alan G. > I am newbie at programming, and though I have allready > send this mail to Alan Gauld From alan.gauld at blueyonder.co.uk Sun Nov 9 18:43:18 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 9 18:42:14 2003 Subject: [Tutor] code blocks and output streams References: <20031109163032.83573.qmail@web41813.mail.yahoo.com> Message-ID: <002e01c3a71b$40752340$6401a8c0@xp> > I am trying to create a program that can have php-like > embedding of Python in html files. Apart from the academic curiosity of figuring out how, you do realize that there are at least two implementations of this already? I think the best known of which is PSP. Also the winall package contains a script to enable Python support for Active scripting within windows and IE. Zope of course does something somewhat similar at te server end and there are other solutions too. Thus if you are not just doing it for fun you should be able to find what you want already built. Alan G. From op73418 at mail.telepac.pt Mon Nov 10 07:16:59 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Nov 10 07:15:27 2003 Subject: [Tutor] code blocks and output streams In-Reply-To: <20031109163032.83573.qmail@web41813.mail.yahoo.com> References: <20031109163032.83573.qmail@web41813.mail.yahoo.com> Message-ID: On Sun, 9 Nov 2003 08:30:32 -0800 (PST), you wrote: >I am trying to create a program that can have php-like >embedding of Python in html files. First, I want to >start out with a program that can take an html file >with python code inside tags (ie something like >print 'hi'). In trying to do this, I found >two problems: executing complex code blocks (eg ones >that must have some indentation) and creating a new >output stream to direct things that are printed to. >All I know about how to do this is that the exec >keyword should be used to execute things and that I >should change sys.stdout to change the output stream. > Let me add a bit on A. Gauld's answer and suggest that you visit the Active State Python cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python There is a recipe by A. Martelli (the martellibot) called YAPTU, Yet Another Python Templating Utility. It may be all that you ever need as far as templating goes. The code is also worth studying. With my best regards, G. Rodrigues From mhansen at cso.atmel.com Mon Nov 10 11:39:44 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon Nov 10 11:39:07 2003 Subject: [Tutor] Re: code blocks and output streams (Daniel Ehrenberg) In-Reply-To: References: Message-ID: <3FAFBF50.6000709@cso.atmel.com> Generally I like to keep the presentation separate from the code and shy away from embedded scripting like ASP and PHP. To me, it just seems really messy and harder to follow. Ok, we're in HTML, oh..now we're in script, now back to HTML, followed by script that pumps out large chunks of HTML...(you get the picture) I heard that embedded scripting can be faster and easier. Anyone know if there have been any studies to prove it? What's the price you pay for "faster and easier"? Harder to maintain? I dunno. I suppose it can be a good way to learn by writing up an engine that does embedded scripting. > Subject: > [Tutor] code blocks and output streams > From: > Daniel Ehrenberg > Date: > Sun, 9 Nov 2003 08:30:32 -0800 (PST) > To: > pytutor > > >I am trying to create a program that can have php-like >embedding of Python in html files. First, I want to >start out with a program that can take an html file >with python code inside tags (ie something like >print 'hi'). In trying to do this, I found >two problems: executing complex code blocks (eg ones >that must have some indentation) and creating a new >output stream to direct things that are printed to. >All I know about how to do this is that the exec >keyword should be used to execute things and that I >should change sys.stdout to change the output stream. > >Daniel Ehrenberg > > > From tim.ronning at start.no Mon Nov 10 13:47:28 2003 From: tim.ronning at start.no (Tim Ronning) Date: Mon Nov 10 11:47:47 2003 Subject: [Tutor] More OOP In-Reply-To: <003e01c3a567$501b3240$6401a8c0@xp> References: <20031107143306.40409.qmail@web41812.mail.yahoo.com> <003e01c3a567$501b3240$6401a8c0@xp> Message-ID: P? Fri, 7 Nov 2003 19:42:43 -0000, skrev Alan Gauld : > Its not necessary but there is a natural synergy between GUI widgets > and objects. Also many GUI toolkits are implemented as object > frameworks > so you have to use objects anyway, you might as well make your code > fit in. > The attached code is a new little learning project of mine. And it somewhat ilustrates what I meant with "learning GUI" straight away. I think the code (albeit small) is fairly OO (correct me if I'm wrong). And it felt natural somehow to devide things into functions and a class and work with attributes of an object(instance). I know that if I had done this without a GUI I would have gone with batch style (the old autoexec.bat is haunting me!) So to the question, is this more difficult to learn? Or is it just moore to learn? I think, if you have good tools like QTDesigner+Eric/Blackadder or wxPython+wxGlade or pyfltk+flconvert, one can go GUI quite soon in ones learningprocess without overloading oneself with new stuff to learn. It took me 5 minutes to generate the FLTK GUI code in this script, and going through it, line by line, it's fairly easy to understand what each line do, even for a novice like myself. The concepts behind the core Python lines are a bit more difficult to learn, but for me personally I think the GUI portion helps me understand the Python objects because it introduces the concepts of object attributes(methodes). And somehow these attributes makes more sense when I can fixate them to visible widgets. Maybe it's just me? Anyway, here's the Python/FLTK code for a simple product/VAT calculator. Best regards Tim R. ------------------------------------------------------- #!/usr/bin/env python # -*-coding: iso-8859-1 -*- from fltk import * import sys # global object names window_main = None # type 'Fl_Window' from 'make_window()' gross_pris = None # type 'Fl_Value_Input' from 'make_window()' outp_umoms = None # type 'Fl_Value_Output' from 'make_window()' outp_mmoms = None # type 'Fl_Value_Output' from 'make_window()' outp_inntj = None # type 'Fl_Value_Output' from 'make_window()' outp_skyldig = None # type 'Fl_Value_Output' from 'make_window()' kalk_knapp = None # type 'Fl_Button' from 'make_window()' logo = None # type 'Fl_Box' from 'make_window()' pris_u_moms = 0 pris_m_moms = 0 inntjening = 0 skyldig_moms = 0 verdi = 0 def createobj(ptr): global pris_u_moms, pris_m_moms, inntjening, skyldig_moms i = Productcalc(verdi) pris_u_moms = i.umoms() pris_m_moms = i.mmoms() inntjening = i.inntj() skyldig_moms = i.skyldig() outp_umoms.value(pris_u_moms) outp_mmoms.value(pris_m_moms) outp_inntj.value(inntjening) outp_skyldig.value(skyldig_moms) def getValue(ptr): global verdi valuator = castWidget2Valuator(ptr) verdi = valuator.value() return verdi def make_window(): global window_main global gross_pris global outp_umoms global outp_mmoms global outp_inntj global outp_skyldig global kalk_knapp global logo window_main = Fl_Double_Window(404, 471, 308, 235, """Productcalculations""") gross_pris = Fl_Value_Input(100, 40, 90, 25, """Gross. price""") gross_pris.callback(getValue) gross_pris.label('''Gross. price''') outp_umoms = Fl_Value_Output(100, 75, 90, 25, """Price ex. vat""") outp_umoms.label('''Price ex. vat''') outp_umoms.value(pris_u_moms) outp_mmoms = Fl_Value_Output(100, 110, 90, 25, """Customer""") outp_mmoms.label('''Customer''') outp_mmoms.value(pris_m_moms) outp_inntj = Fl_Value_Output(100, 145, 90, 25, """Profit""") outp_inntj.label('''Profit''') outp_inntj.value(inntjening) outp_skyldig = Fl_Value_Output(100, 180, 90, 25, """VAT to pay""") outp_skyldig.label('''VAT to pay''') outp_skyldig.value(skyldig_moms) kalk_knapp = Fl_Button(205, 40, 90, 25, """Calculate""") kalk_knapp.labelsize(12) kalk_knapp.labelfont(1) kalk_knapp.label('''Calculate''') kalk_knapp.callback(createobj) logo = Fl_Box(50, 5, 215, 25, """Productcalculations v. 0.1.0""") logo.box(FL_SHADOW_FRAME) logo.labelfont(9) logo.label('''Productcalculations v. 0.1.0''') window_main.box(FL_PLASTIC_DOWN_BOX) window_main.color(53) window_main.labeltype(FL_NORMAL_LABEL) window_main.label('''Productcalculations''') window_main.end() return window_main class Productcalc: def __init__(self, g_pris): self.g_pris = g_pris def umoms(self): return self.g_pris+(self.g_pris*0.35) def mmoms(self): return (self.g_pris+(self.g_pris*0.35))*1.24 def inntj(self): return (self.g_pris*0.24)+((self.g_pris+(self.g_pris*0.35))- (self.g_pris+(self.g_pris*0.24))) def skyldig(self): return (((self.g_pris+(self.g_pris*0.35))*1.24)- (self.g_pris+(self.g_pris*0.35)))-(self.g_pris*0.24) if __name__=='__main__': window = make_window() window.show(len(sys.argv), sys.argv) Fl.run() -- _______________________________________ Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From jeffq16 at yahoo.com Mon Nov 10 14:07:21 2003 From: jeffq16 at yahoo.com (j j) Date: Mon Nov 10 14:07:27 2003 Subject: [Tutor] Help with a game Message-ID: <20031110190721.62976.qmail@web9802.mail.yahoo.com> Hey guys, i'm in a programmng class and i need some help. I made a game based off of the pygame example "Chimp" and it won't run. Maybe a little look over to see if i've missed something or if i've made a mistake. Thank you for your time guys. Later. import os, pygame from pygame.locals import * if not pygame.font:print 'Warning, fonts disabled' def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() class Gun(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('gun.bmp', -1) self.punching = 0 def update(self): pos = pygame.mouse.get_pos() self.rect.midtop = pos if self.punching: self.rect.move_ip(5, 10) def shoot(self, target): if not self.punching: self.punching = 1 hitbox = self.rect.inflate(-5,-5) return hitbox.colliderect(target.rect) def unshoot(self): self.punching = 0 class ship(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('new.bmp',-1) screen = pygame.display.get_suface() self.area = screen.get_rect() self.rect.topleft = 10, 10 self.move = 9 self.dizzy = 0 def update(self): if self.dizzy: self._spin() else: self._walk() def _walk(self): change = self.rect.move((self.move, 0)) if self.rect.left< self.area.left or \ self.rect.right > self.area.right: self.move = -self.move change = self.rect.move((self.move, 0)) self.image = pygame.transform.flip(self.image, 1, 0) self.rect = change def _change(self): center = self.rect.center self.dizzy = self.dizzy + 12 if self.dizzy >= 360: self.dizzy = 0 self.image = self.original else: rotate = pygame.transform.rotate self.image = rotate(self.original, slef.dizzy) self.rect = self.image.get_rect() self.rect.center = center def done(self): if not self.dizzy: self.dizzy = 1 self.original = self.image def main(): pygame.init() screen = pygame.display.set_mode((480, 60)) pygame.display.set_caption('Battleship') pygame.mouse.set_visible(0) backround = pygame.Surface(screen.get_size()) backround = backround.convert() backround.fill((250, 250, 250)) screen.blit(backround, (0, 0)) pygame.display.flip() clock = pygame.time.Clock() new = New() gun = Gun() allsprites = pygame.sprite.RenderPlain((gun, new)) while 1: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type == MOUSEBUTTONDOWN: if fist.punch(chimp): chimp.punched() elif event.type == MOUSEBUTTONUP: fist.unpunch() allsprites.update() screen.blit(backround, (0, 0)) allsprites.draw(screen) pygame.display.flip() --------------------------------- Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031110/cdf18d63/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Nov 10 15:08:28 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 10 15:08:31 2003 Subject: [Tutor] Help with a game In-Reply-To: <20031110190721.62976.qmail@web9802.mail.yahoo.com> Message-ID: On Mon, 10 Nov 2003, j j wrote: > Hey guys, i'm in a programmng class and i need some help. I made a game > based off of the pygame example "Chimp" and it won't run. Hello! Can you be more specific by what you mean by "won't run"? This question may sound silly, but we're actually a little serious here: does Python give out an exception or traceback? Do you see anything at all on the screen when you run the program? And have you been able to get other pygame examples to work yet? Many of us have already seen the Chimp example from pygame's web page: http://pygame.org/docs/tut/chimp/ChimpLineByLine.html so I'm pretty sure we can get this straightened out quickly. But we really do need more information about how the program is failing; otherwise, we can't effectively debug the situation. Good luck to you! From rcsmith at speakeasy.net Mon Nov 10 21:54:37 2003 From: rcsmith at speakeasy.net (Ryan Smith) Date: Mon Nov 10 21:54:42 2003 Subject: [Tutor] Local variables and functions Message-ID: Hello All, I have been reading "How To Think Like a Computer Scientist" to learn how to program in python since I am a complete newbie. I am having problems with declaring variables. Namely when they are local to a function. Below is an example that I have been working on: def counterLetters(fruit): fruit = "bananna" count = 0 for char in fruit: count = count + 1 print count print counterLetters(fruit) If I make the fruit variable global the function works, however when I have it local to the function, I get a print counterLetters(fruit) NameError: name 'fruit' is not defined, error message. Can someone please point out what I maybe missing? The concept of local variables seems pretty straight forward, but I have been struggling with this issue since the 4th chapter. I tried searching on google to see if someone else was having a similar problem, but to no avail. Thank you Ryan Smith -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 1972 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031110/1d2903cc/winmail.bin From fredm at smartypantsco.com Mon Nov 10 22:32:45 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Mon Nov 10 22:32:25 2003 Subject: [Tutor] IDLE and __name__, variables, etc. Message-ID: <5.1.0.14.0.20031111140612.0341a400@192.168.1.1> Hi: I wonder what I am doing wrong with my configuration of IDLE on Windows. My version of IDLE is IDLE 0.8, and I am running Python 2.2. If I try the usual structure of if __name__ == "__main__": then my programs don't run. By using print __name__ I have found that __name__ is set to the filename (less the ".py" extension), such as 'test' (when I save my program as test.py). As well, it used to be that after running my programs I could use the Python shell to see the values of various variables in my program or test individual subroutines. Now it comes up with "NameError: name 'a' is not defined", and I have to use 'test.a' to do view the variables. How do I set the behaviour back to be able to use the __name__ trick? In my file association, .py file are set to open using IDLE by the command: C:\PYTHON22\pythonw.exe C:\PYTHON22\Tools\idle\idle.pyw -e "%1" Thanks in anticipation, Fred Milgrom From dyoo at hkn.eecs.berkeley.edu Mon Nov 10 22:32:39 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 10 22:32:45 2003 Subject: [Tutor] Local variables and functions In-Reply-To: Message-ID: On Mon, 10 Nov 2003, Ryan Smith wrote: > > def counterLetters(fruit): > fruit = "bananna" > count = 0 > for char in fruit: > count = count + 1 > print count > print counterLetters(fruit) Hi Ryan, There's a small bug here: there's a "hardcoded" value for fruit here, on the line right below the 'def': > fruit = "bananna" Any definition of counterLetters() probably shouldn't depend on a particular fruit. It turns out that we can actually just yank it out: ### def counterLetters(fruit): count = 0 for char in fruit: count = count + 1 print count ### This'll still work because the input to counterLetters is a "fruit" --- counterLetters expects to take a fruit in when we call it. By the way, if we call counterLetters() with too few fruits: ### >>> counterLetters() Traceback (most recent call last): File "", line 1, in ? TypeError: counterLetters() takes exactly 1 argument (0 given) ### or too many fruits: ### >>> counterLetters("apple", "banana", "squash") Traceback (most recent call last): File "", line 1, in ? TypeError: counterLetters() takes exactly 1 argument (3 given) ### Python will say something fruity about it. > If I make the fruit variable global the function works, however when I > have it local to the function, I get a > print counterLetters(fruit) > NameError: name 'fruit' is not defined, error message. Hmmm... try something like: print counterLetters("apple") print counterLetters("breadfruit") We can even say something like: a = "apple" b = "breadfruit" print counterLetters(a) print counterLetters(b) print counterLetters(a + b) Do you see how the last example "print counterLetters(a+b)" works? > Can someone please point out what I maybe missing? The concept of local > variables seems pretty straight forward, but I have been struggling with > this issue since the 4th chapter. I tried searching on google to see if > someone else was having a similar problem, but to no avail. That's what the Tutor list is for. *grin* Please feel free to ask more questions about this; we'll be happy to point to toward more examples to make the concepts clearer. Good luck to you! From karl.fast at pobox.com Mon Nov 10 22:35:01 2003 From: karl.fast at pobox.com (Karl Fast) Date: Mon Nov 10 22:35:31 2003 Subject: [Tutor] win32com on activepython 2.3 Message-ID: <20031110213501.A19770@signal.lights.com> This probably isn't the right list for this question, but maybe some here can help. I've got code to create a win32 COM client. It worked fine under Python 2.2 (ActivePython). I just upgraded to the new ActivePython 2.3 and it doesn't work. In the shell if I do this: import win32com.client I get this traceback: Traceback (most recent call last): File "", line 1, in ? File "D:\python\Lib\site-packages\win32com\client\__init__.py", line 12, in ? import dynamic, gencache, pythoncom File "D:\python\Lib\site-packages\win32com\client\gencache.py", line 623, in ? __init__() File "D:\python\Lib\site-packages\win32com\client\gencache.py", line 52, in __ init__ Rebuild() File "D:\python\Lib\site-packages\win32com\client\gencache.py", line 610, in R ebuild _SaveDicts() File "D:\python\Lib\site-packages\win32com\client\gencache.py", line 57, in _S aveDicts raise RuntimeError, "Trying to write to a readonly gencache ('%s')!" \ RuntimeError: Trying to write to a readonly gencache ('C:\DOCUME~1\fast\LOCALS~1 \Temp\gen_py\2.3')! It all worked until I upgraded. I can go back to 2.2, but I don't know if this is (a) a problem with the latest ActivePython (b) a problem with the latest win32 extensions (c) me doing something wrong and getting away with in 2.2 Anyone able to help? I'm actually importing it like so, but I still get the same "trying to write to a readonly gencache" error.... from win32com.client import constants, Dispatch --karl From fredm at smartypantsco.com Mon Nov 10 22:54:42 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Mon Nov 10 22:54:26 2003 Subject: [Tutor] Local variables and functions In-Reply-To: Message-ID: <5.1.0.14.0.20031111143411.0343c380@192.168.1.1> Hi Ryan: You have a few different errors, but first look at how you have defined the variables 'fruit' in two different places: * In the subroutine - as in def counterLetters(fruit) * In the program calling the subroutine - as in print counterLetters(fruit), here the name fruit is not actually defined! First you have to understand how to pass values to subroutines and how subroutines treat names: If you have a subroutine defined by def counterLetters(fruit), then this means that the subroutine expects you to pass it a variable (which can have any name in the calling routine) and the subroutine will then deal with that variable under the variable name 'fruit'. So you can call that subroutine in any of the following ways: fruit = 'banana' counterFruit(fruit) or apple = 'apple' counterFruit(apple) or counterFruit('pear') In each case the subroutine will take what you have given it and call it 'fruit' locally. The names of the variables passed to the subroutine are local to that subroutine. You can use any name (even if it is in the global namespace), and it will treat it as a separate instance. Look at the following example: def myname(name): print "My name is", name name = 'Bill' myname('Fred') print "My name is", name Once you run it, you should get the following output: My name is Fred My name is Bill You can see from this that the variable 'name' in the main routine hasn't changed, although in the subroutine 'myname' the variable 'name' has a different value! Looking at your example, you will see that in your subroutine you say: - I will accept a variable called fruit as input to the routine, - but then you define fruit to be 'bananna', no matter what the input! Finally your calling routine is print counterLetters(fruit) . This is wrong, as counterFruit subroutine does not actually return anything! If you want a specific value to come back, you have to specify it as (for example): return count Otherwise you have an implied "return None" So the line print counterLetters(fruit) will print out 'None' Your program should therefore be as follows: def counterLetters(fruit): count = 0 for char in fruit: count = count + 1 print count fruit = "bananna" counterLetters(fruit) Hope this helps, Fred Milgrom At 09:54 PM 10/11/03 -0500, you wrote: >Hello All, > >I have been reading "How To Think Like a Computer Scientist" to learn how to >program in python since I am a complete newbie. I am having problems with >declaring variables. Namely when they are local to a function. Below is an >example that I have been working on: > >def counterLetters(fruit): > fruit = "bananna" > count = 0 > for char in fruit: > count = count + 1 > print count >print counterLetters(fruit) > >If I make the fruit variable global the function works, however when I have >it local to the function, I get a > print counterLetters(fruit) >NameError: name 'fruit' is not defined, error message. Can someone please >point out what I maybe missing? The concept of local variables seems pretty >straight forward, but I have been struggling with this issue since the 4th >chapter. I tried searching on google to see if someone else was having a >similar problem, but to no avail. > >Thank you > >Ryan Smith From darnold02 at sprynet.com Mon Nov 10 22:55:45 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Mon Nov 10 22:56:21 2003 Subject: [Tutor] Local variables and functions References: Message-ID: <04f401c3a807$b9b17c80$6f11ba3f@defaultcomp> ----- Original Message ----- From: "Danny Yoo" To: "Ryan Smith" Cc: Sent: Monday, November 10, 2003 9:32 PM Subject: Re: [Tutor] Local variables and functions > > > On Mon, 10 Nov 2003, Ryan Smith wrote: > > > > > def counterLetters(fruit): > > fruit = "bananna" > > count = 0 > > for char in fruit: > > count = count + 1 > > print count > > print counterLetters(fruit) > > Hi Ryan, > > There's a small bug here: there's a "hardcoded" value for fruit here, on > the line right below the 'def': > > > fruit = "bananna" > > > Any definition of counterLetters() probably shouldn't depend on a > particular fruit. It turns out that we can actually just yank it out: > > ### > def counterLetters(fruit): > count = 0 > for char in fruit: > count = count + 1 > print count > ### > the rest of Danny's (typically) excellent response. When you execute this function, you might notice something is still a little odd: >>> print counterLetters("banana") 6 None >>> We expect to see the 6, but where does the None come from? You see, we're really doing two things here: 1) calling counterLetters("banana"), and 2) printing its result. The counterLetters() function prints its count value within the function (the 6), but doesn't return a value (so its value is None). One small change will take care of this: def counterLetters(fruit): count = 0 for char in fruit: count = count + 1 return count >>> print counterLetters("banana") 6 All better. HTH, Don From missive at hotmail.com Tue Nov 11 01:17:06 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Nov 11 01:17:17 2003 Subject: [Tutor] Re: Help with a game Message-ID: >Hey guys, i'm in a programmng class and i need some help. I made a game >based off of the pygame example "Chimp" and it won't run. Maybe a little >look over to see if i've missed something or if i've made a mistake. > I see two problems: 1. Your main() function is at the same indentation as methods in class ship. Push that one out to the left. 2. Python does not automatically run the main() function. The idiom normally used to do that is: if __name__ == '__main__': main() Put that right at the end of your program. _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From glingl at aon.at Tue Nov 11 03:47:06 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue Nov 11 03:49:03 2003 Subject: [Tutor] Help with a game In-Reply-To: <20031110190721.62976.qmail@web9802.mail.yahoo.com> References: <20031110190721.62976.qmail@web9802.mail.yahoo.com> Message-ID: <3FB0A20A.70403@aon.at> Hi Jeff! If I wrote a program of more than 100 lines and then tried it out, it very probably won't run! For programming beginners I would suggest that you develop your programs incrementally, i. e. step by step. Break up your program in many tiny tasks and implement them on after the other. After having completed a task test it. Only if it works continue with the next task. (Don't they tell you things like that in your programming class?) This way you will find much more easily your mistakes, because there are only the recently added lines where your mistake has to be located. Moreover a long program may contain a lot of mistakes (which possibly interact in a complicated way) and of course it's harder to locate them all than to find only one or two in a small portion of your program. (Of course I've simplified things a bit, because the reason why some portion of added code doesn't work properly may lie in a design flaw of the rest of program ... . But even in this case you easily find out which small part of the code is in conflict with the rest ... and finally Python gives you it's error-massages which you definitly should not only read but also try to understand.) Concerning YOUR PROGRAM the problem with main(), observed by Lee, would have been found much earlier if you had tried to test it after you had written the first 10 to 15 lines. I observed - additionally to what Lee mentioned - that in main() you call the constructor of some not existing class New whereas you define a class ship() which is never used. (And please note, that we cannot try to run your program as we don't have the necessary bitmap files.) Regards, Gregor j j schrieb: > Hey guys, i'm in a programmng class and i need some help. I made a > game based off of the pygame example "Chimp" and it won't run. Maybe > a little look over to see if i've missed something or if i've made a > mistake. Thank you for your time guys. Later. > > import os, pygame > from pygame.locals import * > if not pygame.font:print 'Warning, fonts disabled' > > def load_image(name, colorkey=None): > fullname = os.path.join('data', name) > try: > image = pygame.image.load(fullname) > except pygame.error, message: > print 'Cannot load image:', fullname > raise SystemExit, message > image = image.convert() > if colorkey is not None: > if colorkey is -1: > colorkey = image.get_at((0,0)) > image.set_colorkey(colorkey, RLEACCEL) > return image, image.get_rect() > > class Gun(pygame.sprite.Sprite): > def __init__(self): > pygame.sprite.Sprite.__init__(self) > self.image, self.rect = load_image('gun.bmp', -1) > self.punching = 0 > def update(self): > pos = pygame.mouse.get_pos() > self.rect.midtop = pos > if self.punching: > self.rect.move_ip(5, 10) > def shoot(self, target): > if not self.punching: > self.punching = 1 > hitbox = self.rect.inflate(-5,-5) > return hitbox.colliderect(target.rect) > def unshoot(self): > self.punching = 0 > > class ship(pygame.sprite.Sprite): > def __init__(self): > pygame.sprite.Sprite.__init__(self) > self.image, self.rect = load_image('new.bmp',-1) > screen = pygame.display.get_suface() > self.area = screen.get_rect() > self.rect.topleft = 10, 10 > self.move = 9 > self.dizzy = 0 > def update(self): > if self.dizzy: > self._spin() > else: > self._walk() > def _walk(self): > change = self.rect.move((self.move, 0)) > if self.rect.left< self.area.left or \ > self.rect.right > self.area.right: > self.move = -self.move > change = self.rect.move((self.move, 0)) > self.image = pygame.transform.flip(self.image, 1, 0) > self.rect = change > def _change(self): > center = self.rect.center > self.dizzy = self.dizzy + 12 > if self.dizzy >= 360: > self.dizzy = 0 > self.image = self.original > else: > rotate = pygame.transform.rotate > self.image = rotate(self.original, slef.dizzy) > self.rect = self.image.get_rect() > self.rect.center = center > def done(self): > if not self.dizzy: > self.dizzy = 1 > self.original = self.image > def main(): > pygame.init() > screen = pygame.display.set_mode((480, 60)) > pygame.display.set_caption('Battleship') > pygame.mouse.set_visible(0) > backround = pygame.Surface(screen.get_size()) > backround = backround.convert() > backround.fill((250, 250, 250)) > > screen.blit(backround, (0, 0)) > pygame.display.flip() > clock = pygame.time.Clock() > new = New() > gun = Gun() > allsprites = pygame.sprite.RenderPlain((gun, new)) > while 1: > clock.tick(60) > for event in pygame.event.get(): > if event.type == QUIT: > return > elif event.type == KEYDOWN and event.key == K_ESCAPE: > return > elif event.type == MOUSEBUTTONDOWN: > if fist.punch(chimp): > chimp.punched() > elif event.type == MOUSEBUTTONUP: > fist.unpunch() > allsprites.update() > screen.blit(backround, (0, 0)) > allsprites.draw(screen) > pygame.display.flip() > > > > ------------------------------------------------------------------------ > Do you Yahoo!? > Protect your identity with Yahoo! Mail AddressGuard > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From Harm_Kirchhoff at mail.digital.co.jp Tue Nov 11 04:14:37 2003 From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp) Date: Tue Nov 11 04:15:22 2003 Subject: [Tutor] Comparing Numbers: Equal Numbers are Unequal when compared ? Message-ID: I thought it would be interesting to sink the following newbie catch into the archieves of this mailing list: In my code, 2 seemingly equal numbers, return a non-true comparison ! The following code in a program: if wwsales <> total[1]: print type(wwsales),'/',type(total[1]) print round(wwsales,2) == round(total[1],2) print str(wwsales) == str(total[1]) print wwsales-total[1] print 'cmp:',cmp(wwsales,total[1]) print 'Country Sales ',wwsales,' differ from total sales ',total[1] Produces the following output: / True True 2.98023223877e-008 cmp: 1 Country Sales 198970507.478 differ from total sales 198970507.478 As you can see, the floating point numbers seem unequal, however, when converted to strings, the resulting strings will be the same. If rounded, they also are the same. The subtraction shows a slight difference, that is apparently not printed so that the printed version of both numbers is also the same. You can avoid this by rounding both numbers before comparison, in case you can live with a sligt discrepancy. From eur at fiwihex.nl Tue Nov 11 05:07:45 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Tue Nov 11 05:09:02 2003 Subject: [Tutor] reading configuration file Message-ID: Hi all I've made a prog that reads a configuration file. While it works, I think it is butt-ugly and defintely not the way it should be done in Python. I tried to understand dictionaries and I tried to make eval() work. I failed. What is the good Python way to do what I do below? config file: >----------------------------------- # parameter settings for pump board and fan boards # from six fans and pump controller # pump controller settings CO2_soll 80 pump_1_manual_override 0 pump_1_manual_speed 120 pump_2_manual_override 0 pump_2_manual_speed 130 # Fan board settings: fan_manual_override 0 fan_manual_speed 140 >----------------------------------- code: >----------------------------------- #! /usr/local/bin/python #################################################################### # # program config.py # version 0.1 09-11-2003 # # reads configuration variables # writes them to boards # keeps file date: if file is touched, will make new file # ################################################################### import sys import os from time import strftime, localtime, sleep import random, fpformat from xwisp_fwx3 import fwx import string def parse_line(s): global CO2_soll global pump_1_manual_override, pump_1_manual_speed global pump_2_manual_override, pump_2_manual_speed global fan_manual_override, fan_manual_speed ls = string.split(s) if ls[0] == 'CO2_soll': CO2_soll = int(ls[1]) elif ls[0] == 'pump_1_manual_override': pump_1_manual_override = int(ls[1]) elif ls[0] == 'pump_1_manual_speed': pump_1_manual_speed = int(ls[1]) elif ls[0] == 'pump_2_manual_override': pump_2_manual_override = int(ls[1]) elif ls[0] == 'pump_2_manual_speed': pump_2_manual_speed = int(ls[1]) elif ls[0] == 'fan_manual_override': fan_manual_override = int(ls[1]) elif ls[0] == 'fan_manual_speed': fan_manual_speed = int(ls[1]) def read_config(): config = open('config','r') line = config.readline() while line: line = string.strip(line) if len(line) > 0 and line[0] != "#": # ignore comments and blank lines parse_line(line) line = config.readline() config.close() ############################ START OF PROGRAM ####################### # initialisation of global variables # pumps and CO2 CO2_soll = 81 # ppm /10 pump_1_manual_override = 1 # 0 = auto, 1 = manual pump_1_manual_speed = 121 # [0..255] pump_2_manual_override = 1 pump_2_manual_speed = 131 # Fan board settings: fan_manual_override = 1 # 0 = auto, 1 = manual fan_manual_speed = 141 read_config() print CO2_soll print pump_1_manual_override, pump_1_manual_speed print pump_2_manual_override, pump_2_manual_speed print fan_manual_override, fan_manual_speed #config_time_old = os.path.getmtime('config') #print config_time_old #config_time_old = os.path.getmtime('config') #print config_time_old #while True: # config_time = os.path.getmtime('config') # if config_time != config_time_old: # print config_time_old, config_time # make_configfile # config_time_old = os.path.getmtime('config') # parameter settings for pump board and fan boards # from six fans and pump controller # pump controller settings -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From op73418 at mail.telepac.pt Tue Nov 11 06:43:36 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Nov 11 06:42:05 2003 Subject: [Tutor] reading configuration file In-Reply-To: References: Message-ID: <9qi1rvobr9jlfi3855arr9lljmimvk5s00@4ax.com> On Tue, 11 Nov 2003 11:07:45 +0100, you wrote: >Hi all > >I've made a prog that reads a configuration file. While it works, I think it is >butt-ugly and defintely not the way it should be done in Python. > >I tried to understand dictionaries and I tried to make eval() work. I failed. >What is the good Python way to do what I do below? > >config file: > >>----------------------------------- ># parameter settings for pump board and fan boards ># from six fans and pump controller > ># pump controller settings >CO2_soll 80 >pump_1_manual_override 0 >pump_1_manual_speed 120 >pump_2_manual_override 0 >pump_2_manual_speed 130 > ># Fan board settings: >fan_manual_override 0 >fan_manual_speed 140 >>----------------------------------- > As you mention the best way to do this is to fill a dictionary where the keys are the "titles" and the values the numbers. Let me first fire up the interpreter and show you a typical use of a dictionary: >>> #Create an empty dictionary. >>> dct = {} >>> print dct {} >>> #Add a key, value pair. >>> dct["my key"] = "my value" >>> print dct {'my key': 'my value'} >>> #Rebind the associated value of the key. >>> dct["my key"] = 0 >>> print dct {'my key': 0} >>> This is enough for what we want to do. The idea is - read file - parse the contents into a dictionary From what I gleaned from your code there are also default values, filled up at initialization time. We can start there and instead of having a bunch of global variables we just stuff everything in a (global) dictionary. As in: DEFAULTDICT = {"CO2_soll": 81, "pump_1_manual_override": 1, "pump_1_manual_speed": 121, "pump_2_manual_override": 1, "pump_2_manual_speed": 131, "fan_manual_override": 1, "fan_manual_speed": 141} We use capital letters to signal that this is a constant and the user should not modify this dictionary in any way. Now we want to code a function, call it parse, that receives the *contents* of a file, a string, and parses it. A rule of thumb is that each function does only one thing. As such we *do not* put things like opening files and handling IO error conditions inside it. The usage of the function we envision is as in #Open file: filename is... the filename. f = file(filename) try: #Read whole file as one string. data = f.read() finally: #Close file f.close() #Parse data string. config = parse(data) Now we can go on with the function. Since we receive data as a string we must first split it in lines and then we go through each line reading it, putting the values inside the dictionary. def parse(s): """Parse a string into a dictionary.""" #Fetch a *copy* of the default dictionary. ret = DEFAULTDICT.copy() #Split lines. lines = s.split("\n") #Loop through lines. for line in lines: #Strip whitespace. line = line.strip() #Skip comment and blank lines. if line and line[0] != "#": #Split the line in the pair key, value values = line.split() #Fill dictionary. ret[values[0]] = int(values[1]) #Return dictionary. return ret The above function is commented all the way so you should be able to see what is going on. With my best regards, G. Rodrigues From project5 at redrival.net Tue Nov 11 07:52:08 2003 From: project5 at redrival.net (Andrei) Date: Tue Nov 11 07:54:29 2003 Subject: [Tutor] Re: reading configuration file References: Message-ID: <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net> Eur van Andel wrote on Tue, 11 Nov 2003 11:07:45 +0100: Hi, > I've made a prog that reads a configuration file. While it works, I think it is > butt-ugly and defintely not the way it should be done in Python. You should look at the ConfigParser module. > I tried to understand dictionaries and I tried to make eval() work. I failed. > What is the good Python way to do what I do below? A dictionary would indeed be a good way to make it elegant. A dictionary stores a value for each unique key. A key is a configuration setting in your case. Keys are a bit like variables: you can't have two variables with the same name, but different values, but you can have different variables with the same value. > config file: > CO2_soll 80 > pump_1_manual_override 0 > pump_1_manual_speed 120 > code: > import sys > import os > from time import strftime, localtime, sleep > import random, fpformat > from xwisp_fwx3 import fwx > import string Don't use the string module. Use string methods instead, e.g. instead of: string.split("bla bla") do: "bla bla".split(). ---code (untested)--- # here's an alternative # first, define an empty settings dictionary settings = {} # open the config file configfile = file("somefile.cfg", "r") # read line by line using "for line in " for line in configfile: # only read config setting if line is not # empty and does not start with "#" if line and line[0]!="#": # split in key-value pairs using string method key, value = line.split() # save them in dictionary; convert value to # integer (assuming you have only integers stored, # otherwise you'll need more intelligence here settings[key] = int(value) # close file configfile.close() -------- Now the settings dictionary looks like this: {"pump_1_manual_override": 0, "CO2_soll": 80, "pump_2_manual_speed": 130, <... etc.>} You can access a single setting from it using square brackets with in between them the key you want (like you do with lists), like this: print settings["pump_1_manual_override"] will print 0. > # initialisation of global variables You can initialize the key-value pairs in the dictionary too (doesn't change the loading method mentioned above), like this: settings = {"CO2_soll": 81, "pump_1_manual_override": 1, "pump_1_manual_speed": 121, <... etc.>, } I would also recommend *not* hard-coding those strings, but defining a number of constants (use uppercase for these constants) to use everywhere instead of typing the whole string: CO2SOLL = "CO2_soll" PUMP1MAN = "pump_1_manual_override" <... etc.> Then you can write this: settings = {CO2SOLL: 81, PUMP1MAN: 1, <... etc.>, } -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From karl.fast at pobox.com Tue Nov 11 08:06:02 2003 From: karl.fast at pobox.com (Karl Fast) Date: Tue Nov 11 08:06:36 2003 Subject: [Tutor] Re: reading configuration file In-Reply-To: <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net>; from project5@redrival.net on Tue, Nov 11, 2003 at 01:52:08PM +0100 References: <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net> Message-ID: <20031111070602.B19770@signal.lights.com> > You should look at the ConfigParser module. I'll second that. ConfigParser is good for .ini style config files. The Python Cookbook has a recipe illustrating basic usage: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 --karl From eur at fiwihex.nl Tue Nov 11 11:06:09 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Tue Nov 11 11:07:33 2003 Subject: [Tutor] Re: reading configuration file In-Reply-To: <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net> References: <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net> Message-ID: On Tue, 11 Nov 2003 13:52:08 +0100, Andrei wrote: >You should look at the ConfigParser module. I did. I couldn't understand. Karl Fast pointed me to an example that is much enlightening. Examples are hard to come by, in Python. The cookbook is nice. >A dictionary would indeed be a good way to make it elegant. A dictionary >stores a value for each unique key. A key is a configuration setting in >your case. Keys are a bit like variables: you can't have two variables with >the same name, but different values, but you can have different variables >with the same value. > >> config file: > >> CO2_soll 80 >> pump_1_manual_override 0 >> pump_1_manual_speed 120 > > >> code: > >> import sys >> import os >> from time import strftime, localtime, sleep >> import random, fpformat >> from xwisp_fwx3 import fwx >> import string > >Don't use the string module. Use string methods instead, e.g. instead of: > string.split("bla bla") >do: > "bla bla".split(). Ive seen that. Now I understand it. >---code (untested)--- ># here's an alternative ># first, define an empty settings dictionary >settings = {} ># open the config file >configfile = file("somefile.cfg", "r") ># read line by line using "for line in " >for line in configfile: > # only read config setting if line is not > # empty and does not start with "#" > if line and line[0]!="#": > # split in key-value pairs using string method > key, value = line.split() > # save them in dictionary; convert value to > # integer (assuming you have only integers stored, > # otherwise you'll need more intelligence here > settings[key] = int(value) ># close file >configfile.close() >-------- > >Now the settings dictionary looks like this: > > {"pump_1_manual_override": 0, "CO2_soll": 80, > "pump_2_manual_speed": 130, <... etc.>} > >You can access a single setting from it using square brackets with in >between them the key you want (like you do with lists), like this: > > print settings["pump_1_manual_override"] > >will print 0. I understand. So if I want to send a msg (to a chain of PIC controllers) with the format: Send( addr, cmd, data3, data2, data1, data0) I should use: Send (1, set_CO2_level, settings["CO2_soll"], settings["pump_1_max"], settings["pump_2_max"], settings[pump_1_manual_override"]) ? >> # initialisation of global variables > >You can initialize the key-value pairs in the dictionary too (doesn't >change the loading method mentioned above), like this: > > settings = {"CO2_soll": 81, > "pump_1_manual_override": 1, > "pump_1_manual_speed": 121, > <... etc.>, > } > >I would also recommend *not* hard-coding those strings, but defining a >number of constants (use uppercase for these constants) to use everywhere >instead of typing the whole string: > > CO2SOLL = "CO2_soll" > PUMP1MAN = "pump_1_manual_override" > <... etc.> > >Then you can write this: > > settings = {CO2SOLL: 81, > PUMP1MAN: 1, > <... etc.>, > } Yeah, well the names are explicit so the config file is human readable. These names are used in the PIC controllers too. So I rather not add yet another set of vars. PS. Why can't I just reply to the list? Now I have to set the reply address manually to tutor@python.org -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From eur at fiwihex.nl Tue Nov 11 11:13:16 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Tue Nov 11 11:14:33 2003 Subject: [Tutor] reading configuration file In-Reply-To: References: <9qi1rvobr9jlfi3855arr9lljmimvk5s00@4ax.com> Message-ID: On Tue, 11 Nov 2003 13:28:48 +0000, Gon?alo Rodrigues wrote: >>Or do I have to invoke config[...] ? >>Do the elements of the dictionary become global variables? > >You have to use the config dictionary. > >> >>Somehow the purpose of a dictionary eludes me. > >There are 2 main problems with your approach. > >- You are polluting the global namespace with a lot of variables. Yes, that is my FORTRAN heritage. Sorry. >Since they are all related isn't it better to put then all together? Yes. >And now you can do other things. For example, write a report based on >the config dictionary, e.g. something like > >>>> DEFAULTDICT = {"CO2_soll": 81} >>>> lst = ["The config dictionary."] >>>> for key, value in DEFAULTDICT.iteritems(): >... lst.append("%s = %s" % (key, value)) >... >>>> print "\n".join(lst) >The config dictionary. >CO2_soll = 81 > >Now try to do that with global variables. You are right. >- Global variables are almost always BAD. In your example they were >BAD because they got tightly coupled with the parse function. A >function should be like a black box: it receives input via the >arguments it receives, it gives output via return values. There should >be no more interaction with its environment. By using global variables I see that now too. I was used to globals. Sometimes, with not too many globals it is easier, like in a microcontroller. >as you did you made the parse function dependent on its environment - >a recipe for disaster. By avoiding global variables and having a >dictionary as a return value we have made our function like a black >box - no side effects on the surrounding environment. > >Any more question just holler, >G. Rodrigues > >P.S: In the future send emails *also* to the Tutor list. That way all >the participants can chime in and, hopefully, learn something. I replied. I see now that replying doesn't work on the tutor mailing list. Why? -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From project5 at redrival.net Tue Nov 11 11:33:56 2003 From: project5 at redrival.net (Andrei) Date: Tue Nov 11 11:36:26 2003 Subject: [Tutor] Re: Re: reading configuration file References: <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net> Message-ID: <17svornfsa78.1ltdm1k0v6oax$.dlg@40tude.net> Eur van Andel wrote on Tue, 11 Nov 2003 17:06:09 +0100: >>You should look at the ConfigParser module. > I did. I couldn't understand. Karl Fast pointed me to an example that is much > enlightening. Examples are hard to come by, in Python. The cookbook is nice. True for some topics. But usually it helps a lot to play with the module you don't understand at the Python interactive prompt. If you use a good one (like PyCrust which is included in wxPython), you get all kinds of tips and auto-completion to help you figure it out. > So if I want to send a msg (to a chain of PIC controllers) with the format: > > Send( addr, cmd, data3, data2, data1, data0) > > I should use: > > Send (1, set_CO2_level, settings["CO2_soll"], settings["pump_1_max"], > settings["pump_2_max"], settings[pump_1_manual_override"]) I don't know what PIC controllers are, but the syntax looks OK. >>I would also recommend *not* hard-coding those strings, but defining a >>number of constants (use uppercase for these constants) to use everywhere >>instead of typing the whole string: >> >> CO2SOLL = "CO2_soll" >> PUMP1MAN = "pump_1_manual_override" >> <... etc.> >> >>Then you can write this: >> >> settings = {CO2SOLL: 81, >> PUMP1MAN: 1, >> <... etc.>, >> } > Yeah, well the names are explicit so the config file is human readable. > These names are used in the PIC controllers too. So I rather not add yet > another set of vars. Use whatever works for you :). Note that defining those string constants does *not* influence the data or the config file, only the amount you type to get to that data. E.g. if you'd define your dictionary using the constants above and you'd print it, it would still show this: {"CO2_soll": 81, "pump_1_manual_override": 1, <... etc.>} NOT this: {CO2SOLL: 81, PUMP1MAN: 1, <... etc.>} Another difference is that if at some point you decide to e.g. change all pump_1_manual_override to pump_2_manual_override and the other way around, you have a single-point change to make if you use the string constants, while otherwise you'll have to run three global replaces. Generally speaking, I don't think it's wise to have overly long variable names or string constants. > PS. Why can't I just reply to the list? Now I have to set the reply address > manually to tutor@python.org Is this a general problem or with my post only? I read the list and post to it using the newsgroup interface offered by Gmane.org, so I don't really notice any problems. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Tue Nov 11 14:38:21 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 11 14:38:29 2003 Subject: [Tutor] Help with a game (fwd) Message-ID: Forwarding to tutor@python.org. Ok, good, the error message gives us something to look for. The error message is saying that the system can't find the 'main()' function: where is it? Please continue to reply to the address 'tutor@python.org'; I might be a little busy today, but the others on the Python-Tutor list can help you. ---------- Forwarded message ---------- Date: Tue, 11 Nov 2003 11:13:46 -0800 (PST) From: j j To: Danny Yoo Subject: Re: [Tutor] Help with a game I'm really sorry about the mistake of not including such information. An exception is raised when i attempt to run my program, this is what the interactive window says...(it also Traceback (most recent call last): File "C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "A:\game folder\game.py", line 129, in ? main() NameError: name 'main' is not defined Again, i've included my code and i'll add in the bitmap files i've obtained, any help is apprieciated and i thank you so much for helping me out. Here is the code and agian, Thank you. import os, pygame from pygame.locals import * if not pygame.font:print 'Warning, fonts disabled' def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() class Gun(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('gun.bmp', -1) self.punching = 0 def update(self): pos = pygame.mouse.get_pos() self.rect.midtop = pos if self.punching: self.rect.move_ip(5, 10) def shoot(self, target): if not self.punching: self.punching = 1 hitbox = self.rect.inflate(-5,-5) return hitbox.colliderect(target.rect) def unshoot(self): self.punching = 0 class ship(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('new.bmp',-1) screen = pygame.display.get_suface() self.area = screen.get_rect() self.rect.topleft = 10, 10 self.move = 9 self.dizzy = 0 def update(self): if self.dizzy: self._spin() else: self._walk() def _walk(self): change = self.rect.move((self.move, 0)) if self.rect.left< self.area.left or \ self.rect.right > self.area.right: self.move = -self.move change = self.rect.move((self.move, 0)) self.image = pygame.transform.flip(self.image, 1, 0) self.rect = change def _change(self): center = self.rect.center self.dizzy = self.dizzy + 12 if self.dizzy >= 360: self.dizzy = 0 self.image = self.original else: rotate = pygame.transform.rotate self.image = rotate(self.original, slef.dizzy) self.rect = self.image.get_rect() self.rect.center = center def done(self): if not self.dizzy: self.dizzy = 1 self.original = self.image def main(): pygame.init() screen = pygame.display.set_mode((480, 60)) pygame.display.set_caption('Battleship') pygame.mouse.set_visible(0) backround = pygame.Surface(screen.get_size()) backround = backround.convert() backround.fill((250, 250, 250)) screen.blit(backround, (0, 0)) pygame.display.flip() clock = pygame.time.Clock() new = New() gun = Gun() allsprites = pygame.sprite.RenderPlain((gun, new)) while 1: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type == MOUSEBUTTONDOWN: if fist.punch(chimp): chimp.punched() elif event.type == MOUSEBUTTONUP: fist.unpunch() allsprites.update() screen.blit(backround, (0, 0)) allsprites.draw(screen) pygame.display.flip() if __name__ == '__main__': main() >>> Danny Yoo wrote: On Mon, 10 Nov 2003, j j wrote: > Hey guys, i'm in a programmng class and i need some help. I made a game > based off of the pygame example "Chimp" and it won't run. Hello! Can you be more specific by what you mean by "won't run"? This question may sound silly, but we're actually a little serious here: does Python give out an exception or traceback? Do you see anything at all on the screen when you run the program? And have you been able to get other pygame examples to work yet? Many of us have already seen the Chimp example from pygame's web page: http://pygame.org/docs/tut/chimp/ChimpLineByLine.html so I'm pretty sure we can get this straightened out quickly. But we really do need more information about how the program is failing; otherwise, we can't effectively debug the situation. Good luck to you! --------------------------------- Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard From dyoo at hkn.eecs.berkeley.edu Tue Nov 11 14:41:00 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 11 14:41:06 2003 Subject: [Tutor] reading configuration file In-Reply-To: Message-ID: > >P.S: In the future send emails *also* to the Tutor list. That way all > >the participants can chime in and, hopefully, learn something. > I replied. I see now that replying doesn't work on the tutor mailing > list. Why? Hmmm... what email client are you using? Good email clients these days have a "reply to all" command that's specifically designed for things like mailing lists. Good luck! From eur at fiwihex.nl Tue Nov 11 16:57:51 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Tue Nov 11 16:59:13 2003 Subject: [Tutor] reading configuration file In-Reply-To: References: Message-ID: <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> On Tue, 11 Nov 2003 11:41:00 -0800 (PST), Danny Yoo wrote: >> >P.S: In the future send emails *also* to the Tutor list. That way all >> >the participants can chime in and, hopefully, learn something. >> I replied. I see now that replying doesn't work on the tutor mailing >> list. Why? > >Hmmm... what email client are you using? Good email clients these days Agent 1.8 >have a "reply to all" command that's specifically designed for things like >mailing lists. I hate "reply to all" especially if "out-of-office" bots do that. Good email clients have reply to all default off. If I reply to all, I send mail to the poster and the list. Is that the way I should do it? I'm used to mailing list where everything goes through the list. -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From david at graniteweb.com Tue Nov 11 17:02:49 2003 From: david at graniteweb.com (David Rock) Date: Tue Nov 11 17:02:55 2003 Subject: [Tutor] reading configuration file In-Reply-To: <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> References: <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> Message-ID: <20031111220249.GB22948@wdfs.graniteweb.com> * Eur van Andel [2003-11-11 22:57]: > On Tue, 11 Nov 2003 11:41:00 -0800 (PST), Danny Yoo > wrote: > > >> >P.S: In the future send emails *also* to the Tutor list. That way all > >> >the participants can chime in and, hopefully, learn something. > >> I replied. I see now that replying doesn't work on the tutor mailing > >> list. Why? > > > >Hmmm... what email client are you using? Good email clients these days > Agent 1.8 > > >have a "reply to all" command that's specifically designed for things like > >mailing lists. > I hate "reply to all" especially if "out-of-office" bots do that. > Good email clients have reply to all default off. > > If I reply to all, I send mail to the poster and the list. Is that the way I > should do it? I'm used to mailing list where everything goes through the list. If you use mutt, it has an option to reply to list. A nice variation on the reply to all options. -- 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/20031111/40a82583/attachment.bin From sigurd at 12move.de Tue Nov 11 17:38:34 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Nov 11 17:41:29 2003 Subject: [Tutor] reading configuration file In-Reply-To: <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> (Eur van Andel's message of "Tue, 11 Nov 2003 22:57:51 +0100") References: <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> Message-ID: On 11 Nov 2003, Eur van Andel <- eur@fiwihex.nl wrote: > I hate "reply to all" especially if "out-of-office" bots do that. > Good email clients have reply to all default off. ACK. > If I reply to all, I send mail to the poster and the list. Is that the way I > should do it? I'm used to mailing list where everything goes through the list. I always send replies only to the list address. I you write to a list you also should read it IMO. But there are some people who only read the list as digest; they will see replies later. Because of that some people here reply to all; i.e. to the list address and to the poster. Well what happens you get two emails if it happens that these people answer an e-mail with your address in the From or Cc. IMO if your e-mail client is able to only send an email to the list address than do that. But there are also reasons why it could be nice from you to send a Cc to the author (I don't send one; maybe I'm not a nice person?) Karl -- Please do *not* send copies of replies to me. I read the list From maddoxflower at web.de Mon Nov 10 16:21:20 2003 From: maddoxflower at web.de (maddox flower) Date: Tue Nov 11 18:42:54 2003 Subject: [Tutor] dynamic class method creation? Message-ID: <3FB00150.1040708@web.de> Hi there, here's my problem: I'd like to be able to create a class method dynamically. Some background information: I am using the Numeric module which provides a nice and fast function called sum() to sum over the elements of an array, but only along one axis of the array. Now, I want to sum over ALL elements of the array, so I need to apply sum() repeatedly. No problem here as long as I know the rank (i.e. the number of axes or dimensions) of the array beforehand. Which I do not. Of course I could just do the sum recursively, but unfortunately this is quite slow since it involves checking conditions at runtime. I need to run this sum business like maybe a couple of million times in my program, so slowness really is an issue. Consider the following class. Depending on the rank of the array which is used to create a class instance, the sumArray() method should look different: class ArrayContainer: def __init(self, array): self.array = array # create sumArray() method dynamically at this place! def sumArray(self): ## if rank of array = 1, i.e. only one axis (e.g. [1, 2, 3]): return sum(self.array) ## if rank of array = 2 (e.g. [[1, 2, 3], [4, 5, 6]]): return sum(sum(self.array)) ## if rank of array = n: return sum(sum(...sum(self.array)...)) # call sum() n times Actually checking the rank of the array INSIDE the sumArray() method again decreases speed significantly when running through the check some million times! So, how can this dynamic method creation be achieved? Can I use the exec statement for this? Cheers, Maddox From shobhan.challa at cybernetsoft.com Wed Nov 5 23:57:17 2003 From: shobhan.challa at cybernetsoft.com (Shobhan Challa) Date: Tue Nov 11 18:43:00 2003 Subject: [Tutor] jpg to doc conversion Message-ID: <1068094638.14514.5.camel@shobs.cybernetsoft.com> Hi Alan, Yes, what i mean is typically the jpg files are images of text, and i want to convert them to Microsoft Word .doc format. Any ideas about any Open Source apps...?? Thanks and regards Schalla > Im new to python, I have an idea about converting jpg/jpeg image files > into doc files. The jpg files contain text and the text should be > converted into doc format. You mean the jpg files are images of text - eg from a scanner? And you want to perform a kind of OCR function on them to convert it to text, but in a Doc format (I assume you mean Microsoft Word .doc and not any other proprietary format called .doc - there are several!) Before we all start jumping in with ideas can you confirm that's what you mean please? Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031106/47bd0c36/attachment.html From lsloan-000002 at umich.edu Tue Nov 11 16:25:47 2003 From: lsloan-000002 at umich.edu (Lance E Sloan) Date: Tue Nov 11 18:43:09 2003 Subject: [Tutor] special object method for method calls? Message-ID: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> Is there a special method that's called when the method of a class is called? That is, I know __getattr__() is called when an attribute of a class is requested. Is there something like __callmethod__()? -- Lance E Sloan 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 clay at shirky.com Tue Nov 11 18:58:45 2003 From: clay at shirky.com (Clay Shirky) Date: Tue Nov 11 18:58:57 2003 Subject: [Tutor] Speeding up file processing? In-Reply-To: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> Message-ID: So I have a webserver log, and need to post process it a bit. I wrote a simple script in both python and perl, and the perl runs just about twice as fast. Here are the two scripts -- the logic is line-by-line identical, except for one try/except idiom. My question is: what should I do to speed up the python? #!/usr/bin/python import re f = open("today.test") # the server log file fields = [] for line in f: if re.match('^shirky.com', line): # find hits from my site fields = line.split() try: referer = fields[11] # grab the referer except: continue # continue if there is a mangled line referer = re.sub('"', '', referer) if re.search("shirky", referer): continue # ignore internal links if re.search("-", referer): continue # ...and email clicks referer = re.sub("www.", "", referer) print referer # ----------------------------------------------- #!/usr/bin/perl open (F, "today.test"); while () { if (/^shirky.com/) { @fields = split; $referer = $fields[11]; $referer =~ s/"//g; next if $referer =~ /shirky/; next if $referer =~ /-/; $referer =~ s/www.//; print "$referer\n"; } } From dyoo at hkn.eecs.berkeley.edu Tue Nov 11 19:16:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 11 19:16:54 2003 Subject: [Tutor] special object method for method calls? In-Reply-To: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> Message-ID: On Tue, 11 Nov 2003, Lance E Sloan wrote: > Is there a special method that's called when the method of a class is > called? That is, I know __getattr__() is called when an attribute of a > class is requested. Is there something like __callmethod__()? Hi Lance, __getattr__() applies equally well to methods as well as other attributes. When Python sees something like: foo.bar() Python will first do a getattr() of 'bar' from foo. Once it gets the attribute, it'll __call__() that attribute. ### >>> class Foo: ... def bar(self): print "hi!" ... >>> foo = Foo() >>> bar = foo.bar >>> bar > >>> bar() hi! ### Python's uniform object system is pretty nice, though it means that we have to be careful that our regular attribute names don't collide with our method names, since they share the same namespace within our instance. Anyway, since attribute access goes through __getattr__(), we can do something like this: ### >>> class DoubleTalk: ... def __getattr__(self, attr): ... def function(): ... print attr, attr ... return function ... >>> d = DoubleTalk() >>> d.jump() jump jump >>> d.leap() leap leap >>> d.hello() hello hello ### I hope this helps! From pythontutor at venix.com Tue Nov 11 19:41:42 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Nov 11 19:41:47 2003 Subject: [Tutor] dynamic class method creation? In-Reply-To: <3FB00150.1040708@web.de> References: <3FB00150.1040708@web.de> Message-ID: <3FB181C6.6040300@venix.com> http://www-106.ibm.com/developerworks/linux/library/l-cpnum.html?ca=dgr-lnxw06NumericalPython Charming Python: Numerical Python This article uses a flat attribute to sum the whole array directly. I think your code would look like: sum(self.array.flat) Hope this helps. (I haven't used numeric or numarray myself.) maddox flower wrote: > Hi there, > > here's my problem: > I'd like to be able to create a class method dynamically. > Some background information: I am using the Numeric module which > provides a nice and fast function called sum() to sum over the elements > of an array, but only along one axis of the array. Now, I want to sum > over ALL elements of the array, so I need to apply sum() repeatedly. No > problem here as long as I know the rank (i.e. the number of axes or > dimensions) of the array beforehand. Which I do not. Of course I could > just do the sum recursively, but unfortunately this is quite slow since > it involves checking conditions at runtime. I need to run this sum > business like maybe a couple of million times in my program, so slowness > really is an issue. > > Consider the following class. Depending on the rank of the array which > is used to create a class instance, the sumArray() method should look > different: > > class ArrayContainer: > def __init(self, array): > self.array = array > # create sumArray() method dynamically at this place! > > def sumArray(self): > ## if rank of array = 1, i.e. only one axis (e.g. [1, 2, 3]): > return sum(self.array) > ## if rank of array = 2 (e.g. [[1, 2, 3], [4, 5, 6]]): > return sum(sum(self.array)) > ## if rank of array = n: > return sum(sum(...sum(self.array)...)) # call sum() n times > > Actually checking the rank of the array INSIDE the sumArray() method > again decreases speed significantly when running through the check some > million times! > > So, how can this dynamic method creation be achieved? Can I use the exec > statement for this? > > Cheers, Maddox > > > > _______________________________________________ > 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 missive at hotmail.com Tue Nov 11 19:47:36 2003 From: missive at hotmail.com (Lee Harr) Date: Tue Nov 11 19:47:42 2003 Subject: [Tutor] Re: Speeding up file processing? Message-ID: #!/usr/bin/python import re f = open("today.test") # the server log file fields = [] for line in f: if re.match('^shirky.com', line): # find hits from my site fields = line.split() try: referer = fields[11] # grab the referer except: continue # continue if there is a mangled line referer = re.sub('"', '', referer) if re.search("shirky", referer): continue # ignore internal links if re.search("-", referer): continue # ...and email clicks referer = re.sub("www.", "", referer) print referer I am not sure, but I think string methods will be faster than using all those regular expressions: if line.startswith('shirky') referer.replace('"', '') referer.find('shirky') >= 0 Makes the code easier to read (for me) anyhow. If you try it, let us know if it helps... _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From abli at freemail.hu Tue Nov 11 19:51:23 2003 From: abli at freemail.hu (Abel Daniel) Date: Tue Nov 11 19:51:20 2003 Subject: [Tutor] Re: special object method for method calls? In-Reply-To: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> (Lance E. Sloan's message of "Tue, 11 Nov 2003 16:25:47 -0500") References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> Message-ID: Lance E Sloan writes: > Is there a special method that's called when the method of a class is > called? That is, I know __getattr__() is called when an attribute of > a class is requested. Is there something like __callmethod__()? See http://python.org/doc/current/ref/callable-types.html Note that the _method's_ __call__ method will be called, not the class's, so its not exactly what you wanted. However, it's pretty easy to fake it: class A: def __getattr__(self, name): def f(*a, **kw): self.notify() print 'called %s' % name return f def notify(self): print 'our method was called' >>> a=A() >>> a.foo() our method was called called foo >>> a.bar >>> a.zork() our method was called called zork >>> f=a.bar >>> f() our method was called called bar >>> -- Abel Daniel p.s. you might also want to look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078 (I have to admit I have no idea how that works.) From karl.fast at pobox.com Tue Nov 11 19:51:25 2003 From: karl.fast at pobox.com (Karl Fast) Date: Tue Nov 11 19:52:09 2003 Subject: [Tutor] dynamic class method creation? In-Reply-To: <3FB00150.1040708@web.de>; from maddoxflower@web.de on Mon, Nov 10, 2003 at 10:21:20PM +0100 References: <3FB00150.1040708@web.de> Message-ID: <20031111185125.A12162@signal.lights.com> > I'd like to be able to create a class method dynamically. This recipe from the python cookbook might help: Dynamically added methods to a class http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732 --karl From jeff at ccvcorp.com Tue Nov 11 20:01:56 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Nov 11 19:58:06 2003 Subject: [Tutor] special object method for method calls? In-Reply-To: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> Message-ID: <3FB18684.6020808@ccvcorp.com> Lance E Sloan wrote: > > Is there a special method that's called when the method of a class is > called? That is, I know __getattr__() is called when an attribute of a > class is requested. Is there something like __callmethod__()? Well, there's a builtin iscallable() function, so you could try something like: def __getattr__(self, attr): if iscallable(self.__dict__[attr]): # do whatever here return self.__dict__[attr] However, this isn't exactly what you asked for -- it will take that action whenever a callable attribute is looked up, not specifically when it's called. Thus, item.method() # This triggers your special action func = item.method # and so does this func() # but this doesn't Methods are usually only looked up when they're called, and most usage of methods doesn't involve caching references, so there's a good chance that this will (at least mostly) work for your purposes... Jeff Shannon Technician/Programmer Credit International From amk at amk.ca Tue Nov 11 21:29:46 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue Nov 11 21:30:26 2003 Subject: [Tutor] Speeding up file processing? In-Reply-To: References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> Message-ID: <20031112022946.GA32502@rogue.amk.ca> On Tue, Nov 11, 2003 at 06:58:45PM -0500, Clay Shirky wrote: > for line in f: > if re.match('^shirky.com', line): # find hits from my site > fields = line.split() > try: referer = fields[11] # grab the referer > except: continue # continue if there is a mangled line > referer = re.sub('"', '', referer) > if re.search("shirky", referer): continue # ignore internal links > if re.search("-", referer): continue # ...and email clicks > referer = re.sub("www.", "", referer) > print referer While this code is using the re module, it's not doing anything that can't be done with string operations; all of the things being searched for are fixed strings such as 'shirky.com', not patterns such as \w+[.](com|net). An untested rewrite: for line in f: if line.startswith('shirky.com'): fields = line.split() try: referer = fields[11] # grab the referer except: continue # continue if there is a mangled line referer = referer.replace('"', '') if referer.find("shirky") == -1: continue # ignore internal links if '-' in referer: continue # ...and email clicks referer = referer.replace('www.', "") print referer In Python 2.3, referer.find("shirky") == -1 can be replaced with the more readable "if ('shirky' in referer): ...". Perl avoids using the C stdio library for the sake of speed, using the internals of the FILE structure instead, while Python sticks to strict ANSI C. This results in a certain speed penalty, but I don't know how much; you could try just running the two loops with a 'pass' in the body to compare the I/O overhead. --amk From abli at freemail.hu Tue Nov 11 21:49:40 2003 From: abli at freemail.hu (Abel Daniel) Date: Tue Nov 11 21:49:34 2003 Subject: [Tutor] Re: special object method for method calls? In-Reply-To: <3FB18684.6020808@ccvcorp.com> (Jeff Shannon's message of "Tue, 11 Nov 2003 17:01:56 -0800") References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> <3FB18684.6020808@ccvcorp.com> Message-ID: Jeff Shannon writes: > def __getattr__(self, attr): > if iscallable(self.__dict__[attr]): > # do whatever here > return self.__dict__[attr] This won't work. From http://python.org/doc/current/ref/attribute-access.html: "Note that if the attribute is found through the normal mechanism, __getattr__() is not called." So calling self.__dict__[attr] in __getattr__ will result in a KeyError. -- Abel Daniel From abli at freemail.hu Tue Nov 11 22:07:19 2003 From: abli at freemail.hu (Abel Daniel) Date: Tue Nov 11 22:07:14 2003 Subject: [Tutor] Re: Speeding up file processing? References: Message-ID: Clay Shirky writes: > So I have a webserver log, and need to post process it a bit. I wrote a > simple script in both python and perl, and the perl runs just about twice as > fast. > > Here are the two scripts -- the logic is line-by-line identical, except for > one try/except idiom. My question is: what should I do to speed up the > python? [...snipped code...] I haven't tried it but maybe the following help: - merge the two 'if re.search(): continue' into one search - use pre-compiled regexes (i.e. use re.compile. In your python version you to compile the same regexes for every line, and I think that's what slows you down.) -- Abel Daniel ps. Please don't write to a mailling list by replying to an unrelated mail. Your post will show up in the wrong place for mail-clients which can handle threading. From jeff at ccvcorp.com Tue Nov 11 22:43:03 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Nov 11 22:39:08 2003 Subject: [Tutor] Re: special object method for method calls? In-Reply-To: References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> <3FB18684.6020808@ccvcorp.com> Message-ID: <3FB1AC47.2050606@ccvcorp.com> Abel Daniel wrote: > Jeff Shannon writes: > > >>def __getattr__(self, attr): >> if iscallable(self.__dict__[attr]): >> # do whatever here >> return self.__dict__[attr] > > > This won't work. From http://python.org/doc/current/ref/attribute-access.html: > > "Note that if the attribute is found through the normal > mechanism, __getattr__() is not called." > > So calling self.__dict__[attr] in __getattr__ will result in a > KeyError. Hm, you're right. That's odd, I'd have *sworn* that __getattr__() could be used to intercept lookups of existing attributes. Or at least that *something* could be. Unfortunately I don't have time to track this down right now... Jeff Shannon Technician/Programmer Credit International From eur at fiwihex.nl Wed Nov 12 06:32:06 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Wed Nov 12 06:32:23 2003 Subject: [Tutor] calling a function with a variable number of arguments Message-ID: Hi Am I correct in assuming that a function: def funct_1(a0, a1=1, a2=2) can be called with either 1, 2 or 3 arguments? And if I call it: funct_1(4, 4) a2 will stay 2? And so to modify the default value for a2, three arguments are needed? Where can I find this in the manual? -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From eur at fiwihex.nl Wed Nov 12 06:40:06 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Wed Nov 12 06:40:18 2003 Subject: [Tutor] trailing comma behind print '\n'? Message-ID: Hi Is it correct that print always generates a newline, so that: print '\n' will generate two? Undersigned newbie is confused. Should he use print '\n', or print for generating newlines? -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From darnold02 at sprynet.com Wed Nov 12 07:22:34 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Wed Nov 12 07:23:15 2003 Subject: [Tutor] trailing comma behind print '\n'? References: Message-ID: <085501c3a917$b2e77100$6f11ba3f@defaultcomp> ----- Original Message ----- From: "Eur van Andel" To: Sent: Wednesday, November 12, 2003 5:40 AM Subject: [Tutor] trailing comma behind print '\n'? > Hi > > Is it correct that print always generates a newline, so that: > > print '\n' > > will generate two? > Correct. > Undersigned newbie is confused. Should he use > > print '\n', > > or > > print > > for generating newlines? > Depends on how much you like to type. ; ) A lone 'print' should suffice. > -- > Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com > Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl > phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 > HTH, Don From amk at amk.ca Wed Nov 12 07:34:40 2003 From: amk at amk.ca (A.M. Kuchling) Date: Wed Nov 12 07:35:33 2003 Subject: [Tutor] calling a function with a variable number of arguments In-Reply-To: References: Message-ID: <20031112123440.GA1778@rogue.amk.ca> On Wed, Nov 12, 2003 at 12:32:06PM +0100, Eur van Andel wrote: > Am I correct in assuming that a function: > def funct_1(a0, a1=1, a2=2) > can be called with either 1, 2 or 3 arguments? Correct. > And if I call it: > funct_1(4, 4) > a2 will stay 2? > And so to modify the default value for a2, three arguments are needed? Also correct. If you specify keyword arguments, you can supply them in any order, e.g. funct_1(a1=4, a2=3, a0=1). You couldn't leave off the 'a0' value because it has no specified default; you'd get a TypeError exception with the message 'funct_1() takes at least 1 non-keyword argument (0 given)'. http://www.python.org/doc/current/ref/calls.html explains this very formally -- so formally that it might be confusing. Anyone know of a better explanation of Python function calls? --amk From project5 at redrival.net Wed Nov 12 08:11:50 2003 From: project5 at redrival.net (Andrei) Date: Wed Nov 12 08:14:17 2003 Subject: [Tutor] Re: calling a function with a variable number of arguments References: Message-ID: <12z3b15xcj1dw$.1cef2hoypbo3g.dlg@40tude.net> Eur van Andel wrote on Wed, 12 Nov 2003 12:32:06 +0100: > Hi > > Am I correct in assuming that a function: > > def funct_1(a0, a1=1, a2=2) > > can be called with either 1, 2 or 3 arguments? Yep. > And if I call it: > > funct_1(4, 4) > > a2 will stay 2? Yep. > And so to modify the default value for a2, three arguments are needed? Nope. If you use arguments with default values, you can do this: funct_1(45, a2=30) a1 will then keep its default value. > Where can I find this in the manual? Paragraphs 4.6 and 4.7 of the tutorial. -- Yours, Andrei ===== Mail address in header catches spam. 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 annika.scheffler at gmx.net Wed Nov 12 08:52:29 2003 From: annika.scheffler at gmx.net (Annika Scheffler) Date: Wed Nov 12 08:54:50 2003 Subject: [Tutor] access all files in one directory? Message-ID: <24636.1068645149@www2.gmx.net> Hi, I would like to access all files in one directory, read their contents. I need them for a program. So far I have a very simple program which takes two input files and creates one output file. I need to give the program file1 and then one file after another in order to compare it with file1. In conclusion I need to create an output file for each of the files, except file1. All the files I need (except file1) are in one directory. Can I give my program that directory to loop over all the files in it? Thanks very much for your help, Annika -- Ravens fly in flights, but the eagle flies alone. NEU F?R ALLE - GMX MediaCenter - f?r Fotos, Musik, Dateien... Fotoalbum, File Sharing, MMS, Multimedia-Gru?, GMX FotoService Jetzt kostenlos anmelden unter http://www.gmx.net +++ GMX - die erste Adresse f?r Mail, Message, More! +++ From op73418 at mail.telepac.pt Wed Nov 12 09:50:53 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 12 09:49:09 2003 Subject: [Tutor] access all files in one directory? In-Reply-To: <24636.1068645149@www2.gmx.net> References: <24636.1068645149@www2.gmx.net> Message-ID: <3vh4rvsrhb89v13pufaa90s3rcbu26eeoj@4ax.com> On Wed, 12 Nov 2003 14:52:29 +0100 (MET), you wrote: >Hi, > >I would like to access all files in one directory, read their contents. I >need them for a program. > >So far I have a very simple program which takes two input files and creates >one output file. >I need to give the program file1 and then one file after another in order to >compare it with file1. In conclusion I need to create an output file for >each of the files, except file1. All the files I need (except file1) are in one >directory. >Can I give my program that directory to loop over all the files in it? > What you need is the listdir function is the os module. Firing up the interpreter: >>> import os >>> print os.listdir.__doc__ listdir(path) -> list_of_strings Return a list containing the names of the entries in the directory. path: path of directory to list The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory. >>> for elem in os.listdir("C:\\"): ... print elem ... AUTOEXEC.BAT [rest of list snipped] With my best regards, G. Rodrigues From op73418 at mail.telepac.pt Wed Nov 12 06:24:50 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 12 12:07:04 2003 Subject: [Tutor] Re: special object method for method calls? In-Reply-To: <3FB1AC47.2050606@ccvcorp.com> References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> <3FB18684.6020808@ccvcorp.com> <3FB1AC47.2050606@ccvcorp.com> Message-ID: On Tue, 11 Nov 2003 19:43:03 -0800, you wrote: >Abel Daniel wrote: > >> Jeff Shannon writes: >> >> >>>def __getattr__(self, attr): >>> if iscallable(self.__dict__[attr]): >>> # do whatever here >>> return self.__dict__[attr] >> >> >> This won't work. From http://python.org/doc/current/ref/attribute-access.html: >> >> "Note that if the attribute is found through the normal >> mechanism, __getattr__() is not called." >> >> So calling self.__dict__[attr] in __getattr__ will result in a >> KeyError. > >Hm, you're right. That's odd, I'd have *sworn* that __getattr__() >could be used to intercept lookups of existing attributes. Or at >least that *something* could be. Unfortunately I don't have time to >track this down right now... > What you want is __getattribute__ which intercepts *every* attribute lookup. It only works with *new-style* classes though. With my best regards, G. Rodrigues From eur at fiwihex.nl Wed Nov 12 19:05:39 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Wed Nov 12 19:05:50 2003 Subject: [Tutor] newbie bragging about code Message-ID: <1gh5rvcojfjvdafjk6vob26lorfvepcq5l@4ax.com> Hi I sent the prog hereunder to my father with comments. Maybe these comments will help others or draw better comments. The program sends data to and from a string of PIC microcontrollers that measure 4 temperatures of a water to air heat exchanger. These messages leave the PC as hex strings like ;0123FAFAFAFACC where ; is the delimiter, 01 the address, 23 the command, FA the four data bytes and CC the checksum. They get cnverted by a PIC converter board to pulse duration code msgs on a two signal wire bus with hardware node costs of $2 (two RJ 6/6 amp connectors and 74HC14). The bus carries power too. I need to connect several 1000's of these later. The PIC controllers (16F819) have a bootloader that allows reprogramming of the application program in flash memory. The program hereunder deals just with receiving and sending temperatures. Output first: >/home/eur # cd xwisp/ >/home/eur/xwisp # python almeria4.py >Run all PICs run (from bootloader to app) >1 0x4E4D4E4E 2 0x4B464A49 3 0x4C4D4F4E 4 0x4C4A4B4C >5 0x53534F53 6 0x4B4D544F 7 0x53515152 8 0x4F4E4E54 raw-output, nice debugging. Only data in recvd msgs shown > >1 15.6 15.4 15.6 15.6 2 15.0 14.0 14.8 14.6 3 15.2 15.4 15.8 15.6 >4 15.2 14.8 15.0 15.2 5 16.6 16.6 15.8 16.6 6 15.0 15.4 16.8 15.8 >7 16.6 16.2 16.2 16.4 8 15.8 15.6 15.6 16.8 15.6 15.4 15.7 15.7 8 PICs with board number and 4 temps each. last four are average temps that get send to first PIC (which has no sensors, it controls the water flow) > > >1 0x4E4D4E4E 2 0x4B464A49 3 0x4C4D4F4E 4 0x4C4A4B4C >5 0x52535053 6 0x4B4D544F 7 0x53515152 8 0x4F4E4E54 > >1 15.6 15.4 15.6 15.6 2 15.0 14.0 14.8 14.6 3 15.2 15.4 15.8 15.6 >4 15.2 14.8 15.0 15.2 5 16.4 16.6 16.0 16.6 6 15.0 15.4 16.8 15.8 >7 16.6 16.2 16.2 16.4 8 15.8 15.6 15.6 16.8 15.6 15.4 15.8 15.7 Quite cold in here. Netherlands in winter, Pythoneer to cheap to turn on heating after office hours. > > >1 0x4D4D4E4E 2 0x4B464A4A 3 0x4C4D4F4E 4 0x4C4A4B4C >5 0x52534E53 6 0x4C4D544F 7 0x53515151 8 0x4E4D4D54 > >1 15.4 15.4 15.6 15.6 2 15.0 14.0 14.8 14.8 3 15.2 15.4 15.8 15.6 >4 15.2 14.8 15.0 15.2 5 16.4 16.6 15.6 16.6 6 15.2 15.4 16.8 15.8 >7 16.6 16.2 16.2 16.2 8 15.6 15.4 15.4 16.8 15.6 15.4 15.7 15.7 > Code follows, inline bragging after that: #################################################################### # # program almeria3.py # makes logfile # polls boards for temperatures # writes temperatures to screen # records temperatures in logfile # makes new logfile every midnight # can output raw packets # # to do: config file, separate data routine for msgs # fault-tolerant: no output (or the lack of output) # may NOT crash the program # re-boot boards if necessary # send average temps to pump board # ################################################################### from time import strftime, localtime, sleep import random, fpformat import sys from xwisp_fwx3 import fwx import string def make_logfile(): logfile = open(strftime("%d-%m-%Y_%H-%M.log", localtime()),'w') #logfile = open(strftime("%d_%H%M.log", localtime()),'w') # MSDOS logfile.write('temperatures and pump duty cycles\n') logfile.write('from six fans and pump controller\n') return(logfile) def make_rawfile(): rawfile = open(strftime("%d-%m-%Y_%H-%M.raw", localtime()),'w') #logfile = open(strftime("%d_%H%M.log", localtime()),'w') # MSDOS logfile.write('raw msgs from fwx boards\n') return(rawfile) def data_send_X(B3,B2,B1, B0): # makes integer that is a 8-char in hex data = '%02X' % B3 + '%02X' % B2 + '%02X' % B1 + '%02X' % B0 data = long(data, 16) #print '%08X' % data return data def send_temps_to_pumpcontr(Tai, Tao, Twl, Twh): Response = f.Send_Receive(75, data_send_X(Tai*5, Tao*5, Twl*5, Twh*5), 1) # pump_controller has address 1 #print Response ############################ START OF PROGRAM ####################### number_of_boards = 8 # should be in config file raw_output = True T = [ [None] * 5 for i in range(1,number_of_boards+2) ] # array of [0..num][0..4] f = fwx( '/dev/cuaa0' ) Errors = 0 f.CMD_RUN() date = localtime()[2] logfile = make_logfile() if raw_output: rawfile = make_rawfile() # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ START OF MAIN LOOP $$$$$$$$$$$$$$ while True: minutes, seconds = localtime()[4], localtime()[5] if date != localtime()[2]: # a new day has dawned, open a new logfile logfile = make_logfile() date = localtime()[2] if minutes % 1 == 0: if seconds % 10 == 0: if raw_output: rawfile.write(strftime('"%d-%m-%Y %H:%M:%S" ', localtime())) for n in range(1, number_of_boards + 1): Response = f.Send_Receive(33, Address = n) if Response == None: if raw_output: print '%1d None ' % n, rawfile.write('%1d None ') if n % 4 == 0: # after 4 raw packets print '\n', Response = 825307441L else: if raw_output: print '%1d 0x%08X' % (n,Response), rawfile.write('%1d 0x%08X ' % (n, Response)) if n % 4 == 0: # after 4 raw packets print '\n', D = '%08X' % Response T[n][1] = int(D[0:2],16)/5.0 # T air in T[n][2] = int(D[2:4],16)/5.0 # T air out T[n][3] = int(D[4:6],16)/5.0 # T water high T[n][4] = int(D[6:8],16)/5.0 # T water low # end of looping over boards if raw_output: print '\n', rawfile.write('\n') logfile.write(strftime('"%d-%m-%Y %H:%M:%S" ', localtime())) Tai = Tao = Twl = Twh = 0 print Tai, Tao, Twl, Twh for n in range(1, number_of_boards+1): print '%1d' % n, logfile.write('%1d' % n) if n > 1 and n < number_of_boards: # 1 = pump, last= control group Tai = Tai + T[n][1] Tao = Tao + T[n][2] Twl = Twl + T[n][3] Twh = Twh + T[n][4] for i in range(1,5): print '%4.1f' % T[n][i], logfile.write('%4.1f' % T[n][i]) if n % 3 == 0: # after three temperature quads print '\n', Tai = Tai / (number_of_boards - 2) # 1 pump board, 1 control group board Tao = Tao / (number_of_boards - 2) Twl = Twl / (number_of_boards - 2) Twh = Twh / (number_of_boards - 2) print '%4.1f %4.1f %4.1f %4.1f' % (Tai, Tao, Twl, Twh) print '\n' logfile.write('\n') logfile.flush() send_temps_to_pumpcontr(Tai, Tao, Twl, Twh) sleep(2) # if seconds < 55: # sleep(55 - seconds) >#################################################################### ># ># program almeria3.py ># makes logfile ># polls boards for temperatures ># writes temperatures to screen ># records temperatures in logfile ># makes new logfile every midnight ># can output raw packets ># ># to do: config file, separate data routine for msgs needs work ># fault-tolerant: no output (or the lack of output) ># may NOT crash the program works. ># re-boot boards if necessary needs work ># send average temps to pump board works ># >################################################################### > >from time import strftime, localtime, sleep >import random, fpformat >import sys several libs, but I'll have to check if still needed >from xwisp_fwx3 import fwx wouter's msg routines >import string > >def make_logfile(): def: define function (): no arguments > logfile = open(strftime("%d-%m-%Y_%H-%M.log", localtime()),'w') 12-11-2003_23-59.log, open for writing, the 'w' > #logfile = open(strftime("%d_%H%M.log", localtime()),'w') # MSDOS > logfile.write('temperatures and pump duty cycles\n') > logfile.write('from six fans and pump controller\n') > return(logfile) so function returns logfile object. Call function with logfile = make_logfile() after that, you can do things like: logfile.close() logfile.flush() > >def make_rawfile(): > rawfile = open(strftime("%d-%m-%Y_%H-%M.raw", localtime()),'w') > #logfile = open(strftime("%d_%H%M.log", localtime()),'w') # MSDOS 12_23-59.log, 8-char MSDOS compatible file name. This code snippet was developed under DOS. > logfile.write('raw msgs from fwx boards\n') > return(rawfile) > >def data_send_X(B3,B2,B1, B0): # makes integer that is a 8-char in hex > data = '%02X' % B3 + '%02X' % B2 + '%02X' % B1 + '%02X' % B0 '02X' % 255 means: write 255 as hexadecimal (X) string ('..'), two chars wide (2) with leading zeroes (0). Yes, Python is powerful. I took 3 days to understand this. > data = long(data, 16) > #print '%08X' % data debugging :-) > return data as 8-char hex string from 4 integers. If integers are 199498535 or other useless number >255, hex string will always be 8 char wide. Very robust. > > >def send_temps_to_pumpcontr(Tai, Tao, Twl, Twh): > Response = f.Send_Receive(75, data_send_X(Tai*5, Tao*5, Twl*5, Twh*5), 1) # pump_controller has address 1 > #print Response remember: internal byte representation of temps in PIC is degree celsius * 5 75 is bad: needs to be replaced by cmd_set_av_temps constant. > >############################ START OF PROGRAM ####################### > > >number_of_boards = 8 # should be in config file indeed. >raw_output = True idem, in config file > >T = [ [None] * 5 for i in range(1,number_of_boards+2) ] # array of [0..num][0..4] clumsy array of stupid newbie that wants arrays like T[1..n][1..4] instead of Python way T[0..n-1][0..3]. Array should be replaced with nice set of fourfold tuples. > >f = fwx( '/dev/cuaa0' ) FreeBSD serial port 1 >Errors = 0 >f.CMD_RUN() run boards > >date = localtime()[2] > >logfile = make_logfile() >if raw_output: > rawfile = make_rawfile() > > ># $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ START OF MAIN LOOP $$$$$$$$$$$$$$ > >while True: > minutes, seconds = localtime()[4], localtime()[5] powerful Python tuple (data set) value setting. a,b,c,d = 1,2,3,4 is normal Python. Typically T = [a,b,c,d] should be used > > if date != localtime()[2]: # a new day has dawned, open a new logfile > logfile = make_logfile() > date = localtime()[2] > > if minutes % 1 == 0: > if seconds % 10 == 0: for fast response Note that Python has no begin...end, only indentation. One space off and the compilers hurls abuse at you, rightly so. Even one tab and 8 spaces on different lines are not accepted. ":" is "then" > if raw_output: > rawfile.write(strftime('"%d-%m-%Y %H:%M:%S" ', localtime())) Writing time to raw log, to match the raw packets later to the temperatures. > > for n in range(1, number_of_boards + 1): stupid newbie counting from 1 to n. Python way is for n in range(number_of_boards) n will be 0...8 > Response = f.Send_Receive(33, Address = n) get 4 temperatures > if Response == None: > if raw_output: > print '%1d None ' % n, > rawfile.write('%1d None ') > if n % 4 == 0: # after 4 raw packets > print '\n', > Response = 825307441L is 0x31313131 is 49 49 49 49 is 4 times 9.8*5 which will thoroughly confuse pump_controller. Bad. > else: > if raw_output: > print '%1d 0x%08X' % (n,Response), print n as 1 digit integer, Response as 0xXXXXXXXX 8-digit hex number trailing comma means no newline after print print '\n' with no trailing comma means TWO newlines > rawfile.write('%1d 0x%08X ' % (n, Response)) note middle and trailing space in format string: chunk.write() will not spaced numbers like print does > if n % 4 == 0: # after 4 raw packets > print '\n', to the screen, not to the file > > D = '%08X' % Response D now 8 (hex) char long string > T[n][1] = int(D[0:2],16)/5.0 # T air in T[n][1] is integer of first two chars of string, with base number 16, divided by 5. 5.0 is written so Python will understand T[n][1] is a float > T[n][2] = int(D[2:4],16)/5.0 # T air out > T[n][3] = int(D[4:6],16)/5.0 # T water high > T[n][4] = int(D[6:8],16)/5.0 # T water low > # end of looping over boards > > if raw_output: > print '\n', > rawfile.write('\n') Now a newline to the raw file > > logfile.write(strftime('"%d-%m-%Y %H:%M:%S" ', localtime())) > Tai = Tao = Twl = Twh = 0 resetting the values for averaging > print Tai, Tao, Twl, Twh debugging > for n in range(1, number_of_boards+1): clueless newbie loops again over boards, sigh > print '%1d' % n, > logfile.write('%1d' % n) > if n > 1 and n < number_of_boards: # 1 = pump, last= control group first board is pump_contr, last board is control_group, both should not be used for calculating average > Tai = Tai + T[n][1] > Tao = Tao + T[n][2] > Twl = Twl + T[n][3] > Twh = Twh + T[n][4] Real Pythoneers would combine these statements: T[n][1] = int(D[0:2],16)/5.0 # T air in Tai = Tai + T[n][1] to Tai = Tai + T[n][1] = int(D[0:2],16)/5.0 # T air in in a single loop > > for i in range(1,5): > print '%4.1f' % T[n][i], > logfile.write('%4.1f' % T[n][i]) no space, bad > if n % 3 == 0: # after three temperature quads > print '\n', print board number and temperatures in line of three > > Tai = Tai / (number_of_boards - 2) # 1 pump board, 1 control group board > Tao = Tao / (number_of_boards - 2) > Twl = Twl / (number_of_boards - 2) > Twh = Twh / (number_of_boards - 2) averaging > > print '%4.1f %4.1f %4.1f %4.1f' % (Tai, Tao, Twl, Twh) debugging > > print '\n' > > logfile.write('\n') > logfile.flush() flush data stream to logfile so no data loss when power failure > > send_temps_to_pumpcontr(Tai, Tao, Twl, Twh) ha! This took me a full day to get this single statement working! > > sleep(2) so not 6 times in the same second. Yes, Python is that fast. ># if seconds < 55: ># sleep(55 - seconds) To minimize system load? -- Ir. E.E. van Andel, Fine Wire Heat Exchangers, Fiwihex B.V. www.fiwihex.com Wierdensestraat 74, NL-7604 BK Almelo, The Netherlands eur@fiwihex.nl phone +31-546-491106 fax +31-546-491107 mobile +31-653-286573 From benm at cyber.com.au Wed Nov 12 20:45:56 2003 From: benm at cyber.com.au (Ben McGinnes) Date: Wed Nov 12 20:46:11 2003 Subject: [Tutor] (probably obvious) question about Tkinter Message-ID: <20031113014556.GC4309@vanilla.office.cyber.com.au> Good morning(-ish), I have a brief query about Python with Tkinter. I programmed a cute little thing which I call Time Check using Python (of course) and Tkinter (because it was there). It was an excuse to fiddle and see what stuff did. The web page for it (and prior versions) is here: http://www.adversary.org/sanctuary/geekstuff/timecheck.html The current version (0.1.3) is here: http://www.adversary.org/sanctuary/files/timecheck/timecheck.py It does more or less what I want it to do in that it opens up new widgets to show different things and can produce relevant results. When it does this, however, it leaves the previous widget open. This is fine for the main/starting screen, but with the other widgets it can get a little annoying. I'm sure there's a standard command which will close a widget without closing the entire program (via sys.exit) and would love to know what it is. I've trawled through _Programming Python_ and _Python In A Nutshell_, but cannot find it. I also haven't been able to find the appropriate way to phrase what I'm looking for such that Google will return the result I want. ;) Thanks in advance and please post responses to the list. Regards, Ben PS: Yes, I know wxPython is supposed to be the "wave of the future," but I'll get to that in good time. PPS: Alex Martelli, thanks for writing _Python In A Nutshell_ it combined with Alan Gauld's tutorial helped me more than _Learning Python_, which was painful to read (no offence to Mark Lutz & David Ascher, but it really wasn't a good book to learn from). From rozani at bppn.go.id Wed Nov 12 21:01:23 2003 From: rozani at bppn.go.id (Rozani Ismail) Date: Wed Nov 12 21:10:52 2003 Subject: [Tutor] Which things need to be set up first? Message-ID: Hi all Our community would like to set up an automatic mailing group in our mailing list (create not by admin). The specification of our mailing server : Pentium III RAM 256Mbyte Harddisk sekitar 14 Gbyte If you have any experiences regarding to this set up, please don't hesitate to give us some guidance. Which things had to be set up first, since we are still the beginner in python programming. _____________ DISCLAIMER : The information contained in this communication is intended solely for the use of the individual or entity to whom it is addressed and others authorized to receive it. It may contain confidential or legally privileged information. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking any action in reliance on the contents of this information is strictly prohibited and may be unlawful. Unless otherwise specifically stated by the sender, any documents or views presented are solely those of the sender and do not constitute official documents or views of The Indonesian Bank Restructuring Agency (IBRA). If you have received this communication in error, please notify us immediately by responding to this email and then delete it from your system. IBRA is neither liable for the proper and complete transmission of the information contained in this communication nor for any delay in its receipt. _____________ DISCLAIMER : The information contained in this communication is intended solely for the use of the individual or entity to whom it is addressed and others authorized to receive it. It may contain confidential or legally privileged information. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking any action in reliance on the contents of this information is strictly prohibited and may be unlawful. Unless otherwise specifically stated by the sender, any documents or views presented are solely those of the sender and do not constitute official documents or views of The Indonesian Bank Restructuring Agency (IBRA). If you have received this communication in error, please notify us immediately by responding to this email and then delete it from your system. IBRA is neither liable for the proper and complete transmission of the information contained in this communication nor for any delay in its receipt. _____________ DISCLAIMER : The information contained in this communication is intended solely for the use of the individual or entity to whom it is addressed and others authorized to receive it. It may contain confidential or legally privileged information. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking any action in reliance on the contents of this information is strictly prohibited and may be unlawful. Unless otherwise specifically stated by the sender, any documents or views presented are solely those of the sender and do not constitute official documents or views of The Indonesian Bank Restructuring Agency (IBRA). If you have received this communication in error, please notify us immediately by responding to this email and then delete it from your system. IBRA is neither liable for the proper and complete transmission of the information contained in this communication nor for any delay in its receipt. From clay at shirky.com Wed Nov 12 21:32:29 2003 From: clay at shirky.com (Clay Shirky) Date: Wed Nov 12 21:32:44 2003 Subject: [Tutor] Dictionary and List Question? Message-ID: After seeing how unpythonic my regex-laden string manipulations were (thanks to Messrs. Kuchling and Speno!), I have two questions about pythonic handling of a dictionary later transformed into a list. I'm counting lines in a logfile and making each line a key in a dictionary, so I can get the unique lines, but increment a counter. Later, I want to put the lines in the list, in the form 17 /writings/spam.html 19 /writings/eggs.html ... The first question is about the best way to increment the dictionary every time I see the same line. Right now I have if entry in list: list[entry] += 1 else: list[entry] = 1 but this seems verbose. Is there a way I can say, in one line "increment the value of list[entry], even if its the first time you've seen entry"? Next, I want to loop through the dictionary list, and take each key-value pair, and turn them into a string of value-key, so that the number is first, and then the line. Then I want to sort them so that the lines appear in numerical order. However, when I do this for k, v in list.items(): v = str(v) url_line = space.join( (v, k) ) output.append(url_line) output.sort() the sort order of output puts the lines in the 1, 12, 13, 2, 21, 3 order, which is to say an alpha sort of numeric strings. How do I get output.sort() to sort in numeric order, even though I had to transform the numerical values from the dictionary to strings to make them a single element in the list? Thanks, -clay From speno at isc.upenn.edu Wed Nov 12 22:41:36 2003 From: speno at isc.upenn.edu (John P Speno) Date: Wed Nov 12 22:41:45 2003 Subject: [Tutor] Dictionary and List Question? In-Reply-To: References: Message-ID: <20031113034136.GA6844@isc.upenn.edu> On Wed, Nov 12, 2003 at 09:32:29PM -0500, Clay Shirky wrote: > if entry in list: > list[entry] += 1 > else: > list[entry] = 1 > > but this seems verbose. Is there a way I can say, in one line "increment the > value of list[entry], even if its the first time you've seen entry"? In python, it is better to ask forgivness than permission, so: try: list[entry] +=1 except KeyError: list[entry] = 1 I though that the dict's setdefault method might work here, but after testing, I don't think it will. It's nice when you have a dict of lists, like this: list.setdefault(key, []).append(value) And the next problem: > the sort order of output puts the lines in the 1, 12, 13, 2, 21, 3 order, > which is to say an alpha sort of numeric strings. How do I get output.sort() > to sort in numeric order, even though I had to transform the numerical You probably want to call sort with a customized comparision function. Untested code follows: l = [] l_append = l.append for k, v in list.iteritems(): l_append((v, k)) def my_sort(a, b): return cmp(a[0], b[0]) l.sort(my_sort) for x in l: output.append('%d %s' % x) Hope that helps. From scott_list at mischko.com Wed Nov 12 22:48:54 2003 From: scott_list at mischko.com (Scott Chapman) Date: Wed Nov 12 23:12:25 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? Message-ID: <200311121948.54035.scott_list@mischko.com> Is there a way to get the Python Tutorial all in one document so I can print it without wasting so much paper? Scott From phthenry at earthlink.net Thu Nov 13 01:52:31 2003 From: phthenry at earthlink.net (Paul Tremblay) Date: Thu Nov 13 01:52:48 2003 Subject: [Tutor] sorting by values in dict Message-ID: <20031113065231.GB3015@localhost.localdomain> Is there a way to sort a dictionary by values? My problem involves a simple script that sorts files by size. I make dictionary that looks like this: {'file1': 10000, 'file2' : 10000, file3' : 5000, } I simply can't switch values and keys and sort by keys, because files might have the same size. For example, if I simply switched values and keys in the above dictionary, I would get: {10000 : 'file1', 5000 : 'file3', } Obviously, I can sort the values like this: values = the_dict.values() values.sort() But I need to know which value is associated with each key. There is probably a very easy answer to this. My python book doesn't mention it. thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From norvell at houseofspearman.org Thu Nov 13 02:07:40 2003 From: norvell at houseofspearman.org (Norvell Spearman) Date: Thu Nov 13 02:07:46 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? In-Reply-To: <200311121948.54035.scott_list@mischko.com> References: <200311121948.54035.scott_list@mischko.com> Message-ID: <20031113070740.GA27207@houseofspearman.org> On Wednesday, 2003.11.12, 19:48:54 -0800, Scott Chapman wrote: > Is there a way to get the Python Tutorial all in one document so I can > print it without wasting so much paper? Do you mean another format besides html? If so, the Tutorial (along with the other documentation) is available in PDF, PostScript, and LaTeX source formats at the following address: http://www.python.org/doc/current/download.html -- Norvell Spearman From project5 at redrival.net Thu Nov 13 04:50:38 2003 From: project5 at redrival.net (Andrei) Date: Thu Nov 13 04:53:10 2003 Subject: [Tutor] Re: sorting by values in dict References: <20031113065231.GB3015@localhost.localdomain> Message-ID: <1cenjk0a6a5da.sg5w2d325tc2$.dlg@40tude.net> Paul Tremblay wrote on Thu, 13 Nov 2003 01:52:31 -0500: > Is there a way to sort a dictionary by values? A dictionary is by definition unsorted. > My problem involves a simple script that sorts files by size. > > I make dictionary that looks like this: > > {'file1': 10000, > 'file2' : 10000, > file3' : 5000, > } You'll then have to convert this back to a list of tuples of the form (size, filename), and then use the sort() method of the list, e.g.: >>> files = [(1000, 'file2'), (2000, 'file1'), (900, 'file3')] >>> files.sort() >>> files [(900, 'file3'), (1000, 'file2'), (2000, 'file1')] -- Yours, Andrei ===== Mail address in header catches spam. 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 speno at isc.upenn.edu Thu Nov 13 08:07:42 2003 From: speno at isc.upenn.edu (John P Speno) Date: Thu Nov 13 08:07:54 2003 Subject: [Tutor] Dictionary and List Question? In-Reply-To: <20031113034136.GA6844@isc.upenn.edu> References: <20031113034136.GA6844@isc.upenn.edu> Message-ID: <20031113130742.GA6953@isc.upenn.edu> On Wed, Nov 12, 2003 at 10:41:36PM -0500, John P Speno wrote: > def my_sort(a, b): > return cmp(a[0], b[0]) > > l.sort(my_sort) I forgot that by default, python's list sort method will sort a list of sequences based on the first item in the sequence, so you can get rid of the my_sort function, and just call l.sort(). From pythontutor at venix.com Thu Nov 13 09:39:21 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Nov 13 09:39:29 2003 Subject: [Tutor] Dictionary and List Question? In-Reply-To: References: Message-ID: <3FB39799.7050009@venix.com> Clay Shirky wrote: > if entry in list: > list[entry] += 1 > else: > list[entry] = 1 I think your naming could be improved. list is used by python for the list type. Using list as a variable name prevents you from calling the list type. In addition, list is really a dictionary. I'll use d_lines instead of list for my code snippet. d_lines[entry] = d_lines.setdefault(entry, 0) + 1 setdefault will create the dictionary entry with an initial value, zero in this case. Then we always add one to count each line reference. http://www.brunningonline.net/simon/python/PQR.html Python Quick Reference This is a real handy reference for looking up functions and methods. (I've downloaded the relevant version for me to minimize the load on their server.) > > Next, I want to loop through the dictionary list, and take each key-value > pair, and turn them into a string of value-key, so that the number is first, > and then the line. Then I want to sort them so that the lines appear in > numerical order. You can sort a list of tuples as well as strings. l_lines = [(v,k) for (k,v) in d_lines.items()] l_lines.sort() # v is still a number so it will sort correctly Now you can turn the sorted list of counts and lines into strings for output. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From pythontutor at venix.com Thu Nov 13 09:50:09 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Nov 13 09:50:30 2003 Subject: [Tutor] Which things need to be set up first? In-Reply-To: References: Message-ID: <3FB39A21.5060505@venix.com> Barry Warsaw's Mailman package is very widely used. It runs the tutor list. http://www.list.org/ Mailman, the GNU Mailing List Manager You'll need to install Linux or another unix-like operating system on your mail server. If you are using RedHat Linux 9, they had problems with their mailman package (.rpm). The latest one: mailman-2.1.1-4 works fine. I believe that the main pitfall is getting the generated email aliases configured into your mail server. Rozani Ismail wrote: > Hi all > > Our community would like to set up an automatic mailing group in our mailing > list > (create not by admin). > The specification of our mailing server : > Pentium III > RAM 256Mbyte > Harddisk sekitar 14 Gbyte > If you have any experiences regarding to this set up, please don't hesitate > to give us some guidance. Which things had to be set up first, since we are > still the beginner in python programming. > > _____________ > DISCLAIMER : > The information contained in this communication is intended solely for the use of the individual or entity to whom it is addressed and others authorized to receive it. It may contain confidential or legally privileged information. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking any action in reliance on the contents of this information is strictly prohibited and may be unlawful. Unless otherwise specifically stated by the sender, any documents or views presented are solely those of the sender and do not constitute official documents or views of The Indonesian Bank Restructuring Agency (IBRA). > If you have received this communication in error, please notify us immediately by responding to this email and then delete it from your system. IBRA is neither liable for the proper and complete transmission of the information contained in this communication nor for any delay in its receipt. > > > _____________ > DISCLAIMER : > The information contained in this communication is intended solely for the use of the individual or entity to whom it is addressed and others authorized to receive it. It may contain confidential or legally privileged information. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking any action in reliance on the contents of this information is strictly prohibited and may be unlawful. Unless otherwise specifically stated by the sender, any documents or views presented are solely those of the sender and do not constitute official documents or views of The Indonesian Bank Restructuring Agency (IBRA). > If you have received this communication in error, please notify us immediately by responding to this email and then delete it from your system. IBRA is neither liable for the proper and complete transmission of the information contained in this communication nor for any delay in its receipt. > > > _____________ > DISCLAIMER : > The information contained in this communication is intended solely for the use of the individual or entity to whom it is addressed and others authorized to receive it. It may contain confidential or legally privileged information. If you are not the intended recipient you are hereby notified that any disclosure, copying, distribution or taking any action in reliance on the contents of this information is strictly prohibited and may be unlawful. Unless otherwise specifically stated by the sender, any documents or views presented are solely those of the sender and do not constitute official documents or views of The Indonesian Bank Restructuring Agency (IBRA). > If you have received this communication in error, please notify us immediately by responding to this email and then delete it from your system. IBRA is neither liable for the proper and complete transmission of the information contained in this communication nor for any delay in its receipt. > > > _______________________________________________ > 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 scott_list at mischko.com Thu Nov 13 10:12:16 2003 From: scott_list at mischko.com (Scott Chapman) Date: Thu Nov 13 10:12:28 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? In-Reply-To: <20031113070740.GA27207@houseofspearman.org> References: <200311121948.54035.scott_list@mischko.com> <20031113070740.GA27207@houseofspearman.org> Message-ID: <200311130712.17164.scott_list@mischko.com> On Wednesday 12 November 2003 23:07, Norvell Spearman wrote: > On Wednesday, 2003.11.12, 19:48:54 -0800, Scott Chapman wrote: > > Is there a way to get the Python Tutorial all in one document so I > > can print it without wasting so much paper? > > Do you mean another format besides html? If so, the Tutorial (along > with the other documentation) is available in PDF, PostScript, and > LaTeX source formats at the following address: No, I mean HTML - all one file with the table of contents at the top for each section and subsection. Scott From Janssen at rz.uni-frankfurt.de Thu Nov 13 10:44:22 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Nov 13 10:44:38 2003 Subject: [Tutor] Dictionary and List Question? In-Reply-To: <20031113034136.GA6844@isc.upenn.edu> References: <20031113034136.GA6844@isc.upenn.edu> Message-ID: On Wed, 12 Nov 2003, John P Speno wrote: > On Wed, Nov 12, 2003 at 09:32:29PM -0500, Clay Shirky wrote: > > if entry in list: > > list[entry] += 1 > > else: > > list[entry] = 1 > > > > but this seems verbose. Is there a way I can say, in one line "increment the > > value of list[entry], even if its the first time you've seen entry"? > > In python, it is better to ask forgivness than permission, so: > > try: > list[entry] +=1 > except KeyError: > list[entry] = 1 > > I though that the dict's setdefault method might work here, but after > testing, I don't think it will. It's nice when you have a dict of lists, > like this: > > list.setdefault(key, []).append(value) [don't use builtin names like "list" as variables names. Use aList instead or something else. Second, I will talk about aDict, because we're discussioning dicts not lists ;-)] aDict[entry] = aDict.get(entry, 0) +1 works fine. "aDict.get(key, [default]) is the syntax to retrieve a dictionary value without raising a KeyError. By the Way: aDict.setdefault(key, []).append(value) is rather hard to read. It takes me every time I see it several minutes to understand what python does behind the scene to make it work. Well, since I have spend these minutes right away, I will try to explain why setdefault can be used to append to lists but not to increment an integer: The astonishing part of "aDict.setdefault(key, []).append(value)" is ".append(value)": setdefault sets aDict[key] to [] or leave it untouched depending on if key is given or not. In both ways it also returns the value. ".append(value)" works on this returned value. It seems like it doesn't work on the list inside of aDict. Why then does indeed the change on the return-value of setdefault reflects in the list within aDict (but wouldn't reflect on a integer inside aDict?)? aDict = {} aDict["k1"] = 1 aDict["k2"] = [1] aDict.setdefault("k1", 1) +1 # or aDict.setdefault("k1", 1).__add__(1) ret_val = aDict.setdefault("k2", [1]) # in two steps to make it obvious ret_val.append(1) print aDict["k1"] # ---> 1 print aDict["k2"] # ---> [1, 1] ---> why? The important difference between integers and lists to explain this behaviour is immutability vs mutability plus the python reference mechanism: Python doesn't generate true copies of objects when another reference is created: aList = [] not_a_true_copy_of_aList = aList are references to the same object: aList.append("anEntry") print not_a_true_copy_of_aList # --> "anEntry" This is why one can work on the list returned by setdefault and change the list within aDict, because both lists are references to the same object. Why isn't this possible for integers? Integers are immutuable. This means, it's not possible to change them in place: any attempt to change a immutuable type results in a another object: a = b = 1 are References to the same object but after any change to a, the name a refers to a new object. The name b is yet a reference to the old object and stays untouched from the change of a. This is why the change of the return-value of setdefault doesn't reflect on the value stored within aDict. Michael From gabriel.cooper at mediapulse.com Thu Nov 13 13:09:08 2003 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Thu Nov 13 13:09:15 2003 Subject: [Tutor] sorting by values in dict In-Reply-To: <20031113065231.GB3015@localhost.localdomain> References: <20031113065231.GB3015@localhost.localdomain> Message-ID: <3FB3C8C4.8050905@mediapulse.com> Paul Tremblay wrote: >Is there a way to sort a dictionary by values? > You can do this: >>> x = { 'file1':10000, 'file2':10000, 'file3':5000 } >>> y = x.keys() >>> y.sort() >>> for key in y: print str(key)+", "+ str(x[key]) file1, 10000 file2, 10000 file3, 5000 It's not pretty, but it works. From dyoo at hkn.eecs.berkeley.edu Thu Nov 13 13:09:34 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 13 13:09:43 2003 Subject: [Tutor] sorting by values in dict In-Reply-To: <20031113065231.GB3015@localhost.localdomain> Message-ID: On Thu, 13 Nov 2003, Paul Tremblay wrote: > Is there a way to sort a dictionary by values? > > My problem involves a simple script that sorts files by size. > > I make dictionary that looks like this: > > {'file1': 10000, > 'file2' : 10000, > file3' : 5000, > } > Hi Paul, You can probably take the key-value pairs by using the items() method: ### >>> d = {'file1': 10000, 'file2' : '10000', 'file3' : 5000} >>> d.items() [('file3', 5000), ('file2', '10000'), ('file1', 10000)] ### Hope this helps! From jeffq16 at yahoo.com Thu Nov 13 14:09:43 2003 From: jeffq16 at yahoo.com (j j) Date: Thu Nov 13 14:09:49 2003 Subject: [Tutor] Help with a game Message-ID: <20031113190943.63114.qmail@web9801.mail.yahoo.com> Whenever i run the game it says: script 'A:\game folder\game.py' returned exit code 0 If you want the bitmaps then let me know, i didn't want to send everyone an attachment, thanks again guys. Maybe some help? Thank you guys...here is the code. --Jeff import os, pygame from pygame.locals import * if not pygame.font:print 'Warning, fonts disabled' def load_image(name, colorkey=None): fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except pygame.error, message: print 'Cannot load image:', fullname raise SystemExit, message image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() class Gun(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('gun.bmp', -1) self.punching = 0 def update(self): pos = pygame.mouse.get_pos() self.rect.midtop = pos if self.punching: self.rect.move_ip(5, 10) def shoot(self, target): if not self.punching: self.punching = 1 hitbox = self.rect.inflate(-5,-5) return hitbox.colliderect(target.rect) def unshoot(self): self.punching = 0 class ship(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image, self.rect = load_image('new.bmp',-1) screen = pygame.display.get_suface() self.area = screen.get_rect() self.rect.topleft = 10, 10 self.move = 9 self.dizzy = 0 def update(self): if self.dizzy: self._spin() else: self._walk() def _walk(self): change = self.rect.move((self.move, 0)) if self.rect.left< self.area.left or \ self.rect.right > self.area.right: self.move = -self.move change = self.rect.move((self.move, 0)) self.image = pygame.transform.flip(self.image, 1, 0) self.rect = change def _change(self): center = self.rect.center self.dizzy = self.dizzy + 12 if self.dizzy >= 360: self.dizzy = 0 self.image = self.original else: rotate = pygame.transform.rotate self.image = rotate(self.original, slef.dizzy) self.rect = self.image.get_rect() self.rect.center = center def done(self): if not self.dizzy: self.dizzy = 1 self.original = self.image def main(): pygame.init() screen = pygame.display.set_mode((480, 60)) pygame.display.set_caption('Battleship') pygame.mouse.set_visible(0) backround = pygame.Surface(screen.get_size()) backround = backround.convert() backround.fill((250, 250, 250)) screen.blit(backround, (0, 0)) pygame.display.flip() clock = pygame.time.Clock() new = New() gun = Gun() allsprites = pygame.sprite.RenderPlain((gun, new)) while 1: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type == MOUSEBUTTONDOWN: if fist.punch(chimp): chimp.punched() elif event.type == MOUSEBUTTONUP: fist.unpunch() allsprites.update() screen.blit(backround, (0, 0)) allsprites.draw(screen) pygame.display.flip() if __name__ == '__main__': main() --------------------------------- Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031113/f5c052c5/attachment.html From dyoo at hkn.eecs.berkeley.edu Thu Nov 13 14:23:44 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 13 14:23:50 2003 Subject: [Tutor] sorting by values in dict In-Reply-To: <3FB3C8C4.8050905@mediapulse.com> Message-ID: On Thu, 13 Nov 2003, Gabriel Cooper wrote: > >Is there a way to sort a dictionary by values? > > > You can do this: > > >>> x = { 'file1':10000, 'file2':10000, 'file3':5000 } > >>> y = x.keys() > >>> y.sort() > >>> for key in y: > print str(key)+", "+ str(x[key]) > > file1, 10000 > file2, 10000 > file3, 5000 > > > It's not pretty, but it works. Hi Gabriel, Be careful about fitting a solution to a particular example. *grin* This would work if Paul wanted to sort by the file names --- but he wants to sort on the file sizes. So if we have something like: d = {'a' : 2, 'b' : 7, 'c' : 1, 'd' : 8} we want to be able to sort it so that we get the key-value pairs in the descending order: ('d', 8) ('b', 7) ('a', 2) ('c', 1) Hope this helps! From pv_nair at hotmail.com Thu Nov 13 14:42:40 2003 From: pv_nair at hotmail.com (VN) Date: Thu Nov 13 14:42:48 2003 Subject: [Tutor] newbie string parsing question Message-ID: Hello all, I am new to the pyhon game and have been hitting a stone wall with the re module. I am trying to parse an app server log, in real time, and want return the whole string that contains a value, like "Error". Any help would be great.... Thanks.. VN -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031113/24f22f35/attachment.html From jeff at ccvcorp.com Thu Nov 13 15:08:54 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Nov 13 15:04:17 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? In-Reply-To: <200311130712.17164.scott_list@mischko.com> References: <200311121948.54035.scott_list@mischko.com> <20031113070740.GA27207@houseofspearman.org> <200311130712.17164.scott_list@mischko.com> Message-ID: <3FB3E4D6.3050506@ccvcorp.com> Scott Chapman wrote: >>>Is there a way to get the Python Tutorial all in one document so I >>>can print it without wasting so much paper? >> >>Do you mean another format besides html? If so, the Tutorial (along >>with the other documentation) is available in PDF, PostScript, and >>LaTeX source formats at the following address: > > No, I mean HTML - all one file with the table of contents at the top for > each section and subsection. If you're intending to print it out, why do you want HTML? HTML is great for screen viewing, but as a format for specifying printed output it's far from ideal. And putting everything in one huge document would eliminate half the benefits of HTML anyhow. The other formats that Norvell mentioned, on the other hand, are intended from the start to be printer-friendly. What you really want is to have a version in HTML to view online, and a separate PDF/PostScript version to print out. (I'm pretty sure that the tutorial is *not* available as a single huge HTML document, unless you count the Windows .chm version which is no more suited for being printed in its entirety.) Jeff Shannon Technician/Programmer Credit International From project5 at redrival.net Thu Nov 13 15:12:45 2003 From: project5 at redrival.net (Andrei) Date: Thu Nov 13 15:15:34 2003 Subject: [Tutor] Re: Help with a game References: <20031113190943.63114.qmail@web9801.mail.yahoo.com> Message-ID: j j wrote on Thu, 13 Nov 2003 11:09:43 -0800 (PST): > Whenever i run the game it says: > script 'A:\game folder\game.py' returned exit code 0 > Maybe some help? Thank you guys...here is the code. There is no actual action in the code you sent. You define classes and functions, but you don't do anything with them. So the script runs, reads those definitions, thinks "yeah, they're nice" and then ends. > class ship(pygame.sprite.Sprite): > def _change(self): > allsprites.update() > screen.blit(backround, (0, 0)) > allsprites.draw(screen) > pygame.display.flip() > if __name__ == '__main__': > main() Pay attention to your indentation! 'if __name__=="__main__"' is Python idiom which goes at the bottom of the file with 0 indentation - in your code, it's part of a method of the ship class because of its indentation level. You also call in there the function main(), which is defined in the code somewhere inside the _change() method of the ship class. Again, wrong indentation. You really should browse through a Python tutorial before attempting a program of that size. And get a decent Python editor to help you with indentation (SciTE, Spe, PythonWin). -- Yours, Andrei ===== Mail address in header catches spam. 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 project5 at redrival.net Thu Nov 13 15:15:44 2003 From: project5 at redrival.net (Andrei) Date: Thu Nov 13 15:20:49 2003 Subject: [Tutor] Re: newbie string parsing question References: Message-ID: <145wjzi1khha2$.i9vembpm2ifs$.dlg@40tude.net> VN wrote on Thu, 13 Nov 2003 13:42:40 -0600: > Hello all, > > I am new to the pyhon game and have been hitting a stone wall > with the re module. I am trying to parse an app server log, > in real time, and want return the whole string that contains > a value, like "Error". > Any help would be great.... Your problem description is too vague I think. I'm not even sure how comes you're so sure that the problem you're having concerns the re module - in fact, I don't even understand why you think you need the re module, perhaps string methods would be enough. I also don't know what parsing in real time is supposed to mean. Can you clarify it some more perhaps? -- Yours, Andrei ===== Mail address in header catches spam. 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 scott_list at mischko.com Thu Nov 13 15:37:02 2003 From: scott_list at mischko.com (Scott Chapman) Date: Thu Nov 13 15:37:13 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? In-Reply-To: <3FB3E4D6.3050506@ccvcorp.com> References: <200311121948.54035.scott_list@mischko.com> <200311130712.17164.scott_list@mischko.com> <3FB3E4D6.3050506@ccvcorp.com> Message-ID: <200311131237.02947.scott_list@mischko.com> On Thursday 13 November 2003 12:08, Jeff Shannon wrote: > Scott Chapman wrote: > >>>Is there a way to get the Python Tutorial all in one document so I > >>>can print it without wasting so much paper? > >> > >>Do you mean another format besides html? If so, the Tutorial > >> (along with the other documentation) is available in PDF, > >> PostScript, and LaTeX source formats at the following address: > > > > No, I mean HTML - all one file with the table of contents at the > > top for each section and subsection. > > If you're intending to print it out, why do you want HTML? HTML is > great for screen viewing, but as a format for specifying printed > output it's far from ideal. And putting everything in one huge > document would eliminate half the benefits of HTML anyhow. The other > formats that Norvell mentioned, on the other hand, are intended from > the start to be printer-friendly. What you really want is to have a > version in HTML to view online, and a separate PDF/PostScript version > to print out. All that you've said is true in the main. However HTML prints quite well for the Python docs. They are not making use of fancy tables, etc. I can make my side margins a bit bigger with HTML. I can't do that with PDF's. The other Python modules, such as Psycopg, Draco, etc. all use the same doc format as the Python Tutor and they print nicely as well right from HTML. This is not about printing all docs from HTML where PDF would work better, just Python-related docs. The problem I have is that some of these HTML docs have lots of very little files that end up wasting a lot of paper. I'd be happy with HTML all-in-one-file or PDF that didn't page break at each sub-topic. The Python Tutorial PDF's would work fine in my case except that Acrobat Reader 5.1 won't print it to either of my printers. (I can print HTML just fine. I'll try upgrading Acrobat, etc.) I can't get the other docs (Draco, Psycopg, etc. ) in PDF format all the time. Often they are just published by the author in one format. Thus, I need to know how to turn these into single HTML files (or PDF files with my margins specified), easily, if possible. Scott From amk at amk.ca Thu Nov 13 16:32:43 2003 From: amk at amk.ca (A.M. Kuchling) Date: Thu Nov 13 16:32:56 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? In-Reply-To: <200311131237.02947.scott_list@mischko.com> References: <200311121948.54035.scott_list@mischko.com> <200311130712.17164.scott_list@mischko.com> <3FB3E4D6.3050506@ccvcorp.com> <200311131237.02947.scott_list@mischko.com> Message-ID: <20031113213243.GA27696@rogue.amk.ca> On Thu, Nov 13, 2003 at 12:37:02PM -0800, Scott Chapman wrote: > Thus, I need to know how to turn these into single HTML files (or PDF > files with my margins specified), easily, if possible. If you have LaTeX and LaTeX2HTML installed, you can download the Python source tree and hack Doc/Makefile. Change the '-split 3' in the rules for the "tut" target to "-split 1"; this results in one great big HTML file. If you hurry, I've put a copy of the single-file tutorial at http://www.amk.ca/files/tut.html ; it'll disappear the next time I push an update to my web pages. --amk From dyoo at hkn.eecs.berkeley.edu Thu Nov 13 16:46:45 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 13 16:47:04 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? In-Reply-To: <3FB3E4D6.3050506@ccvcorp.com> Message-ID: On Thu, 13 Nov 2003, Jeff Shannon wrote: > Scott Chapman wrote: > > >>>Is there a way to get the Python Tutorial all in one document so I > >>>can print it without wasting so much paper? If you're really interested in having a paper copy of the Python documentation, you may want to look at: http://www.network-theory.co.uk/python/manual/ Hope this helps! From sigurd at 12move.de Thu Nov 13 16:52:32 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Nov 13 16:54:20 2003 Subject: [Tutor] newbie string parsing question In-Reply-To: (VN's message of "Thu, 13 Nov 2003 13:42:40 -0600") References: Message-ID: On 13 Nov 2003, VN <- pv_nair@hotmail.com wrote: > the re module. I am trying to parse an app server log, in real time, > and want return the whole string that contains a value, like "Error". > Any help would be great.... If you gave us a bit more info it would be easier to help. I'm not sure if you really need a regexp. But anyway let's see. ******************************************************************** $ ipython In [1]: import sre In [2]: string = "I'm a server log entry which describes an Error" In [3]: reg = sre.compile(".*Error.*") In [4]: match = reg.search(string).group() In [5]: match Out[5]: "I'm a server log entry which describes an Error" In [6]: match = reg.findall(string) In [7]: match Out[7]: ["I'm a server log entry which describes an Error"] In [8]: "Error" in string Out[8]: True ******************************************************************** Here you see in line 3 how an regular expression object is build (with compile). That object has some methods. In line 4 you see the `search()' method which is used to to scan the string. Its return value is another object which has a `group' method. As we have only one group in our regexp which spans the whole string that is returned (line 5). In line 6 a different method is used: `findall()'. Here the matches are entries in a list. In line 8 you see that you don't necessarily need a regexp. If you search for a literal string you can simple say `String in Searched_string' If String is a part of Searched_string True is returned. I hope that helps and if not give more information. Karl -- Please do *not* send copies of replies to me. I read the list From clay at shirky.com Thu Nov 13 17:07:23 2003 From: clay at shirky.com (Clay Shirky) Date: Thu Nov 13 17:07:38 2003 Subject: [Tutor] newbie string parsing question In-Reply-To: Message-ID: Avoid re if you can If you are parsing an apache error log, and you have python 2.2.2 or higher, something like this might work: #!/usr/bin/python for line in file("/usr/local/apache/var/log/error_log"): line = line.strip() line = line.replace("[", "") fields = line.split("]") # needs 2.2.2 or higher for entry in fields: print entry, print Fields is a list of date, error, client, and message. -c > Hello all, > > I am new to the pyhon game and have been hitting a stone wall with the re > module. I am trying to parse an app server log, in real time, and want return > the whole string that contains a value, like "Error". > Any help would be great.... > > Thanks.. > VN > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From littledanehren at yahoo.com Thu Nov 13 17:32:39 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Nov 13 17:32:54 2003 Subject: [Tutor] sorting by values in dict In-Reply-To: <20031113065231.GB3015@localhost.localdomain> Message-ID: <20031113223239.78909.qmail@web41803.mail.yahoo.com> --- Paul Tremblay wrote: > Is there a way to sort a dictionary by values? > Dictionaries are unordered, so technically no. But there are ways to sort lists derived from dictionaries. > My problem involves a simple script that sorts files > by size. > > I make dictionary that looks like this: > > {'file1': 10000, > 'file2' : 10000, > file3' : 5000, > } > > I simply can't switch values and keys and sort by > keys, because files > might have the same size. For example, if I simply > switched values and > keys in the above dictionary, I would get: > > {10000 : 'file1', > 5000 : 'file3', > } > > Obviously, I can sort the values like this: > > values = the_dict.values() > values.sort() > > But I need to know which value is associated with > each key. > > There is probably a very easy answer to this. My > python book doesn't > mention it. > > thanks > > Paul To get a list of tuples of keys and values in dictionary d, simply use d.items(). This is automatically sorted using the cmp() function, as all sorts are unless a different function is explicitly given. Here's an example: >>> d = {"hello":0, "world":1} >>> x = d.items() >>> print x #This is in a non-sensical, but consistent, order. Sorted low to high, as Python sees it internally. [('world', 1), ('hello', 0)] >>> def cmp_by_value(item1, item2): ... return cmp(item1[1], item2[1]) ... >>> x.sort() >>> print x #Now it should be sorted by the second element in the tuples, increacing [('hello', 0), ('world', 1)] >>> x.reverse() #make it high to low instead >>> print x [('world', 1), ('hello', 0)] Although it looks like it was sorted correctly the first time, it shouldn't be that way most of the time. Now here's a simple loop to print out the names of the files and how big they are suitable for actual reading: >>> print "The files in high to low order:" The files in high to low order: >>> for name, size in x: ... print "%s is %i bytes" %(name, size) ... world is 1 bytes hello is 0 bytes but it would have nicer output if placed in an external script file. Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From scott_list at mischko.com Thu Nov 13 20:26:31 2003 From: scott_list at mischko.com (Scott Chapman) Date: Thu Nov 13 20:26:38 2003 Subject: [Tutor] How to get Python Tutorial all in one document for better printing? In-Reply-To: <20031113213243.GA27696@rogue.amk.ca> References: <200311121948.54035.scott_list@mischko.com> <200311131237.02947.scott_list@mischko.com> <20031113213243.GA27696@rogue.amk.ca> Message-ID: <200311131726.31664.scott_list@mischko.com> On Thursday 13 November 2003 13:32, A.M. Kuchling wrote: > On Thu, Nov 13, 2003 at 12:37:02PM -0800, Scott Chapman wrote: > > Thus, I need to know how to turn these into single HTML files (or > > PDF files with my margins specified), easily, if possible. > > If you have LaTeX and LaTeX2HTML installed, you can download the > Python source tree and hack Doc/Makefile. Change the '-split 3' in > the rules for the "tut" target to "-split 1"; this results in one > great big HTML file. > > If you hurry, I've put a copy of the single-file tutorial at > http://www.amk.ca/files/tut.html ; it'll disappear the next time I > push an update to my web pages. Thanks for the tip and the link. I got it. Scott From eur at fiwihex.nl Thu Nov 13 20:33:42 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Thu Nov 13 20:34:01 2003 Subject: [Tutor] string-formatted dictionary keys of configparsed INI file Message-ID: <1pb8rvkb34o10fdnsgqcfl8qfisifesrk3@4ax.com> Hi I managed to parse an ini file with the configparser thanks to Karl who pointed me at an example in the cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 I have the values as integers, just as I want, but the dictionary keys are strings: >import ConfigParser >import string > >_ConfigDefault = {} > >def LoadConfig(file, config={}): > """ > returns a dictionary with key's of the form >
.