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><E1AFSuB-0001wx-00@hooloovoo> <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: <E1AFSuB-0001wx-00@hooloovoo><20031031061006.GA18340@localhost.localdomain><E1AFSuB-0001wx-00@hooloovoo> <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: <Pine.LNX.4.44.0311011811360.7426-100000@hkn.eecs.berkeley.edu> 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: <oprx0omkpu2p1q98@smtp.start.no> 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: <oprx0omkpu2p1q98@smtp.start.no> References: <oprx0omkpu2p1q98@smtp.start.no> Message-ID: <oprx0r8rx72p1q98@smtp.start.no> 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: <E1AFSuB-0001wx-00@hooloovoo> <20031031061006.GA18340@localhost.localdomain> <E1AFSuB-0001wx-00@hooloovoo> <5.1.0.14.2.20031031142641.029d28a8@mail.30below.com> Message-ID: <Pine.A41.4.56.0311021558540.2044504@hermes-22.rz.uni-frankfurt.de> 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: <oprx0r8rx72p1q98@smtp.start.no> References: <oprx0omkpu2p1q98@smtp.start.no> <oprx0r8rx72p1q98@smtp.start.no> Message-ID: <Pine.A41.4.56.0311021615260.2044504@hermes-22.rz.uni-frankfurt.de> 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: <Pine.A41.4.56.0311021615260.2044504@hermes-22.rz.uni-frankfurt.de> References: <oprx0omkpu2p1q98@smtp.start.no> <oprx0r8rx72p1q98@smtp.start.no> <Pine.A41.4.56.0311021615260.2044504@hermes-22.rz.uni-frankfurt.de> Message-ID: <oprx0ylsa62p1q98@smtp.start.no> P? Sun, 2 Nov 2003 16:27:50 +0100 (CET), skrev Michael Janssen <Janssen@rz.uni-frankfurt.de>: > > 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 <type 'function'> ?? 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: <pckaqvchsvfgj0jolrbaabk664fcp3pebd@4ax.com> 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) <generator object at 0x01120BC0> >>> 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 "<interactive input>", 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('<!--***INSERT NAME HERE***-->', post[1], posts) posts = re.sub('<!--***INSERT DATE HERE***-->', post[2], posts) posts = re.sub('<!--***INSERT SUBJECT HERE***-->', post[3], posts) posts = re.sub('<!--***INSERT POST HERE***-->', post[4], posts) hello.append(posts) posts = posttemplate print hello the error message is: traceback (most recent call last): File "<stdin>", line 1, in ? File "retrieveposts.py", line 32, in retrieve_posts posts = re.sub('<!--***INSERT NAME HERE***-->', 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 "<stdin>", line 1, in ? File "retrieveposts.py", line 32, in retrieve_posts posts = re.sub('<!--***INSERT NAME HERE***-->', 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: '<div class="postholder">\n\t<div class="name">\n\t\t\t\t\t<br>\n\t\t\t\t\t <!--***INSERT NAME HERE***-->\n\t\t\t\t\t<br>\n\t\t\t\t\t<p>Posted on: <!--***INSERT DATE HERE***--> </p>\n\t</div>\n\t<div class="subject">\n\t\t\t <!--***INSERT SUBJECT HERE***--> \n\t</div>\n\t<div class="post"> <!--***INSERT POST HERE***--> \n\t\t\t<br>\t\n\t\t\t<br>\n\t\t\t\n\t\t\t<br>\n\t\t\t<br>\n\t\t\ t<br>\n\t\t\t<br>\n\t\t\t<br>\n\t\t\t<br>\t\n\t</div>\n</div>\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: <oprx0ylsa62p1q98@smtp.start.no> 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: <Pine.A41.4.56.0311021558540.2044504@hermes-22.rz.uni-frankfurt.de> References: <E1AFSuB-0001wx-00@hooloovoo> <20031031061006.GA18340@localhost.localdomain> <E1AFSuB-0001wx-00@hooloovoo> <5.1.0.14.2.20031031142641.029d28a8@mail.30below.com> <Pine.A41.4.56.0311021558540.2044504@hermes-22.rz.uni-frankfurt.de> 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: <Pine.LNX.4.44.0311021443210.25184-100000@hkn.eecs.berkeley.edu> > 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 "<stdin>", line 1, in ? > File "retrieveposts.py", line 32, in retrieve_posts > posts = re.sub('<!--***INSERT NAME HERE***-->', 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 "<stdin>", 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: '<!--***INSERT NAME HERE***-->' 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 = '<!--***INSERT NAME HERE***-->' >>> 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: <Pine.LNX.4.44.0311022334330.32252-100000@hkn.eecs.berkeley.edu> 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: <Pine.LNX.4.44.0310301715250.27144-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0311022346590.32252-100000@hkn.eecs.berkeley.edu> > > > >>> 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 "<stdin>", 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 "<stdin>", 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 <built-in function 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 <built-in function 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: <oprx18egb92p1q98@smtp.start.no> P? Sun, 2 Nov 2003 12:55:00 -0800 (PST), skrev Daniel Ehrenberg <littledanehren@yahoo.com>: >> 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: <Sea1-F119dC2zhmYreS00042402@hotmail.com> 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: <Sea1-F119dC2zhmYreS00042402@hotmail.com> References: <Sea1-F119dC2zhmYreS00042402@hotmail.com> 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 "<interactive input>", 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 "<interactive input>", line 1, in ? File "<interactive input>", 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: <Sea1-F148eFlX7nHJj800007d36@hotmail.com> 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çalo Rodrigues <op73418@mail.telepac.pt> >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 "<interactive input>", 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 "<interactive input>", line 1, in ? > File "<interactive input>", 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: <Sea1-F148eFlX7nHJj800007d36@hotmail.com> References: <Sea1-F148eFlX7nHJj800007d36@hotmail.com> 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 "<pyshell#18>", line 1, in -toplevel- str2num('0.') File "<pyshell#17>", 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: <E1AGinj-0000xo-00@hooloovoo> 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: <Pine.LNX.4.44.0311022334330.32252-100000@hkn.eecs.berkeley.edu> References: <1067785409.2561.2.camel@24-159-248-140.jvl.wi.charter.com> <Pine.LNX.4.44.0311022334330.32252-100000@hkn.eecs.berkeley.edu> Message-ID: <20031103192625.5f46b387.klappnase@freenet.de> On Sun, 2 Nov 2003 23:42:11 -0800 (PST) Danny Yoo <dyoo@hkn.eecs.berkeley.edu> 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: <Sea1-F119dC2zhmYreS00042402@hotmail.com> 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: <ABC0FFFEC46ED411BC9500D0B791511201E794F9@panini.logica.co.uk> 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: <oprx4pf9mx2p1q98@smtp.start.no> 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" <tim.ronning@start.no> > To: <tutor@python.org> > 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('<!--INSERT NAME HERE-->') content2 = re.escape('<!--INSERT DATE HERE-->') content3 = re.escape('<!--INSERT SUBJECT HERE-->') content4 = re.escape('<!--INSERT POST HERE-->') 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 "<stdin>", 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: <div class="postholder"> <div class="name"> <br> <!--INSERT NAME HERE--> <br> <p>Posted on: <!--INSERT DATE HERE--> </p> </div> <div class="subject"> <!--INSERT SUBJECT HERE--> </div> <div class="post"> <br> <br> <!--INSERT POST HERE--> <br> <br> <br> <br> <br> <br> </div> </div> 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 = '<!--INSERT %s HERE-->' 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: <Pine.LNX.4.44.0311041635360.20321-100000@hkn.eecs.berkeley.edu> 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('<!--INSERT NAME HERE-->') > content2 = re.escape('<!--INSERT DATE HERE-->') > content3 = re.escape('<!--INSERT SUBJECT HERE-->') > content4 = re.escape('<!--INSERT POST HERE-->') > > 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 "<stdin>", 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: <Pine.LNX.4.44.0311041648190.20321-100000@hkn.eecs.berkeley.edu> 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('<!--***INSERT NAME HERE***-->', post[1], posts) > posts = re.sub('<!--***INSERT DATE HERE***-->', post[2], posts) > posts = re.sub('<!--***INSERT SUBJECT HERE***-->', post[3], posts) > posts = re.sub('<!--***INSERT POST HERE***-->', 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: <BAY2-F101MScBkOs3vD0001d2e5@hotmail.com> >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: <oprx0ylsa62p1q98@smtp.start.no> References: <oprx0omkpu2p1q98@smtp.start.no> <oprx0r8rx72p1q98@smtp.start.no> <Pine.A41.4.56.0311021615260.2044504@hermes-22.rz.uni-frankfurt.de> <oprx0ylsa62p1q98@smtp.start.no> Message-ID: <Pine.A41.4.56.0311050950530.2052862@hermes-22.rz.uni-frankfurt.de> 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: <uvshqvstt7151893nvvf9qhe79pqft4ssa@4ax.com> 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: <uvshqvstt7151893nvvf9qhe79pqft4ssa@4ax.com> References: <uvshqvstt7151893nvvf9qhe79pqft4ssa@4ax.com> 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: <E1AHNOA-0000sk-SW@mail.python.org> References: <E1AHNOA-0000sk-SW@mail.python.org> 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 <arkamir@softhome.net> > 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('<!--INSERT NAME HERE-->') > content2 = re.escape('<!--INSERT DATE HERE-->') > content3 = re.escape('<!--INSERT SUBJECT HERE-->') > content4 = re.escape('<!--INSERT POST HERE-->') > > 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 "<stdin>", 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: > ><div class="postholder"> > <div class="name"> > <br> > <!--INSERT NAME HERE--> > <br> > <p>Posted on: <!--INSERT DATE HERE--> </p> > </div> > <div class="subject"> > > <!--INSERT SUBJECT HERE--> > </div> > <div class="post"> > <br> > <br> > > <!--INSERT POST HERE--> > <br> > <br> > <br> > <br> > <br> > <br> > </div> ></div> > >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 = '<!--INSERT %s HERE-->' > > 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: <uvshqvstt7151893nvvf9qhe79pqft4ssa@4ax.com> Message-ID: <1wlvxakd1uhlu$.4px9do8o1968.dlg@40tude.net> Eur van Andel wrote on Wed, 05 Nov 2003 14:26:05 +0100: Hi, <snip> > 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. <snip> > 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: <uvshqvstt7151893nvvf9qhe79pqft4ssa@4ax.com> Message-ID: <Pine.LNX.4.44.0311050948560.5039-100000@hkn.eecs.berkeley.edu> > 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 "<stdin>", line 1, in ? File "<stdin>", line 2, in foo File "<stdin>", line 2, in bar File "<stdin>", 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: <B9347A7A668DC84290DC609C86848EF61C3312@usboswmxmp03.ma.fbf1.com> References: <B9347A7A668DC84290DC609C86848EF61C3312@usboswmxmp03.ma.fbf1.com> 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: <B9347A7A668DC84290DC609C86848EF61C3312@usboswmxmp03.ma.fbf1.com> Message-ID: <Pine.LNX.4.44.0311050956360.5039-100000@hkn.eecs.berkeley.edu> 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: <m34qxi4rvz.fsf@hamster.pflaesterer.de> 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: <E1AHTb3-0000C2-00@hooloovoo> 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: <oprx4pf9mx2p1q98@smtp.start.no> 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: <uvshqvstt7151893nvvf9qhe79pqft4ssa@4ax.com> 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: <Pine.LNX.4.44.0311050948560.5039-100000@hkn.eecs.berkeley.edu> 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: <m3znfa32ud.fsf@hamster.pflaesterer.de> 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: <m3znfa32ud.fsf@hamster.pflaesterer.de> 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: <m3znfa32ud.fsf@hamster.pflaesterer.de> (Karl =?iso-8859-1?q?Pfl=E4sterer's?= message of "Wed, 05 Nov 2003 22:59:38 +0100") References: <3FA8DFE1.3050300@aon.at> <m3znfa32ud.fsf@hamster.pflaesterer.de> Message-ID: <m3vfpy2zbi.fsf@hamster.pflaesterer.de> 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: <m3znfa32ud.fsf@hamster.pflaesterer.de> References: <3FA8DFE1.3050300@aon.at> <m3znfa32ud.fsf@hamster.pflaesterer.de> 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: <m3vfpy2zbi.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.44.0311051530560.1213-100000@hkn.eecs.berkeley.edu> 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: <m3znfa32ud.fsf@hamster.pflaesterer.de> <20031105223417.96469.qmail@web41807.mail.yahoo.com> Message-ID: <s6viqv07m1nbojkfgn7kcm8adj0631i5n7@4ax.com> 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: <ABC0FFFEC46ED411BC9500D0B791511201EA8B0C@panini.logica.co.uk> 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" <missive@hotmail.com> Subject: [Tutor] Re: signalrestart To: tutor@python.org Message-ID: <BAY2-F101MScBkOs3vD0001d2e5@hotmail.com> 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: <bodntq$vsk$1@sea.gmane.org> Message-ID: <z2sl6ilrlug0.1mdxhub5nlup$.dlg@40tude.net> 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: <bodntq$vsk$1@sea.gmane.org>; from RoT@245T.com on Thu, Nov 06, 2003 at 11:03:39PM +0800 References: <bodntq$vsk$1@sea.gmane.org> 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> <m3znfa32ud.fsf@hamster.pflaesterer.de> <3FA986EE.2010706@aon.at> Message-ID: <m3he1hmqdr.fsf@hamster.pflaesterer.de> 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: <bodntq$vsk$1@sea.gmane.org> <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: <bodntq$vsk$1@sea.gmane.org> 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: <bodntq$vsk$1@sea.gmane.org> <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: <Pine.LNX.4.44.0311041635360.20321-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311041635360.20321-100000@hkn.eecs.berkeley.edu> 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 = '<!--INSERT %s HERE-->' content1 = re.escape('<!--INSERT NAME HERE-->') content2 = re.escape('<!--INSERT DATE HERE-->') content3 = re.escape('<!--INSERT SUBJECT HERE-->') content4 = re.escape('<!--INSERT POST HERE-->') 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: <div class="postholder"> <div class="name"> <br> <!--INSERT NAME HERE--> <br> <p>Posted on: <!--INSERT DATE HERE--> </p> </div> <div class="subject"> <!--INSERT SUBJECT HERE--> </div> <div class="post"> <br> <br> <!--INSERT POST HERE--> <br> <br> <br> <br> <br> <br> </div> </div> This is the error message: >>> import retrieveposts >>> retrieveposts.retrieve_posts('general', 'Hello, World', 20) Traceback (most recent call last): File "<stdin>", 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: <bodntq$vsk$1@sea.gmane.org> 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: <Pine.LNX.4.44.0311061815400.29898-100000@hkn.eecs.berkeley.edu> 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: <Pine.LNX.4.44.0311061824550.29898-100000@hkn.eecs.berkeley.edu> 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: <Pine.LNX.4.44.0311061824550.29898-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0311061852450.29898-100000@hkn.eecs.berkeley.edu> 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: <Pine.LNX.4.44.0311061916350.29898-100000@hkn.eecs.berkeley.edu> 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: <BAY2-F63bB8qrkgCeR900002c60@hotmail.com> 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: <Pine.LNX.4.44.0311061852450.29898-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311061852450.29898-100000@hkn.eecs.berkeley.edu> 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: <Pine.A41.4.56.0311050950530.2052862@hermes-22.rz.uni-frankfurt.de> References: <oprx0omkpu2p1q98@smtp.start.no> <oprx0r8rx72p1q98@smtp.start.no> <Pine.A41.4.56.0311021615260.2044504@hermes-22.rz.uni-frankfurt.de> <oprx0ylsa62p1q98@smtp.start.no> <Pine.A41.4.56.0311050950530.2052862@hermes-22.rz.uni-frankfurt.de> Message-ID: <oprx9sx7jc2p1q98@smtp.start.no> P? Wed, 5 Nov 2003 14:07:42 +0100 (CET), skrev Michael Janssen <Janssen@rz.uni-frankfurt.de>: > 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: <oprx9wyxip2p1q98@smtp.start.no> 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: <oprx9wyxip2p1q98@smtp.start.no> 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: <oprx927bry2p1q98@smtp.start.no> P? Fri, 7 Nov 2003 06:33:06 -0800 (PST), skrev Daniel Ehrenberg <littledanehren@yahoo.com>: >> 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: <oprx9wyxip2p1q98@smtp.start.no>; from tim.ronning@start.no on Fri, Nov 07, 2003 at 04:21:59PM +0100 References: <oprx9wyxip2p1q98@smtp.start.no> 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: <bodntq$vsk$1@sea.gmane.org> <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: <bodntq$vsk$1@sea.gmane.org> <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: <Pine.LNX.4.44.0311070957130.13658-100000@hkn.eecs.berkeley.edu> > 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: <Pine.LNX.4.44.0311071011380.13658-100000@hkn.eecs.berkeley.edu> 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 <jsoons@juilliard.edu> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> 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: <oprx9wyxip2p1q98@smtp.start.no> 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> <oprx927bry2p1q98@smtp.start.no> 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: <bodntq$vsk$1@sea.gmane.org> <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: <BAY2-F54kGhAj5p1Fjx000051aa@hotmail.com> >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: <bodntq$vsk$1@sea.gmane.org> <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: <BAY2-F54kGhAj5p1Fjx000051aa@hotmail.com> 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: <rti23f7hzdm5.16zwhra1lbvvy.dlg@40tude.net> 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: <bodntq$vsk$1@sea.gmane.org> <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: <Pine.LNX.4.44.0311081756420.17749-100000@hkn.eecs.berkeley.edu> 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 <tayiper@volja.net> 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" <ptwaugh@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 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 <built-in function 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" <ptwaugh@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 > >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 ><built-in function 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: <BAY2-F45MPqngL6wxvw00013010@hotmail.com> >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 <py> tags (ie something like <py>print 'hi'</py>). 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: <Pine.LNX.4.44.0311051530560.1213-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311051530560.1213-100000@hkn.eecs.berkeley.edu> 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: <Pine.LNX.4.44.0311081756420.17749-100000@hkn.eecs.berkeley.edu> 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: <jvvuqvg64lemeour21qujqd8ke7hpksarg@4ax.com> 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 <py> tags (ie something like ><py>print 'hi'</py>). 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: <E1AIsyb-0005de-7w@mail.python.org> References: <E1AIsyb-0005de-7w@mail.python.org> 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? <shrug>I dunno.</shrug> 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 <littledanehren@yahoo.com> > Date: > Sun, 9 Nov 2003 08:30:32 -0800 (PST) > To: > pytutor <tutor@python.org> > > >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 <py> tags (ie something like ><py>print 'hi'</py>). 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> <oprx927bry2p1q98@smtp.start.no> <003e01c3a567$501b3240$6401a8c0@xp> Message-ID: <opryfqheah2p1q98@smtp.start.no> P? Fri, 7 Nov 2003 19:42:43 -0000, skrev Alan Gauld <alan.gauld@blueyonder.co.uk>: > 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: <Pine.LNX.4.44.0311101202290.28358-100000@hkn.eecs.berkeley.edu> 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: <PGEBJFNMBPADGGPAJHGLCEEOCAAA.rcsmith@speakeasy.net> 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: <PGEBJFNMBPADGGPAJHGLCEEOCAAA.rcsmith@speakeasy.net> Message-ID: <Pine.LNX.4.44.0311101922360.8835-100000@hkn.eecs.berkeley.edu> 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 "<stdin>", 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 "<stdin>", 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 "<stdin>", 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: <PGEBJFNMBPADGGPAJHGLCEEOCAAA.rcsmith@speakeasy.net> 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: <Pine.LNX.4.44.0311101922360.8835-100000@hkn.eecs.berkeley.edu> Message-ID: <04f401c3a807$b9b17c80$6f11ba3f@defaultcomp> ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Ryan Smith" <rcsmith@speakeasy.net> Cc: <tutor@python.org> 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 > ### > <Snip> 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: <BAY2-F32uQwM9NPuBcl00010605@hotmail.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. > 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 > <http://antispam.yahoo.com/whatsnewfree> > >------------------------------------------------------------------------ > >_______________________________________________ >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: <OF413BFE8B.9A06FB22-ON49256DDB.003068E2-49256DDB.0032A6BB@jp.schneider-electric.com> 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: <type 'float'> / <type 'float'> 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: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> 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: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> References: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> 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: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> 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: <snip> > CO2_soll 80 > pump_1_manual_override 0 > pump_1_manual_speed 120 <snip> > code: <snip> > 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 <file>" 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. <snip> > # 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.>, } <snip> -- 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: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> <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: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net> Message-ID: <nou1rvg7bp2mf2ueosmooa3u335mugu9l4@4ax.com> On Tue, 11 Nov 2003 13:52:08 +0100, Andrei <project5@redrival.net> 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: ><snip> >> CO2_soll 80 >> pump_1_manual_override 0 >> pump_1_manual_speed 120 ><snip> > >> code: ><snip> >> 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 <file>" >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: <c6o1rvk2fjb8eer3bimntpeghp3ofdo7hi@4ax.com> References: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> <9qi1rvobr9jlfi3855arr9lljmimvk5s00@4ax.com> <h6m1rvg4cglu27be6j5n8v1nvmg5bbosfp@4ax.com> <c6o1rvk2fjb8eer3bimntpeghp3ofdo7hi@4ax.com> Message-ID: <bd22rvk6ge57i2vnd1rcgd20c80ul1hbie@4ax.com> On Tue, 11 Nov 2003 13:28:48 +0000, Gon?alo Rodrigues <op73418@mail.telepac.pt> 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: <tsc1rvsm8b6tdfus2n88ce600s5r7inlh6@4ax.com> <3c4yw22hlo5n.1bdqrk83ql2zb$.dlg@40tude.net> <nou1rvg7bp2mf2ueosmooa3u335mugu9l4@4ax.com> 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. <snip> > 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. <snip> >>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: <Pine.LNX.4.44.0311111135010.21181-100000@hkn.eecs.berkeley.edu> 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 <jeffq16@yahoo.com> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> 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 <dyoo@hkn.eecs.berkeley.edu> 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: <bd22rvk6ge57i2vnd1rcgd20c80ul1hbie@4ax.com> Message-ID: <Pine.LNX.4.44.0311111139360.21181-100000@hkn.eecs.berkeley.edu> > >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: <Pine.LNX.4.44.0311111139360.21181-100000@hkn.eecs.berkeley.edu> References: <bd22rvk6ge57i2vnd1rcgd20c80ul1hbie@4ax.com> <Pine.LNX.4.44.0311111139360.21181-100000@hkn.eecs.berkeley.edu> Message-ID: <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> On Tue, 11 Nov 2003 11:41:00 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> 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: <bd22rvk6ge57i2vnd1rcgd20c80ul1hbie@4ax.com> <Pine.LNX.4.44.0311111139360.21181-100000@hkn.eecs.berkeley.edu> <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> Message-ID: <20031111220249.GB22948@wdfs.graniteweb.com> * Eur van Andel <eur@fiwihex.nl> [2003-11-11 22:57]: > On Tue, 11 Nov 2003 11:41:00 -0800 (PST), Danny Yoo > <dyoo@hkn.eecs.berkeley.edu> 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: <bd22rvk6ge57i2vnd1rcgd20c80ul1hbie@4ax.com> <Pine.LNX.4.44.0311111139360.21181-100000@hkn.eecs.berkeley.edu> <7mm2rvs07m6sbkfndhk0l5s4b8stn5v6ii@4ax.com> Message-ID: <m3ad72zgha.fsf@hamster.pflaesterer.de> 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: <BBD6E1E5.116E6%clay@shirky.com> 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 (<F>) { 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: <Pine.LNX.4.44.0311111604150.11420-100000@hkn.eecs.berkeley.edu> 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 <bound method Foo.bar of <__main__.Foo instance at 0x400e654c>> >>> 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: <BAY2-F465f94h0FiXiF0001d3a3@hotmail.com> #!/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: <E1AJjEB-0000Ej-00@hooloovoo> 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 <function f at 0x40214e64> >>> 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: <BBD6E1E5.116E6%clay@shirky.com> References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> <BBD6E1E5.116E6%clay@shirky.com> 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: <E1AJl4e-0000NP-00@hooloovoo> 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: <BBD6E1E5.116E6%clay@shirky.com> Message-ID: <E1AJlLk-0000OO-00@hooloovoo> 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: <E1AJl4e-0000NP-00@hooloovoo> References: <2147483647.1068567947@141-213-238-92.umnet.umich.edu> <3FB18684.6020808@ccvcorp.com> <E1AJl4e-0000NP-00@hooloovoo> 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: <u664rvsaulkhf83s476l12octaqgdgokvv@4ax.com> 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: <ip64rvc2la5df2e0jvito0nm350ihp932h@4ax.com> 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: <ip64rvc2la5df2e0jvito0nm350ihp932h@4ax.com> Message-ID: <085501c3a917$b2e77100$6f11ba3f@defaultcomp> ----- Original Message ----- From: "Eur van Andel" <eur@fiwihex.nl> To: <tutor@python.org> 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: <u664rvsaulkhf83s476l12octaqgdgokvv@4ax.com> References: <u664rvsaulkhf83s476l12octaqgdgokvv@4ax.com> 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: <u664rvsaulkhf83s476l12octaqgdgokvv@4ax.com> 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> <E1AJl4e-0000NP-00@hooloovoo> <3FB1AC47.2050606@ccvcorp.com> Message-ID: <t064rvkr2ra3le0156nohaplvoi7eepp3m@4ax.com> 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: <A3ED9AAAE30FD611944200508B62C6B20483D42E@BPPNEXAMAIL> 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: <BBD8576D.11857%clay@shirky.com> 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: <BBD8576D.11857%clay@shirky.com> References: <BBD8576D.11857%clay@shirky.com> 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: <BBD8576D.11857%clay@shirky.com> <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: <BBD8576D.11857%clay@shirky.com> References: <BBD8576D.11857%clay@shirky.com> 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: <A3ED9AAAE30FD611944200508B62C6B20483D42E@BPPNEXAMAIL> References: <A3ED9AAAE30FD611944200508B62C6B20483D42E@BPPNEXAMAIL> 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: <BBD8576D.11857%clay@shirky.com> <20031113034136.GA6844@isc.upenn.edu> Message-ID: <Pine.A41.4.56.0311131537120.698042@hermes-22.rz.uni-frankfurt.de> 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: <Pine.LNX.4.44.0311131005080.3149-100000@hkn.eecs.berkeley.edu> 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: <Pine.LNX.4.44.0311131119300.3149-100000@hkn.eecs.berkeley.edu> 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: <BAY7-DAV15Jecd92bXC00000fce@hotmail.com> 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: <t504him8b22j$.re1jytis623p$.dlg@40tude.net> 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 <snip> > 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. <snip> > class ship(pygame.sprite.Sprite): <snip> > def _change(self): <snip> > 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: <BAY7-DAV15Jecd92bXC00000fce@hotmail.com> 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: <Pine.LNX.4.44.0311131332570.19815-100000@hkn.eecs.berkeley.edu> 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: <BAY7-DAV15Jecd92bXC00000fce@hotmail.com> (VN's message of "Thu, 13 Nov 2003 13:42:40 -0600") References: <BAY7-DAV15Jecd92bXC00000fce@hotmail.com> Message-ID: <m3brrgx8lw.fsf@hamster.pflaesterer.de> 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: <BAY7-DAV15Jecd92bXC00000fce@hotmail.com> Message-ID: <BBD96ACB.11956%clay@shirky.com> 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 > <section>.<option> and the values > """ > config = config.copy() > cp = ConfigParser.ConfigParser() > cp.read(file) > for sec in cp.sections(): > name = sec > for opt in cp.options(sec): > config[name + "." + opt] = int(cp.get(sec, opt).strip()) modified from example to get int() values. > return config > >if __name__=="__main__": > cf = LoadConfig("config.ini", _ConfigDefault) > print cf > > for n in range(cf['main.number_of_fans']): > print cf['fan' + '%1d' % n+'.dtai'] While this does work (ini file is posted below) I would like to address the values as: cf[fan0.dtai] instead of cf['fan0.dtai'] What did I do wrong? INI file: >; >; config.ini >; >; comment starts with a ; > >[main] >pump_address = 1 >number_of_boards = 8 >number_of_fans = 6 >control_address = 8 > > >[CO2] >sollwert = 800 > >[pump1] >max_speed = 100 >manual = 0 >manual_speed = 100 > >[pump2] >max_speed = 100 >manual = 0 >manual_speed = 100 > >[temps] >cool = 30 >heat = 15 > >; values for all fans > >[fans] >manual = 0 >manual_speed = 100 > >; values for specific fans, fans numbered from 0..number_of_fans - 1 > >[fan0] >dTai = -2 >dTao = +3 >dTwl = -1 >dTwh = 0 > > >[fan1] >dTai = 1 >dTao = -2 >dTwl = 3 >dTwh = -4 > >[fan2] >dTai = 0 >dTao = 0 >dTwl = 0 >dTwh = 0 > >[fan3] >dTai = 0 >dTao = 0 >dTwl = 0 >dTwh = 0 > >[fan4] >dTai = 0 >dTao = 0 >dTwl = 0 >dTwh = 0 > >[fan5] >dTai = 0 >dTao = 0 >dTwl = 0 >dTwh = 0 > >[control_group] >dTai = 0 >dTao = 0 >dTwl = 0 >dTwh = 0 > -- 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 cepl at surfbest.net Thu Nov 13 17:00:23 2003 From: cepl at surfbest.net (Matej Cepl) Date: Thu Nov 13 23:10:21 2003 Subject: [Tutor] IMAPlib.py problem -- search Message-ID: <1636309.7ihsGO9MNE@komensky.surfbest.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, can somebody explain me why this script fails saying that SEARCH is BAD? #!/usr/bin/env python import imaplib, sys, re, os, popen2, getpass, getopt, string imapuser="somebody" imaphost='neumail04.neu.edu' imapport=143 imappassword='something' imapinbox="INBOX" imap=imaplib.IMAP4(imaphost,imapport) res=imap.login(imapuser, imappassword) assertok(res, "login",imapuser, 'xxxxxxxx') res=imap.select(imapinbox, 1) assertok(res, 'select', imapinbox, 1) # it returns number of messages in response low=1 high=int(res[1][0]) # make the search #uids=imap.search(None,'NEW','HEADER Mailing-List ""',\ #'NOT HEADER List-Post') uids=imap.search(None,r'( NEW HEADER Mailing-List "" )') #Mailing-List: list neu-lps-students@yahoogroups.com; \ #contact neu-lps-students-owner@yahoogroups.com print uids Thanks, Matej - -- Matej Cepl, GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC 138 Highland Ave. #10, Somerville, Ma 02143, (617) 623-1488 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/s/774J/vJdlkhKwRAnEwAKCHaxgKIpaFVcdOJ2IKdv2v/rsYzACfWPjH mpZ5Md0q4elw2HoqEO2awpg= =jDGC -----END PGP SIGNATURE----- From phthenry at earthlink.net Fri Nov 14 02:47:58 2003 From: phthenry at earthlink.net (Paul Tremblay) Date: Fri Nov 14 02:48:09 2003 Subject: [Tutor] Re: sorting by values in dict In-Reply-To: <1cenjk0a6a5da.sg5w2d325tc2$.dlg@40tude.net> References: <20031113065231.GB3015@localhost.localdomain> <1cenjk0a6a5da.sg5w2d325tc2$.dlg@40tude.net> Message-ID: <20031114074758.GA2278@localhost.localdomain> On Thu, Nov 13, 2003 at 10:50:38AM +0100, Andrei wrote: > > 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')] > Ah, thanks. Thanks everyone else, too. Instead of making a dictionary to begin with, I simply will make a list of tupples and sort. I didn't know you could use sort with a list of tupples. That does the trick. Paul > > ===== > 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. What is this? So a robot can't read this, right? But how do you decode it? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From op73418 at mail.telepac.pt Fri Nov 14 06:54:40 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Nov 14 06:53:06 2003 Subject: [Tutor] dynamically creating files In-Reply-To: <bp1t9r$ao2$1@sea.gmane.org> References: <bp1t9r$ao2$1@sea.gmane.org> Message-ID: <4ig9rvcjgvrp95bvb92nv9isq3caiap0ke@4ax.com> On Fri, 14 Nov 2003 22:38:52 +0800, you wrote: >I am creating a program and have come to a problem. >I wish to write a class that handles file objects, ie opening, writing to, >and closing a file. I wish to dynamically create the file name, as each >instance would have its own file too use for processing. I am not sure on >what syntax is required to derive a filename from the 'self' instance. >Any tips/ TIA > Why bother? Isn't the builtin file object enough? With my best regards, G. Rodrigues From darnold02 at sprynet.com Fri Nov 14 07:39:47 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Fri Nov 14 07:41:47 2003 Subject: [Tutor] dynamically creating files References: <bp1t9r$ao2$1@sea.gmane.org> Message-ID: <0f2401c3aaac$6d2a6e60$6f11ba3f@defaultcomp> ----- Original Message ----- From: "bob" <nospam@245t.com> To: <tutor@python.org> Sent: Friday, November 14, 2003 8:38 AM Subject: [Tutor] dynamically creating files > I am creating a program and have come to a problem. > I wish to write a class that handles file objects, ie opening, writing to, > and closing a file. I wish to dynamically create the file name, as each > instance would have its own file too use for processing. I am not sure on > what syntax is required to derive a filename from the 'self' instance. > Any tips/ TIA > Would something like this work? It's not too thoroughly tested, but it might be a starting point : import os def getNewFile(dirStr): for i in xrange(0,1000): testname = '/'.join([dirStr,'filer%04d' % i]) try: f = open(testname,'r') f.close() except IOError: f = open(testname,'w') return (f,testname) class Filer(object): def __init__(self,targetDir): self.myfile, self.myfilename = getNewFile(targetDir) print 'using ', self.myfilename def writeLines(self): for i in range(10): txt = 'writing line %d to %s...' % (i, self.myfilename) print txt self.myfile.write(txt+'\n') def closeMyFile(self): self.myfile.close() if __name__ == '__main__': filer1 = Filer('c:/temp2') filer1.writeLines() filer1.closeMyFile() filer2 = Filer('c:/temp2') filer2.writeLines() filer2.closeMyFile() > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Fri Nov 14 08:14:57 2003 From: project5 at redrival.net (Andrei) Date: Fri Nov 14 08:17:29 2003 Subject: [Tutor] Re: dynamically creating files References: <bp1t9r$ao2$1@sea.gmane.org> <0f2401c3aaac$6d2a6e60$6f11ba3f@defaultcomp> Message-ID: <1ev2y5orm57a3.1clypetz85u0m.dlg@40tude.net> Don Arnold wrote on Fri, 14 Nov 2003 06:39:47 -0600: <snip> >> I am creating a program and have come to a problem. >> I wish to write a class that handles file objects, ie opening, writing to, >> and closing a file. I wish to dynamically create the file name, as each >> instance would have its own file too use for processing. I am not sure on >> what syntax is required to derive a filename from the 'self' instance. >> Any tips/ TIA >> > > Would something like this work? It's not too thoroughly tested, but it might > be a starting point : > <snip> > class Filer(object): > def __init__(self,targetDir): > self.myfile, self.myfilename = getNewFile(targetDir) > print 'using ', self.myfilename > def writeLines(self): > for i in range(10): > txt = 'writing line %d to %s...' % (i, self.myfilename) <snip> That's a wrapper for the file class which doesn't do a lot more than the file class itself. If it's necessary to have lines appear on the screen as well as in the file, it's better to subclass the file class and add that behaviour instead of making a new one from scratch. E.g.: >>> class myfile(file): ... def write(self, line="\n"): ... """Writes a line and appends "\n" if necessary.""" ... if line[-1]!="\n": # append newline ... line = line + "\n" ... print line, ... file.write(self, line) ... >>> mf = myfile("deleteme.txt", "w") >>> mf.write("bla") bla >>> mf.write("bla\n") bla >>> mf.close() >>> mf <closed file 'deleteme.txt', mode 'w' at 0x016B2088> -- 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 kalle at lysator.liu.se Fri Nov 14 08:33:36 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Fri Nov 14 08:33:55 2003 Subject: [Tutor] Re: sorting by values in dict In-Reply-To: <20031114074758.GA2278@localhost.localdomain> References: <20031113065231.GB3015@localhost.localdomain> <1cenjk0a6a5da.sg5w2d325tc2$.dlg@40tude.net> <20031114074758.GA2278@localhost.localdomain> Message-ID: <20031114133336.GC29814@i92.ryd.student.liu.se> [Paul Tremblay] > On Thu, Nov 13, 2003 at 10:50:38AM +0100, Andrei wrote: > > ===== > > 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. > > What is this? So a robot can't read this, right? But how do you > decode it? Rot13 is a very simple encryption method where you rotate each letter 13 steps alphabetically (a 13-step Caesar cipher). Example: A -> N C -> P N -> A Q -> D Note that rot13(rot13(x)) == x. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From karthik at james.hut.fi Fri Nov 14 08:54:55 2003 From: karthik at james.hut.fi (Karthikesh Raju) Date: Fri Nov 14 09:30:46 2003 Subject: [Tutor] Curses Programming Message-ID: <Pine.SGI.4.58.0311141549320.4797@james.hut.fi> Hi All, i am looking for a tutorial on curses other than the famous two: 1) Curses Programming in Python - David Mertz It is quite nice and good, but stops after the most basic key board inupt, on cant use the tab keys and other keys 2) Curses Programming with Python - AMK It is very nice, but i need more experience to read it ... :-(( . Actually i would want to have : a) tab and arrow based movements between fields b) colored input Presently i have just experimented with the nice curses of David Mertz in his example. Thankx in advance With warm regards karthik ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From project5 at redrival.net Fri Nov 14 09:47:22 2003 From: project5 at redrival.net (Andrei) Date: Fri Nov 14 09:49:50 2003 Subject: [Tutor] Re: Re: sorting by values in dict References: <20031113065231.GB3015@localhost.localdomain> <1cenjk0a6a5da.sg5w2d325tc2$.dlg@40tude.net> <20031114074758.GA2278@localhost.localdomain> Message-ID: <5vkkz2i7r92m$.1tqiiiuez3g2v.dlg@40tude.net> Paul Tremblay wrote on Fri, 14 Nov 2003 02:47:58 -0500: <snip> >> 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. > > What is this? So a robot can't read this, right? But how do you decode > it? Some newsreaders have an option to decode rot13. E.g. I use 40tude Dialog to read the Tutor list from the interface provided by Gmane.org and I can select the text and then select Unscramble. If your reader doesn't have this, you can use Python: >>> "text".encode('rot13') 'grkg' >>> "grkg".encode('rot13') 'text' Shows that re-encoding the encoded text returns the original text, like Kalle mentioned in a previous message. It is indeed protection against spam. Has worked nicely so far - my header address catches a full mailbox per day, the other one none at all. -- 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 jeff at ccvcorp.com Fri Nov 14 13:28:49 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Nov 14 13:24:02 2003 Subject: [Tutor] dynamically creating files In-Reply-To: <bp1t9r$ao2$1@sea.gmane.org> References: <bp1t9r$ao2$1@sea.gmane.org> Message-ID: <3FB51EE1.40808@ccvcorp.com> bob wrote: > I am creating a program and have come to a problem. > I wish to write a class that handles file objects, ie opening, writing to, > and closing a file. I wish to dynamically create the file name, as each > instance would have its own file too use for processing. I am not sure on > what syntax is required to derive a filename from the 'self' instance. > Any tips/ TIA Instead of trying to derive a filename from 'self', why not use the tempfile module? This will give you a file with a guaranteed unique filename. self.filename = tempfile.mktemp('.ext') fileobj = file(self.filename, "w+b") This will give you a fully qualified filename of a file that does not exist at the time mktemp() is called, and ensures that the filename will end in '.ext' (or whatever you pass as an argument). You can also control the directory that the tempfile is created in. Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Fri Nov 14 13:44:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 14 13:44:55 2003 Subject: [Tutor] Re: sorting by values in dict In-Reply-To: <20031114133336.GC29814@i92.ryd.student.liu.se> Message-ID: <Pine.LNX.4.44.0311141042420.22914-100000@hkn.eecs.berkeley.edu> > > > 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. > > > > What is this? So a robot can't read this, right? But how do you > > decode it? > > Rot13 is a very simple encryption method where you rotate each letter 13 > steps alphabetically (a 13-step Caesar cipher). Example: > > A -> N > C -> P > N -> A > Q -> D > > Note that rot13(rot13(x)) == x. By the way, Python has a built-in rot13 encoder and decoder: ### >>> "hello world".encode("rot13") 'uryyb jbeyq' ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Fri Nov 14 13:51:00 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 14 13:51:12 2003 Subject: [Tutor] dynamically creating files In-Reply-To: <bp1t9r$ao2$1@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0311141046200.22914-100000@hkn.eecs.berkeley.edu> On Fri, 14 Nov 2003, bob wrote: > I am creating a program and have come to a problem. I wish to write a > class that handles file objects, ie opening, writing to, and closing a > file. I wish to dynamically create the file name, as each instance would > have its own file too use for processing. Hi Bob, Sounds good. Can you tell us how you would like to make those names? The open() or file() function will let us open up a file of our choice. When we call it, we always pass in the name of the file to open: open("helloworld1.txt") It turns out that we can send in any "expression" in there, as long as it calculates to a string. So: open("hello" + "world1.txt") will do the same thing. Would something like this work for your program? Tell us more details about what kind of files you're trying to create; you might not even have to write a class. Good luck to you! From barnabydscott at yahoo.com Fri Nov 14 13:52:02 2003 From: barnabydscott at yahoo.com (Barnaby Scott) Date: Fri Nov 14 13:52:10 2003 Subject: [Tutor] [newbie] sanitizing HTML Message-ID: <20031114185202.48910.qmail@web41401.mail.yahoo.com> I am trying to write a script which will take some HTML and go through it stripping out all tags that are not expressly permitted in my script. The ones that I will permit will generally be the basic harmless ones like <p>, <br>, <hr>, <h1...>, <b> etc. I also want to allow some of the more complex ones (e.g. <a>, <img>, <body>, <table>) but limit their attributes to a permitted subset. Lastly I want to subvert all URI's that might be present in an img src, or a body background etc, only to be allowed to point to files stored locally. (Links will be permitted though). I obviously don't expect someone to hand me all this on a plate - unless someone has already done something exactly this - but I am a beginner and find the modules that I probably need rather baffling. Even reading the examples I found by searching the archives has left me thoroughly confused! I really need a shove in the right direction, and if possible some pointers to lots of examples of the modules in action. (Just in case you're wondering, my reason for wanting it is HTML email. At present I use a script that I wrote to delete all HTML sections of incoming email on the mail server. However I feel that this may have been a little harsh! In particular, I was surprised by the number of people who send HTML mail without a plain text alternative.) __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From littledanehren at yahoo.com Fri Nov 14 13:54:56 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Fri Nov 14 13:55:02 2003 Subject: [Tutor] dynamically creating files In-Reply-To: <bp1t9r$ao2$1@sea.gmane.org> Message-ID: <20031114185456.94002.qmail@web41812.mail.yahoo.com> --- bob wrote: > I am creating a program and have come to a problem. > I wish to write a class that handles file objects, > ie opening, writing to, > and closing a file. I wish to dynamically create the > file name, as each > instance would have its own file too use for > processing. I am not sure on > what syntax is required to derive a filename from > the 'self' instance. > Any tips/ TIA I think what you want to do is subclass the file type. Here's a simple subtype of the file class that has input from one file and output to another class. It will act similarly to a file in rU+ mode. class newfile(file): def __init__(self, inputfile, outputfile): self.inputfile = file(inputfile, 'rU') self.outputfile = file(outputfile, 'w') def read(self, *args): return self.inputfile.read(*args) def write(self, *args): return self.outputfile.write(*args) This code is untested and there may be errors in it. Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From vicki at thepenguin.org Fri Nov 14 14:24:14 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Fri Nov 14 14:28:00 2003 Subject: [Tutor] Write array to Status text Message-ID: <29748.206.53.226.235.1068837854.squirrel@www.thepenguin.org> I have a program wherein I write to the status bar like this: self.SetStatusText("This is the status bar") self.frame.SetStatusText(StatusText) I also have an array created like this: while i < 10: array[i]=value i = i +1 I would like to write the values in the array to the status bar. I tried: StatusText=errorarray[0:4] self.frame.SetStatusText(StatusText) TypeError: String or Unicode type required So, how does one convert the values of an array into a string for this purpose? --vicki From project5 at redrival.net Fri Nov 14 14:44:21 2003 From: project5 at redrival.net (Andrei) Date: Fri Nov 14 14:46:49 2003 Subject: [Tutor] Re: [newbie] sanitizing HTML References: <20031114185202.48910.qmail@web41401.mail.yahoo.com> Message-ID: <1a7n00jec7lof.4lmn3hxldyxv.dlg@40tude.net> Barnaby Scott wrote on Fri, 14 Nov 2003 10:52:02 -0800 (PST): > I am trying to write a script which will take some > HTML and go through it stripping out all tags that are > not expressly permitted in my script. The ones that I > will permit will generally be the basic harmless ones > like <p>, <br>, <hr>, <h1...>, <b> etc. You can subclass sgmllib.SGMLParser. By providing unknown_starttag, unknown_endtag, handle_entityref and handle_data implementations, you can "trap" every tag and analyze/modify/delete it. > I also want to allow some of the more complex ones > (e.g. <a>, <img>, <body>, <table>) but limit their > attributes to a permitted subset. <snip> The methods I mentioned above receive as parameters (tag, attrs), with attrs being a tuple (or list, I'm not sure) of attribute-value pairs. You can do with these attributes whatever you like when you rebuild the data. > I obviously don't expect someone to hand me all this > on a plate - unless someone has already done something > exactly this - but I am a beginner and find the Actually, I have. Not exactly (I have code which converts URL's to hyperlinks and changes img tags into links to the images), but it's not hard to see you could adapt it for your needs. If you're interested, download the code from http://pears.sf.net. Look at the LinkMaker class in de pearsengine.py file. It's pretty well documented. > modules that I probably need rather baffling. Even > reading the examples I found by searching the archives > has left me thoroughly confused! I really need a shove It looks harder than it is really :). <snip> > been a little harsh! In particular, I was surprised by > the number of people who send HTML mail without a > plain text alternative.) May they all burn. :) -- 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 amk at amk.ca Fri Nov 14 15:03:21 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri Nov 14 15:03:35 2003 Subject: [Tutor] Re: [newbie] sanitizing HTML In-Reply-To: <1a7n00jec7lof.4lmn3hxldyxv.dlg@40tude.net> References: <20031114185202.48910.qmail@web41401.mail.yahoo.com> <1a7n00jec7lof.4lmn3hxldyxv.dlg@40tude.net> Message-ID: <20031114200321.GA19016@rogue.amk.ca> On Fri, Nov 14, 2003 at 08:44:21PM +0100, Andrei wrote: > You can subclass sgmllib.SGMLParser. By providing unknown_starttag, > unknown_endtag, handle_entityref and handle_data implementations, you can > "trap" every tag and analyze/modify/delete it. I think these days you may want to start with HTMLParser.HTMLParser, which can also handle XML syntax (<br/>). --amk From sigurd at 12move.de Fri Nov 14 16:03:36 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Nov 14 16:04:50 2003 Subject: [Tutor] Write array to Status text In-Reply-To: <29748.206.53.226.235.1068837854.squirrel@www.thepenguin.org> (Vicki Stanfield's message of "Fri, 14 Nov 2003 14:24:14 -0500 (EST)") References: <29748.206.53.226.235.1068837854.squirrel@www.thepenguin.org> Message-ID: <m31xsak773.fsf@hamster.pflaesterer.de> On 14 Nov 2003, Vicki Stanfield <- vicki@thepenguin.org wrote: > I also have an array created like this: > while i < 10: > array[i]=value > i = i +1 Is that an array or a list? If you did nothing special it is a list. What is value? Do all entries have the same value? > I would like to write the values in the array to the status bar. I tried: > StatusText=errorarray[0:4] > self.frame.SetStatusText(StatusText) > TypeError: String or Unicode type required > So, how does one convert the values of an array into a string for this > purpose? Let's say your array is a list. So the slice (your [0:4]) returns a list with the first 4 items (index 0 upto 3) of the sliced list. So you must find a way to convert your list to a string. You can use the `join' method of strings. >>> l = ['a', 'b', 'c'] >>> ''.join(l) 'abc' >>> If your array would really be an array you could use the `tostring' method of arrays. >>> import array >>> arr = array.array('c', "I am an array of characters") >>> arr[0:4] array('c', 'I am') >>> arr[0:4].tostring() 'I am' >>> Karl -- Please do *not* send copies of replies to me. I read the list From BranimirP at cpas.com Fri Nov 14 16:11:59 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Fri Nov 14 16:12:09 2003 Subject: [Tutor] How to "install" new package? Message-ID: <33678E78A2DD4D418396703A750048D45E6924@RIKER> What is the proper procedure to install Python package? Do I have to create folder for package in any particular place in order to run successfull install, or initial location does not matter? >From the setup.py: """Distutils script for cx_PyOracleLib. To install: python setup.py install """ Not knowing any better, the above leaves impression that actual location of cx_PyOracleLib should not matter. Therefore, from the command prompt on my Win2K: C:\Py232>python C:\Python22Stuff\cx_PyOracleLib-2.1\setup.py install C:\Py232\lib\distutils\dist.py:213: UserWarning: 'licence' distribution option is deprecated; use 'license' warnings.warn(msg) running install running build running build_py file cx_CursorCache.py (for module cx_CursorCache) not found file cx_DumpData.py (for module cx_DumpData) not found file cx_ExportData.py (for module cx_ExportData) not found file cx_ImportData.py (for module cx_ImportData) not found error: package directory 'cx_OracleObject' does not exist No matter where I move cx_PyOracleLib-2.1 folder before I run setup.py - install fails. What am I doing wrong (how should it be done)? Branimir Petrovic From aschmidt at fredericksburg.com Fri Nov 14 16:16:05 2003 From: aschmidt at fredericksburg.com (aschmidt@fredericksburg.com) Date: Fri Nov 14 16:13:04 2003 Subject: [Tutor] Unlocking a windows file Message-ID: <200311142116.hAELG5CV015667@sws002.fredericksburg.com> Strange. I have a small script that runs and looks in a folder on a windows server for the existence of a file that matches a pattern. The files are put there as the result of another windows appplication that has chewed on the file in one folder and moved it to a new folder. I am trying to process the file and then move/rename/whatever that file to an archive folder of sorts. I can copy it, but cannot move it or rename it to a new folder. Its just not working. If the old process locked it somehow, how can I unlock it? Remove all system hooks it could have on it. Its just a text file. Thanks! Allen From rsmith at cff.org Fri Nov 14 16:46:49 2003 From: rsmith at cff.org (Smith, Ryan) Date: Fri Nov 14 16:49:30 2003 Subject: [Tutor] using global variables with functions Message-ID: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> Hello All, I am having some trouble with the way global variables interace with functions. I found some practice problems on the Ibilio.org website and one of them is creating a program that converts celcius to farenheit and vice versa. The following code is what I have come up with: #Prompt for user to enter the temp to convert >>>temp = raw_input("Enter a temperature: ") >>>>print temp >>>>choice = raw_input("Convert to (F)arhenheit or (C)elcius: ") #Function to convert from celcius to farenheit >>>def convert_cel(temp): ... tc = (5/9)*(temp - 32) ... return tc if choice == 'C': print convert_cel(temp) My problem is when I try to use temp as a variable in the convert_cel function. My understanding is that whatever the user enters as the temperature that is now the value of the temp variable. Since it is outside the function should it not be a global variable? I get the following error message: #Prompt for user to enter the temp to convert temp = raw_input("Enter a temperature: ") print temp choice = raw_input("Convert to (F)arhenheit or (C)elcius: ") #Function to convert from celcius to farenheit def convert_cel(): tc = (5/9)*(temp - 32) return tc if choice == 'C': print convert_cel() If anyone could help me see the "light" I would be most greatful. I would like to point out that I am not asking for the answer just help with clarifying my understanding and correcting any misconceptions. I have never programmed a day in my life but am really trying to learn. Thanks Ryan Smith From aschmidt at fredericksburg.com Fri Nov 14 16:53:21 2003 From: aschmidt at fredericksburg.com (aschmidt@fredericksburg.com) Date: Fri Nov 14 16:50:18 2003 Subject: [Tutor] Unlocking a windows file Message-ID: <200311142153.hAELrLKT017255@sws002.fredericksburg.com> Nevermind. Sorry for the disturbance. Getting late on a Friday and my head is just not thinking clearly. Danged Windows permissions.... aschmidt@fredericksburg.com wrote .. > Strange. > I have a small script that runs and looks in a folder on a windows server > for the existence of a file that matches a pattern. The files are put there > as the result of another windows appplication that has chewed on the file > in one folder and moved it to a new folder. I am trying to process the > file and then move/rename/whatever that file to an archive folder of sorts. > I can copy it, but cannot move it or rename it to a new folder. Its just > not working. > If the old process locked it somehow, how can I unlock it? Remove all system > hooks it could have on it. Its just a text file. > > Thanks! > > Allen From project5 at redrival.net Fri Nov 14 17:40:30 2003 From: project5 at redrival.net (Andrei) Date: Fri Nov 14 17:43:01 2003 Subject: [Tutor] Re: How to "install" new package? References: <33678E78A2DD4D418396703A750048D45E6924@RIKER> Message-ID: <hu0t0giaslvb.yigpllsjmbzg$.dlg@40tude.net> Branimir Petrovic wrote on Fri, 14 Nov 2003 16:11:59 -0500: > What is the proper procedure to install Python package? Do I have Extract it to some temp folder and execute "setup.py install". Things generally install themselves into the lib/site-packages subdirectory of Python. <snip> > file cx_ImportData.py (for module cx_ImportData) not found > error: package directory 'cx_OracleObject' does not exist Do you have anything with this name? Perhaps the package was incomplete or something. -- 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 sigurd at 12move.de Fri Nov 14 17:51:19 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Nov 14 17:55:41 2003 Subject: [Tutor] using global variables with functions In-Reply-To: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> (Ryan Smith's message of "Fri, 14 Nov 2003 16:46:49 -0500") References: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> Message-ID: <m3llqiinrh.fsf@hamster.pflaesterer.de> On 14 Nov 2003, Smith, Ryan <- rsmith@cff.org wrote: > #Prompt for user to enter the temp to convert >>>>temp = raw_input("Enter a temperature: ") >>>>>print temp >>>>>choice = raw_input("Convert to (F)arhenheit or (C)elcius: ") > #Function to convert from celcius to farenheit >>>>def convert_cel(temp): > ... tc = (5/9)*(temp - 32) > ... return tc > if choice == 'C': > print convert_cel(temp) > My problem is when I try to use temp as a variable in the convert_cel > function. My understanding is that whatever the user enters as the > temperature that is now the value of the temp variable. Since it is outside > the function should it not be a global variable? I get the following error > message: [same code] > If anyone could help me see the "light" I would be most greatful. I would > like to point out that I am not asking for the answer just help with We could speak about the design of your code but at the moment it should just work. Did you try at the Python prompt help(raw_input)? If so you would have seen that the return value is always a string. In your function you must have a number not a string. So how do you convert a string to a number? If it is an integer you write int(string) if it as a floating point value you write float(string). Then the second problem is your function. Type at the python prompt 5/9 What is the answer? I think 0. That is because of the way Python treats integer division. You can either use a floating point number 5/9.0 or if your Python version is newer than 2.2 you could write from __future__ import division Integer division will then behave like the floating point variant; if you wanted the old behaviour you could write 5//9 If you never programmed before it will help you IMO if you read the Python tutorial in the docs of Python. There are also some very good tutorials for beginners around especially for Python. Take a look ath the website http://www.python.org And ask questions here. Karl -- Please do *not* send copies of replies to me. I read the list From jsoons at juilliard.edu Fri Nov 14 17:57:31 2003 From: jsoons at juilliard.edu (Jonathan Soons) Date: Fri Nov 14 17:57:38 2003 Subject: [Tutor] function fails on recursion Message-ID: <33E101AC5AFF78419F466954A96854202F5A9E@mailbox.juilliard.edu> I would really like to uncomment the commented lines. This program runs well as is and produces one good page but when it iterates (or recurses?) to produce page 2, etc. it fails with the message: Traceback (most recent call last): File "./parseapps.py", line 171, in ? mklines(essay) File "./parseapps.py", line 46, in mklines words[0] = words[0] + " " + words[1] TypeError: object doesn't support item assignment I suspect 'words' has been somehow turned into a tuple. (It started out as a string) but I'd like to know the truth. Can anyone help? def mklines(field) : if len(field) < 4 : return words = field.split() while len(words) > 1 : while (len(words[0]) < 60) and len(words) > 1 : words[0] = words[0] + " " + words[1] words.remove(words[1]) PDF_continue_text(pdf, words[0]) words.remove(words[0]) # if PDF_get_value(pdf, "texty", 0) < INCH : # If text gets too low on the page # words = string.joinfields(words, " ") # turn words back into a string # newpage(words) # now I can feed it to newpage(string) if len(words) == 1 : PDF_continue_text(pdf, " " + words[0]) def newpage(words) : PDF_end_page(pdf) PDF_begin_page(pdf, WIDTH, HEIGHT) PDF_setfont(pdf, font0, 14) PDF_set_text_pos(pdf, INCH, 704) PDF_show(pdf, last + ", " + first) PDF_set_text_pos(pdf, INCH, 690) mklines(words) ##################### THIS IS THE ESSAY ###################### if len(fields[321]) > 4 : essay = fields[321] from pdflib_py import * pdf = PDF_new() PDF_open_file(pdf, os.path.join(fullpath, thisguy, thisguy + "_essay.pdf")) font0 = PDF_findfont(pdf, "Courier-Bold", "host", 0) font1 = PDF_findfont(pdf, "Courier", "host", 0) PDF_begin_page(pdf, WIDTH, HEIGHT) PDF_setfont(pdf, font0, 14) PDF_set_text_pos(pdf, 40, 690) PDF_show(pdf, last + ", " + first) PDF_set_text_pos(pdf, WIDTH - 144, 690) PDF_show(pdf, "ESSAY") PDF_setfont(pdf, font1, 12) PDF_set_text_pos(pdf, 40, 670) mklines(essay) # This is my function PDF_end_page(pdf) PDF_close(pdf) PDF_delete(pdf) From dyoo at hkn.eecs.berkeley.edu Fri Nov 14 18:13:53 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 14 18:14:00 2003 Subject: [Tutor] function fails on recursion In-Reply-To: <33E101AC5AFF78419F466954A96854202F5A9E@mailbox.juilliard.edu> Message-ID: <Pine.LNX.4.44.0311141510220.11364-100000@hkn.eecs.berkeley.edu> On Fri, 14 Nov 2003, Jonathan Soons wrote: > I would really like to uncomment the commented lines. This program runs > well as is and produces one good page but when it iterates (or > recurses?) to produce page 2, etc. it fails with the message: > > Traceback (most recent call last): > File "./parseapps.py", line 171, in ? > mklines(essay) > File "./parseapps.py", line 46, in mklines > words[0] = words[0] + " " + words[1] > TypeError: object doesn't support item assignment > > I suspect 'words' has been somehow turned into a tuple. (It started out > as a string) Hi Jonathan, Yes. The lines: if PDF_get_value(pdf, "texty", 0) < INCH : words = string.joinfields(words, " ") newpage(words) turns words from a list of strings into a single string, so it's a type problem. Instead of reassigning the result of joinfields() back into 'words', you may really want to use a different variable: if PDF_get_value(pdf, "texty", 0) < INCH : text = string.joinfields(words, " ") newpage(text) This should prevent the TypeError (although the program might not be correct quite yet... *grin*) Hope this helps! From BranimirP at cpas.com Fri Nov 14 18:56:19 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Fri Nov 14 18:56:28 2003 Subject: [Tutor] Re: How to "install" new package? Message-ID: <33678E78A2DD4D418396703A750048D45E6927@RIKER> > -----Original Message----- > From: Andrei [mailto:project5@redrival.net] > Sent: Friday, November 14, 2003 5:41 PM > To: tutor@python.org > Subject: [Tutor] Re: How to "install" new package? > > > Branimir Petrovic wrote on Fri, 14 Nov 2003 16:11:59 -0500: > > > What is the proper procedure to install Python package? Do I have > > Extract it to some temp folder and execute "setup.py install". Things > generally install themselves into the lib/site-packages > subdirectory of > Python. > Andrei, thanks for your reply. That's how I too understood package business - extract it anywhere then let distutils do its job and migrate whatever it needs to wherever appropriate. Unfortunately it does not work like that for me. My fear is that the problem has to do with where I've installed Python - instead in default C:\Python23 I installed it in C:\Py232. Now that you confirmed that my initial understanding of package installs was on the right track, I might explore what happens if I start from scratch and let Python install itself where it wants. > <snip> > > file cx_ImportData.py (for module cx_ImportData) not found > > error: package directory 'cx_OracleObject' does not exist > > Do you have anything with this name? Perhaps the package was > incomplete or > something. > No, I do not have anything with this name. What I do have is Anthony Tuininga's package called cx_Oracle that comes wrapped in Windows Installer and does install itself nicely and without problems (regardless of my questionable choice of installing Python into Py232 folder). I was trying to see what can I make of packages Anthony kindly open-sourced and shared (http://starship.python.net/crew/atuining/), so I've got his cx_OracleDBATools and cx_OracleTools both having goodies I'd very much like to play with, but none of which I can install. If extract package to temp folder then passing package's setup.py with install switch to python.exe does not do the trick, may be there is something in Python's disutils that breaks if the beast (Python) is to be found in unexpected place? Branimir From darnold02 at sprynet.com Fri Nov 14 19:01:59 2003 From: darnold02 at sprynet.com (Don Arnold) Date: Fri Nov 14 19:02:36 2003 Subject: [Tutor] Re: dynamically creating files References: <bp1t9r$ao2$1@sea.gmane.org><0f2401c3aaac$6d2a6e60$6f11ba3f@defaultcomp> <1ev2y5orm57a3.1clypetz85u0m.dlg@40tude.net> Message-ID: <0f5901c3ab0b$b9768c90$6f11ba3f@defaultcomp> ----- Original Message ----- From: "Andrei" <project5@redrival.net> To: <tutor@python.org> Sent: Friday, November 14, 2003 7:14 AM Subject: [Tutor] Re: dynamically creating files > Don Arnold wrote on Fri, 14 Nov 2003 06:39:47 -0600: > > <snip> > >> I am creating a program and have come to a problem. > >> I wish to write a class that handles file objects, ie opening, writing to, > >> and closing a file. I wish to dynamically create the file name, as each > >> instance would have its own file too use for processing. I am not sure on > >> what syntax is required to derive a filename from the 'self' instance. > >> Any tips/ TIA > >> > > > > Would something like this work? It's not too thoroughly tested, but it might > > be a starting point : > > > <snip> > > class Filer(object): > > def __init__(self,targetDir): > > self.myfile, self.myfilename = getNewFile(targetDir) > > print 'using ', self.myfilename > > def writeLines(self): > > for i in range(10): > > txt = 'writing line %d to %s...' % (i, self.myfilename) > <snip> > > That's a wrapper for the file class which doesn't do a lot more than the > file class itself.... True. The behaviour I was focusing on was each instance having its own unique file. > If it's necessary to have lines appear on the screen as > well as in the file, it's better to subclass the file class and add that > behaviour instead of making a new one from scratch. E.g.: > <snip> That's behaviour I introduced in my example as throwaway code just to give the instance something to do. I'm not sure if the OP wanted a 'has a' or an 'is a' relationship, so I opted for aggregation. Don From vicki at thepenguin.org Fri Nov 14 19:10:27 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Fri Nov 14 19:14:06 2003 Subject: [Tutor] Write array to Status text In-Reply-To: <m31xsak773.fsf@hamster.pflaesterer.de> References: <29748.206.53.226.235.1068837854.squirrel@www.thepenguin.org> <m31xsak773.fsf@hamster.pflaesterer.de> Message-ID: <33158.12.223.197.34.1068855027.squirrel@www.thepenguin.org> This looks like what I need, but I have to wait until I am in my office again on Monday to be sure. Thanks. --vicki > If your array would really be an array you could use the `tostring' > method of arrays. > >>>> import array >>>> arr = array.array('c', "I am an array of characters") >>>> arr[0:4] > array('c', 'I am') >>>> arr[0:4].tostring() > 'I am' >>>> > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythontutor at venix.com Fri Nov 14 20:41:37 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Fri Nov 14 20:41:52 2003 Subject: [Tutor] Re: How to "install" new package? In-Reply-To: <33678E78A2DD4D418396703A750048D45E6927@RIKER> References: <33678E78A2DD4D418396703A750048D45E6927@RIKER> Message-ID: <3FB58451.5060508@venix.com> The name and location of the "root" python directory should not matter. I've always used non-standard names and locations in Windows with no difficulty. Even if re-doing the install to the standard location fixes your problem, I would be astonished if the name and location were the real problem. Branimir Petrovic wrote: > > > If extract package to temp folder then passing package's > setup.py with install switch to python.exe does not do > the trick, may be there is something in Python's disutils > that breaks if the beast (Python) is to be found in > unexpected place? > > Branimir > > _______________________________________________ > 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 tachmelik13 at hotmail.com Fri Nov 14 23:04:01 2003 From: tachmelik13 at hotmail.com (Thomas Chmelik) Date: Fri Nov 14 23:04:08 2003 Subject: [Tutor] (no subject) Message-ID: <Law9-F9hPdHfKsp3MSi0000aa5a@hotmail.com> i am a beginning programmer and would really like to learn how to program in python, my teacher says it is a simple yet powerful computer language and can be learned by almost anyone, but he says lots of logic is involved in writing much of the programs, which i would love to do, but are there any tips you can give me, or any projects or programs to write to get me going to become a good programmer, please email me at tachmelik13@hotmail.com. _________________________________________________________________ Compare high-speed Internet plans, starting at $26.95. https://broadband.msn.com (Prices may vary by service area.) From mwagman at charter.net Fri Nov 14 23:12:45 2003 From: mwagman at charter.net (Mike Wagman) Date: Fri Nov 14 23:13:37 2003 Subject: [Tutor] (no subject) In-Reply-To: <Law9-F9hPdHfKsp3MSi0000aa5a@hotmail.com> References: <Law9-F9hPdHfKsp3MSi0000aa5a@hotmail.com> Message-ID: <1068869561.2591.8.camel@24-159-248-140.jvl.wi.charter.com> Start with some little number crunching - command line program. The give it a Gui. Ideas dice roller, days between dates, program that reverses text in a file, just something to give you some problem to think through. Also learn the shell and how to run things interactively. On Fri, 2003-11-14 at 22:04, Thomas Chmelik wrote: > i am a beginning programmer and would really like to learn how to program in > python, my teacher says it is a simple yet powerful computer language and > can be learned by almost anyone, but he says lots of logic is involved in > writing much of the programs, which i would love to do, but are there any > tips you can give me, or any projects or programs to write to get me going > to become a good programmer, please email me at tachmelik13@hotmail.com. > > _________________________________________________________________ > Compare high-speed Internet plans, starting at $26.95. > https://broadband.msn.com (Prices may vary by service area.) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From missive at hotmail.com Fri Nov 14 23:19:30 2003 From: missive at hotmail.com (Lee Harr) Date: Fri Nov 14 23:19:37 2003 Subject: [Tutor] IMAPlib.py problem -- search Message-ID: <BAY2-F816onZJ1X6ewx00007ab9@hotmail.com> >can somebody explain me why this script fails saying that SEARCH >is BAD? Do you get a traceback? > imapuser="somebody" > imaphost='neumail04.neu.edu' > imapport=143 > imappassword='something' > imapinbox="INBOX" My guess is that somebody is not in the database, or imaphost is not responding, or imappassword is incorrect. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From zehoefler at adelphia.net Sat Nov 15 00:28:36 2003 From: zehoefler at adelphia.net (zehoefler@adelphia.net) Date: Sat Nov 15 00:28:41 2003 Subject: [Tutor] trouble understanding "for" loops Message-ID: <20031115052836.RSFZ15666.mta8.adelphia.net@mail.adelphia.net> I was wondering if somebody could explain the "for" loop to me. I have a book on Python (Python Programming for the absolute beginner, ISBN 1-59200-073-8) and I couldn't understand the explanation very well. Here is an example: for i in range(10): print i, would make "0 1 2 3 4 5 6 7 8 9" be printed I'm mostly confused as to the purpose of the variable and how it is used. I understand that something is read, and that it is assigned to the variable "i". What exactly is happening here? I noticed that it cycles through range... going one number at a time... I mostly get it, but I'm still having just a tad bit of trouble. Something like "for letter in word:" is printing each letter of the string "word" on each line (apparently it inserts line breaks [\n] itself) P.S. Is there a way to get the Windows version of IDLE to, when you save your script, put the extension '.py' after the strings without having to enter it each time. I add the .py so I can access it faster, and its a bit tedious. From missive at hotmail.com Sat Nov 15 00:37:29 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Nov 15 00:37:37 2003 Subject: [Tutor] Re: Curses Programming Message-ID: <BAY2-F156rEzMXHVM1F0001bae5@hotmail.com> >i am looking for a tutorial on curses other than the famous two: >Actually i would want to have : > >a) tab and arrow based movements between fields Two things I learned while working with curses: 1. You can't just print values to debug your program :o) 2. Systems return different values for the same keys (even the same operating system on different hardware) Maybe this will help you: # keyvalues.py import logging import curses logger = logging.getLogger() hdlr = logging.FileHandler('keyvalues.log') logger.addHandler(hdlr) logger.setLevel(logging.INFO) def main(scr): ch = scr.getch() while ch != ord(' '): # press space bar to exit logger.info(ch) ch = scr.getch() curses.wrapper(main) _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From thomi at imail.net.nz Sat Nov 15 03:04:19 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Nov 15 03:04:29 2003 Subject: [Tutor] problems with re module Message-ID: <200311152104.19848.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Guys, I'm trying to write a function that searches through a string of plain text, that may (or may not) contain some tags which look like this: <Graphics file: pics/PCs/barbar2.jpg> and replace those tags with docbook markup, which looks like this: <graphic srccredit="Fix Me!" fileref='pics/PCs/barbar2.jpg' /> I'm using the re module, and a recursive algorithm to find and replace the offending strings, but I'm getting very weird results... I've tried to nut this out for the last 3-4 hours, but can't seem to get anywhere with it... here's the code: - --------------------------------- def processcol(message): """This procedure takes a column text as an argument, and returns the same text, without any illegal characters for XML. It even does a bit of text tidying""" message = message.replace('\n',' ') message = message.replace('\t',' ') m = re.search(r"<Graphics\s+file:\s+",message) #search for the starting tag. if m: start,end = m.span() cstart,cend = re.search(r">",message).span() fname = message[end:cstart - 1] message = message[:start] + "<graphic srccredit='Fix Me!' fileref='%s' />" % (fname)+ message[cend:] return processcol(message[cend:]) else: return message - ----------------------------------- There's some really simple reason why this doesn't go, but I can't quite put my finger on it... There were a whole raft of debugging print statements, but I removed them for your sanity ;) What's *meant* to happen: a string which may contain the offending tags gets passed to the processcol() function. a few simple cleanup operations are performed (removing newlines and tabs). Then, if a bad tag is found, the index where the tag starts is recorded, as well as where the tag ends. the filename is extracted, and the bad tag is replaced. Because the regex searching goes from left to right, we now pass the string to the right of the tag we have just fixed to ourselves - this means that if there were twobad tags, one after the other, the left hand one would be fixed first, and then the right hand one. If no bad tags are found, the message is returned. Can anyone here help me get this going properly? - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/td4D2tSuYV7JfuERAuFRAJ9p//NL94AWovOw3EBnAaZA1mu7gwCfbqjN FGl/VfrI/r4Zxe4fmrU7EU8= =BzZz -----END PGP SIGNATURE----- From project5 at redrival.net Sat Nov 15 06:34:32 2003 From: project5 at redrival.net (Andrei) Date: Sat Nov 15 06:37:01 2003 Subject: [Tutor] Re: Re: How to "install" new package? References: <33678E78A2DD4D418396703A750048D45E6927@RIKER> Message-ID: <1phvdhlfopngj.g7hg8fj8ty1m.dlg@40tude.net> Branimir Petrovic wrote on Fri, 14 Nov 2003 18:56:19 -0500: <snip> > it does not work like that for me. My fear is that the problem > has to do with where I've installed Python - instead in default > C:\Python23 I installed it in C:\Py232. Nah, I have Python in non-standard folders too (in fact, even non-standard drives). Can't be the problem. <snip> > If extract package to temp folder then passing package's > setup.py with install switch to python.exe does not do > the trick, may be there is something in Python's disutils > that breaks if the beast (Python) is to be found in > unexpected place? I don't think so. Perhaps you should ask the author of that package what's going on. -- 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 Sat Nov 15 06:45:34 2003 From: project5 at redrival.net (Andrei) Date: Sat Nov 15 06:48:01 2003 Subject: [Tutor] Re: trouble understanding "for" loops References: <20031115052836.RSFZ15666.mta8.adelphia.net@mail.adelphia.net> Message-ID: <18bx4j01ryur$.cjk1xfuvconz$.dlg@40tude.net> <zehoefler@adelphia.net> wrote on Sat, 15 Nov 2003 0:28:36 -0500: > I was wondering if somebody could explain the "for" loop to me. <snip> > > for i in range(10): > print i, range(X) is a function which returns a list of values starting at 0 and up to but not including X. So in this case the loop is equivalent to: for i in [0,1,2,3,4,5,6,7,8,9]: print i, What this loop does is this: it takes each element in that list (reading left to right) and assigns to the variable i the value of that element. Then it executes the loop code with it - in this case, it means that it prints i. Note that it's not required to use i inside the loop, you could just as well 'print 2' if you liked or whatever. Once the loop code is executed, it picks the next element in the list, assigns it to i and runs the loop code again. Etc. until it's at the end of the list. <snip> > I noticed that > it cycles through range... going one number at a time... I mostly > get it, but I'm still having just a tad bit of trouble. Something > like "for letter in word:" is printing each letter of the string > "word" on each line (apparently it inserts line breaks [\n] itself) Exactly like for letter in word (assuming word is a string). Strings are a bit like lists of individual chars so you can loop over them in the same way as you can loop over any other sequence (list, tuple). > P.S. Is there a way to get the Windows version of IDLE to, when you > save your script, put the extension '.py' after the strings without > having to enter it each time. I add the .py so I can access it faster, > and its a bit tedious. IDLE is a cross-platform editor. There isn't a 'Windows' version of it as such. I recommend you look at PythonWin or Scite or Spe which IMO are all better than IDLE. If you download the ActiveState Python distro, you get PythonWin installed for you: http://www.activestate.com/Products/ActivePython/ You can also get PythonWin from Mark Hammond's Win32 page, but you'll have to google for it because I don't have the address right now. Scite is at http://scintilla.org and Spe at http://spe.pycs.net. -- 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 Sat Nov 15 06:56:14 2003 From: project5 at redrival.net (Andrei) Date: Sat Nov 15 06:58:41 2003 Subject: [Tutor] Re: (no subject) References: <Law9-F9hPdHfKsp3MSi0000aa5a@hotmail.com> Message-ID: <h0b0wh1jygo9$.14pfjcv1h2qp3.dlg@40tude.net> Thomas Chmelik wrote on Fri, 14 Nov 2003 23:04:01 -0500: > i am a beginning programmer and would really like to learn how to program in > python, my teacher says it is a simple yet powerful computer language and > can be learned by almost anyone, but he says lots of logic is involved in > writing much of the programs, which i would love to do, but are there any Your teacher is right :). > tips you can give me, or any projects or programs to write to get me going I for one prefer working through a tutorial first. Look on the Python.org page at the beginners section - there are several good newbie tutorials, like Alan Gauld's, or How to think like a computer scientist in Python. Once you know all basics, you can start coding some simple project. Depending on what your interests are, pick something that can be done in less than 100 lines of code. A simple quiz, number guessing game, hangman, etc. Once you've figured it out, pick something harder. If you know what you want to use programming for (games, web, database, sciences, etc.), you can start focusing on that particular topic. > to become a good programmer, please email me at tachmelik13@hotmail.com. You should read the list if you want to learn Python IMO. Even if you don't have questions, just by reading other people's problems and solutions, you can learn things that might come in useful some time. Make sure when you subscribe that you select for the digest delivery method, otherwise you'll get lots of inidividual messages. Or use gmane.org to read the list as a newsgroup, the address is gmane.comp.python.tutor. -- 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 missive at hotmail.com Sat Nov 15 09:48:11 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Nov 15 09:48:17 2003 Subject: [Tutor] Re: problems with re module Message-ID: <BAY2-F41ix4A2DreBBs00009d01@hotmail.com> >I'm trying to write a function that searches through a string of plain >text, >that may (or may not) contain some tags which look like this: > ><Graphics file: pics/PCs/barbar2.jpg> > >and replace those tags with docbook markup, which looks like this: > ><graphic srccredit="Fix Me!" fileref='pics/PCs/barbar2.jpg' /> > Once the task becomes more complex, I usually end up using groups and moving the substitution out in to a separate function: import re def f(matchobj): #print matchobj.group(0), matchobj.group(1), matchobj.group(2) return '<graphic srccredit="Fix Me!" fileref="%s" />' % matchobj.group(2) def procol(message): """This procedure takes a column text as an argument, and returns the same text, without any illegal characters for XML. It even does a bit of text tidying""" message = message.replace('\n',' ') message = message.replace('\t',' ') msg = re.sub(r"<(Graphics\s+file:\s+)([^>]*)>", f, message) return msg if __name__ == '__main__': test_messages = ['<Graphics file: pics/PCs/barbar2.jpg>', 'some text before <Graphics file: pics/PCs/barbar2.jpg> two tags <Graphics file: pics/PCs/barbar2.jpg> and after'] for message in test_messages: print procol(message) _________________________________________________________________ >From Beethoven to the Rolling Stones, your favorite music is always playing on MSN Radio Plus. No ads, no talk. Trial month FREE! http://join.msn.com/?page=offers/premiumradio From BranimirP at cpas.com Sat Nov 15 12:05:20 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Sat Nov 15 12:05:25 2003 Subject: [Tutor] Re: Re: How to "install" new package? Message-ID: <33678E78A2DD4D418396703A750048D45E6928@RIKER> > -----Original Message----- > From: Andrei [mailto:project5@redrival.net] > <snip> > > it does not work like that for me. My fear is that the problem > > has to do with where I've installed Python - instead in default > > C:\Python23 I installed it in C:\Py232. > > Nah, I have Python in non-standard folders too (in fact, even > non-standard > drives). Can't be the problem. > Andrei, you are 100% right! Non-standard location for Python install is NOT it. As matter of fact, problem was in the way I tried to "install" the package. I did this: C:\Py232>python C:\Python22Stuff\cx_PyOracleLib-2.1\setup.py install Instead of: C:\temp\cx_PyOracleLib-2.1>C:\Py232\python setup.py install (python.exe is on my system path) The difference - current working directory MUST be one where package setup.py is! Once I've started from proper place distutils created: C:\temp\cx_PyOracleLib-2.1\build\lib then placed required modules inside lib, then copied stuff to Python's site-packages, then compiled all copied modules, and then I became richer for an experience... So the moral of the story is - "Always change your working directory to temp folder where the package you want to install is before issuing setup.py install!". Thanks for help. Branimir From phthenry at earthlink.net Fri Nov 14 23:48:12 2003 From: phthenry at earthlink.net (Paul Tremblay) Date: Sat Nov 15 15:57:56 2003 Subject: [Tutor] Re: How to "install" new package? In-Reply-To: <3FB58451.5060508@venix.com> References: <33678E78A2DD4D418396703A750048D45E6927@RIKER> <3FB58451.5060508@venix.com> Message-ID: <20031115044812.GA2307@localhost.localdomain> On Fri, Nov 14, 2003 at 08:41:37PM -0500, Lloyd Kvam wrote: > > The name and location of the "root" python directory should > not matter. I've always used non-standard names and locations > in Windows with no difficulty. Even if re-doing the install > to the standard location fixes your problem, I would be astonished > if the name and location were the real problem. > That's been my experience as well. What happens if you try to install another package? Could you download a small one (try sourceforge) and see what happens? If you get the same error, we know the problem lies outside the individual package. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From nullpointer at heartoftn.net Sat Nov 15 16:02:31 2003 From: nullpointer at heartoftn.net (Null Pointer) Date: Sat Nov 15 16:03:49 2003 Subject: [Tutor] Reading eth0 With Python Message-ID: <200311151602.31782.nullpointer@heartoftn.net> Anyone know if it is possible to read Linux's eth0 device using Python? Thanks, N.P. From kalle at lysator.liu.se Sat Nov 15 16:38:07 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Sat Nov 15 16:38:13 2003 Subject: [Tutor] Reading eth0 With Python In-Reply-To: <200311151602.31782.nullpointer@heartoftn.net> References: <200311151602.31782.nullpointer@heartoftn.net> Message-ID: <20031115213807.GE29814@i92.ryd.student.liu.se> [Null Pointer] > Anyone know if it is possible to read Linux's eth0 device using > Python? What do you mean by reading eth0? If you want to write an application that uses the network for communication of some sort you might want to take a look at a high level networking interface like the Twisted framework (http://twistedmatrix.com/products/twisted). Otherwise, a low level networking interface is available in the standard library module "socket". Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From thomi at imail.net.nz Sat Nov 15 16:50:25 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Nov 15 16:50:32 2003 Subject: [Tutor] Re: problems with re module In-Reply-To: <BAY2-F41ix4A2DreBBs00009d01@hotmail.com> References: <BAY2-F41ix4A2DreBBs00009d01@hotmail.com> Message-ID: <200311161050.25539.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > > Once the task becomes more complex, I usually end up using groups > and moving the substitution out in to a separate function: > hmm.. your test app worked great, but when i try to use your functions in my code, I get the following error: Traceback (most recent call last): File "./scripts/conv.py", line 119, in ? writeln('<entry>%s</entry>' % (procol(col)) ) File "./scripts/conv.py", line 42, in procol msg = re.sub(r"<(Graphics\s+file:\s+)([^>]*)>", f, message) File "/usr/lib/python2.3/sre.py", line 143, in sub return _compile(pattern, 0).sub(repl, string, count) File "/usr/lib/python2.3/sre.py", line 257, in _subx template = _compile_repl(template, pattern) File "/usr/lib/python2.3/sre.py", line 237, in _compile_repl p = _cache_repl.get(key) TypeError: list objects are unhashable However, I'm sure that the line: writeln('<entry>%s</entry>' % (procol(col)) ) passes a string to the function... the functions themselves remain unchanged... Given that I'm passing a string to the procol function (as you did in your code), surely everything should work? still stumped :-/ Thanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/tp+h2tSuYV7JfuERAhOpAJ0Xectitt44o+jnDK+RyRgKa7lrAACgkGwX G3EbVq3tGjhGndBPKbjLcbw= =o4CE -----END PGP SIGNATURE----- From pythontutor at venix.com Sat Nov 15 16:53:19 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Nov 15 16:53:39 2003 Subject: [Tutor] Reading eth0 With Python In-Reply-To: <200311151602.31782.nullpointer@heartoftn.net> References: <200311151602.31782.nullpointer@heartoftn.net> Message-ID: <3FB6A04F.1040703@venix.com> Python's device access is normally provided with C programs that are managed through a Python interface. Python is usually too slow to directly handle data from a fast device. Even a C program like tcpdump has difficulty keeping up with a busy network connection. Your best bet is probably to use tcpdump (or the equivalent) to store the packets and use python to analyze the data. Are you trying to communicate with or manage a device that doesn't support TCP/IP (or some other higher-level protocol)? Null Pointer wrote: > Anyone know if it is possible to read Linux's eth0 device using > Python? > > Thanks, N.P. > > > _______________________________________________ > 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 Sat Nov 15 17:14:19 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Nov 15 17:14:25 2003 Subject: [Tutor] Re: problems with re module Message-ID: <BAY2-F111Sd99VHGLfF0000a9c5@hotmail.com> >However, I'm sure that the line: > >writeln('<entry>%s</entry>' % (procol(col)) ) > >passes a string to the function... the functions themselves remain >unchanged... > (procol(col)) is not a tuple, but (procol(col),) is. I think I would write it as: writeln('<entry>%s</entry>' % procol(col)) though. _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From nullpointer at heartoftn.net Sat Nov 15 17:21:35 2003 From: nullpointer at heartoftn.net (Null Pointer) Date: Sat Nov 15 17:22:54 2003 Subject: [Tutor] Reading eth0 With Python In-Reply-To: <3FB6A04F.1040703@venix.com> References: <200311151602.31782.nullpointer@heartoftn.net> <3FB6A04F.1040703@venix.com> Message-ID: <200311151721.35614.nullpointer@heartoftn.net> On Saturday 15 November 2003 16:53, you wrote: > Python's device access is normally provided with C programs that > are managed through a Python interface. Python is usually too > slow to directly handle data from a fast device. Even a C > program like tcpdump has difficulty keeping up with a busy > network connection. I suspected that. > > Your best bet is probably to use tcpdump (or the equivalent) to > store the packets and use python to analyze the data. > > Are you trying to communicate with or manage a device that > doesn't support TCP/IP (or some other higher-level protocol)? Actually, I'm trying to determine when packets are flowing into and out of eth0, __except__ for the UDP status packets originating from my ISDN-TA/Hub/Router, which arrive every ten seconds. To do that, I need to examine the packets for sending host/port information, AFAIK. To put it another way, I want to be able to react to any outbound packet and any inbound packet that isn't coming from my ISDN-TA/Hub/Router. I do have a script running monitoring the UDP status packets on port 2071, but I also need to know when data comes in destined for any other port, and when any outbound packets occur. I've considered piping the output of tcpdump into a Python script, but I was hoping for a cleaner solution. Did I mention I am new to Linux and Python. Nothing like jumping in the deep end. {:^)> N. P. > Null Pointer wrote: > > Anyone know if it is possible to read Linux's eth0 device using > > Python? From amk at amk.ca Sat Nov 15 17:27:22 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sat Nov 15 17:27:36 2003 Subject: [Tutor] Reading eth0 With Python In-Reply-To: <200311151721.35614.nullpointer@heartoftn.net> References: <200311151602.31782.nullpointer@heartoftn.net> <3FB6A04F.1040703@venix.com> <200311151721.35614.nullpointer@heartoftn.net> Message-ID: <20031115222722.GA20755@rogue.amk.ca> On Sat, Nov 15, 2003 at 05:21:35PM -0500, Null Pointer wrote: > I've considered piping the output of tcpdump into a Python script, > but I was hoping for a cleaner solution. I believe tcpdump is built on top of of a lower-level library called libpcap, and there's a Python wrapper for it. --amk From thomi at imail.net.nz Sat Nov 15 17:27:33 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Nov 15 17:27:44 2003 Subject: [Tutor] Re: problems with re module In-Reply-To: <BAY2-F111Sd99VHGLfF0000a9c5@hotmail.com> References: <BAY2-F111Sd99VHGLfF0000a9c5@hotmail.com> Message-ID: <200311161127.33223.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > (procol(col)) is not a tuple, but (procol(col),) is. > I think I would write it as: > writeln('<entry>%s</entry>' % procol(col)) > though. Unfortunately, that doesn't make any difference :-/ attached is the complete source. hopefully someone can spot what I'm doing wrong .... - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/tqhV2tSuYV7JfuERAvk9AJ960RxIJk2MfU8m0Wyc8sCMpViWJgCeOTvV dsT9r/iDb/NdPP8MeGRm+No= =OI9u -----END PGP SIGNATURE----- -------------- next part -------------- A non-text attachment was scrubbed... Name: conv.py Type: text/x-python Size: 3624 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20031116/8eda1fb5/conv.py From missive at hotmail.com Sat Nov 15 17:41:44 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Nov 15 17:41:50 2003 Subject: [Tutor] Re: problems with re module Message-ID: <BAY2-F12uSNGDQ6on7g00009982@hotmail.com> for col in CurrentLine: writeln('<entry>%s</entry>' % procol(col)) Since this is where it is failing, check what you are feeding this... for col in CurrentLine: print col writeln('<entry>%s</entry>' % procol(col)) My guess is that col is an empty list at some point. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From thomi at imail.net.nz Sat Nov 15 17:44:44 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Nov 15 17:44:56 2003 Subject: [Tutor] Re: problems with re module In-Reply-To: <BAY2-F12uSNGDQ6on7g00009982@hotmail.com> References: <BAY2-F12uSNGDQ6on7g00009982@hotmail.com> Message-ID: <200311161144.44513.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > > for col in CurrentLine: > print col > writeln('<entry>%s</entry>' % procol(col)) > > > My guess is that col is an empty list at some point. > nope ;) I've done this: for col in CurrentLine: print "type of col is: %s \tCol is: %s" % (type(col),string.strip(col)) writeln('<entry>%s</entry>' % procol(string.strip(col)) ) ... the output is: <row>type of col is: <type 'str'> Col is: Race and then the traceback... - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/tqxc2tSuYV7JfuERAtbyAJ4kpAq2wijRZgO4NrJw8kRlNrBYNgCdGgeT TovQe/guyM71Lo4sJOlPKaY= =VHHa -----END PGP SIGNATURE----- From nullpointer at heartoftn.net Sat Nov 15 17:54:00 2003 From: nullpointer at heartoftn.net (Null Pointer) Date: Sat Nov 15 17:55:57 2003 Subject: [Tutor] Reading eth0 With Python Message-ID: <200311151754.00896.nullpointer@heartoftn.net> On Saturday 15 November 2003 17:27, A.M. Kuchling wrote: > On Sat, Nov 15, 2003 at 05:21:35PM -0500, Null Pointer wrote: > > I've considered piping the output of tcpdump into a Python > > script, but I was hoping for a cleaner solution. > > I believe tcpdump is built on top of of a lower-level library > called libpcap, and there's a Python wrapper for it. Thank you; that is very helpful information. Google reveals it is at Sourceforge. I'll see what I can do with it. N.P. From pythontutor at venix.com Sat Nov 15 18:30:45 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Nov 15 18:30:57 2003 Subject: [Tutor] Reading eth0 With Python In-Reply-To: <200311151721.35614.nullpointer@heartoftn.net> References: <200311151602.31782.nullpointer@heartoftn.net> <3FB6A04F.1040703@venix.com> <200311151721.35614.nullpointer@heartoftn.net> Message-ID: <3FB6B725.2090905@venix.com> I expect that snort should be able to do what you want. http://www.linuxsecurity.com/articles/intrusion_detection_article-6514.html Linux Snort-Inline Toolkit That link should help you get started. Null Pointer wrote: > On Saturday 15 November 2003 16:53, you wrote: > > >>Python's device access is normally provided with C programs that >>are managed through a Python interface. Python is usually too >>slow to directly handle data from a fast device. Even a C >>program like tcpdump has difficulty keeping up with a busy >>network connection. > > > I suspected that. > > >>Your best bet is probably to use tcpdump (or the equivalent) to >>store the packets and use python to analyze the data. >> >>Are you trying to communicate with or manage a device that >>doesn't support TCP/IP (or some other higher-level protocol)? > > > Actually, I'm trying to determine when packets are flowing into and > out of eth0, __except__ for the UDP status packets originating from > my ISDN-TA/Hub/Router, which arrive every ten seconds. To do that, > I need to examine the packets for sending host/port information, > AFAIK. > > To put it another way, I want to be able to react to any outbound > packet and any inbound packet that isn't coming from my > ISDN-TA/Hub/Router. > > I do have a script running monitoring the UDP status packets on port > 2071, but I also need to know when data comes in destined for any > other port, and when any outbound packets occur. > > I've considered piping the output of tcpdump into a Python script, > but I was hoping for a cleaner solution. > > Did I mention I am new to Linux and Python. Nothing like jumping in > the deep end. {:^)> > > N. P. > > > >>Null Pointer wrote: >> >>>Anyone know if it is possible to read Linux's eth0 device using >>>Python? > > > > _______________________________________________ > 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 simple_stuff at hotmail.com Sat Nov 15 18:39:18 2003 From: simple_stuff at hotmail.com (Tom Semple) Date: Sat Nov 15 18:39:48 2003 Subject: [Tutor] PythonWin cannot find win32ui.pyd Message-ID: <Sea2-DAV3GT9KP4vtAs000020d9@hotmail.com> I wanted to replace my Python 2.3 with the ActiveState edition of same. I uninstalled the former, installed the latter, but when I try to launch PythonWin I get the aforementioned error (the file is there in one of the Lib subdirectories, presumably where it is supposed to be). Have tried restarting Windows, and the 'repair' option of the install, to no avail. Install directory is 'd:\python23\" rather than the default of "c:\python23\". Any suggestions of what to check? Thanks Tom Semple -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031115/41dc702e/attachment.html From phthenry at earthlink.net Sat Nov 15 18:42:06 2003 From: phthenry at earthlink.net (Paul Tremblay) Date: Sat Nov 15 18:42:13 2003 Subject: [Tutor] Re: How to "install" new package? In-Reply-To: <20031115044812.GA2307@localhost.localdomain> References: <33678E78A2DD4D418396703A750048D45E6927@RIKER> <3FB58451.5060508@venix.com> <20031115044812.GA2307@localhost.localdomain> Message-ID: <20031115234206.GA1918@localhost.localdomain> On Fri, Nov 14, 2003 at 11:48:12PM -0500, Paul Tremblay wrote: > > On Fri, Nov 14, 2003 at 08:41:37PM -0500, Lloyd Kvam wrote: > > > > The name and location of the "root" python directory should > > not matter. I've always used non-standard names and locations > > in Windows with no difficulty. Even if re-doing the install > > to the standard location fixes your problem, I would be astonished > > if the name and location were the real problem. > > > > That's been my experience as well. What happens if you try to install > another package? Could you download a small one (try sourceforge) and > see what happens? If you get the same error, we know the problem lies > outside the individual package. > > Paul > Since you wrote me off this mailing list and indicated that you install other packages with no problem, it would seem that the problem is not with your python installation, but with the individual package. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From missive at hotmail.com Sat Nov 15 19:40:41 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Nov 15 19:40:47 2003 Subject: [Tutor] Re: problems with re module Message-ID: <BAY2-F105VgKMy5KINz000047d9@hotmail.com> >the output is: > ><row>type of col is: <type 'str'> Col is: Race > You are using CurrentLine in two different places, and in two different ways. Here at the beginning, it is a string... CurrentLine = "" for line in f: if line.isspace() or line == '': pass elif line[0] == '+': if initial: writeln("<tgroup cols='%d'>\n<tbody>\n" % (len(string.split(line,'+')[1:-1] initial=False else: #can we assume that formatting ends with a newline? probably - for the time if CurrentLine: writeln('<row>') #process the line here: CurrentLine = string.split(CurrentLine,'|')[1:-1] and now here, you change it in to a list. Try changing the name of one of these, or rethinking your algorithm. _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From BranimirP at cpas.com Sat Nov 15 21:13:57 2003 From: BranimirP at cpas.com (Branimir Petrovic) Date: Sat Nov 15 21:13:59 2003 Subject: [Tutor] Re: How to "install" new package? Message-ID: <33678E78A2DD4D418396703A750048D45E6929@RIKER> > -----Original Message----- > From: Paul Tremblay [mailto:phthenry@earthlink.net] > Sent: Saturday, November 15, 2003 6:42 PM > To: tutor@python.org > Subject: Re: [Tutor] Re: How to "install" new package? > > > > Since you wrote me off this mailing list and indicated that > you install > other packages with no problem, it would seem that the problem is not > with your python installation, but with the individual package. > To install that particular package I had to change working directory to the temp folder where package setup.py was located, and after that - everything went just fine. Since I lack Python know-how I can not say if this is normal (the way it normally is with other packages as well) or not. This is how full setup.py I ran looks like: """Distutils script for cx_PyGenLib. To install: python setup.py install """ from distutils.core import setup MODULES = [ "cx_ClassLibrary", "cx_CVS", "cx_Freezer", "cx_FTP", "cx_IniFile", "cx_OptionParser", "cx_Parser", "cx_PrettyPrinter", "cx_ReadLine", "cx_ServiceFramework", "cx_Settings", "cx_ShellUtils", "cx_Threads", "cx_Utils", "cx_Win32Pipe", "cx_Win32Service", "cx_XML", "modulefinder", "optparse", "_strptime", "tarfile", "textwrap" ] setup( name = "cx_PyGenLib", version = "2.2", description = "Set of general Python modules", licence = "See LICENSE.txt", long_description = "Set of general Python modules used by a " + \ "number of Computronix projects (cx_Freeze, " + \ "cx_OracleTools, cx_OracleDBATools)", author = "Anthony Tuininga", author_email = "anthony@computronix.com", url = "http://www.computronix.com/utilities.shtml", py_modules = MODULES) By the looks of it - I'd say that real culprit (reason for forcing change of working directory) is hiding somewhere in distutils.core.setup (but beeing Python newbe - what do I know, may be its not?)... Branimir From eur at fiwihex.nl Sat Nov 15 21:56:37 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Sat Nov 15 21:56:43 2003 Subject: [Tutor] troubles with ConfigParser Message-ID: <j4pdrvksv3bs11lnfssqp8hlllinq8lvr0@4ax.com> Hi I did use the configparser and it is working great. There are some troubles, though, especially when writing an INI file. Reading is just fine. here is my code: # program settings4.py import sys import ConfigParser if __name__=="__main__": st = ConfigParser.ConfigParser() # get pump controller parameters st.add_section('co2') st.set('co2', 'sollwert', 77) st.add_section('pump1') st.add_section('pump2') st.set('pump1', 'max_speed', 17) st.set('pump2', 'max_speed', 27) st.set('pump1', 'manual_speed', 37) st.set('pump2', 'manual_speed', 47) st.set('pump1', 'manual', 7) st.set('pump2', 'manual', 7) st.add_section('temps') st.set('temps', 'heat', 57) st.set('temps', 'cool', 67) # get fan settings for n in range(6): st.add_section('fan%1d' % n ) st.set('fan%1d' % n, 'heat', 50+n) st.set('fan%1d' % n, 'cool', 60+n) st.set('fan%1d' % n, 'fan_manual_speed', n) st.set('fan%1d' % n, 'fan_manual', 10+n) st.set('fan%1d' % n, 'dtai', 1) st.set('fan%1d' % n, 'dtao', 1) st.set('fan%1d' % n, 'dtwl', 1) st.set('fan%1d' % n, 'dtwh', 1) for sect in st.sections(): print '[', sect, ']' for opt in st.options(sect): print opt # print st.get(sect, opt) print # st.write('settings.ini') ################# If I unhash either of the two lines, I run into trouble: >Traceback (most recent call last): > File "st_try.py", line 78, in ? > print st.get(sect, opt) > File "/usr/local/lib/python2.2/ConfigParser.py", line 280, in get > return self._interpolate(section, option, value, d) > File "/usr/local/lib/python2.2/ConfigParser.py", line 288, in _interpolate > if value.find("%(") != -1: >AttributeError: 'int' object has no attribute 'find' ??? It seems the get() doesn't work. Did I use the set() function wrong? >Traceback (most recent call last): > File "st_try.py", line 81, in ? > st.write('settings.ini') > File "/usr/local/lib/python2.2/ConfigParser.py", line 351, in write > fp.write("[%s]\n" % section) >AttributeError: 'str' object has no attribute 'write' ??? Should this file exist? (It does) Should I open it first? (I tried) -- 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 thomi at imail.net.nz Sat Nov 15 22:04:20 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Nov 15 22:04:28 2003 Subject: [Tutor] Re: problems with re module In-Reply-To: <BAY2-F105VgKMy5KINz000047d9@hotmail.com> References: <BAY2-F105VgKMy5KINz000047d9@hotmail.com> Message-ID: <200311161604.20773.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > You are using CurrentLine in two different places, and > in two different ways. Here at the beginning, it is > a string... > > and now here, you change it in to a list. > > Try changing the name of one of these, or rethinking your algorithm. > While what you say it true, it works (It's not very beautiful, but it works). I've changed it, so the loop now reads: - -------------------------------- CurrentLine = "" for line in f: if line.isspace() or line == '': pass elif line[0] == '+': if initial: writeln("<tgroup cols='%d'>\n<tbody>\n" % (len(string.split(line,'+') [1:-1]) )) initial=False else: #can we assume that formatting ends with a newline? probably - for the time being. if CurrentLine: writeln('<row>') #process the line here: Line = string.split(CurrentLine,'|')[1:-1] for col in Line: print "type of col is: %s \tCol is: %s" % (type(col),string.strip(col)) writeln('<entry>%s</entry>' % procol(string.strip(col)) ) writeln('</row>\n') CurrentLine = "" else: CurrentLine = CurrentLine + line - ------------------------------------------ I'm sorry, but I still cannot see the error here.. As far as I can see, this *should* work.. what does the error message mean anyway? what is a "hashable" object? THat might enable me to debug my own programs better ;) Thanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/tuk02tSuYV7JfuERAn+2AJ4myM3mwZIxxy2cAiuqEBgB5l31lgCeK9LG gE9Cl6HT8tw8XWYJP2AtggE= =Jbh4 -----END PGP SIGNATURE----- From beyondthezero at earthlink.net Sun Nov 16 01:28:38 2003 From: beyondthezero at earthlink.net (Peter Jakubowicz) Date: Sun Nov 16 01:28:51 2003 Subject: [Tutor] IDLE question Message-ID: <5.2.1.1.0.20031115222403.00b390b8@earthlink.net> Hi, After having been idle myself w/r/t Python programming for a while, I've just installed version 2.3. For some weird reason, I can run programs from the command line and from the interactive prompt; but I can't run a script in IDLE, i.e., write my script in a new window and then press F5; when I do, the focus switches back to the interactive window and my program hasn't run. I had no problems with the previous version of IDLE. Any help would be appreciated. TIA, Peter From glingl at aon.at Sun Nov 16 05:53:07 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Nov 16 05:55:04 2003 Subject: [Tutor] IDLE question In-Reply-To: <5.2.1.1.0.20031115222403.00b390b8@earthlink.net> References: <5.2.1.1.0.20031115222403.00b390b8@earthlink.net> Message-ID: <3FB75713.90003@aon.at> Peter Jakubowicz schrieb: > Hi, > > After having been idle myself w/r/t Python programming for a while, > I've just installed version 2.3. For some weird reason, I can run > programs from the command line and from the interactive prompt; but I > can't run a script in IDLE, i.e., write my script in a new window and > then press F5; when I do, the focus switches back to the interactive > window and my program hasn't run. I had no problems with the previous > version of IDLE. Any help would be appreciated. TIA, Hi Peter, Does your programm produce any output? E. g. via print statements? (Or does it only define functions?) Or is it a GUI-Program using Tkinter? In this case IDLE 1.0 behaves different form the older versions. If you sent a short sample-program showing your problem, more precise help could be given. Regards, Gregor > > Peter > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From python at comber.cix.co.uk Sun Nov 16 06:05:13 2003 From: python at comber.cix.co.uk (Eddie Comber) Date: Sun Nov 16 06:08:57 2003 Subject: [Tutor] Accessing the name of an instance variable Message-ID: <BEEOLJNPLOPIONOMGLAAIEGHCIAA.python@comber.cix.co.uk> For debugging purposes, I would like to be able to print the name of some instances of classes directly from the program, together with the class data. The data is of course simple but getting the name is a problem to me. The best I have come up with so far is vars(), from which I can scan for instances of the relevant classes. However the name of the instance is returned as a string. How would I get my hands on the actual instance from this in order to get at its instance so as to print the data? Or is there a better way of going about what I need to do? Thanks, Eddie. From glingl at aon.at Sun Nov 16 07:26:05 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Nov 16 07:28:03 2003 Subject: [Tutor] Accessing the name of an instance variable Message-ID: <3FB76CDD.3070402@aon.at> Eddie Comber schrieb: >For debugging purposes, I would like to be able to print the name of some >instances of classes directly from the program, together with the class >data. The data is of course simple but getting the name is a problem to me. > >The best I have come up with so far is vars(), from which I can scan for >instances of the relevant classes. > >However the name of the instance is returned as a string. How would I get my >hands on the actual instance from this in order to get at its instance so as >to print the data? Or is there a better way of going about what I need to >do? > > Here an example, which uses the built-in function getattr. Is it this, what you need? >>> class A: def __init__(self,x,y): self.one = x self.two = y >>> a = A(1,2) >>> b = A(1001,1002) >>> for name, instance in vars().items(): if isinstance(instance,A): print name, instance.one, instance.two a 1 2 b 1001 1002 >>> for name, instance in vars().items(): if isinstance(instance,A): print name for var in vars(instance): print var, getattr(instance,var) a two 2 one 1 b two 1002 one 1001 >>> Regards, Gregor >Thanks, >Eddie. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From op73418 at mail.telepac.pt Sun Nov 16 07:41:35 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Nov 16 07:39:55 2003 Subject: [Tutor] Accessing the name of an instance variable In-Reply-To: <BEEOLJNPLOPIONOMGLAAIEGHCIAA.python@comber.cix.co.uk> References: <BEEOLJNPLOPIONOMGLAAIEGHCIAA.python@comber.cix.co.uk> Message-ID: <khrervgj9mejrrmavf35d3i7t6am30oueg@4ax.com> On Sun, 16 Nov 2003 11:05:13 -0000, you wrote: >For debugging purposes, I would like to be able to print the name of some >instances of classes directly from the program, together with the class >data. The data is of course simple but getting the name is a problem to me. > >The best I have come up with so far is vars(), from which I can scan for >instances of the relevant classes. > >However the name of the instance is returned as a string. How would I get my >hands on the actual instance from this in order to get at its instance so as >to print the data? Or is there a better way of going about what I need to >do? Variables in Python are just names (e.g. strings) that are bounded (or reference) some value, a Python object. Object's per se are nameless. A collection of names, values is called a namespace, and is currently implemented as a dictionary. The following shows that, as in real life, an object can have more than one name. >>> a = b = [] >>> print a is b True Having said this, look at the globals, locals functions >>> print globals.__doc__ globals() -> dictionary Return the dictionary containing the current scope's global variables. >>> print locals.__doc__ locals() -> dictionary Update and return a dictionary containing the current scope's local variables. As a final note, shouldn't you be using a *debugger* for debugging purposes? Also consider the unittest module for testing your code. If well exercised you can dispense with a debugger altogether. With my best regards, G. Rodrigues From missive at hotmail.com Sun Nov 16 07:58:33 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Nov 16 07:58:38 2003 Subject: [Tutor] Re: problems with re module Message-ID: <BAY2-F49mEIkLeoOWGM0000be20@hotmail.com> >what does the error message mean anyway? what is a "hashable" object? THat >might enable me to debug my own programs better ;) Only certain objects can be used as dictionary keys: >>>key1 = 55 >>>key2 = 'fifty-six' >>>key3 = ('five', 'seven') >>>key4 = [5, 8] >>>d = {} >>>d[key1] = 'foo' >>>d[key2] = 'foo' >>>d[key3] = 'foo' >>>d[key4] = 'foo' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: list objects are unhashable _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From missive at hotmail.com Sun Nov 16 08:17:23 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Nov 16 08:17:29 2003 Subject: [Tutor] Re: problems with re module Message-ID: <BAY2-F170vDpEDiOa7d0000bea3@hotmail.com> CurrentLine = "" for line in f: if line.isspace() or line == '': pass elif line[0] == '+': # I think maybe you want != here if initial: writeln("<tgroup cols='%d'>\n<tbody>\n" % (len(string.split(line,'+')[1:-1]) )) initial=False else: #can we assume that formatting ends with a newline? probably - for the time being. if CurrentLine: # so the first time through, do nothing. # second time, CurrentLine will actually be the # previous line. This is very confusing. writeln('<row>') #process the line here: Line = string.split(CurrentLine,'|')[1:-1] for col in Line: # instead of just checking col, try looking at # line, Line, and CurrentLine here. print "type of col is: %s \tCol is: %s" % (type(col),string.strip(col)) writeln('<entry>%s</entry>' % procol(string.strip(col)) ) writeln('</row>\n') CurrentLine = "" else: CurrentLine = CurrentLine + line _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From op73418 at mail.telepac.pt Sun Nov 16 09:32:52 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Nov 16 09:31:13 2003 Subject: [Tutor] Accessing the name of an instance variable In-Reply-To: <BEEOLJNPLOPIONOMGLAAMEGJCIAA.comber@cix.co.uk> References: <khrervgj9mejrrmavf35d3i7t6am30oueg@4ax.com> <BEEOLJNPLOPIONOMGLAAMEGJCIAA.comber@cix.co.uk> Message-ID: <qj1frvof6e9k1oika0trrai9k4dih6mcsm@4ax.com> On Sun, 16 Nov 2003 13:53:41 -0000, you wrote: >Thanks Goncalo. I have sorted something out with the below, but it won't >work from another module (see further below). > >The purpose is to print a description of the objects created for third party >users of my code. > >Eddie. > >class A: > def __init__(self,x,y): > self.one = x > self.two = y > > def describe(self): > print 'Describing' > this_instance = id(self) > for name, instance in globals().items(): # vars() > print name > if isinstance(instance,A): > if id(instance) == this_instance: > print 'Description of', name > >#pp.pprint(read_code_helper.helper.description(self)) > print self.one, self.two > >if __name__ == '__main__' : > > a = A(1,2) > b = A(1001,1002) > > a.describe() > b.describe() > > >import get_name > >a = get_name.A(1,2) > >a.describe() #dosen't pick up the name, presumably a scoping issue. > > Yes, I forgot to add that globals is really only *module-level* globals. Stil,l I don't grok why do you have to mess up with vars or globals (or whatever) to, in your own words, "print a description of the objects created for third party users of my code." As a rule of thumb, Python classes that want to display a string-like description useful for debugging implement a __repr__ method, e.g. >>> class A(object): ... def __init__(self, x, y): ... self.one = x ... self.two = y ... def __repr__(self): ... return "%s(%r, %r)" % (self.__class__.__name__, self.one, self.two) ... >>> a = A(1, 2) >>> a A(1, 2) >>> When at the interative prompt, a variable name will simply display repr(<variable name>), which in its turn calls __repr__ for classes that implement it. The way I coded __repr__ as the advantage of allowing the sometimes useful idiom: >>> eval(repr(a)) A(1, 2) >>> :-) With my best regards, G. Rodrigues P.S: Don't want to be a pain but could you please do: 1. Reply *also* to the Tutor list. That way everybody can learn and chime in. And even correct me when I'm wrong :-) 2. Don't top-post, it makes harder to follow the threads. From missive at hotmail.com Sun Nov 16 09:44:47 2003 From: missive at hotmail.com (Lee Harr) Date: Sun Nov 16 09:44:57 2003 Subject: [Tutor] Re: problems with re module Message-ID: <BAY2-F140Mp69YDqSkc0000c23b@hotmail.com> def f(matchobj): #print matchobj.group(0), matchobj.group(1), matchobj.group(2) return '<graphic srccredit="Fix Me!" fileref="%s" />' % matchobj.group(2) f = INFILE.readlines() #inefficient! changing this in the future would be a good idea... You are using the same variable name twice. This is probably the root cause of the problem. _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From alan.gauld at blueyonder.co.uk Sun Nov 16 12:37:34 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 16 12:37:09 2003 Subject: [Tutor] Accessing the name of an instance variable References: <khrervgj9mejrrmavf35d3i7t6am30oueg@4ax.com><BEEOLJNPLOPIONOMGLAAMEGJCIAA.comber@cix.co.uk> <qj1frvof6e9k1oika0trrai9k4dih6mcsm@4ax.com> Message-ID: <004401c3ac68$51f7dac0$6401a8c0@xp> > The purpose is to print a description of the objects > created for third party users of my code. Just to make sure we aren't going into overkill here... If you have provided a doc string for your class that names the objects variables then your users can just print the doc string and use that to reference the values directly. [Printing the variable name in Python is usually a pretty pointless exercise since it's only a reference which you either know or don't need.] However, assuming you really do need this level of introspection... This could be made into a mixin class: >class A: > def describe(self): > print 'Describing' > this_instance = id(self) > for name, instance in globals().items(): # vars() > print name > if isinstance(instance,A): > if id(instance) == this_instance: > print 'Description of', name This can now be used as a superclass of any other class that you need to describe: #----------- class B(A): ''' Class B, inherits A Class is initialised by two values x and y. Can be described using describe()''' def __init__(self,x,y): self.one = x self.two = y b = B(1,2) b.describe() print '########### Using doc string to explore #######' print b.__doc__ print 'x,y = ',b.x,b.y #------------ Which produces the following output: Describing A B __builtins__ b Description of b __name__ __doc__ ########### Using doc string to explore ####### Class B, inherits A Class is initialised by two values x and y. Can be described using describe() x,y = 1 2 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 16 14:25:00 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Nov 16 14:26:56 2003 Subject: [Tutor] Accessing the name of an instance variable - from Edward Comber Message-ID: <3FB7CF0C.9050704@aon.at> <forwarded to tutor@python.org> Hi Gregor. I'm not sure how I should reply. I would have thought I should reply to the list but this seems to go to you. This works fine - notice change to globals() file get_name.py class A: def __init__(self,x,y): self.one = x self.two = y def describe(self): print 'Describing' this_instance = id(self) for name, instance in globals().items(): # vars() print name if isinstance(instance,A): if id(instance) == this_instance: print 'Description of', name print self.one, self.two if __name__ == '__main__' : a = A(1,2) b = A(1001,1002) a.describe() b.describe() But this won't, from another file presumably because of namespace problems. I hoped globals() would pick up everything but it doesn't appear to. import get_name a = get_name.A(1,2) a.describe() Eddie -----Original Message----- From: Gregor Lingl [mailto:glingl@aon.at] Sent: 16 November 2003 11:33 To: Eddie Comber Subject: Re: [Tutor] Accessing the name of an instance variable Eddie Comber schrieb: >For debugging purposes, I would like to be able to print the name of some >instances of classes directly from the program, together with the class >data. The data is of course simple but getting the name is a problem to me. > >The best I have come up with so far is vars(), from which I can scan for >instances of the relevant classes. > >However the name of the instance is returned as a string. How would I get my >hands on the actual instance from this in order to get at its instance so as >to print the data? Or is there a better way of going about what I need to >do? > > Here an example, which uses the built-in function getattr. Is it this, what you need? >>> class A: def __init__(self,x,y): self.one = x self.two = y >>> a = A(1,2) >>> b = A(1001,1002) >>> for name, instance in vars().items(): if isinstance(instance,A): print name, instance.one, instance.two a 1 2 b 1001 1002 >>> for name, instance in vars().items(): if isinstance(instance,A): print name for var in vars(instance): print var, getattr(instance,var) a two 2 one 1 b two 1002 one 1001 >>> Regards, Gregor >Thanks, >Eddie. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From pythontutor at venix.com Sun Nov 16 15:30:50 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Nov 16 15:30:45 2003 Subject: [Tutor] Re: How to "install" new package? In-Reply-To: <20031115234206.GA1918@localhost.localdomain> References: <33678E78A2DD4D418396703A750048D45E6927@RIKER> <3FB58451.5060508@venix.com> <20031115044812.GA2307@localhost.localdomain> <20031115234206.GA1918@localhost.localdomain> Message-ID: <3FB7DE7A.6010904@venix.com> I got my wires crossed. I mis-read your message as being addressed to me and responded to you directly. I was not the one who originally posted the problem. I posted a brief message that I use non-standard locations in windows with no difficulty. I think his problem was solved and I accidently extended the thread by replying to your message. Sorry about that. Paul Tremblay wrote: > On Fri, Nov 14, 2003 at 11:48:12PM -0500, Paul Tremblay wrote: > >>On Fri, Nov 14, 2003 at 08:41:37PM -0500, Lloyd Kvam wrote: >> >>>The name and location of the "root" python directory should >>>not matter. I've always used non-standard names and locations >>>in Windows with no difficulty. Even if re-doing the install >>>to the standard location fixes your problem, I would be astonished >>>if the name and location were the real problem. >>> >> >>That's been my experience as well. What happens if you try to install >>another package? Could you download a small one (try sourceforge) and >>see what happens? If you get the same error, we know the problem lies >>outside the individual package. >> >>Paul >> > > > Since you wrote me off this mailing list and indicated that you install > other packages with no problem, it would seem that the problem is not > with your python installation, but with the individual package. > > Paul > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From maddoxflower at web.de Wed Nov 12 13:57:19 2003 From: maddoxflower at web.de (maddox flower) Date: Sun Nov 16 17:08:30 2003 Subject: [Tutor] dynamic class method creation? Message-ID: <3FB2828F.8030108@web.de> Thanks for the link. But I still do have a problem: What I want to do is not only attach a method dynamically to a class, but to create/write it dynamically. What I tried so far is this: ######################### from Numeric import * def sum_string(r, a): """returns a string representing an expression; r is the rank of an array, a is the name of the array. E.g. sum_string(3, 'ary') returns 'sum(sum(sum(ary)))' """ s = "sum(%s)" % a for i in range(r-1): s = "sum(%s)" % s return s def sumFunc_string(r): """returns a string representing the definition of a function called 'sumFunc'; 'sumFunc' is supposed to take an array as an argument and to return the sum over all elements of the array """ s = """ def sumFunc(a): return %s """ % sum_string(r, 'a') return s my_a = array([[1, 2], [3, 4]]) s = sumFunc_string(rank(my_a)) exec s print sumFunc(my_a) ######################### Output: 10 Ok, not bad. So, after creating/writing the function 'sumFunc' 'dynamically' I can actually use it as I would use any other function. Now, I want to be able to do the following: Create/write a method dynamically and attach it to an existing class (all inside the __init__ method of the class), so I can use it like a normal method of that class. Something along the following line (reusing the sum_string function from the example above): ######################### def sumFunc_string(r): """returns a string representing the definition of a function called 'sumFunc'; 'sumFunc' is supposed to take an array as an argument and to return the sum over all elements of the array """ s = """ def sumFunc(self, a): return %s """ % sum_string(r, 'self.a') return s class ArrayContainer: def __init(self, a): self.a = a s = sumFunc_string(rank(a)) exec s self.sum = sumFunc my_a = array([[1, 2], [3, 4]]) ac = ArrayContainer(my_a) ac.sum() ######################### Well, this doesn't work. After I had had a look at this post by Guido van Rossum: http://groups.google.com/groups?q=g:thl1797684596d&dq=&hl=en&lr=lang_en&ie=UTF-8&oe=UTF-8&safe=active&selm=mailman.997701621.7351.python-list%40python.org&rnum=69 I came up with this (reuse the sum_string function again): ######################### class ArrayContainer(object): __dynamic__ = 1 def __init__(self, a): self.a = a ## s = sumFunc_string(rank(a)) ## exec s ## self.sum = sumFunc def sumall(self): return sum(sum(self.a)) def __str__(self): s = "" for k in self.__class__.__dict__: s += "%s: \n" % k return s my_a = array([[1, 2], [3, 4]]) s = sumFunc_string(rank(my_a)) exec s ArrayContainer.sum = sumFunc ac = ArrayContainer(my_a) print "function:", sumFunc(ac, ac.a) print "method:", ac.sum() ######################### Output: function: 10 method: Traceback (most recent call last): File "<stdin>", line 71, in ? NameError: name 'insac' is not defined Why does the 'function' call work, but the 'method' call not? How can I actually do the exec stuff inside the __init__ method of the ArrayContainer class? Cheers, maddox From classyjoes at btopenworld.com Thu Nov 13 05:24:58 2003 From: classyjoes at btopenworld.com (classyjoes@btopenworld.com) Date: Sun Nov 16 17:08:40 2003 Subject: [Tutor] (no subject) Message-ID: <4599847.1068719098409.JavaMail.root@127.0.0.1> I'm trying to create a function that accepts two parameters, it takes the size of a side of a square to print and the ASCII character that this square is made up of. I then need to call it in a calling program. Any ideas would be so greatly appreciated!!! Martyn Booth M. Booth M. Booth From comber at cix.co.uk Sat Nov 15 07:18:56 2003 From: comber at cix.co.uk (Edward Comber) Date: Sun Nov 16 17:08:46 2003 Subject: [Tutor] Accessing the name of and instance variable Message-ID: <BEEOLJNPLOPIONOMGLAAMEGBCIAA.comber@cix.co.uk> for debugging purposes, I would like to be able to print the name of some instances of classes directly from the program, together with the class data. the data is of course simple but getting the name is a problem to me. The best I have come up with so far is vars(), from which I can scan for instances of the relevant classes. However the name of the instance is returned as a string. How would I get my hands on the actual instance from this in order to get at its instance so as to print teh data? Or is ther a better way of going about what I need to do? Thanks, Eddie. From shantanoo at ieee.org Sat Nov 15 10:26:56 2003 From: shantanoo at ieee.org (Shantanoo Mahajan) Date: Sun Nov 16 17:08:50 2003 Subject: [Tutor] Re: using global variables with functions In-Reply-To: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> References: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> Message-ID: <20031115152656.GB312@dhumketu.homeunix.net> +++ Smith, Ryan [14-11-03 16:46 -0500]: | Hello All, | | I am having some trouble with the way global variables interace with | functions. I found some practice problems on the Ibilio.org website and one | of them is creating a program that converts celcius to farenheit and vice | versa. The following code is what I have come up with: | | | | | #Prompt for user to enter the temp to convert | >>>temp = raw_input("Enter a temperature: ") | >>>>print temp | >>>>choice = raw_input("Convert to (F)arhenheit or (C)elcius: ") | #Function to convert from celcius to farenheit | >>>def convert_cel(temp): | ... tc = (5/9)*(temp - 32) | ... return tc | if choice == 'C': | print convert_cel(temp) | | My problem is when I try to use temp as a variable in the convert_cel | function. My understanding is that whatever the user enters as the | temperature that is now the value of the temp variable. Since it is outside | the function should it not be a global variable? I get the following error | message: | | | #Prompt for user to enter the temp to convert | temp = raw_input("Enter a temperature: ") | print temp | choice = raw_input("Convert to (F)arhenheit or (C)elcius: ") | #Function to convert from celcius to farenheit | def convert_cel(): | tc = (5/9)*(temp - 32) | return tc | if choice == 'C': | print convert_cel() | | If anyone could help me see the "light" I would be most greatful. I would | like to point out that I am not asking for the answer just help with | clarifying my understanding and correcting any misconceptions. I have never | programmed a day in my life but am really trying to learn. Thanks | | | Ryan Smith | | and also instead of 5/9 in convert_sel it should be 5.0/9.0 or 5/9.0 or 5.0/9 else everytime 0 will be returned. Regards, Shantanoo From shantanoo at ieee.org Sat Nov 15 10:22:51 2003 From: shantanoo at ieee.org (Shantanoo Mahajan) Date: Sun Nov 16 17:08:55 2003 Subject: [Tutor] Re: using global variables with functions In-Reply-To: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> References: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> Message-ID: <20031115152251.GA312@dhumketu.homeunix.net> +++ Smith, Ryan [14-11-03 16:46 -0500]: | Hello All, | | I am having some trouble with the way global variables interace with | functions. I found some practice problems on the Ibilio.org website and one | of them is creating a program that converts celcius to farenheit and vice | versa. The following code is what I have come up with: | | | | | #Prompt for user to enter the temp to convert | >>>temp = raw_input("Enter a temperature: ") | >>>>print temp | >>>>choice = raw_input("Convert to (F)arhenheit or (C)elcius: ") | #Function to convert from celcius to farenheit | >>>def convert_cel(temp): | ... tc = (5/9)*(temp - 32) | ... return tc | if choice == 'C': | print convert_cel(temp) | | My problem is when I try to use temp as a variable in the convert_cel | function. My understanding is that whatever the user enters as the | temperature that is now the value of the temp variable. Since it is outside | the function should it not be a global variable? I get the following error | message: | | | #Prompt for user to enter the temp to convert | temp = raw_input("Enter a temperature: ") | print temp | choice = raw_input("Convert to (F)arhenheit or (C)elcius: ") | #Function to convert from celcius to farenheit | def convert_cel(): | tc = (5/9)*(temp - 32) | return tc | if choice == 'C': | print convert_cel() | | If anyone could help me see the "light" I would be most greatful. I would | like to point out that I am not asking for the answer just help with | clarifying my understanding and correcting any misconceptions. I have never | programmed a day in my life but am really trying to learn. Thanks | | | Ryan Smith | | ------------------------------ the above prog. didn't work for. it gave TypeError instead of raw_input, try input. raw_input ---> string input ---> integer or if you want to use raw_input, in convert_cel change tc = (5/9)*(temp - 32) to tc = (5/9)*(int(temp) - 32) or maybe tc = (5/9)*(float(temp) - 32) Regards, Shantanoo From tayiper at volja.net Sun Nov 16 01:36:00 2003 From: tayiper at volja.net (Tadey) Date: Sun Nov 16 17:08:59 2003 Subject: [Tutor] double result ... Message-ID: <017b01c3ac0b$e71c38b0$324548d9@mz9s680eu689tz> Hello, I was just trying some different combinations, and noticed, that in sequence of commands: >>> a=7 >>> b=9 >>> c=8 >>> for i in range(a,b,c): >>> print i ... ... 7 ... gives value a, becuse it is the first value in the row, and because a, b, c are no "logical sequence" for computer (it doesn't support alphabet) !! >>> a=4 >>> b=6 >>> c=8 >>> for d in range(a,b,c): ... print d ... 4 .. I changed the order of letters to check if I am right. >>> a=4 >>> b=6 >>> c=8 >>> for d in range(b,c): ... print b ... 6 6 but then I accidentally mixed values and have instead of "print d", used "print b" - and I got two results one after another, two 6. So, I see one stands for varaiable b, and the other for d, from "for d in range" loop, but how is it possible, what happened, how computer gets that result ?? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031116/5377e29f/attachment-0001.html From rafael.sousa at netcabo.pt Sun Nov 16 17:10:04 2003 From: rafael.sousa at netcabo.pt (Rafael Sousa) Date: Sun Nov 16 17:16:20 2003 Subject: [Tutor] Converting between image types Message-ID: <EXCH01SMTP02Zv7FDwf000012e3@smtp.netcabo.pt> I need to convert gif images to png's. Is there a python module that does this? If not, can anyone please tell me what's the best way to do this? Thanks in advance, Rafael Sousa -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031116/54a90c3f/attachment.html From thomi at imail.net.nz Sun Nov 16 17:17:42 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sun Nov 16 17:17:50 2003 Subject: [Tutor] Converting between image types In-Reply-To: <EXCH01SMTP02Zv7FDwf000012e3@smtp.netcabo.pt> References: <EXCH01SMTP02Zv7FDwf000012e3@smtp.netcabo.pt> Message-ID: <200311171117.42572.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Mon, 17 Nov 2003 11:10, Rafael Sousa wrote: > I need to convert gif images to png's. Is there a python module that does > this? The python imaging library does this just fine ;) do a google on "python imaging module", and you'll get it ;) > > If not, can anyone please tell me what's the best way to do this? > Using the above library, you can do this conversion in < 5 lines of code ;) HTH! - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/t/eG2tSuYV7JfuERAp0OAJ46Oioa9FpBG1dyx7teUVM/yNBMXACeN+YE 7jmoFChD9dZSbc6OXw60Tak= =fjM2 -----END PGP SIGNATURE----- From amonroe at columbus.rr.com Sun Nov 16 17:25:20 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Nov 16 17:25:40 2003 Subject: [Tutor] double result ... In-Reply-To: <017b01c3ac0b$e71c38b0$324548d9@mz9s680eu689tz> References: <017b01c3ac0b$e71c38b0$324548d9@mz9s680eu689tz> Message-ID: <1891015121137.20031116172520@columbus.rr.com> >>>> a=7 >>>> b=9 >>>> c=8 >>>> for i in range(a,b,c): >>>> print i > ... > ... > 7 > ... gives value a, becuse it is the first value in the row, and > because a, b, c are no "logical sequence" for computer (it doesn't > support alphabet) !! Try the exact same program, but remove the "range" keyword, see if that's more of what you were expecting. Alan From dyoo at hkn.eecs.berkeley.edu Sun Nov 16 17:27:26 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 16 17:27:31 2003 Subject: [Tutor] double result ... [home on the range()] In-Reply-To: <017b01c3ac0b$e71c38b0$324548d9@mz9s680eu689tz> Message-ID: <Pine.LNX.4.44.0311161417430.11790-100000@hkn.eecs.berkeley.edu> On Sun, 16 Nov 2003, Tadey wrote: > >>> a=7 > >>> b=9 > >>> c=8 > >>> for i in range(a,b,c): > >>> print i > ... > ... > 7 > > > ... gives value a, becuse it is the first value in the row, and because > a, b, c are no "logical sequence" for computer (it doesn't support > alphabet) !! Hi Tadey, Ah! range() is a sequence builder, but it's not the only one --- you can directly build sequences by using lists: ### >>> [3, 7, 19, 42] [3, 7, 19, 42] >>> >>> >>> mylist = [7, 9, 8] >>> mylist [7, 9, 8] >>> mylist[0] 7 >>> mylist[1] 9 ### But range() is meant to make it easy to generate lists of ascending numbers: ### >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(10, 20) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> range(10, 20, 3) [10, 13, 16, 19] ### So those numbers that we feed it are meant to be used as "endpoints" of a number range. range() can take in either one, two, or three arguments, and it behaves slightly differently in each case. The third case is asking Python: "Give me the range of numbers between 10 and 20, by skipping foward three numbers at a time." Once we understand range(), then it should be easier to see why: range(7, 9, 8) is only giving us [7] --- There's only one number between 7 and 9, if we skip 8 numbers forward at a time. But if we try getting the numbers from 10 to 0, by stepping forward 1 at a time, we're sunk: ### >>> range(10, 0, 1) [] ### But, by the way, we can go "backwards", just as long as the step is negative: ### >>> range(10, 0, -1) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] ### Does this make sense so far? Please feel free to ask more questions about this. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Nov 16 17:36:27 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 16 17:37:08 2003 Subject: [Tutor] (no subject) In-Reply-To: <4599847.1068719098409.JavaMail.root@127.0.0.1> Message-ID: <Pine.LNX.4.44.0311161428370.11790-100000@hkn.eecs.berkeley.edu> On Thu, 13 Nov 2003 classyjoes@btopenworld.com wrote: > I'm trying to create a function that accepts two parameters, it takes > the size of a side of a square to print and the ASCII character that > this square is made up of. I then need to call it in a calling program. > Any ideas would be so greatly appreciated!!! Hi Martyn, Ask us what problems you're having with, and we'll try to help as best we can. Your problem does sounds like homework, though, so we're fairly restricted to what we can say comfortably. You may want to try a simpler problem to get more familiar with Python and programming. One approach to solving things like this is to make the problem easier: since you're drawing something in two dimensions, one simplification is drop down to one dimension. Can you write a program that takes a numeric length, and draws a line with that many dashes? This problem should be easier to solve. And if can draw a line, then drawing a square should be a bit simpler to do. If you want supplementary tutorial on learning how to program, you can find more stuff here: http://www.python.org/topics/learn/non-prog.html Good luck to you! From python-tutor at ml03q3.pinguin.uni.cc Sun Nov 16 18:04:34 2003 From: python-tutor at ml03q3.pinguin.uni.cc (Al Bogner) Date: Sun Nov 16 18:04:51 2003 Subject: [Tutor] how to do "bash here" Message-ID: <200311170004.03473.python-tutor@ml03q3.pinguin.uni.cc> I try to learn python by writing working bash-scripts in python. How can I do a bash-syntax like this with python: mysql --host=$MYSQLHOST -A --user=$MYSQLUSER --password=$MYSQLPWD $MYSQLDB <<END_OF_SQLINPUT | sed '1,/^export/d' > "$FDIMPORT" $MYSQLEXPORTCMDFD END_OF_SQLINPUT Thanks a lot for your help! Al From alan.gauld at blueyonder.co.uk Sun Nov 16 19:09:28 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 16 19:08:59 2003 Subject: [Tutor] (no subject) References: <4599847.1068719098409.JavaMail.root@127.0.0.1> Message-ID: <006f01c3ac9f$118df780$6401a8c0@xp> > I'm trying to create a function that accepts two > parameters, it takes the size of a side of a square > to print and the ASCII character that this square > is made up of. I then need to call it in a calling > program. Any ideas would be so greatly appreciated!!! Forgive me if I'm being overly suspicious but this looks like a homework exercise. Even if it isn't you will get a better response if you show us what you've done so far and explain why you need help with it - like what bit doesn't work. As for some ideas to get started, try solving the problem by hand, as if you were the computer. Then reverse engineer what you did and tell the computer to do the same. There may be more efficient algorithms but at least it's a start! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sun Nov 16 19:14:20 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 16 19:13:50 2003 Subject: [Tutor] Re: using global variables with functions References: <3D39FA2611E0D311857B00508B644D1E05387EBD@msnbex02.usi.net> <20031115152656.GB312@dhumketu.homeunix.net> Message-ID: <007401c3ac9f$bf5aead0$6401a8c0@xp> > | #Function to convert from celcius to farenheit > | >>>def convert_cel(temp): > | ... tc = (5/9)*(temp - 32) > | ... return tc > | if choice == 'C': > | print convert_cel(temp) > | > | My problem is when I try to use temp as a variable in the convert_cel > | function. My understanding is that whatever the user enters as the > | temperature that is now the value of the temp variable. Since it is outside > | the function should it not be a global variable? The problem is that by caling the function parameter temp you have created a new local variable in the function which hides the global one. The other problem as has been pointed out is that you are using integer division, you need at least one value to be a float. My tutorial deals with this issue in the very first coding topic, the one on simple sequences. global names are covered in the Advanced topic "What's in a Name?" Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Sun Nov 16 19:23:48 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 16 19:23:17 2003 Subject: [Tutor] double result ... References: <017b01c3ac0b$e71c38b0$324548d9@mz9s680eu689tz> Message-ID: <007e01c3aca1$11f002c0$6401a8c0@xp> >>> a=7 >>> b=9 >>> c=8 >>> for i in range(a,b,c): Let's look at this more closely. You called range(7,9,8) that returns a list of values from 7 to (9-1) separated by 8. That means you only get one value, 7. try it by typing range() at the >>> prompt. Experiment with some values till you understand how it works. > sequence" for computer (it doesn't support alphabet) !! Support for the alphabet is another issue and nothing to do with what's happening here. Lets come back to that later. >>> a=4 >>> b=6 >>> c=8 >>> for d in range(a,b,c): This time you created a list from 4 to (6-1) stepping by 8 - again the single value 4 >>> a=4 >>> b=6 >>> c=8 >>> for d in range(b,c): This time a list from 6 to 8-1, that is 6 and 7. So you have two values that d is set to and so you print b twice. What I think you shjould have written was: for d in [a,b,c]: print d That is, instead of using range() to create a list you just create the list by hand. As for letters, you can access them using the predefined sequence in the string module: import string for char in string.letters: print char for char in string.uppercase: print char and so on. Take a look at the string module to see what other character sets are defined. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From thomi at imail.net.nz Sun Nov 16 21:11:27 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sun Nov 16 21:11:36 2003 Subject: [Tutor] Re: problems with re module In-Reply-To: <BAY2-F140Mp69YDqSkc0000c23b@hotmail.com> References: <BAY2-F140Mp69YDqSkc0000c23b@hotmail.com> Message-ID: <200311171511.27303.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Mon, 17 Nov 2003 03:44, Lee Harr wrote: > def f(matchobj): > #print matchobj.group(0), matchobj.group(1), matchobj.group(2) > return '<graphic srccredit="Fix Me!" fileref="%s" />' % > matchobj.group(2) > > > f = INFILE.readlines() #inefficient! changing this in the future would be > a good idea... > > > You are using the same variable name twice. > This is probably the root cause of the problem. ahhh!!!! so simple, once you see it! thanks a lot!!! ;-) - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/uC5P2tSuYV7JfuERAo8kAJ91pYsEg9NpBLTcB+24JL3Fpv+wAACfd9FN 27a4YprolEP/TraQiDL5qS4= =VXfK -----END PGP SIGNATURE----- From littledanehren at yahoo.com Sun Nov 16 21:20:17 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Nov 16 21:20:23 2003 Subject: [Tutor] how to do "bash here" In-Reply-To: <200311170004.03473.python-tutor@ml03q3.pinguin.uni.cc> Message-ID: <20031117022017.15943.qmail@web41808.mail.yahoo.com> Al Bogner wrote: > I try to learn python by writing working > bash-scripts in python. > Al How do you do any bash scripts in Python? Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From scott_list at mischko.com Sun Nov 16 21:55:33 2003 From: scott_list at mischko.com (Scott Chapman) Date: Sun Nov 16 21:55:39 2003 Subject: [Tutor] How to run a system application and get the stdout in Python? Message-ID: <200311161855.33474.scott_list@mischko.com> Hi! I want to run a system application on my web server (using Draco) and send the stdout of the system command (htmldoc) to the client's web browser. I see a number of os module possibilities to run system commands. Here's what I'm trying to run: /usr/bin/htmldoc -t pdf --webpage 'http://127.0.0.1/draco/wiki.dsp/Lund?cmd=View&page=FrontPage&PDF=True' What's the best way to run this and how do I grab the stdout of the command? Thanks! Scott From simple_stuff at hotmail.com Sun Nov 16 22:07:47 2003 From: simple_stuff at hotmail.com (Tom Semple) Date: Sun Nov 16 22:08:00 2003 Subject: [Tutor] PythonWin cannot find win32ui.pyd Message-ID: <Sea2-DAV70h3VMboGDT00002ab6@hotmail.com> [sorry for the repost, but I'm not sure it got posted properly the first time - at least I never saw it in the digests I get:] I wanted to replace my Python 2.3 with the ActiveState edition of same. I uninstalled the former, installed the latter, but when I try to launch PythonWin I get the aforementioned error (the file is there in one of the Lib subdirectories, presumably where it is supposed to be). Have tried restarting Windows, and the 'repair' option of the install, to no avail. Install directory is 'd:\python23\" rather than the default of "c:\python23\". Any suggestions of what to check? Thanks Tom Semple From dyoo at hkn.eecs.berkeley.edu Mon Nov 17 01:05:30 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 17 01:05:36 2003 Subject: [Tutor] how to do "bash here" In-Reply-To: <200311170004.03473.python-tutor@ml03q3.pinguin.uni.cc> Message-ID: <Pine.LNX.4.44.0311162154480.343-100000@hkn.eecs.berkeley.edu> On Mon, 17 Nov 2003, Al Bogner wrote: > I try to learn python by writing working bash-scripts in python. How can > I do a bash-syntax like this with python: > > mysql --host=$MYSQLHOST -A --user=$MYSQLUSER --password=$MYSQLPWD $MYSQLDB > <<END_OF_SQLINPUT | sed '1,/^export/d' > "$FDIMPORT" > $MYSQLEXPORTCMDFD > END_OF_SQLINPUT Hi Al, Hmmm, nice shell command! One thing you may need to fix, though, is the variable interpolation: passwords, too, can potentially contain spaces, so you need to protect those shell variables with quotes, just like how you protected $FDIMPORT. Anyway, you may find the os.popen() command useful to simulate the "pipes" that the Unix shell gives us: http://www.python.org/doc/lib/os-newstreams.html#l2h-1379 And that should take care of it. But instead of doing a literal translation, it might be more educational to take advantage of the tools that Python provides. Otherwise, you'll probably only learn how to use os.popen() well. *grin* For example, you can use the 'MySQLdb' module to talk to your database, and the 're' module to perform that regular expression substitution. You can find out more about doing database manipulation with: http://www.devshed.com/Server_Side/Python/PythonMySQL/print_html and there's a nice tutorial by A.M. Kuchling for regular expressions: http://www.amk.ca/python/howto/regex/ If you have more questions, please feel free to ask. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Nov 17 01:10:45 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 17 01:10:49 2003 Subject: [Tutor] How to run a system application and get the stdout in Python? In-Reply-To: <200311161855.33474.scott_list@mischko.com> Message-ID: <Pine.LNX.4.44.0311162206010.343-100000@hkn.eecs.berkeley.edu> On Sun, 16 Nov 2003, Scott Chapman wrote: > I want to run a system application on my web server (using Draco) and > send the stdout of the system command (htmldoc) to the client's web > browser. > > I see a number of os module possibilities to run system commands. > Here's what I'm trying to run: > > /usr/bin/htmldoc -t pdf --webpage > 'http://127.0.0.1/draco/wiki.dsp/Lund?cmd=View&page=FrontPage&PDF=True' > > What's the best way to run this and how do I grab the stdout of the > command? Hi Scott, (It's sorta funny how simliar questions come in streaks. *grin*) You'll want to look at os.popen(): it'll let you execute an external command and grab its output as if it were a file-like object. For example: ### >>> import os >>> os.popen("ls src/python") <open file 'ls src/python', mode 'r' at 0x60320> >>> f = os.popen("ls src/python") >>> f.readline() 'block_sorting.py\n' >>> f.readline() 'block_sorting.py~\n' ### There's another function called os.system() that does something similar: it also executes external commands, but its return value is the "errorlevel" of the command, and not its stdout. If you're looking for more fine-grained control, there a module called 'popen2' that has more powerful process-opening functions: http://www.python.org/doc/lib/module-popen2.html but I think that, for the moment, os.popen() should do the trick. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Nov 17 01:24:45 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 17 01:27:58 2003 Subject: [Tutor] PythonWin cannot find win32ui.pyd In-Reply-To: <Sea2-DAV70h3VMboGDT00002ab6@hotmail.com> Message-ID: <Pine.LNX.4.44.0311162210570.343-100000@hkn.eecs.berkeley.edu> On Sun, 16 Nov 2003, Tom Semple wrote: > I wanted to replace my Python 2.3 with the ActiveState edition of same. > I uninstalled the former, installed the latter, but when I try to launch > PythonWin I get the aforementioned error (the file is there in one of > the Lib subdirectories, presumably where it is supposed to be). Have > tried restarting Windows, and the 'repair' option of the install, to no > avail. Install directory is 'd:\python23\" rather than the default of > "c:\python23\". Any suggestions of what to check? Hi Tom, Sorry, but this might be a tough question for us on Python-Tutor, since it's so specialized. Have you asked your question on ActiveState's ActivePython mailing list? The folks there should know more about that error. http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/ActivePython You may also want to look at: http://starship.python.net/crew/mhammond/win32/InstallationProblems.html Someone else appears to have had a similar problem, and posted on the main comp.lang.python archives: http://aspn.activestate.com/ASPN/Mail/Message/python-list/1843113 I hope you can find a solution to this. Good luck to you! From eur at fiwihex.nl Mon Nov 17 03:36:27 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Mon Nov 17 03:36:29 2003 Subject: [Tutor] troubles with ConfigParser In-Reply-To: <j4pdrvksv3bs11lnfssqp8hlllinq8lvr0@4ax.com> References: <j4pdrvksv3bs11lnfssqp8hlllinq8lvr0@4ax.com> Message-ID: <742hrvcmapbsirlp3hc80uo0hmv85crcu3@4ax.com> On Sun, 16 Nov 2003 03:56:37 +0100, Eur van Andel <eur@fiwihex.nl> wrote: >There are some troubles, >though, especially when writing an INI file. ># st.write('settings.ini') > >>Traceback (most recent call last): >> File "st_try.py", line 81, in ? >> st.write('settings.ini') >> File "/usr/local/lib/python2.2/ConfigParser.py", line 351, in write >> fp.write("[%s]\n" % section) >>AttributeError: 'str' object has no attribute 'write' write(fp) expects a file pointer. So open a file first and pass the pointer: sett = open('settings.ini, 'w') st.write(sett) -- 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 alan.gauld at blueyonder.co.uk Mon Nov 17 05:15:08 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Nov 17 05:14:30 2003 Subject: [Tutor] how to do "bash here" References: <200311170004.03473.python-tutor@ml03q3.pinguin.uni.cc> Message-ID: <009e01c3acf3$ad826460$6401a8c0@xp> > I try to learn python by writing working bash-scripts in python. How can I do > a bash-syntax like this with python: Thats probably a mistake. Bash is a command shell designed to launch other programs and combine their outputs. Python is a general purpose programming language. While it is possible to do what bash does in Python it will be much harder and teach you very little about Python. > mysql --host=$MYSQLHOST -A --user=$MYSQLUSER --password=$MYSQLPWD $MYSQLDB > <<END_OF_SQLINPUT | sed '1,/^export/d' > "$FDIMPORT" > $MYSQLEXPORTCMDFD > END_OF_SQLINPUT This is a good example of bash calling external programs(mysql & sed) but there is actually no bash program as such here at all. If you really really want you can use Python's os module with its popen function to call mysql too. You could use Pythons string operations to replace the sed bit. But there is very little point! The end result would be longer and probably slower than the bash version. Use bash for what it is good at and Python for what it is good at. I think you would be better off going through some of the tutorials on the Python website. 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 Mon Nov 17 05:18:20 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Nov 17 05:17:55 2003 Subject: [Tutor] How to run a system application and get the stdout in Python? References: <200311161855.33474.scott_list@mischko.com> Message-ID: <00ab01c3acf4$205169f0$6401a8c0@xp> > I see a number of os module possibilities to run system commands. > Here's what I'm trying to run: > > /usr/bin/htmldoc -t pdf --webpage 'http://127.0.0.1/draco/wiki.dsp/Lund?cmd=View&page=FrontPage&PDF=True ' > > What's the best way to run this and how do I grab the stdout of the command? The best way is to use the popen function. But make sure that your script has the right permissions set etc and that you check for errors carefully. Also be aware that you are opening up a potential security hole in your system, so make sure that only the commands you want can be executed! Alan G From wes at the-edge.us Mon Nov 17 11:21:52 2003 From: wes at the-edge.us (Wes) Date: Mon Nov 17 11:21:19 2003 Subject: [Tutor] round() Message-ID: <E1ALm8O-0006rd-Dm@freedom.imhosted.com> Hi, Why are the results different? x=2.5463 >>>round(x,2) 2.5499999999999998 >>>str(round(x,2)) '2.55' Thanks, ~wes --------------------- We need more power captain. From karl.fast at pobox.com Mon Nov 17 11:31:30 2003 From: karl.fast at pobox.com (Karl Fast) Date: Mon Nov 17 11:32:03 2003 Subject: [Tutor] PythonWin cannot find win32ui.pyd In-Reply-To: <Pine.LNX.4.44.0311162210570.343-100000@hkn.eecs.berkeley.edu>; from dyoo@hkn.eecs.berkeley.edu on Sun, Nov 16, 2003 at 10:24:45PM -0800 References: <Sea2-DAV70h3VMboGDT00002ab6@hotmail.com> <Pine.LNX.4.44.0311162210570.343-100000@hkn.eecs.berkeley.edu> Message-ID: <20031117103130.E9317@signal.lights.com> > Sorry, but this might be a tough question for us on Python-Tutor, > since it's so specialized. Have you asked your question on > ActiveState's ActivePython mailing list? The folks there should > know more about that error. I would also recommend the python-win32 mailing list. I recently had a problem with importing win32com.client in the new ActivePython 2.3. The win32 list solved my problem immediately. ASPN archives for python-win32: http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/Python-win32 If you want to subscribe: http://mail.python.org/mailman/listinfo/python-win32 --karl From jsoons at juilliard.edu Mon Nov 17 11:32:10 2003 From: jsoons at juilliard.edu (Jonathan Soons) Date: Mon Nov 17 11:32:17 2003 Subject: [Tutor] Newbie problem with TypeError Message-ID: <33E101AC5AFF78419F466954A96854202F5A9F@mailbox.juilliard.edu> I am completely baffled by this TypeError. The program is 617 lines so I am just showing the relevant part. Please help. def newpage(words) : PDF_end_page(pdf) PDF_begin_page(pdf, WIDTH, HEIGHT) PDF_setfont(pdf, font0, 14) PDF_set_text_pos(pdf, INCH, 704) PDF_show(pdf, last + ", " + first) PDF_set_text_pos(pdf, INCH, 690) mklines(words) def mklines(field) : if len(field) < 4 : return words = field.split(" ") while len(words) > 1 : line = "" list(words) #definitely a list while (len(line) < 60) and len(words) > 1 : line = line + " " + words[0] if len(words) > 0 : del(words[0]) PDF_continue_text(pdf, line) if PDF_get_value(pdf, "texty", 0) < INCH : words = string.joinfields(words, " ") str(words) #newpage() requires string argument newpage(words) if len(words) == 1 : PDF_continue_text(pdf, " " + words[0]) Traceback (most recent call last): File "./parseapps.py", line 174, in ? mklines(essay) File "./parseapps.py", line 50, in mklines del(words[0]) TypeError: object doesn't support item deletion From tpc at csua.berkeley.edu Mon Nov 17 11:32:21 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Nov 17 11:32:39 2003 Subject: [Tutor] round() In-Reply-To: <E1ALm8O-0006rd-Dm@freedom.imhosted.com> Message-ID: <20031117083110.M79075-100000@localhost.name> hi Wes, you want to use repr(). Here's a earlier post with an answer to a similar question: http://mail.python.org/pipermail/python-list/2002-August/118501.html On Mon, 17 Nov 2003, Wes wrote: > Hi, > Why are the results different? > > x=2.5463 > > >>>round(x,2) > 2.5499999999999998 > > >>>str(round(x,2)) > '2.55' > > Thanks, > ~wes > --------------------- > We need more power captain. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jsoons at juilliard.edu Mon Nov 17 12:13:18 2003 From: jsoons at juilliard.edu (Jonathan Soons) Date: Mon Nov 17 12:13:28 2003 Subject: [Tutor] RE: Newbie problem with TypeError Message-ID: <33E101AC5AFF78419F466954A96854202F5AA0@mailbox.juilliard.edu> >I am completely baffled by this TypeError. >The program is 617 lines so I am just showing the relevant part. >Please help. >def newpage(words) : > PDF_end_page(pdf) > PDF_begin_page(pdf, WIDTH, HEIGHT) > PDF_setfont(pdf, font0, 14) > PDF_set_text_pos(pdf, INCH, 704) > PDF_show(pdf, last + ", " + first) > PDF_set_text_pos(pdf, INCH, 690) > mklines(words) I just took Danny Yoo's advice and changed this to: def mklines(field) : if len(field) < 4 : return words = field.split(" ") while len(words) > 1 : line = "" list(words) #definitely a list while (len(line) < 60) and len(words) > 1 : line = line + " " + words[0] if len(words) > 0 : del(words[0]) PDF_continue_text(pdf, line) if PDF_get_value(pdf, "texty", 0) < INCH : txt = string.joinfields(words, " ") #new variable???!!! newpage(txt) #since the old one got stuck as a tuple. if len(words) == 1 : #and couldn't be made into a string PDF_continue_text(pdf, " " + words[0]) No error now but I don't know why I can't reuse the 'words' variable and cast it to string. I can live with that tho since it now runs. Thanks >Traceback (most recent call last): > File "./parseapps.py", line 174, in ? > mklines(essay) > File "./parseapps.py", line 50, in mklines > del(words[0]) > TypeError: object doesn't support item deletion From alan.gauld at blueyonder.co.uk Mon Nov 17 12:31:35 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Nov 17 12:31:04 2003 Subject: [Tutor] Newbie problem with TypeError References: <33E101AC5AFF78419F466954A96854202F5A9F@mailbox.juilliard.edu> Message-ID: <002601c3ad30$a63a7430$6401a8c0@xp> > I am completely baffled by this TypeError. I'm not sure this will help but... def mklines(field) : if len(field) < 4 : return words = field.split(" ") while len(words) > 1 : line = "" list(words) #definitely a list list returns a new list it doesn't convert the argument. I think you want words = list(words) if PDF_get_value(pdf, "texty", 0) < INCH : words = string.joinfields(words, " ") str(words) #newpage() requires string argument Similarly str just returns a copy it does not change the original. You probably want words = str(words) or just newpage(str(words)) File "./parseapps.py", line 50, in mklines del(words[0]) TypeError: object doesn't support item deletion But why you get that I'm not sure, you appear to test for length > 0 so it shouldn't be trying to delete a None object. Alan G. From VICKI.STANFIELD at roche.com Mon Nov 17 13:09:58 2003 From: VICKI.STANFIELD at roche.com (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Nov 17 13:11:34 2003 Subject: [Tutor] Write array to Status text Message-ID: <CA3458C84C976E45B6372A6C14724C9F355E97@ridmsem02.nala.roche.com> Okay, it looks like an array but when I do this I get an error saying that: 'list' object has no attribute 'tostring' So I guess it is really a list. It looks so much like an array in C. I'm afraid that I don't see the reason for both existing. Is there a place where I can find out more about the differences? I'm sure that I could use a real array for what I am doing if I only understood the difference between arrays and lists. --vicki -----Original Message----- From: Vicki Stanfield [mailto:vicki@thepenguin.org] Sent: Friday, November 14, 2003 7:10 PM To: tutor@python.org Subject: Re: [Tutor] Write array to Status text This looks like what I need, but I have to wait until I am in my office again on Monday to be sure. Thanks. --vicki > If your array would really be an array you could use the `tostring' > method of arrays. > >>>> import array >>>> arr = array.array('c', "I am an array of characters") arr[0:4] > array('c', 'I am') >>>> arr[0:4].tostring() > 'I am' >>>> > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Mon Nov 17 13:30:02 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 17 13:30:38 2003 Subject: [Tutor] Newbie problem with TypeError In-Reply-To: <33E101AC5AFF78419F466954A96854202F5A9F@mailbox.juilliard.edu> Message-ID: <Pine.LNX.4.44.0311170949170.23780-100000@hkn.eecs.berkeley.edu> On Mon, 17 Nov 2003, Jonathan Soons wrote: > def mklines(field) : > if len(field) < 4 : > return > words = field.split(" ") > while len(words) > 1 : > line = "" list(words) #definitely a list ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Hi Jonathan, That line that's I've underlined is one possible problem. It asks Python to compute the list of words. But it does not rebind 'words' to that list value. ### >>> s = 'hello' >>> >>> list(s) ['h', 'e', 'l', 'l', 'o'] >>> >>> s 'hello' ### So list(s) does not mutate 's' itself. If we want to capture the value of list(s), we can bind it with an assignment: s = list(s) The same bug occurs later in the code with str(): > str(words) #newpage() requires string argument Anyway, the block of code: > if PDF_get_value(pdf, "texty", 0) < INCH : > words = string.joinfields(words, " ") > str(words) #newpage() requires string argument > newpage(words) looks very suspicious. Why is this rebinding the name 'words' to a string? Once we come out of the if statement, 'words' doesn't revert back to a list, so this is most likely the location where the TypeError arises. Try to avoid rebinding variables to different types. Doing so is tempting --- it feels like we're saving variable names. But it's problematic, since it makes it less simple to figure out what's going on with the variable. We can avoid the problem by not rebinding to 'words'. Instead of: ### if PDF_get_value(pdf, "texty", 0) < INCH : words = string.joinfields(words, " ") newpage(words) ### we can say: ### if PDF_get_value(pdf, "texty", 0) < INCH : newpage(string.joinfields(words, " ")) ### Please feel free to ask questions about this on Python-Tutor. Good luck! From guillermo.fernandez at epfl.ch Mon Nov 17 13:44:25 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Mon Nov 17 13:44:32 2003 Subject: [Tutor] Unix philosophy Message-ID: <3FB91709.5080002@epfl.ch> hi, I was having a look at the UNIX philosophy and I readed that: "Make every program a filter This makes it easy to build a set of filter components into ``one big filter.'' Programs can communicate by explicitly reading and writing files; that is / much / more complex to manage, and requires a lot of disk I/O for interim output. A set of filters may pass data straight from memory buffer to memory buffer, avoiding disk altogether." I was wondering how I could be able to make my python programs work in a filter mode? Thanks, Guille From kalle at lysator.liu.se Mon Nov 17 14:17:23 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Mon Nov 17 14:17:30 2003 Subject: [Tutor] Unix philosophy In-Reply-To: <3FB91709.5080002@epfl.ch> References: <3FB91709.5080002@epfl.ch> Message-ID: <20031117191723.GG29814@i92.ryd.student.liu.se> Hi! [Guillermo Fernandez Castellanos] > I was having a look at the UNIX philosophy and I readed that: > "Make every program a filter > This makes it easy to build a set of filter components into ``one > big filter.'' Programs can communicate by explicitly reading and > writing files; that is / much / more complex to manage, and requires > a lot of disk I/O for interim output. A set of filters may pass data > straight from memory buffer to memory buffer, avoiding disk > altogether." > > I was wondering how I could be able to make my python programs work > in a filter mode? Basically, what you have to do is read input from stdin and write output to stdout. That makes it possible to use it as a filter in a pipeline like grep something < file | python myprog.py | lp or whatever. The "|" signs here connect the first program's stdout to the second program's stdin. Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From VICKI.STANFIELD at roche.com Mon Nov 17 14:17:11 2003 From: VICKI.STANFIELD at roche.com (Stanfield, Vicki {D167~Indianapolis}) Date: Mon Nov 17 14:18:55 2003 Subject: [Tutor] Write array to Status text Message-ID: <CA3458C84C976E45B6372A6C14724C9F355E98@ridmsem02.nala.roche.com> I don't know if this made it to the list or not. Here is the code that I tried. It doesn't work correctly. The new values don't get appended to the array. ------------------------------------ errorarray=array('i', [0]*10) <snip part where returnedval gets set to hexadecimal value.> if count == 1: errorarray.append(returnedval) StatusText=errorarray[0:4].tostring() self.frame.SetStatusText(StatusText) print errorarray[0:4] ------------------------------------ Can you see what I am doing wrong here? --vicki -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Stanfield, Vicki {D167~Indianapolis} Sent: Monday, November 17, 2003 1:10 PM To: Vicki Stanfield; tutor@python.org Subject: RE: [Tutor] Write array to Status text Okay, it looks like an array but when I do this I get an error saying that: 'list' object has no attribute 'tostring' So I guess it is really a list. It looks so much like an array in C. I'm afraid that I don't see the reason for both existing. Is there a place where I can find out more about the differences? I'm sure that I could use a real array for what I am doing if I only understood the difference between arrays and lists. --vicki From python-tutor at ml03q3.pinguin.uni.cc Mon Nov 17 14:50:11 2003 From: python-tutor at ml03q3.pinguin.uni.cc (Al Bogner) Date: Mon Nov 17 16:17:21 2003 Subject: [Tutor] how to do "bash here" In-Reply-To: <Pine.LNX.4.44.0311162154480.343-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311162154480.343-100000@hkn.eecs.berkeley.edu> Message-ID: <200311172048.19145.python-tutor@ml03q3.pinguin.uni.cc> Am Montag, 17. November 2003 07:05 schrieb Danny Yoo: Hi Danny, > > I try to learn python by writing working bash-scripts in python. How can > > I do a bash-syntax like this with python: > > > > mysql --host=$MYSQLHOST -A --user=$MYSQLUSER --password=$MYSQLPWD > > $MYSQLDB <<END_OF_SQLINPUT | sed '1,/^export/d' > "$FDIMPORT" > > $MYSQLEXPORTCMDFD > > END_OF_SQLINPUT > Hmmm, nice shell command! One thing you may need to fix, though, is the > variable interpolation: passwords, too, can potentially contain spaces, so > you need to protect those shell variables with quotes, just like how you > protected $FDIMPORT. Thanks for this hint, but in this case $MYSQLPWD is nothing more than a placeholder. > Anyway, you may find the os.popen() command useful to simulate the "pipes" > that the Unix shell gives us: > > http://www.python.org/doc/lib/os-newstreams.html#l2h-1379 > > And that should take care of it. But instead of doing a literal > translation, it might be more educational to take advantage of the tools > that Python provides. Otherwise, you'll probably only learn how to use > os.popen() well. *grin* I would like to do my shellscrips with python as an exercise only. I don't want to replace my shellscripts with pythonscripts! > If you have more questions, please feel free to ask. Good luck to you! Thanks a lot! The reaseon why I came to python, is to build a mysql-frontend with a GUI and I think I have to be more familiar with python, before I start this project. Any hints/links are welcome. As a next step I will have a look at pythoncard. But first, I have to compile wxPythonSrc-2.4.2.4.tar.gz, because the rpm, which is included in the SuSE 8.2 distro is too old. Al From abli at freemail.hu Mon Nov 17 17:38:27 2003 From: abli at freemail.hu (Abel Daniel) Date: Mon Nov 17 17:38:14 2003 Subject: [Tutor] Re: (probably obvious) question about Tkinter References: <20031113014556.GC4309@vanilla.office.cyber.com.au> Message-ID: <E1ALs0q-00008J-00@hooloovoo> Ben McGinnes writes: [ ... question about closing Toplevel windows ... ] Well, you could call .destroy() on that Toplevel window. You could also make each Toplevel window once, (your current code re-creates them every time one of the functions is called) and use the .withdraw() and .wm_deiconify() methods to hide and show them. Some other notes: You need to call .mainloop() only once. Tkinter programs usually have the folowing structure: - make classes (by deriving from Tkinter classes, where appropriate) - a bit of setup (not much, maybe things like reading config files, etc. Mostly only instantiate one of the classes you created above, or have simething like 'mainwindow = Tkinter.Tk()' and place some widgets in that) - call .mainloop() The program won't exit the mainloop until you shut down the gui. As long as the gui is running, your program is in the mainloop. To do something actually usefull, you write a function, and hook it up as a callback. Thats what you did with the 'now' function in your example. The important thing to note is that when your callback is called (so in this case, the function 'now'), it is called from the mainloop. The mainloop is alread running, so you don't have to call 'Tkinter.mainloop()' again. Most of your program consists of creating widgets like: reallyB2 = Tkinter.Button(reallyTL, text="No", command=sys.exit) reallyB2.config(bg='blue') reallyB2.config(activebackground='purple') This can be written as: reallyB2 = Tkinter.Button(reallyTL, text="No", command=sys.exit bg='blue', activebackground='purple') Second, I think instead of creating a lot of custom windows, you could use existing ones instead. Reusing existing code will mean shorter and better code. The tkSimpleDialog module might provide some useful stuff. -- Abel Daniel From david at graniteweb.com Mon Nov 17 18:53:28 2003 From: david at graniteweb.com (David Rock) Date: Mon Nov 17 18:53:49 2003 Subject: [Tutor] Unix philosophy In-Reply-To: <20031117191723.GG29814@i92.ryd.student.liu.se> References: <3FB91709.5080002@epfl.ch> <20031117191723.GG29814@i92.ryd.student.liu.se> Message-ID: <20031117235328.GB11803@wdfs.graniteweb.com> * Kalle Svensson <kalle@lysator.liu.se> [2003-11-17 20:17]: > Hi! > > [Guillermo Fernandez Castellanos] > > I was having a look at the UNIX philosophy and I readed that: > > "Make every program a filter > > This makes it easy to build a set of filter components into ``one > > big filter.'' Programs can communicate by explicitly reading and > > writing files; that is / much / more complex to manage, and requires > > a lot of disk I/O for interim output. A set of filters may pass data > > straight from memory buffer to memory buffer, avoiding disk > > altogether." > > > > I was wondering how I could be able to make my python programs work > > in a filter mode? > > Basically, what you have to do is read input from stdin and write > output to stdout. That makes it possible to use it as a filter in a > pipeline like > > grep something < file | python myprog.py | lp > > or whatever. The "|" signs here connect the first program's stdout to > the second program's stdin. Yes, but the question is "how" to make it do that ;-) I use the fileinput module to do this: http://www.python.org/doc/current/lib/module-fileinput.html works great for all kinds of files, multiple files, stdin, etc. -- 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/20031117/58616d69/attachment.bin From littledanehren at yahoo.com Mon Nov 17 20:25:15 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Nov 17 20:25:30 2003 Subject: [Tutor] Unix philosophy In-Reply-To: <3FB91709.5080002@epfl.ch> Message-ID: <20031118012515.73720.qmail@web41802.mail.yahoo.com> Guillermo Fernandez Castellanos wrote: > Hi, > > I was having a look at the UNIX philosophy and I > readed that: > "Make every program a filter > This makes it easy to build a set of filter > components into ``one big > filter.'' Programs can communicate by explicitly > reading and writing > files; that is / much / more complex to manage, and > requires a lot of > disk I/O for interim output. A set of filters may > pass data straight > from memory buffer to memory buffer, avoiding disk > altogether." > > I was wondering how I could be able to make my > python programs work in a > filter mode? > > Thanks, > > Guille There are probably other ways to do this using exec or something, but I'd probably make all of the programs as libraries and make one short script connecting them all together. You know how do do that, don't you? Daniel Ehrenberg __________________________________ Do you Yahoo!? Protect your identity with Yahoo! Mail AddressGuard http://antispam.yahoo.com/whatsnewfree From dyoo at hkn.eecs.berkeley.edu Mon Nov 17 21:31:10 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 17 21:31:20 2003 Subject: [Tutor] Write array to Status text In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F355E98@ridmsem02.nala.roche.com> Message-ID: <Pine.LNX.4.44.0311171815510.29324-100000@hkn.eecs.berkeley.edu> On Mon, 17 Nov 2003, Stanfield, Vicki {D167~Indianapolis} wrote: > I don't know if this made it to the list or not. Here is the code that I > tried. It doesn't work correctly. The new values don't get appended to > the array. Hi Vicki, Sorry for abruptly jumping in, but I'm getting the feeling we shouldn't be using the 'array' module here. A Python 'List' is a collection that can dynamically grow in size, and that's probably what you want to use for general use. We can construct lists by using '[]'. An 'array' is meant to be a statically-sized homogenous collection of primitive objects --- like numbers --- and it has a very very specialized purpose that most folks won't need to touch. I guess I'm trying to say politely: don't use them now! *grin* > ------------------------------------ > errorarray=array('i', [0]*10) > > <snip part where returnedval gets set to hexadecimal value.> > > if count == 1: > errorarray.append(returnedval) > > StatusText=errorarray[0:4].tostring() > self.frame.SetStatusText(StatusText) > print errorarray[0:4] > ------------------------------------ Hmmm... How about this? ### errorarray=[] if count == 1: errorarray.append(returnedval) StatusText = str(errorarray[0:4]) self.frame.SetStatusText(StatusText) ### SetStatusText() probably expects a string. The subexpression above: errorarray[0:4] is a slice of the list 'errorarray', but it's still a list --- most API's that expect a string will NOT automagically convert objecst to strings. Since string conversion isn't an automatic thing, we need to explicitely wrap the value with str(): str(errorarray[0:4]) so that it produces a string representation of the list for SetStatusText(). If you have questions on any of this, please feel free to ask. Good luck! From dyoo at hkn.eecs.berkeley.edu Mon Nov 17 21:43:43 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 17 21:43:53 2003 Subject: [Tutor] Re: global In-Reply-To: <bpa5uc$rj7$1@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0311171835140.8441-100000@hkn.eecs.berkeley.edu> On Mon, 17 Nov 2003, RoT wrote: > Let us sit on the grass and tell stories of RoT > > > This problem tends to crop fairly regularly in my programming: > > > > global dummy > > global doit > > > > class dostuff: > > def=A0__init__(self): > > try: > > do=A0some=A0stuff > > if=A0doit=A0=3D=3D=A0True=A0and=A0dummy=A0=3D=3D= =A0False: > > do=A0some=A0more=A0stuff > > > > except=A0AttributeError: > > print=A0"I=A0said=A0dont=A0do=A0it=A0if= =A0it=A0is=A0Tuesday" > > #=A0Global=A0dummy=A0(this=A0works=A0but= =A0gives=A0a=A0warning=A0all=A0the=A0time) > > dummy=A0=3D=A0True > > def=A0morestuff(self): > > do=A0morestuffx > > > >x =3D raw_input("shall I do this thing, dont do it if it is Tuesday") Hi RoT, I have a slightly silly question: are you really using global variables in your regular programs, or are you just trying to learn how to use 'global'? If it's the former, then we have to recommend: don't use globals if you can help it. They're not automatically evil, but they seem to be all too easy to abuse. But I have to admit: I have no clue about what the example above is trying to accomplish. *grin* Can you show us another concrete example where you use globals? If you're regularly using global variables, we need to see some examples and find out why they're necessary in the code. Talk to you later! From vicki at thepenguin.org Mon Nov 17 22:06:05 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Mon Nov 17 22:09:59 2003 Subject: [Tutor] Write array to Status text In-Reply-To: <Pine.LNX.4.44.0311171815510.29324-100000@hkn.eecs.berkeley.edu> References: <CA3458C84C976E45B6372A6C14724C9F355E98@ridmsem02.nala.roche.com> <Pine.LNX.4.44.0311171815510.29324-100000@hkn.eecs.berkeley.edu> Message-ID: <36626.12.223.197.34.1069124765.squirrel@www.thepenguin.org> > > > On Mon, 17 Nov 2003, Stanfield, Vicki {D167~Indianapolis} wrote: > >> I don't know if this made it to the list or not. Here is the code that I >> tried. It doesn't work correctly. The new values don't get appended to >> the array. > > Hi Vicki, > > > Sorry for abruptly jumping in, but I'm getting the feeling we shouldn't be > using the 'array' module here. > > > A Python 'List' is a collection that can dynamically grow in size, and > that's probably what you want to use for general use. We can construct > lists by using '[]'. > > > An 'array' is meant to be a statically-sized homogenous collection of > primitive objects --- like numbers --- and it has a very very specialized > purpose that most folks won't need to touch. I guess I'm trying to say > politely: don't use them now! *grin* Funny thing though, my application is just that. There are exactly 4 entries and all are hexadecimal values. The 10 in my array initialization was just to make sure I didn't exceed my array boundaries. I changed it to 4 later. It is a far more comfortable thing for me since I used them in C, and it allows me the convenience of the tostring functionality. But having said that, I will use either if I can make the StatusText thing work. It is such a minimal part of the project that I really don't care which I use. It seems really klunky to have to do a join each time I add a value to my array (list), but if that is what it takes, I'll do it. --vicki From alan.gauld at blueyonder.co.uk Tue Nov 18 06:16:46 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 18 06:15:52 2003 Subject: [Tutor] Unix philosophy References: <3FB91709.5080002@epfl.ch> Message-ID: <004901c3adc5$7462a410$6401a8c0@xp> > I was having a look at the UNIX philosophy and I readed that: > "Make every program a filter > I was wondering how I could be able to make my python programs work in a > filter mode? A filter in Unix is a program that reads its input from stdin and writes its output to stdout (and ideally its errors to stderr) This allows us to build up commands as sequences(called pipelines) like: cat foo.txt | sort | uniq Which sends(cat) the file foo.txt into sort which sends the sorted result into uniq which removes duplicates. The final output being a list of the unique words in foo.txt. So how do we write such a program in Python? In Python raw_input and input both read from stdin by default and print writes to stdout. BUt raw_input waits for the input line by line, to be a true Unix filter there should be no prompts or waiting, so instead of raw_input we need to read() from sys.stdin... What it means about files is that ideally you shouldn't write a program that does this: fname = raw_input("Whats your filename?") text = file(fname).read() rather you should do: text = sys.stdin.read() And rely on the previous command in the pipeline(possibly cat) to send the file content to you. If the program is not part of a pipeline it will just sit and wait for you to type input and read it until you type EndOfFile (Ctrl-D in Unix). This is a bit unfriendly so its common to write programs that take a command line argument which switches filter behavious on or off. There is no fixed convention for how this is done. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From guillermo.fernandez at epfl.ch Tue Nov 18 06:23:49 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Tue Nov 18 06:23:57 2003 Subject: [Tutor] Unix philosophy Message-ID: <3FBA0145.3060008@epfl.ch> Hi, Thanks for the answers. I'm reading the digest version of the mailing list, that's why I grouped the answers. > There are probably other ways to do this using exec or > something, but I'd probably make all of the programs > as libraries and make one short script connecting them > all together. You know how do do that, don't you? Actually it was my philosophy until now. I am developing a utility and I'm separating it into libraries (one to parse text, another to join files, another to make database queries) but I always try to also allow the libraries to be used as single programs (with the if __name__=='__main__':). But I though it would be neat to do it the 'pipeline' way :-) It would allow the user to reproduce my program using a single command line and that way 'personalize' the execution (if he don't need a library for example). > I use the fileinput module to do this: > http://www.python.org/doc/current/lib/module-fileinput.html > > works great for all kinds of files, multiple files, stdin, etc. Indeed it seems to answer what I was looking for :-) > Basically, what you have to do is read input from stdin and write > output to stdout. That makes it possible to use it as a filter in a > pipeline like > > grep something < file | python myprog.py | lp > > or whatever. The "|" signs here connect the first program's stdout to > the second program's stdin. > This is a bit unfriendly so its common to write programs that > take a command line argument which switches filter behavious > on or off. There is no fixed convention for how this is done. That means that if I wanted to do it in a more general way that with fileinput module I should use the sys.stdin/out functions? Are you thinking to something like this: guillecat.py # Simple cat UNIX command import sys if len(sys.argv)==1: while(1): readed=sys.stdin.read(1) sys.stdout.write(readed) else: for files in sys.argv[1:]: filed=file(files,'r') readed=filed.read() sys.stdout.write(readed) Thanks, Guille From amk at amk.ca Tue Nov 18 07:17:40 2003 From: amk at amk.ca (A.M. Kuchling) Date: Tue Nov 18 07:18:06 2003 Subject: [Tutor] Unix philosophy In-Reply-To: <3FBA0145.3060008@epfl.ch> References: <3FBA0145.3060008@epfl.ch> Message-ID: <20031118121740.GA26384@rogue.amk.ca> On Tue, Nov 18, 2003 at 12:23:49PM +0100, Guillermo Fernandez Castellanos wrote: > That means that if I wanted to do it in a more general way that with > fileinput module I should use the sys.stdin/out functions? I would write it so that the library function takes any iterable for the input, and any object with a .write() method for output. Callers could then supply a file object, sys.stdin, or some constructed object of their own. For example: def process (input, output): for line in input: ... output.write(line) if __name__ == '__main__': import sys # (Or process command-line arguments to specify files...) process(sys.stdin, sys.stdout) --amk From op73418 at mail.telepac.pt Tue Nov 18 09:52:19 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Nov 18 09:51:10 2003 Subject: [Tutor] Accessing the name of an instance variable In-Reply-To: <BEEOLJNPLOPIONOMGLAACEHGCIAA.comber@cix.co.uk> References: <qj1frvof6e9k1oika0trrai9k4dih6mcsm@4ax.com> <BEEOLJNPLOPIONOMGLAACEHGCIAA.comber@cix.co.uk> Message-ID: <48bkrvoq6i6ap4t35okj3fks3p2eeil3or@4ax.com> On Tue, 18 Nov 2003 10:51:17 -0000, you wrote: >To explain why I want to this sort of thing - I have derived a simple >language for my partners to use in our medical practice by subclassing the >Python container classes. They don't program themselves but can easily >handle these classes which extract and manipulate groups of patients >depending on diseases. > >A definition takes the form of.. > >non_smoker_group = DiseaseCode(['1371','137L','137P0','137S','137T']) > >which extracts matching patients from the DB. > >I want them to be able to do some simple debugging by outputting the >contents of the containers preceded by the container name, so they can check >that the codes they have used are correct (by doing a lookup in another DB). Excellent. > >I can do this of course by explicitly stating the container name: > >describe_disease_group('non_smokerR',non_smoker_group) > >but it would be nicer and more fool-proof to incorporate it in container >behaviour like > >non_smoker_group.describe() > Great but what does that got to do with messing with globals? Let me go back a little and repost the example you posted a while back: class A: def __init__(self,x,y): self.one = x self.two = y def describe(self): print 'Describing' this_instance = id(self) for name, instance in globals().items(): # vars() print name if isinstance(instance,A): if id(instance) == this_instance: print 'Description of', name The describe method, as you code it, is very bizarre. What you seem to be doing is to go through the global names to *find the instance itself* and then print a description. Don't do that, there is no need! The first argument being called self is a clue... :-) Bear with me a little. When you do the following #Create an A instance. a = A(1, 2) #Describe it. a.describe() The last line is equivalent to: A.describe(a) So that, as you can see, when the describe method is called the self argument is set to the instance itself. So describe can be coded just as def describe(self): print "Describing" print "Description of", self No need to grovel through the globals to find the instance, since the instance is supplied as... self :-) Just one more note: It is better for a method like describe to return "something that can be printed" (a string) instead of print-ing directly. That way you can combine describe with other methods, compose fancier descriptions, etc. def describe(self): return "Describing\n" + "Description of " + repr(self) etc., etc. If you need more help just holler. With my best regards, G. Rodrigues P.S: Consider reading the tutorial coming with every Python distro or reading some of the online tutorials to learn more about objects, for example, A. Gauld's is great. He is also on this list so you can always try to squeeze more information out of him if my attempts at explanation are too unnerving :-) From dyoo at hkn.eecs.berkeley.edu Tue Nov 18 11:50:38 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 18 11:53:09 2003 Subject: [Tutor] for loops ... (fwd) Message-ID: <Pine.LNX.4.44.0311180850310.19876-100000@hkn.eecs.berkeley.edu> ---------- Forwarded message ---------- Date: Tue, 18 Nov 2003 06:49:25 +0100 From: Tadey <tayiper@volja.net> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: for loops ... Hello ... 1.) yet on the beggining I had problem understanding, or better imaging while loop, >>> j = 1 >>> while j <= 12: ... print "%d x 12 = %d" % (j, j*12) ... j = j + 1 ... the part, where it says j = j + 1 ... looked at first a bit illogical, like 1 = 1 + 1, so 1 = 2 come after,so this equation seems illogical (the value on both sides of = sign should be identical - that is the deffinition of equation). So I tryed to imagine it not as equation, but rather as some "instructon" how number (set by variable should "change/increase" through "looping" cicles. So I tryed to type j = 1 then j = j + 1, and of course after print j it says j = 2, so in case above (if j = 1) means variable j changes from 1 to 2, and then from 2 to 3, every loop +1, and so on to 11 ... is that it ?? So please, give me some background releted to that kind of equations/instructions (j = j + 1), how they "control" loops, which has higher "priority" - for better imaging !! Though that was relative simple case (for me) . 2.) Here it is something different, though it is again while loop with that kind of "equation", but ... I don't get it, how it print that high values as a result. I thought, that it first "takes" dog value 2, defined in tadey(2), then "calculates" current value for this loop, so dog = dog - 1, that gives 1, than multiplicate with result, which is set 1, which gives the real result ... but as you see (if you calculate in my way), I didn't get the right values. >>> def tadey(glg): result = 1 while glg > 0: result = result * glg glg = glg - 1 return result >>> tadey(6) 720 >>> tadey(5) 120 >>> tadey(4) 24 >>> tadey(3) 6 >>> tadey(2) 2 >>> tadey(1) 1 >>> tadey(0) 1 >>> tadey(-1) 1 >>> tadey(-2) 1 >>> ---> So please, explain, how Python calculates/gets that results in this case ?!? Thanks, Tadey From python at dhumketu.cjb.net Tue Nov 18 09:28:17 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Tue Nov 18 12:27:49 2003 Subject: [Tutor] Re: Unix philosophy In-Reply-To: <20031117235328.GB11803@wdfs.graniteweb.com> References: <20031117235328.GB11803@wdfs.graniteweb.com> Message-ID: <20031118142817.GA614@dhumketu.homeunix.net> +++ David Rock [17-11-03 17:53 -0600]: | * Kalle Svensson <kalle@lysator.liu.se> [2003-11-17 20:17]: | > Hi! | > | > [Guillermo Fernandez Castellanos] | > > I was having a look at the UNIX philosophy and I readed that: | > > "Make every program a filter | > > This makes it easy to build a set of filter components into ``one | > > big filter.'' Programs can communicate by explicitly reading and | > > writing files; that is / much / more complex to manage, and requires | > > a lot of disk I/O for interim output. A set of filters may pass data | > > straight from memory buffer to memory buffer, avoiding disk | > > altogether." | > > | > > I was wondering how I could be able to make my python programs work | > > in a filter mode? | > | > Basically, what you have to do is read input from stdin and write | > output to stdout. That makes it possible to use it as a filter in a | > pipeline like | > | > grep something < file | python myprog.py | lp | > | > or whatever. The "|" signs here connect the first program's stdout to | > the second program's stdin. | | Yes, but the question is "how" to make it do that ;-) | | I use the fileinput module to do this: | http://www.python.org/doc/current/lib/module-fileinput.html checkout sys.stdin, sys.stdout, sys.stderr Regards, Shantanoo | | works great for all kinds of files, multiple files, stdin, etc. | | -- | 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/20031117/58616d69/attachment-0001.bin | | ------------------------------ From alan.gauld at blueyonder.co.uk Tue Nov 18 12:56:57 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 18 12:56:06 2003 Subject: [Tutor] Unix philosophy References: <3FBA0145.3060008@epfl.ch> Message-ID: <002401c3adfd$5c3eb350$6401a8c0@xp> > That means that if I wanted to do it in a more general > way that with fileinput module I should use the > sys.stdin/out functions? > Are you thinking to something like this: > guillecat.py > # Simple cat UNIX command > import sys > if len(sys.argv)==1: > while(1): > readed=sys.stdin.read(1) > sys.stdout.write(readed) > else: > for files in sys.argv[1:]: > filed=file(files,'r') > readed=filed.read() > sys.stdout.write(readed) Exactly so. If no filename is provided assume it's stdin. Another often seen trick is to have a flag for using as a filter (Unix tar is an example) so you specify the tar filename as "-f file" and if the name is '-' use stdin. tar cvf foo.tar writes the output to foo.tar tar cvf - writes the output to stdout (usually a pipe to another command) But your way is a perfectly valid way too. Alan G. From alan.gauld at blueyonder.co.uk Tue Nov 18 13:01:01 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 18 13:00:03 2003 Subject: [Tutor] Unix philosophy References: <3FBA0145.3060008@epfl.ch> <20031118121740.GA26384@rogue.amk.ca> Message-ID: <002d01c3adfd$ed5bbf90$6401a8c0@xp> > def process (input, output): > for line in input: > ... > output.write(line) > > if __name__ == '__main__': > import sys > # (Or process command-line arguments to specify files...) > process(sys.stdin, sys.stdout) Hmm, do we have an old Pascal programmer in our midst? program(input, output) begin readln(input); writeln(output) end. ;-) Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Nov 18 13:06:28 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 18 13:06:33 2003 Subject: [Tutor] for loops ... (fwd) In-Reply-To: <Pine.LNX.4.44.0311180850310.19876-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0311180949510.24389-100000@hkn.eecs.berkeley.edu> > 1.) yet on the beggining I had problem understanding, or better imaging > while loop, > > >>> j = 1 > >>> while j <= 12: > ... print "%d x 12 = %d" % (j, j*12) > ... j = j + 1 > > ... the part, where it says j = j + 1 ... looked at first a bit > illogical, like 1 = 1 + 1, so 1 = 2 come after,so this equation seems > illogical (the value on both sides of = sign should be identical - that > is the deffinition of equation). Right --- the symbol '=' in many programming languages does not mean "mathematical equality", but instead, it's meant to symbolize "assignment". It's one of the major places where programming deviates from standard mathematics: instead of declaring a certain relation, we often have to instruct the computer to take an action. When we say: j = j + 1 imagine seeing a large arrow point to the left, like: j <------------ j + 1 The expression 'j + 1' is being assigned back into 'j'. > So I tryed to imagine it not as equation, but rather as some > "instructon" how number (set by variable should "change/increase" > through "looping" cicles. > > So I tryed to type j = 1 then j = j + 1, and of course after print j it > says j = 2, so in case above (if j = 1) means variable j changes from 1 > to 2, and then from 2 to 3, every loop +1, and so on to 11 ... is that > it ?? Yes, exactly: when we're programming in Python, we're not really writing math equations. > So please, give me some background releted to that kind of > equations/instructions (j = j + 1), how they "control" loops, which has > higher "priority" - for better imaging !! There are a few tutorials that should help introduce these ideas: http://python.org/topics/learn/non-prog.html Try going through one of them first, and then ask your questions again. *grin* > 2.) Here it is something different, though it is again while loop with > that kind of "equation", but ... > > I don't get it, how it print that high values as a result. > > I thought, that it first "takes" dog value 2, defined in tadey(2), then > "calculates" current value for this loop, so dog = dog - 1, that gives > 1, than multiplicate with result, which is set 1, which gives the real > result ... but as you see (if you calculate in my way), I didn't get the > right values. > > >>> def tadey(glg): > result = 1 > while glg > 0: > result = result * glg > glg = glg - 1 > return result Very close. Let's simulate tadey(3), step by step, and see what happens. There are two variables that are in motion here, 'result' and 'glg'. At the very start, we have something like: result = ?, glg = 3 I'm putting a question mark here because we're at the very beginning, and I have no idea what result should be. Let's do the first line: > result = 1 Now we have: result = 1, glg = 3 We then reach a while loop: > while glg > 0: > result = result * glg > glg = glg - 1 Since glg is still greater than 0, we'll repeat the body of this loop till glg is no longer greater than zero. > result = result * glg Now we have: result = 3, glg = 3 > glg = glg - 1 result = 3, glg = 2 > result = result * glg result = 6, glg = 2 > glg = glg - 1 result = 6, glg = 1 We still have to execute the loop body one more time, since glg is still greater than zero! > result = result * glg result = 6, glg = 1 > glg = glg - 1 result = 6, glg = 0 And now we come out of the while loop. But we still have one more statement to execute: > return result And we return 'result' as our answer. tadey(3) == 6. Out of curiosity, would something like this make more sense for you? ### def tadey(glg): if tadey <= 0: return 1 return glg * tadey(glg-1) ### If not, don't worry about it; I'm just curious to see if this "recursive" definition makes more sense than the loopy version of the code. Hope this helps! From alan.gauld at blueyonder.co.uk Tue Nov 18 13:09:27 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 18 13:08:29 2003 Subject: [Tutor] for loops ... (fwd) References: <Pine.LNX.4.44.0311180850310.19876-100000@hkn.eecs.berkeley.edu> Message-ID: <003601c3adff$1b0d5470$6401a8c0@xp> Tadey sent this to me separately, for completeness here is my reply to him. (Spacing seems to have gone wild due to alphabet changes, sorry) Alan G. > ... the part, where it says j = j + 1 ... looked at first a bit illogical, > like 1 = 1 + 1, so 1 = 2 come after,so this equation seems illogical I think I mention this somewhere in the tutor but maybe not strongly enough. In python (and many other languages) equality is represented by a double equals: == So j == j + 1 would, as you expect, be nonsense and always false. A single equals is what is known as "assignment". Some programmers like to read it as "becomes", so j = j + 1 is read as j becomes j + 1 In fact some languages (Pascal, ADA, Smalltalk) use a different symbol for assignment and use a single equals for equality - which is frankly more sensible! So in Pascal it would look like: j := j + 1 Notice the extra colon before the equals sign. > means variable j changes from 1 to 2, and then from 2 to 3, every loop +1, > and so on to 11 ... is that it ?? Yes. > So please, give me some background releted to that kind of > equations/instructions (j = j + 1), how they "control" loops, The while loop has the following abstract form: <Initialise loop control value> while <test value>: < do some processing> <change loop control value> For example: j = 1 while j < 10: print j * 12 j = j+1 > I don't get it, how it print that high values as a result. > I thought, that it first "takes" dog value 2, defined in > tadey(2),then "calculates" current value for this loop, > so dog = dog - 1, that gives 1, than multiplicate > with result, which is set 1, which gives the real result ... That's pretty much right, let's walk through it: >>> def tadey(glg): result = 1 while glg > 0: result = result * glg glg = glg - 1 return result We'll draw a table of the variables: glg result 2 1 while glg > 0, first time 2 2 result = result * glg 1 2 glg = glg - 1 1 2 while glg > 0 , second time 1 2 result = result * glg 0 2 glg = glg - 1 0 2 while glg < 0, third time. Test if false so we exit loop 0 2 return result So the result is 2 Lets do it again for tadey(3): glg result 3 1 while glg > 0, first time 3 3 result = result * glg 2 3 glg = glg - 1 2 3 while glg > 0 , second time 2 6 result = result * glg 1 6 glg = glg - 1 1 6 while glg < 0, third time. 1 6 result = result * glg 0 6 glg = glg - 1 0 6 while glg < 0, 4th time, test fails, loop exits. 0 6 return result So the result is 6. Finally, lets try: >>> tadey(-1) glg result -1 1 while glg > 0, first time, test fails, loop is never entered -1 1 return result Hopefully that makes sense? Alan G. From bgailer at alum.rpi.edu Thu Nov 13 15:42:47 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Nov 18 13:39:49 2003 Subject: [Tutor] newbie bragging about code In-Reply-To: <1gh5rvcojfjvdafjk6vob26lorfvepcq5l@4ax.com> References: <1gh5rvcojfjvdafjk6vob26lorfvepcq5l@4ax.com> Message-ID: <6.0.0.22.0.20031113125052.0328d268@mail.mric.net> At 05:05 PM 11/12/2003, Eur van Andel wrote: >Hi > >I sent the prog hereunder to my father with comments. Maybe these comments >will >help others or draw better comments. I notice you are not using classes, and that's OK. I will show one way to use classes in the hopes of giving you a "leg up" on OOP. One indication of a need for classes is when you are doing the same thing twice (creating files in this case). Consider: class File: def __init__(self, kind): self.fileName = strftime("%d-%m-%Y_%H-%M." + kind, localtime()) self.file = file(self.fileName, 'w') def write(self.txt): self.file.write(txt) # everything that's common to the 2 file types is encapsulated in one class definition. Then you proceed to create 2 instances of File, each dedicated to a unique purpose: ... logfile = File('log') logfile.write('temperatures and pump duty cycles\n') logfile.write('from six fans and pump controller\n') if raw_output: rawfile = File('raw') I factored out the initial writing to the log file to keep the class definition simple. There are numerous other options here, including creating subclasses for the 2 types, and using __call__ instead of write (in which case you'd write to the file thus: logfile('temperatures and pump duty cycles\n') >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 > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.538 / Virus Database: 333 - Release Date: 11/10/2003 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.538 / Virus Database: 333 - Release Date: 11/10/2003 From jsoons at juilliard.edu Tue Nov 18 13:44:53 2003 From: jsoons at juilliard.edu (Jonathan Soons) Date: Tue Nov 18 13:45:04 2003 Subject: [Tutor] more trouble with PDF program Message-ID: <33E101AC5AFF78419F466954A96854202F5AA1@mailbox.juilliard.edu> Many thanks for the advice that got me this far. Now my remaining problem is that any text carrying over to page 2 is printed twice (variable txt below.) newpage() is only called if text gets close to the bottom of page 1. Can anyone see how the duplication is happening? def mklines(field) : if len(field) < 1 : return words = field.split(" ") while len(words) > 0 : line = "" while (len(line) < 60) and len(words) > 0 : line = line + " " + words[0] del(words[0]) PDF_continue_text(pdf, line) line = "" if (PDF_get_value(pdf, "texty", 0) < INCH) and (len(words) > 0): txt = string.joinfields(words, " ") newpage(str(txt)) def newpage(words) : global pagenum pagenum = pagenum + 1 PDF_end_page(pdf) PDF_begin_page(pdf, WIDTH, HEIGHT) PDF_setfont(pdf, font0, 14) PDF_set_text_pos(pdf, INCH, 704) PDF_show(pdf, last + ", " + first) PDF_set_text_pos(pdf, WIDTH - 144, 704) if pagenum > 1 : PDF_show(pdf, "page %d" % pagenum) PDF_setfont(pdf, font1, 12) PDF_set_text_pos(pdf, INCH, 690) mklines(words) Thanks jon soons From sigurd at 12move.de Tue Nov 18 14:01:06 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Nov 18 14:03:07 2003 Subject: [Tutor] for loops ... (fwd) In-Reply-To: <Pine.LNX.4.44.0311180850310.19876-100000@hkn.eecs.berkeley.edu> (Danny Yoo's message of "Tue, 18 Nov 2003 08:50:38 -0800 (PST)") References: <Pine.LNX.4.44.0311180850310.19876-100000@hkn.eecs.berkeley.edu> Message-ID: <m3k75xwmvl.fsf@hamster.pflaesterer.de> On 18 Nov 2003, Danny Yoo <- dyoo@hkn.eecs.berkeley.edu wrote: > ---------- Forwarded message ---------- > Date: Tue, 18 Nov 2003 06:49:25 +0100 > From: Tadey <tayiper@volja.net> > To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> > Subject: for loops ... (I send a Cc to you as I'm not sure if you read the list). [...] >>>> j = 1 >>>> while j <= 12: > ... print "%d x 12 = %d" % (j, j*12) > ... j = j + 1 > ... the part, where it says j = j + 1 ... looked at first a bit illogical, If you think like a mathematician you're perfectly right. Computer scientists sadly thought such a syntax would be no problem (not all; cf eg. Pascal). > like 1 = 1 + 1, so 1 = 2 come after,so this equation seems illogical (the > value on both sides of = sign should be identical - that is the deffinition > of equation). Right. But that is no equation but an assignment. In some languages you'd have to write assignment like that: k := k + 1 to make it clear that there is no equation meant. You have to read k = k + 1 as new value = old value + 1 The left hand side (lhs) gets assigned the value which is computed at the right hand side (rhs). > So I tryed to imagine it not as equation, but rather as some "instructon" > how number (set by variable should "change/increase" through "looping" > cicles. Right. > So I tryed to type j = 1 then j = j + 1, and of course after print j it says > j = 2, so in case above (if j = 1) means variable j changes from 1 to 2, and > then from 2 to 3, every loop +1, and so on to 11 ... is that it ?? Yes. > So please, give me some background releted to that kind of > equations/instructions (j = j + 1), how they "control" loops, which has > higher "priority" - for better imaging !! See above. First the rhs is computed; its value is ssigned to the lhs. [...] > I don't get it, how it print that high values as a result. As you seem to know mathematics the formula computes factorial numbers (alomost). They are only defined for positive natural numbers including zero. > I thought, that it first "takes" dog value 2, defined in tadey(2), then > "calculates" current value for this loop, so dog = dog - 1, that gives 1, > than multiplicate with result, which is set 1, which gives the real result > ... but as you see (if you calculate in my way), I didn't get the right > values. >>>> def tadey(glg): > result = 1 > while glg > 0: > result = result * glg > glg = glg - 1 > return result Let's do it manually. If you call that function with 3 what happens? (I write assignment as `a <- b' which means: assign the value of b to a) tadey(3) Step Operation Result 1 result =1 result <- 1 ********** Entering the loop ********** 2 glg > 0 True (glg is 3) 3 result = ... result <- 1 * 3 4 glg = ... glg <- 3 - 1 ********** check loop condition ********** 5 glg > 0 True (glg is 2) 6 result = ... result <- 3 * 2 (see step 3 for the new value of result and step 4 for the new value of glg) 7 glg = ... glg <- 2 - 1 ********** check loop condition ********** 8 glg > 0 True 9 result = ... result <- 6 * 1 (see step 6 and 7) 10 glg = ... glg <- 1 - 1 ********** check loop condition ********** 11 glg > 0 False (see step 10) ********** leaving loop ********** 12 return result 6 (see step 9) Karl -- Please do *not* send copies of replies to me. I read the list From llwyble at cox.net Tue Nov 18 16:02:11 2003 From: llwyble at cox.net (Larry) Date: Tue Nov 18 15:03:08 2003 Subject: [Tutor] accessing the mixer Message-ID: <20031118150211.40b58108.llwyble@cox.net> Hi, I am trying to access the mixer in order to build a simple volume control, for now. (: Anyway I have found very little on google about doing anything at all with the mixer, though I have found ossaudiodev in the 'python library reference', so I'm trying to work from that. But now I find that my library reference in /usr/doc/python/html has no ossaudiodev listing in it. So where do I get this? is it a module that needs to be installed? Do I call it as a module as in; import ossaudiodev Any help appreciated. Thanks From dyoo at hkn.eecs.berkeley.edu Tue Nov 18 15:05:09 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 18 15:05:14 2003 Subject: [Tutor] Write array to Status text In-Reply-To: <36626.12.223.197.34.1069124765.squirrel@www.thepenguin.org> Message-ID: <Pine.LNX.4.44.0311180852450.19876-100000@hkn.eecs.berkeley.edu> > > A Python 'List' is a collection that can dynamically grow in size, and > > that's probably what you want to use for general use. We can > > construct lists by using '[]'. > > > > An 'array' is meant to be a statically-sized homogenous collection of > > primitive objects --- like numbers --- and it has a very very > > specialized purpose that most folks won't need to touch. I guess I'm > > trying to say politely: don't use them now! *grin* > > Funny thing though, my application is just that. There are exactly 4 > entries and all are hexadecimal values. Hi Vicki, Hmmm! Out of curiosity, what are some examples of StatusText that the code wants to display to the user? I just want to understand the context of this problem better. You've mentioned that you're getting hexadecimal values back, so can I assume you're getting some character string from a hardware device? > The 10 in my array initialization was just to make sure I didn't exceed > my array boundaries. I changed it to 4 later. It is a far more > comfortable thing for me since I used them in C, and it allows me the > convenience of the tostring functionality. Sure. We can also pre-size a Python list: ### >>> l = [0]*4 >>> l [0, 0, 0, 0] >>> l[2] = 0x34 >>> l [0, 0, 52, 0] ### and if we never do an append() on a list, then it behaves almost exactly like a standard C array. Indicing and index assignment should work exactly how you'd expect in C. (If you've used C++ before, you can think of a Python list as a "vector", where we can push back (pushback()) elements at the end of the container with relative ease. Doing the same thing with an array alone won't work, because arrays are fixed-sized containers.) Lists don't have tostring(). On the other hand, they do have quite a few things that arrays don't have: ### >>> dir([]) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ### As Python's generic container class, a list can do a lot of stuff, including sort()s and arbitrary insert()ion. And a key advantage of a list is that we don't have to hardcode its size: ### >>> l = [] >>> while 1: ... text = raw_input('next? ') ... if not text: break ... l.append(int(text, 16)) ... next? 0x32 next? 0x16 next? 0x42 next? 0x7 next? 0xdeadbeef next? >>> l [50, 22, 66, 7, 3735928559L] >>> >>> >>> l2 = [None] * 2 >>> l2[0] = 'hello' >>> l2[1] = 'world' >>> l2 ['hello', 'world'] >>> ':'.join(l2) 'hello:world' ### The last example shows that if our list contains only strings, then it's fairly easy to join them all together into a single string. > But having said that, I will use either if I can make the StatusText > thing work. It is such a minimal part of the project that I really don't > care which I use. It seems really klunky to have to do a join each time > I add a value to my array (list), but if that is what it takes, I'll do > it. Without knowing more about the context of the program, I can't say for certain that the 'array' module is not what you need. You mentioned that you needed the array's tostring() method, so perhaps arrays will be a win here. I won't push too hard on forcing you to use lists. *grin* But when you have the time, I'd recommend looking more into Python lists, because the majority of the Python code you'll see will use lists as a fundamental type. If you'd like more information about them, you can take a look here: http://www.python.org/doc/current/tut/node5.html#SECTION005140000000000000000 Good luck to you! From VICKI.STANFIELD at roche.com Tue Nov 18 15:13:42 2003 From: VICKI.STANFIELD at roche.com (Stanfield, Vicki {D167~Indianapolis}) Date: Tue Nov 18 15:15:37 2003 Subject: [Tutor] Write array to Status text Message-ID: <CA3458C84C976E45B6372A6C14724C9F355E99@ridmsem02.nala.roche.com> I ended up using a list, but I still think my info was better suited to an array. I had trouble getting the array right in my app, so I switched back to a list and finally got the StatusText thing to work. I did this: -------------------- errorarray=[0] *5 <SNIP> StatusText="" <SNIP part where count gets set> while returnedval != EOT: output=port.read() returnedval= hex(ord(output)) if count == 1: errorarray[byte]=returnedval byte = byte +1 StatusText=StatusText.join(str(errorarray[0:4])) self.frame.SetStatusText(StatusText) --------------------- I hope I didn't cut out anything critical to the explanation. --vicki -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Danny Yoo Sent: Tuesday, November 18, 2003 3:05 PM To: Vicki Stanfield Cc: Tutor Subject: RE: [Tutor] Write array to Status text > > A Python 'List' is a collection that can dynamically grow in size, > > and that's probably what you want to use for general use. We can > > construct lists by using '[]'. > > > > An 'array' is meant to be a statically-sized homogenous collection > > of primitive objects --- like numbers --- and it has a very very > > specialized purpose that most folks won't need to touch. I guess > > I'm trying to say politely: don't use them now! *grin* > > Funny thing though, my application is just that. There are exactly 4 > entries and all are hexadecimal values. Hi Vicki, Hmmm! Out of curiosity, what are some examples of StatusText that the code wants to display to the user? I just want to understand the context of this problem better. You've mentioned that you're getting hexadecimal values back, so can I assume you're getting some character string from a hardware device? > The 10 in my array initialization was just to make sure I didn't > exceed my array boundaries. I changed it to 4 later. It is a far more > comfortable thing for me since I used them in C, and it allows me the > convenience of the tostring functionality. Sure. We can also pre-size a Python list: ### >>> l = [0]*4 >>> l [0, 0, 0, 0] >>> l[2] = 0x34 >>> l [0, 0, 52, 0] ### and if we never do an append() on a list, then it behaves almost exactly like a standard C array. Indicing and index assignment should work exactly how you'd expect in C. (If you've used C++ before, you can think of a Python list as a "vector", where we can push back (pushback()) elements at the end of the container with relative ease. Doing the same thing with an array alone won't work, because arrays are fixed-sized containers.) Lists don't have tostring(). On the other hand, they do have quite a few things that arrays don't have: ### >>> dir([]) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ### As Python's generic container class, a list can do a lot of stuff, including sort()s and arbitrary insert()ion. And a key advantage of a list is that we don't have to hardcode its size: ### >>> l = [] >>> while 1: ... text = raw_input('next? ') ... if not text: break ... l.append(int(text, 16)) ... next? 0x32 next? 0x16 next? 0x42 next? 0x7 next? 0xdeadbeef next? >>> l [50, 22, 66, 7, 3735928559L] >>> >>> >>> l2 = [None] * 2 >>> l2[0] = 'hello' >>> l2[1] = 'world' >>> l2 ['hello', 'world'] >>> ':'.join(l2) 'hello:world' ### The last example shows that if our list contains only strings, then it's fairly easy to join them all together into a single string. > But having said that, I will use either if I can make the StatusText > thing work. It is such a minimal part of the project that I really > don't care which I use. It seems really klunky to have to do a join > each time I add a value to my array (list), but if that is what it > takes, I'll do it. Without knowing more about the context of the program, I can't say for certain that the 'array' module is not what you need. You mentioned that you needed the array's tostring() method, so perhaps arrays will be a win here. I won't push too hard on forcing you to use lists. *grin* But when you have the time, I'd recommend looking more into Python lists, because the majority of the Python code you'll see will use lists as a fundamental type. If you'd like more information about them, you can take a look here: http://www.python.org/doc/current/tut/node5.html#SECTION0051400000000000 00000 Good luck to you! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Tue Nov 18 15:29:08 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 18 15:29:17 2003 Subject: [Tutor] Write array to Status text In-Reply-To: <CA3458C84C976E45B6372A6C14724C9F355E99@ridmsem02.nala.roche.com> Message-ID: <Pine.LNX.4.44.0311181220360.6869-100000@hkn.eecs.berkeley.edu> On Tue, 18 Nov 2003, Stanfield, Vicki {D167~Indianapolis} wrote: > I ended up using a list, but I still think my info was better suited to > an array. I had trouble getting the array right in my app, so I switched > back to a list and finally got the StatusText thing to work. I did this: > > -------------------- > errorarray=[0] *5 > <SNIP> > StatusText="" > <SNIP part where count gets set> > while returnedval != EOT: > output=port.read() > returnedval= hex(ord(output)) > if count == 1: > errorarray[byte]=returnedval > byte = byte +1 > > StatusText=StatusText.join(str(errorarray[0:4])) > self.frame.SetStatusText(StatusText) Hi Vicki, Ah, ok, I see now! The returnedval's are hexadecimal strings! Then the code can be simplified to: ### errorarray = [] <SNIP some setup code> while returnedval != EOT: output = port.read() returnedval = hex(ord(output)) if count == 1: errorarray.append(returnedval) StatusText = ''.join(errorarray[0:4]) self.frame.SetStatusText(StatusText) ### StatusText can be formatted in different ways; the code above will just glue them end-to-end, and that might be hard to read. Another way to do it is to just say: StatusText = str(errorarray) which should also show those values, separated by commas. Glad to see the code is working for you now. Talk to you later! From dyoo at hkn.eecs.berkeley.edu Tue Nov 18 17:05:40 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 18 17:05:59 2003 Subject: [Tutor] Write array to Status text In-Reply-To: <54421.206.53.226.235.1069190298.squirrel@www.thepenguin.org> Message-ID: <Pine.LNX.4.44.0311181355560.15016-100000@hkn.eecs.berkeley.edu> On Tue, 18 Nov 2003, Vicki Stanfield wrote: > I have another array (list) which is supposed to hold 3 two digit values. > I initialized it like this: > > bytearray=[0] * int(parameters[2]) > > where parameters[2] is an ascii 3. Evidently this is wrong since I get > this message when I try to run it: > > IndexError: list index out of range Hi Vicki, [Please continue to send your replies to 'tutor@python.org', and not just me directly. You need to give the others on the Tutor list the opportunity to help answer your questions; otherwise, everyone will feel left out!] To diagnose this more accurately, we'll probably need to see the full error traceback to figure out what's happening, stack trace and all. For the moment, I have to assume that the traceback message is applying to the line: bytearray=[0] * int(parameters[2]) but if this assumption is incorrect, you need to point that out to us. An IndexError occurs whenever we try to access beyond the length of our list. My initial guess is that, if the error is being emitted from: bytearray = [0] * int(parameters[2]) then since 'parameters[2]' is the only subexpression in there that's doing an indexing operation, the parameter list probably doesn't have three elements in it. How are you sure you have at least three elements in that 'parameters' list? What happens if you hardcode the value '3' in there, like: bytearray = [0] * 3 Let's see if we can isolate this problem. Good luck to you! From pythontutor at venix.com Wed Nov 19 00:20:15 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Nov 19 00:20:16 2003 Subject: [Tutor] new classes and default attribute Message-ID: <3FBAFD8F.2050002@venix.com> An instance of the builtin types will return its value when referenced. >>> class I(int): ... pass ... >>> i = I(123) >>> i 123 An instance of a "normally" defined class returns type information. >>> class O(object): ... pass ... >>> o = O(123) >>> o <__main__.O object at 0x016F0420> Where does this difference in behavior come from? Is there a __????__ that can be used when defining a class to get similar behavior? -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From op73418 at mail.telepac.pt Wed Nov 19 07:09:59 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 19 07:08:32 2003 Subject: [Tutor] new classes and default attribute In-Reply-To: <3FBAFD8F.2050002@venix.com> References: <3FBAFD8F.2050002@venix.com> Message-ID: <r8nmrvo23jsoq97lmokknls192a95pp9lr@4ax.com> On Wed, 19 Nov 2003 00:20:15 -0500, you wrote: >An instance of the builtin types will return its value when referenced. > >>> class I(int): >... pass >... > >>> i = I(123) > >>> i >123 > >An instance of a "normally" defined class returns type information. > >>> class O(object): >... pass >... > >>> o = O(123) > >>> o ><__main__.O object at 0x016F0420> > >Where does this difference in behavior come from? Is there a __????__ >that can be used when defining a class to get similar behavior? Look up the __repr__ and __str__ methods. In the above __repr__ is used, e.g. >>> class Test(object): ... def __repr__(self): ... return "This is a test." ... >>> a = Test() >>> a This is a test. >>> With my best regards, G. Rodrigues From pythontutor at venix.com Wed Nov 19 10:24:40 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Nov 19 10:25:09 2003 Subject: [Tutor] new classes and default attribute In-Reply-To: <r8nmrvo23jsoq97lmokknls192a95pp9lr@4ax.com> References: <3FBAFD8F.2050002@venix.com> <r8nmrvo23jsoq97lmokknls192a95pp9lr@4ax.com> Message-ID: <3FBB8B38.20801@venix.com> Gon?alo Rodrigues wrote: > On Wed, 19 Nov 2003 00:20:15 -0500, you wrote: > > >>An instance of the builtin types will return its value when referenced. >> >>>>>class I(int): >> >>... pass >>... >> >>>>>i = I(123) >>>>>i >> >>123 >> >>An instance of a "normally" defined class returns type information. >> >>>>>class O(object): >> >>... pass >>... >> >>>>>o = O(123) >>>>>o >> >><__main__.O object at 0x016F0420> >> >>Where does this difference in behavior come from? Is there a __????__ >>that can be used when defining a class to get similar behavior? > > > Look up the __repr__ and __str__ methods. In the above __repr__ is > used, e.g. > > >>>>class Test(object): > > ... def __repr__(self): > ... return "This is a test." > ... > >>>>a = Test() >>>>a > > This is a test. That is true for a string, but doesn't work with a number. >>> repr(i) '123' >>> i.__repr__() '123' >>> i 123 I did try to look this up, but none of the "magic methods" seemed to apply. I do agree that __repr__ comes close. > > > With my best regards, > G. Rodrigues > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From op73418 at mail.telepac.pt Wed Nov 19 10:41:07 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 19 10:39:37 2003 Subject: [Tutor] new classes and default attribute In-Reply-To: <3FBB8B38.20801@venix.com> References: <3FBAFD8F.2050002@venix.com> <r8nmrvo23jsoq97lmokknls192a95pp9lr@4ax.com> <3FBB8B38.20801@venix.com> Message-ID: <vc3nrv41n65ldcaor4fe9guetn6okb9l5s@4ax.com> On Wed, 19 Nov 2003 10:24:40 -0500, you wrote: [text snipped] >That is true for a string, but doesn't work with a number. > > >>> repr(i) >'123' > >>> i.__repr__() >'123' > >>> i >123 > >I did try to look this up, but none of the "magic methods" seemed to apply. >I do agree that __repr__ comes close. > Well, it's either calling __str__ or __repr__. I never quite know when Python calls each. Go figure... The differences between __repr__ and __str__ are indeed subtle and have already motivated some long threads at comp.lang.py - check them out if you're interested. With my best regards, G. Rodrigues P.S: At a Python prompt I get the following: >>> i = 123 >>> i 123 >>> str(i) '123' >>> repr(i) '123' >>> print str(i) 123 >>> print repr(i) 123 >>> print repr(i) == str(i) True >>> i = "123" >>> i '123' >>> print i 123 >>> From alan.gauld at blueyonder.co.uk Wed Nov 19 11:00:03 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 19 10:59:52 2003 Subject: [Tutor] Write array to Status text References: <CA3458C84C976E45B6372A6C14724C9F355E99@ridmsem02.nala.roche.com> Message-ID: <007201c3aeb6$3183d4b0$6401a8c0@xp> Unless there is more going on that you haven't shown... -------- returnedval= ord(output) if count == 1: errorarray[byte]=returnedval # store the ASCII value byte = byte +1 StatusText += "%x%x%x%x" % tuple(errorarray) self.frame.SetStatusText(StatusText) --------- Should achieve the same with fewer conversions. Alan G. From alan.gauld at blueyonder.co.uk Wed Nov 19 11:02:27 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 19 11:02:16 2003 Subject: [Tutor] new classes and default attribute References: <3FBAFD8F.2050002@venix.com> Message-ID: <007b01c3aeb6$87752c70$6401a8c0@xp> > >>> class I(int): > ... pass > ... > >>> i = I(123) > >>> i > 123 > > An instance of a "normally" defined class returns type information. > >>> class O(object): > ... pass > ... > >>> o = O(123) > >>> o > <__main__.O object at 0x016F0420> > > Where does this difference in behavior come from? Is there a __????__ > that can be used when defining a class to get similar behavior? I assume because the inherited str() and repr() methods are different between objects and integers. The integer returns a number for both cases whereas the object returns a type description. Alan G. From VICKI.STANFIELD at roche.com Wed Nov 19 11:02:00 2003 From: VICKI.STANFIELD at roche.com (Stanfield, Vicki {D167~Indianapolis}) Date: Wed Nov 19 11:03:25 2003 Subject: [Tutor] Write array to Status text Message-ID: <CA3458C84C976E45B6372A6C14724C9F9E59B6@ridmsem02.nala.roche.com> Nice. I will try that when I hit another lull moment. Thanks. --vicki -----Original Message----- From: Alan Gauld [mailto:alan.gauld@blueyonder.co.uk] Sent: Wednesday, November 19, 2003 11:00 AM To: Stanfield, Vicki {D167~Indianapolis}; tutor@python.org Cc: Tutor Subject: Re: [Tutor] Write array to Status text Unless there is more going on that you haven't shown... -------- returnedval= ord(output) if count == 1: errorarray[byte]=returnedval # store the ASCII value byte = byte +1 StatusText += "%x%x%x%x" % tuple(errorarray) self.frame.SetStatusText(StatusText) --------- Should achieve the same with fewer conversions. Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Nov 19 18:20:38 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 19 18:20:46 2003 Subject: [Tutor] Re: didn't get right output with stdout ... In-Reply-To: <006c01c3aead$b39fdec0$ae4648d9@mz9s680eu689tz> Message-ID: <Pine.LNX.4.44.0311191058070.19749-100000@hkn.eecs.berkeley.edu> On Wed, 19 Nov 2003, Tadey wrote: > I must say, that I feel more common sending you this questions, than to > mailing list - why ?? They are actual programmers there, talking about > details Hi Tadey, Don't worry about it. The advantage of a list like Tutor is that it has a good mix of folks of all kinds of experience. If you're going to ask questions about how to program, then it's often a good thing that you can talk to real programmers: we're battle tested. *grin* > So, I am asking real "beginers" questions, but they all know how to > program very well, they just need some advises, or something, like I > said in more advanced meaning ... No, no, that's exactly what makes Python-Tutor a good place to ask beginner questions. Python-Tutor is meant for beginners to Python and programming. And if it feels intimidating to ask questions there, then that means that we Tutors are doing something seriously wrong. If you're worried because you don't understand every conversation on Python-Tutor, don't be! You are not expected to understand everything that you see on Tutor. Listen in on the stuff that seems interesting, and ignore the stuff that isn't. And if something on the mailing list seems interesting but somewhat incomprehensible, then ask for an introduction about the subject. I think that you'll find that people are happy to try to explain how things work. Many folks who are answering questions on Tutor like to do it because it helps them understand the concepts better: it's a reciprocity thing. So you're doing everyone a service by asking good questions on the mailing list. Please feel free to ask your questions on Python-Tutor. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Nov 19 18:41:31 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 19 18:41:39 2003 Subject: [Tutor] accessing the mixer In-Reply-To: <20031118150211.40b58108.llwyble@cox.net> Message-ID: <Pine.LNX.4.44.0311191526060.7934-100000@hkn.eecs.berkeley.edu> On Tue, 18 Nov 2003, Larry wrote: > I am trying to access the mixer in order to build a simple volume > control, for now. (: > > Anyway I have found very little on google about doing anything at all > with the mixer, though I have found ossaudiodev in the 'python library > reference', so I'm trying to work from that. > > But now I find that my library reference in /usr/doc/python/html has no > ossaudiodev listing in it. Hi Larry, Hmmm... That's odd. Here's a link to the official documenation on the 'ossaudiodev' module: http://www.python.org/doc/lib/module-ossaudiodev.html but it only works for Unix systems. I wonder why it's missing from your local documentation? If you're on a system that supports the ossaudiodev module, then the following example might work: ### import ossaudiodev mixer = ossaudiodev.openmixer() mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, (50, 50)) ### This should set the left and right channels of the master volume to 50% loudness. But that example probably won't work on Windows. I'm not exactly sure if there's a nice platform-independent way to access the global volume control; does anyone else know about it? The 'pygame' module does provide a mixer so that you can control the volume of your own application: http://pygame.org/ http://pygame.org/docs/ref/pygame_mixer.html http://pygame.org/docs/ref/pygame_mixer_music.html so perhaps you might be able to do something with it. Good luck to you! From klappnase at freenet.de Wed Nov 19 18:47:19 2003 From: klappnase at freenet.de (Michael Lange) Date: Wed Nov 19 18:53:36 2003 Subject: [Tutor] accessing the mixer In-Reply-To: <20031118150211.40b58108.llwyble@cox.net> References: <20031118150211.40b58108.llwyble@cox.net> Message-ID: <20031120004719.35068d78.klappnase@freenet.de> On Tue, 18 Nov 2003 15:02:11 -0600 Larry <llwyble@cox.net> wrote: > > Hi, > I am trying to access the mixer in order to build a simple volume control, > for now. (: > > Anyway I have found very little on google about doing anything at all > with the mixer, though I have found ossaudiodev in the 'python library > reference', so I'm trying to work from that. > > But now I find that my library reference in /usr/doc/python/html has no > ossaudiodev listing in it. > > So where do I get this? is it a module that needs to be installed? > Do I call it as a module as in; > > import ossaudiodev > Hi Larry, I must admit that I don't know much about ossaudiodev, but as far as I know it comes with the standard python installation since python-2.3, maybe it is just not documented in the library reference. Another way to access the mixer is tkSnack: www.speech.kth.se/snack Snack works with both alsa and oss and the usage is quite staightforward, so you can write a complete gui mixer app with a couple of lines. Cheers Michael From intatia at paradise.net.nz Thu Nov 20 02:48:21 2003 From: intatia at paradise.net.nz (Intatia) Date: Thu Nov 20 02:49:15 2003 Subject: [Tutor] Python scripting with kmuddy Message-ID: <3FBC71C5.7060008@paradise.net.nz> Just wondering if there was anyone here who has had any experience with create python script for kmuddy, I'm kinda lost.:) Intatia From alok_rai at persistent.co.in Thu Nov 20 03:34:28 2003 From: alok_rai at persistent.co.in (Alok Rai) Date: Thu Nov 20 03:32:22 2003 Subject: [Tutor] Python script to automatically send mails (running as a cron job in cygwin/linux) Message-ID: <000a01c3af41$1d382660$bb07a8c0@midnapore> Hi, I need to write a python script which would run through a cron job in cygwin/linux. I need the script to authenticate itself and send the mail. The script needs to read my account info(host, login and password) from some encrypted file. Please provide pointers regarding this, especially how I can store my login information in a secure, encrypted format and have my script read it. Regards, Alok. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031120/f3660112/attachment.html From barnabydscott at yahoo.com Thu Nov 20 03:42:08 2003 From: barnabydscott at yahoo.com (Barnaby Scott) Date: Thu Nov 20 03:42:14 2003 Subject: [Tutor] Regular Expressions - who's not working, them or me?! Message-ID: <20031120084208.88871.qmail@web41408.mail.yahoo.com> I'm sure I know the answer to the question in the subject - me! However I am completely stuck and cannot understand why some REs I wrote are not finding matches. They only seem to work at the beginning of the string. Help! Here is my little test script: import re teststr = 'a bunch of text to look in' afewres = ['.+', 'a', '[a-z]*', 'b', '.\Z', 'o{2}', '.$'] print 'Looking in "%s"\n' % teststr for r in afewres: p = re.compile(r) m = p.match(teststr) if m: print 'Match for "%s": ' % r, m.group(0) else: print 'No match for "%s"' % r And here is my output: >>> Looking in "a bunch of text to look in" Match for ".+": a bunch of text to look in Match for "a": a Match for "[a-z]*": a No match for "b" No match for ".\Z" No match for "o{2}" No match for ".$" >>> But I was expecting: Match for ".+": a bunch of text to look in Match for "a": a Match for "[a-z]*": a Match for "b": b Match for ".\Z": n Match for "o{2}": oo Match for ".$": n Can anyone see why I'm not getting what I expected? Apologies if this exposes a lamentable lack of understanding - I am trying to learn! Thanks __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From project5 at redrival.net Thu Nov 20 06:01:34 2003 From: project5 at redrival.net (Andrei) Date: Thu Nov 20 06:04:03 2003 Subject: [Tutor] Re: Regular Expressions - who's not working, them or me?! References: <20031120084208.88871.qmail@web41408.mail.yahoo.com> Message-ID: <11hn12dkwq0q.z9ol7xeiqn53$.dlg@40tude.net> Barnaby Scott wrote on Thu, 20 Nov 2003 00:42:08 -0800 (PST): <snip> > why some REs I wrote are not finding matches. They > only seem to work at the beginning of the string. >From the docs: match( string[, pos[, endpos]]) If zero or more characters AT THE BEGINNING OF string match this regular expression, return a corresponding MatchObject instance. You should use the search() method instead. Or findall. <snip> > But I was expecting: > > Match for ".+": a bunch of text to look in > Match for "a": a > Match for "[a-z]*": a > Match for "b": b > Match for ".\Z": n > Match for "o{2}": oo > Match for ".$": n Here is the output using search instead of match. Match for ".+": a bunch of text to look in Match for "a": a Match for "[a-z]*": a Match for "b": b Match for ".\Z": n Match for "o{2}": oo Match for ".$": n -- 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 AKolinski at nriindustries.com Thu Nov 20 10:44:23 2003 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Thu Nov 20 10:44:02 2003 Subject: [Tutor] 2.3.1/2 setup problems In-Reply-To: <20031118012515.73720.qmail@web41802.mail.yahoo.com> Message-ID: <OF630E76B7.A3544B8A-ON85256DE4.0055B75E-85256DE4.00568D87@NRIINDUSTRIES.COM> Last month I had to change my hard disk and a few days ago I downloaded and installed first 2.3.1 and then 2.3.2. In both cases I couldn't get the IDLE program running. When I click on IDLE in the START/Python23 menu nothing happens. I looked into my autoexec.bat and added c:\Python23; c:\Python\Lib\idlelib\ to the path. I also noticed that in previous versions IDLE file is located in the Tools subdirectory. Would it make any difference? What should I do? Thanks _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031120/147a69fd/attachment.html From project5 at redrival.net Thu Nov 20 12:50:46 2003 From: project5 at redrival.net (Andrei) Date: Thu Nov 20 12:53:18 2003 Subject: [Tutor] Re: 2.3.1/2 setup problems References: <20031118012515.73720.qmail@web41802.mail.yahoo.com> <OF630E76B7.A3544B8A-ON85256DE4.0055B75E-85256DE4.00568D87@NRIINDUSTRIES.COM> Message-ID: <14cozcnwdy7fi.12w3dmbpwog8s.dlg@40tude.net> Andrzej Kolinski wrote on Thu, 20 Nov 2003 10:44:23 -0500: > Last month I had to change my hard disk and a few days ago I downloaded > and installed first 2.3.1 and then 2.3.2. In both cases I couldn't get the > IDLE program running. When I click on IDLE in the START/Python23 menu > nothing happens. I looked into my autoexec.bat and added c:\Python23; > c:\Python\Lib\idlelib\ to the path. I also noticed that in previous > versions IDLE file is located in the Tools subdirectory. Would it make any > difference? What should I do? Do you get any tracebacks? Do Python programs work otherwise? -- 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 vicki at thepenguin.org Thu Nov 20 13:13:26 2003 From: vicki at thepenguin.org (Vicki Stanfield) Date: Thu Nov 20 13:17:52 2003 Subject: [Tutor] bitwise ops in Idle Message-ID: <15652.206.53.226.235.1069352006.squirrel@www.thepenguin.org> I am trying to get the value of a reiterative XOR operation and thought I'd use Idle to figure it out. I thought the module which allows for bitwise ops was the operator module, so I first did: import operator Next, intending to XOR the values of hex 5E and hex 9, I tried this: or_('\x5E','\x09') It didn't like this, returning: Traceback (most recent call last): File "<interactive input>", line 1, in ? NameError: name 'or_' is not defined What am I doing wrong? My intention is to loop through XORing a given value for the required number of iterations. Thanks, --vicki From dyoo at hkn.eecs.berkeley.edu Thu Nov 20 13:28:20 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Nov 20 13:28:25 2003 Subject: [Tutor] bitwise ops in Idle In-Reply-To: <15652.206.53.226.235.1069352006.squirrel@www.thepenguin.org> Message-ID: <Pine.LNX.4.44.0311201024110.32354-100000@hkn.eecs.berkeley.edu> On Thu, 20 Nov 2003, Vicki Stanfield wrote: > I am trying to get the value of a reiterative XOR operation and thought > I'd use Idle to figure it out. Hi Vicki, You can use the exclusive or (XOR) bitwise operator: '^'. For example: ### >>> 8 ^ 7 15 >>> (8 ^ 7) ^ 7 8 ### The 'operator' module, http://www.python.org/doc/lib/module-operator.html also contains XOR, but exposes it as a function instead of a built-in operator. We can access it like this: ### >>> import operator >>> operator.xor(8, 7) 15 >>> operator.xor(operator.xor(8, 7), 7) 8 ### Hope this helps! From alan.gauld at blueyonder.co.uk Thu Nov 20 16:17:51 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Nov 20 16:17:24 2003 Subject: [Tutor] 2.3.1/2 setup problems References: <OF630E76B7.A3544B8A-ON85256DE4.0055B75E-85256DE4.00568D87@NRIINDUSTRIES.COM> Message-ID: <004c01c3afab$c1d8b8a0$6401a8c0@xp> > IDLE program running. When I click on IDLE in the START/Python23 menu > nothing happens. I looked into my autoexec.bat and added c:\Python23; > c:\Python\Lib\idlelib\ to the path. I'd guess that second one should be C:\Python23\Lib... ? However the installer should have set up the menu shortcut to point to the right place anyhow. Try right clicking the IDLE menu item and selecting properties. Mine says: E:\Python22\pythonw.exe "E:\PYTHON22\Lib\idlelib\idle.pyw" Yours should be similar. > versions IDLE file is located in the Tools subdirectory. Would it make any > difference? What should I do? Check the path in the shortcut points to the file it claims to - idle.pyw. Wherever that file lives is where it should point. I assume the interactive prompt works OK from DOS? And that typing python at the Start->Run dialog works OK? Finally try navigating to idle.pyw in windows explorer, double click on it, does it start? If so drag a shortcut onto the desktop, or onto the Start button. See if the new shortcut works. HTH, Alan G. From alan.gauld at blueyonder.co.uk Thu Nov 20 16:33:31 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Nov 20 16:33:01 2003 Subject: [Tutor] Python script to automatically send mails (running as acron job in cygwin/linux) References: <000a01c3af41$1d382660$bb07a8c0@midnapore> Message-ID: <005401c3afad$f2156fc0$6401a8c0@xp> > I need to write a python script which would run through > a cron job in cygwin/linux. That's pretty straightforward cron setup. > I need the script to authenticate itself In what way? The script knows itself, so against what is it authenticating? The user id? Some digitally signed data? A digitally signed version of itself (to ensure it hasn't been tampered with)? We need a tad more info here. > and send the mail. What mail? cron will send email to signal its status. Do you want your job to send another mail? To which user? Containing what? > The script needs to read my account info (host, login > and password) from some encrypted file. OK, Python provides standard modules for encrypting files in a variety of formats. Depends what level of encryption you want to use. > especially how I can store my login information in a > secure, encrypted format and have my script read it. Provided you use the same encryption/decryption technique its fairly painless. Just pack the data into a string, encrypt it and write the result to a standard text file. To read it, open the file, read the whole file back as a string. Unencrypt it and unpack the data. Does that help? Or do you have any more specific questions? Alan G. From littledanehren at yahoo.com Thu Nov 20 18:34:15 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Nov 20 18:34:23 2003 Subject: [Tutor] Python script to automatically send mails (running as acron job in cygwin/linux) In-Reply-To: <005401c3afad$f2156fc0$6401a8c0@xp> Message-ID: <20031120233415.96241.qmail@web41804.mail.yahoo.com> > OK, Python provides standard modules for encrypting > files > in a variety of formats. Depends what level of > encryption > you want to use. How can python do encryption aside from rotor and rot13 within the standard modules? Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From pythontutor at venix.com Thu Nov 20 19:39:58 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Nov 20 19:40:05 2003 Subject: [Tutor] Python script to automatically send mails (running as acron job in cygwin/linux) In-Reply-To: <20031120233415.96241.qmail@web41804.mail.yahoo.com> References: <20031120233415.96241.qmail@web41804.mail.yahoo.com> Message-ID: <3FBD5EDE.8030106@venix.com> Serious encryption requires AMK's crypto tools. http://www.amk.ca/python/code/crypto.html Python Cryptography Toolkit Daniel Ehrenberg wrote: >>OK, Python provides standard modules for encrypting >>files >>in a variety of formats. Depends what level of >>encryption >>you want to use. > > > How can python do encryption aside from rotor and > rot13 within the standard modules? > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > Free Pop-Up Blocker - Get it now > http://companion.yahoo.com/ > > _______________________________________________ > 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 littledanehren at yahoo.com Thu Nov 20 19:44:01 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Thu Nov 20 19:44:05 2003 Subject: [Tutor] using multiple files Message-ID: <20031121004401.30155.qmail@web41805.mail.yahoo.com> I am working on an application to act as a client for Wikipedia (see wikipedia.org for the website and mediawiki.org for the current php/mysql software). It will be based on the pywikipediabot library, which is split up into an annoyingly large number of files. Is it possible to import those modules from files that will be distributed with the main script, or preferably import from a bz2 archive? Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From rozani at bppn.go.id Thu Nov 20 22:12:53 2003 From: rozani at bppn.go.id (Rozani Ismail) Date: Thu Nov 20 22:41:23 2003 Subject: [Tutor] Beginner Message-ID: <A3ED9AAAE30FD611944200508B62C6B204984A15@BPPNEXAMAIL> ok... I'm new to this program .... I'd like to know the pros and cons Python from your point of view... _____________ 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. _____________ 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. _____________ 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 llwyble at cox.net Thu Nov 20 23:50:07 2003 From: llwyble at cox.net (Larry) Date: Thu Nov 20 23:49:46 2003 Subject: [Tutor] string thing Message-ID: <20031121044942.THSO29834.lakemtao05.cox.net@widgeteye.homeip.net> I am trying to get python to print a = ( val, val) print a and the output is: ('0', '0') I want the output to be: (0, 0) How do I get rid of the ' ' gizmos. (: Thanks From glingl at aon.at Fri Nov 21 00:55:20 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Nov 21 00:57:21 2003 Subject: [Tutor] string thing In-Reply-To: <20031121044942.THSO29834.lakemtao05.cox.net@widgeteye.homeip.net> References: <20031121044942.THSO29834.lakemtao05.cox.net@widgeteye.homeip.net> Message-ID: <3FBDA8C8.1050401@aon.at> Larry schrieb: >I am trying to get python to print > >a = ( val, val) >print a > >and the output is: >('0', '0') > >I want the output to be: > >(0, 0) > >How do I get rid of the ' ' >gizmos. (: > Hi Larry, There is more than one way to achieve this ... e.g. turn val into an integer: >>> val = '0' >>> ival = int(val) >>> a = (ival,ival) >>> print a (0, 0) >>> or use Python's string-formatting: >>> a=(val,val) >>> print "(%s, %s)" % a (0, 0) >>> More about this here: http://www.python.org/doc/current/lib/typesseq-strings.html Regards, Gregor > >Thanks > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From llwyble at cox.net Fri Nov 21 01:51:27 2003 From: llwyble at cox.net (Larry) Date: Fri Nov 21 01:51:07 2003 Subject: [Tutor] A volume control (: Message-ID: <20031121065100.WLOA5790.lakemtao08.cox.net@widgeteye.homeip.net> Well, I have been working on this and got this far but I think I screwed up Because I can't figure out how to set the initial volume on the slider instead of it going back to 0 (zero) everytime I start it. I wanted to use: Current_vol = mixer.get(ossaudiodev.SOUND_MIXER_VOLUME) To get the current volume of the mixer. But I didn't consider this until I got this far and I don't think my slider code is going to allow an initial setting of the slider. Or is it? Arg... Any hints or tips or pointers? Thanks I gotta go to bed, it's 12:45 in the morning and I gotta get up and go to work in 5 hours. (: Maybe things will be clearer in the A.M. or not! (: Also thanks to everyone who has helped so far. Larry _________________________________________________________________________________ #!/usr/local/bin/python from Tkinter import * import ossaudiodev mixer = ossaudiodev.openmixer() class VOLUME(Frame): def print_value(self, val): ival = int(val) a = (ival,ival) mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, a) def createWidgets(self): self.slider = Scale(self, from_=0, to=100, orient=HORIZONTAL, length="3i", command=self.print_value) self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) self.slider.pack(side=LEFT) self.QUIT.pack(side=LEFT, fill=BOTH) def __init__(self, master=None): Frame.__init__(self, master) Pack.config(self) self.createWidgets() test = VOLUME() test.mainloop() From alan.gauld at blueyonder.co.uk Fri Nov 21 02:00:14 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Nov 21 01:59:33 2003 Subject: [Tutor] bitwise ops in Idle References: <15652.206.53.226.235.1069352006.squirrel@www.thepenguin.org> Message-ID: <00a701c3affd$1cffd1e0$6401a8c0@xp> > I am trying to get the value of a reiterative XOR operation and thought > I'd use Idle to figure it out. I thought the module which allows for > bitwise ops was the operator module, so I first did: > > import operator You don't need that. Just use the xor operator(~) >>> print ~0x01 -2 >>> print "%X" % ~0x01 '0xFFFFFFFE' Alan G. From alan.gauld at blueyonder.co.uk Fri Nov 21 02:03:19 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Nov 21 02:02:39 2003 Subject: [Tutor] bitwise ops in Idle References: <Pine.LNX.4.44.0311201024110.32354-100000@hkn.eecs.berkeley.edu> Message-ID: <00ac01c3affd$8bbcd1a0$6401a8c0@xp> > You can use the exclusive or (XOR) bitwise operator: '^'. For example: Ooops, yes. '~' it bitwise not... sorry, use '^'. Doh! Alan G. From op73418 at mail.telepac.pt Fri Nov 21 09:19:04 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Nov 21 09:17:30 2003 Subject: [Tutor] using multiple files In-Reply-To: <20031121004401.30155.qmail@web41805.mail.yahoo.com> References: <20031121004401.30155.qmail@web41805.mail.yahoo.com> Message-ID: <297srvofk823m9g50bqmb2vbqrjnrj8ijk@4ax.com> On Thu, 20 Nov 2003 16:44:01 -0800 (PST), you wrote: >I am working on an application to act as a client for >Wikipedia (see wikipedia.org for the website and >mediawiki.org for the current php/mysql software). It >will be based on the pywikipediabot library, which is >split up into an annoyingly large number of files. Is >it possible to import those modules from files that >will be distributed with the main script, or >preferably import from a bz2 archive? > What do you want? Do you want import <some-module-name> to automagically import from some files accompanying the main script? To automagically find the relevant bz2 archive, and then load the modules from there? If yes, yes you can do it. It's *not trivial* though. You may want to read the PEP on the new import hooks. I'm trying to do something similar, but until now I've failed. I suggest you take your questions to comp.lang.py, since this is definitely not a trivial business - although, if someone else on the list knows about this stuff feel free to chime in. Note that currently (as of 2.3) Python automagically supports import from zip archives. With my best regards, G. Rodrigues From eur at fiwihex.nl Fri Nov 21 09:41:53 2003 From: eur at fiwihex.nl (Eur van Andel) Date: Fri Nov 21 09:41:59 2003 Subject: [Tutor] Beginner In-Reply-To: <A3ED9AAAE30FD611944200508B62C6B204984A15@BPPNEXAMAIL> References: <A3ED9AAAE30FD611944200508B62C6B204984A15@BPPNEXAMAIL> Message-ID: <mv8srvc98lnl9uk3uti8l0lvgurp7heqq8@4ax.com> On Fri, 21 Nov 2003 10:12:53 +0700, Rozani Ismail <rozani@bppn.go.id> wrote: >I'm new to this program .... >I'd like to know the pros and cons Python from your point of view... I'm two weeks into Python, but I come from Pascal, BASIC, JAL, assembler, FORTRAN. Pros: very powerful batteries included good suport forces you to write in OO style easy to learn compared to other languages open source (not only the languages, but a lot of the programs too. This forces you to write better programs) Cons: a bit difficult to learn (the % operator comes to mind) few examples on the low level manual has a small and too simple Tutor section manual has a very formal Reference section forces you to write in OO style every command should have a decent Example. (Yes, this increases the number of pages in the manual tenfold.) Nearly all of the cons are one-time only. I had difficulty understanding some stuff which was not or not well explained. Then again, I learned Python in two weeks to get to the level that took me in Pascal 5 years! Shedding the Pascal and BASIC legacy took some time (days) too. I do things now in Python I could not imagine doing in Pascal or C ever again. The configparser, for example. -- 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 dieck.s at dsoftware.de Fri Nov 21 09:47:29 2003 From: dieck.s at dsoftware.de (Stefan Dieck) Date: Fri Nov 21 09:46:51 2003 Subject: [Tutor] Writing BINARY-CONTENT Message-ID: <OFELLIKBJNEKFBIGDFFIGECNCAAA.dieck.s@dsoftware.de> Hi! I have a big problem: How can I write a (binary) File from Python, without extending every "\n" to "\n\r" (I know it's a Windows-Specific Problem) ** Python itself shows written 1 byte, but it writes 2 bytes if a newline occurs ** * Do you have any Ideas? * Or, is there a class which writes only these data I submitted? ################################################################# a = open('c:\\test.me', 'wb') # opens a file for binary writing for x in range(256): # a.write(chr(x)) # This should write 256 bytes (from '\x00' to '\xFF') a.close() ################################################################# But the file has a lenght of 257 ( + '\r') Many Thanks, Stefan From pythontutor at venix.com Fri Nov 21 09:56:28 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Fri Nov 21 10:03:50 2003 Subject: [Tutor] Beginner In-Reply-To: <A3ED9AAAE30FD611944200508B62C6B204984A15@BPPNEXAMAIL> References: <A3ED9AAAE30FD611944200508B62C6B204984A15@BPPNEXAMAIL> Message-ID: <3FBE279C.6050300@venix.com> Rozani Ismail wrote: > ok... > I'm new to this program .... > I'd like to know the pros and cons Python from your point of view... Pros: Supports broad range of programming approaches (OOP, functional, etc.) Easy to learn and read VERY RELIABLE IMPLEMENTATION VERY GOOD DOCUMENTATION strong math support (complex numbers, long int) modules are available to support most programming needs Cons: unknown in commercial/corporate environment (at least my corner of USA) too many choices for some development areas (GUI, WEB) Google around and you will find lots of opinions. One writer whom I have found to be helpful is Peter Norvig: http://www.norvig.com/python-iaq.html Python IAQ: Infrequently Answered Questions http://www.norvig.com/python-lisp.html Python for Lisp Programmers -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From amk at amk.ca Fri Nov 21 10:13:44 2003 From: amk at amk.ca (A.M. Kuchling) Date: Fri Nov 21 10:14:16 2003 Subject: [Tutor] Writing BINARY-CONTENT In-Reply-To: <OFELLIKBJNEKFBIGDFFIGECNCAAA.dieck.s@dsoftware.de> References: <OFELLIKBJNEKFBIGDFFIGECNCAAA.dieck.s@dsoftware.de> Message-ID: <20031121151344.GA5628@rogue.amk.ca> On Fri, Nov 21, 2003 at 03:47:29PM +0100, Stefan Dieck wrote: > a = open('c:\\test.me', 'wb') # opens a file for binary writing This is correct for writing binary. Are you sure that the program or editor you're using to check this isn't opening the file in text mode (with 'r' instead of 'rb')? --amk From abli at freemail.hu Fri Nov 21 10:29:23 2003 From: abli at freemail.hu (Abel Daniel) Date: Fri Nov 21 10:29:31 2003 Subject: [Tutor] Re: using multiple files In-Reply-To: <20031121004401.30155.qmail@web41805.mail.yahoo.com> (Daniel Ehrenberg's message of "Thu, 20 Nov 2003 16:44:01 -0800 (PST)") References: <20031121004401.30155.qmail@web41805.mail.yahoo.com> Message-ID: <E1ANDDo-0000b9-00@hooloovoo> Daniel Ehrenberg writes: > I am working on an application to act as a client for > Wikipedia (see wikipedia.org for the website and > mediawiki.org for the current php/mysql software). It > will be based on the pywikipediabot library, which is > split up into an annoyingly large number of files. http://cvs.sourceforge.net/viewcvs.py/pywikipediabot/pywikipedia/ contains around 20 files. That doesn't sound too bad to me. > Is it possible to import those modules from files that > will be distributed with the main script, You mean as opposed to import them from a system-wide install? Like you install pywikipediabot first, and then from your program import modules the same way as, say importing the 'os' module (where you don't care where the os module is or how many files it is, etc.) I guess adding the directory that contains the files to the front of sys.path will guarantee that you will import from the files you want. (Even if there is a module with the same name installed elsewhere.) But this wouldn't look too nice to me. What would you gain by this? Librarys are librarys and I don't think you should 'statically link' you program with one. If it is installed system-wide, why would you want to use your (not-sytem-widely-installed) version? (Maybe I don't fully understand what you want.) If you want to avoid things like import module.foo, module.bar, module.foobar.deep.hierarchy.stuff (i.e. ease importing for the users) then I think you should make an __init__.py For example by putting from foobar.deep.hierarchy import stuff in it, you can access stuff as module.stuff after 'import module', so your users shouldn't have to care how many files you have. (Or at least that's the idea, I guess. I'm not an expert in this as I didn't have to do it so far.) > or preferably import from a bz2 archive? As of version 2.3, you can import from zipfiles: from http://python.org/2.3/NEWS.txt: - Import from zipfiles is now supported. The name of a zipfile placed on sys.path causes the import statement to look for importable Python modules (with .py, pyc and .pyo extensions) and packages inside the zipfile. The zipfile import follows the specification (though not the sample implementation) of PEP 273. The semantics of __path__ are compatible with those that have been implemented in Jython since Jython 2.1. (I'm not sure whether it works with bz2 archives) -- Abel Daniel From mhansen at cso.atmel.com Fri Nov 21 10:30:33 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Nov 21 10:30:50 2003 Subject: [Tutor] Beginner In-Reply-To: <E1AN2Fg-0000rn-QV@mail.python.org> References: <E1AN2Fg-0000rn-QV@mail.python.org> Message-ID: <3FBE2F99.5030100@cso.atmel.com> You're going to get favorable points of view when you post to a Python list. I'm "sold" on Python. Eric Raymond's article: Why Python? got me interested in Python. http://www.linuxjournal.com/article.php?sid=3882 What got me excited about Python was Dive Into Python. http://diveintopython.org/ The more I read about Python, the more I like it. It just makes sense. I don't find myself struggling with the syntax. It kinda just flows. It's very clean. Another bonus is the Python community. The community is very helpful to everyone. Newbies aren't looked down on. They are nurtured and shown where to find resources and nudged in the right direction. I haven't seen anyone get flamed for asking an obvious question. Usually they are pointed to a resource that should answer the question or given the answer politely. I think Python is easy to learn. It think it's a good language to teach programming. It's also easy for experienced programmers to get up and running. The only con I can find with Python is there really isn't a central repository for modules like Perl's CPAN. Python's claim of "batteries included" is nearly true. There are a pile of modules that are included in the standard distribution of Python and a high percentage of your needs will be met with what's included. There will be times that you need something that isn't in the standard modules. Then it becomes a hunt for the module. The Python Package Index is attempting to resolve this problem. http://www.python.org/pypi Try it! Mike > > Subject: > [Tutor] Beginner > From: > Rozani Ismail <rozani@bppn.go.id> > Date: > Fri, 21 Nov 2003 10:12:53 +0700 > To: > Tutor <tutor@python.org> > > >ok... >I'm new to this program .... >I'd like to know the pros and cons Python from your point of view... > > > > From clay at shirky.com Fri Nov 21 11:03:54 2003 From: clay at shirky.com (Clay Shirky) Date: Fri Nov 21 11:04:08 2003 Subject: [Tutor] string.unprintable? Message-ID: <BBE3A19A.12118%clay@shirky.com> I want to loop over a file with some printable and some binary lines, printing the former. What I really want is for line in file("spam"): if string.unprintable in line: continue print line but there is no string.unprintable, and if not string.printable in line for some reason matches everything in the file, even though I've .strip()ed the line aready. -clay From nas-pytut at python.ca Fri Nov 21 13:16:22 2003 From: nas-pytut at python.ca (Neil Schemenauer) Date: Fri Nov 21 13:14:05 2003 Subject: [Tutor] string.unprintable? In-Reply-To: <BBE3A19A.12118%clay@shirky.com> References: <BBE3A19A.12118%clay@shirky.com> Message-ID: <20031121181622.GB3579@mems-exchange.org> On Fri, Nov 21, 2003 at 11:03:54AM -0500, Clay Shirky wrote: > I want to loop over a file with some printable and some binary lines, > printing the former. > > What I really want is > > for line in file("spam"): > if string.unprintable in line: > continue > print line No, you don't. "string.unprintable in somestring" is a substring test. > but there is no string.unprintable, and > > if not string.printable in line > > for some reason matches everything in the file, even though I've .strip()ed > the line aready. A regex is probably the way to go here. Something like: find_unprintable = re.compile(r'[\x00-\x08\x0d-\x1f\x7f-\xff]').search for line in file("spam"): if not find_unprintable(line): print line Too bad there isn't a re character class. I guess "unprintable" may mean different things to different people. HTH, Neil From dyoo at hkn.eecs.berkeley.edu Fri Nov 21 14:04:39 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 21 14:04:45 2003 Subject: [Tutor] string thing In-Reply-To: <3FBDA8C8.1050401@aon.at> Message-ID: <Pine.LNX.4.44.0311211102510.1780-100000@hkn.eecs.berkeley.edu> > Hi Larry, > There is more than one way to achieve this ... > > e.g. turn val into an integer: > >>> val = '0' > >>> ival = int(val) > >>> a = (ival,ival) > >>> print a > (0, 0) > >>> > > or use Python's string-formatting: > >>> a=(val,val) > >>> print "(%s, %s)" % a > (0, 0) > >>> > > More about this here: > http://www.python.org/doc/current/lib/typesseq-strings.html Hi Larry, There's also a small section on the official Python tutorial that talks about using these string formatting tools. You can find out more by looking here: http://www.python.org/doc/tut/node9.html If you have more questions, please feel free to ask on Python-Tutor! From dyoo at hkn.eecs.berkeley.edu Fri Nov 21 15:33:18 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 21 15:33:24 2003 Subject: [Tutor] bitwise ops in Idle (fwd) Message-ID: <Pine.LNX.4.44.0311211226360.10753-100000@hkn.eecs.berkeley.edu> Hi Vicki, > Then my problem may be that I am trying to do it with hexadecimal > numbers. I tried this first: > > '\x5E' ^ '\x09' XOR works between ints, not strings, so we need to first transform those strings into ordinals: ### >>> ord('\x5e') ^ ord('\x09') 87 >>> hex(87) '0x57' ### It sounds that, as you read those bytes from your port, you'll want to convert each byte internally into an integer by using ord(). Good luck to you! ---------- Forwarded message ---------- Date: Thu, 20 Nov 2003 13:36:29 -0500 From: "Stanfield, Vicki {D167~Indianapolis}" <VICKI.STANFIELD@roche.com> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: RE: [Tutor] bitwise ops in Idle Then my problem may be that I am trying to do it with hexadecimal numbers. I tried this first: '\x5E'^'\x09' and it failed leading me to look for a module. How does one (or does one) do an XOR of hex numbers? --vicki -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Danny Yoo Sent: Thursday, November 20, 2003 1:28 PM To: Vicki Stanfield Cc: tutor@python.org Subject: Re: [Tutor] bitwise ops in Idle On Thu, 20 Nov 2003, Vicki Stanfield wrote: > I am trying to get the value of a reiterative XOR operation and > thought I'd use Idle to figure it out. Hi Vicki, You can use the exclusive or (XOR) bitwise operator: '^'. For example: ### >>> 8 ^ 7 15 >>> (8 ^ 7) ^ 7 8 ### The 'operator' module, http://www.python.org/doc/lib/module-operator.html also contains XOR, but exposes it as a function instead of a built-in operator. We can access it like this: ### >>> import operator >>> operator.xor(8, 7) 15 >>> operator.xor(operator.xor(8, 7), 7) 8 ### Hope this helps! _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Fri Nov 21 15:45:07 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 21 15:45:13 2003 Subject: [Tutor] 3 simple, pithy and short questions (fwd) Message-ID: <Pine.LNX.4.44.0311211235540.10753-100000@hkn.eecs.berkeley.edu> Hi Tadey, Please send your questions to tutor@python.org. I'll forward your question for you this time, but please be careful to ask your questions on the list in the future. Please don't keep sending messages only to me, as you're circumventing the informal "load-balancing" that all the tutors perform. Your questions are very good ones, and it would be an injustice to deny you from getting the best answers that our community can provide you. For more justification for using the mailing lists, you can read: http://www.catb.org/~esr/faqs/smart-questions.html#uselists ---------- Forwarded message ---------- Date: Fri, 21 Nov 2003 05:27:32 +0100 From: Tadey <tayiper@volja.net> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: 3 simple, pithy and short questions Hello ... I discovered in-built help as late as now (or I know there was some help, but didn't know how to use it eficiently), so it is really helpfull ... though sometimes a little indistinct for "pure" begginer ... So I have a few very simple, pithy and short questions: 1.) Where is the difference between "processing" some functon (let say "str" function) like str(a) and like a.__str__() ?? See two examples below: >>> a = "ww" >>> str(a) 'ww' >>> a.__str__() 'ww' 2.) What hash function does ?? I noticed, that in case if some random string is assigned to variable, it returns some long/huge number .... See example below: >>> b = "r" >>> hash(b) 1707142003 3.) About __getattribute__ function: In help it is "represented" by a.getattribute('name') <=> a.name But whatever I typed, I couldn't get some "reasonable" output, meaning I always got an error message ... >>> a= ("ww", "rr", "gggg") >>> a.getattribute(1) Error: attribute name must be a string >>> a.getattribute("rr") Error: string object has no atrribute "rr" >>> a.getattribute() Error: function takes exactly 1 argument (0 given) Thanks, Tadey From alan.gauld at blueyonder.co.uk Fri Nov 21 16:24:55 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Nov 21 16:24:05 2003 Subject: [Tutor] string.unprintable? References: <BBE3A19A.12118%clay@shirky.com> Message-ID: <00e201c3b075$e8966b20$6401a8c0@xp> > but there is no string.unprintable, and > > if not string.printable in line > > for some reason matches everything in the file, Look at what the in operator does: >>> if 'abc' in 'a big cat': print 'True' ... >>> if 'abc' in 'abcdef': print 'True' ... True Thus it only returns true if the entire string is found in the right order in your line. The likeliehood of all the printable characters appearing in one of your lines in the exact order that python lists them is remote! You can either use a nested loop or more usefully a regular expression: import re,string regex = "[%s]" % string.printable printable = re.compile(regex) if printable.search(line): # do it here. else: # or not Caveat the above re code is untested! HTH, Alan G. From klappnase at freenet.de Fri Nov 21 14:45:49 2003 From: klappnase at freenet.de (Michael Lange) Date: Fri Nov 21 16:46:06 2003 Subject: [Tutor] A volume control (: In-Reply-To: <20031121065100.WLOA5790.lakemtao08.cox.net@widgeteye.homeip.net> References: <20031121065100.WLOA5790.lakemtao08.cox.net@widgeteye.homeip.net> Message-ID: <20031121204549.4c28fa27.klappnase@freenet.de> On Fri, 21 Nov 2003 00:51:27 -0600 Larry <llwyble@cox.net> wrote: > > Well, I have been working on this and got this far but I think I screwed up > Because I can't figure out how to set the initial volume on the slider instead of > it going back to 0 (zero) everytime I start it. I wanted to use: > > Current_vol = mixer.get(ossaudiodev.SOUND_MIXER_VOLUME) > > To get the current volume of the mixer. But I didn't consider this until > I got this far and I don't think my slider code is going to allow an initial setting > of the slider. Or is it? Arg... > > Hi Larry, I think you should use a Tkinter.DoubleVar for the volume settings which you can bind to the Scale widget (in case the volume is a float value, I don't know about ossaudiodev, if it is an integer of course you should use a Tkinter.IntVar()). If you set the value of this variable to the current volume before the scale is created I think it should work: > #!/usr/local/bin/python > > > from Tkinter import * > > import ossaudiodev > mixer = ossaudiodev.openmixer() > > class VOLUME(Frame): > def print_value(self, val): > ival = int(val) > a = (ival,ival) > mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, a) > > def createWidgets(self): > self.slider = Scale(self, from_=0, to=100, > orient=HORIZONTAL, > length="3i", > command=self.print_value, variable=self.Current_vol) > > self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) > > self.slider.pack(side=LEFT) > self.QUIT.pack(side=LEFT, fill=BOTH) > > def __init__(self, master=None): > Frame.__init__(self, master) > Pack.config(self) #get the current volume setting: self.Current_vol = IntVar() self.Current_vol.set(mixer.get(ossaudiodev.SOUND_MIXER_VOLUME)) > self.createWidgets() > > test = VOLUME() > test.mainloop() Like I said, I don't know what mixer.get() returns, (I haven't even ossaudiodev installed), but I think this should do the trick to set the initial volume. Cheers Michael From krazie_mu_boi at hotmail.com Fri Nov 21 17:44:07 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Fri Nov 21 17:44:12 2003 Subject: [Tutor] Livewires Robot-5 Message-ID: <Sea2-F61RDyjLQoOuDd00007815@hotmail.com> I'm working on Livewires' worksheet 5 -- Robot (http://www.livewires.org.uk/python/pdf/5-robots.pdf) . I'm 3/4 of the way through this sheet, and I've got a player moving with a robot chasing it. But now, I'm stuck on " a List of Robot" . They are saying something 'bout placing robots inside a list -- but I don't get it!!! Please help. _________________________________________________________________ ¨Ï¥Î MSN Messenger¡A»PªB¤Í¦b½u¤W²á¤Ñ: http://messenger.microsoft.com/tc From glingl at aon.at Fri Nov 21 18:02:13 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Nov 21 18:04:10 2003 Subject: [Tutor] Livewires Robot-5 In-Reply-To: <Sea2-F61RDyjLQoOuDd00007815@hotmail.com> References: <Sea2-F61RDyjLQoOuDd00007815@hotmail.com> Message-ID: <3FBE9975.9070706@aon.at> Leung Cris schrieb: > I'm working on Livewires' worksheet 5 -- Robot > (http://www.livewires.org.uk/python/pdf/5-robots.pdf) . I'm 3/4 of the > way through this sheet, and I've got a player moving with a robot > chasing it. But now, I'm stuck on " a List of Robot" . They are saying > something 'bout placing robots inside a list -- but I don't get it!!! > Please help. Hi Leung! I think you are stuck at this point: About the only thing you might need to know is that the way to add a new item to a list is to say something like my_list.append(new_item) . You can only understand this, if you know something about lists, which is one sort of sequence or collection (of objects, eg. robots) in Python. Fortunately there are several Livewires "reference sheets" on certain fundamental topics of Python programming. One of them is Refernce sheet A, lists. There (on page 2) you will learn how to "append" objects to lists. I recommend that you work through this one an you will easily master your robot problem. It's located here: http://www.livewires.org.uk/python/pdf/A-lists.pdf HTH Gregor > > _________________________________________________________________ > ¨Ï¥Î MSN Messenger¡A»PªB¤Í¦b½u¤W²á¤Ñ: http://messenger.microsoft.com/tc > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From pythontutor at venix.com Fri Nov 21 18:10:31 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Fri Nov 21 18:10:36 2003 Subject: [Tutor] 3 simple, pithy and short questions (fwd) In-Reply-To: <Pine.LNX.4.44.0311211235540.10753-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311211235540.10753-100000@hkn.eecs.berkeley.edu> Message-ID: <3FBE9B67.2050601@venix.com> > ---------- Forwarded message ---------- > Date: Fri, 21 Nov 2003 05:27:32 +0100 > From: Tadey <tayiper@volja.net> > To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> > Subject: 3 simple, pithy and short questions > > > Hello ... > 1.) Where is the difference between "processing" some functon (let say > "str" function) like str(a) and like a.__str__() ?? > > See two examples below: > > >>>>a = "ww" >>>>str(a) > > 'ww' > > >>>>a.__str__() > > 'ww' The __str__ method is a "magic" method that is built into a class to create the string that will be returned when someone uses the builtin str function. >>> class I(int): ... def __str__(self): ... return "just a string" ... >>> i = I(23) >>> i 23 >>> str(i) 'just a string' Very often the default __str__ classes will do exactly what you want. However, if it is necessary for str of a class to be different, you can do it by writing your own __str__ method. > > > 2.) What hash function does ?? I noticed, that in case if some random > string is assigned to variable, it returns some long/huge number .... > > See example below: > > >>>>b = "r" >>>>hash(b) > > 1707142003 The dictionary gets use the hash values in finding the object to be retrieved. In some languages dictionaries would be called hash tables. The key used for storing something in a dictionary needs to support the computation of a hash value. > > > 3.) About __getattribute__ function: In help it is "represented" by > a.getattribute('name') <=> a.name But whatever I typed, I couldn't get > some "reasonable" output, meaning I always got an error message ... > > >>>>a= ("ww", "rr", "gggg") >>>>a.getattribute(1) > > Error: attribute name must be a string > > >>>>a.getattribute("rr") > > Error: string object has no atrribute "rr" > > >>>>a.getattribute() > > Error: function takes exactly 1 argument (0 given) You can use the dir() builtin function to find out about attributes. dir(a) returns a list of the builtin attributes of a tuple: >>> dir(a) ['__add__', '__class__', '__contains__', '__delattr__',... A is bound to a tuple which is tougher to use as an example. Let's use i from the I class above. i.tadey = 1 creates an attribue named tadey and assigns (binds it to) the value 1. >>> print i.tadey 1 dir(i) returns a long list of attributes ending with [......, '__xor__', 'tadey'] >>> getattr(i, 'tadey') 1 I assume that the getattribute method was added to python2.3. I can not do that with my 2.2 version. I expect that if you followed along with this you would be able to type i.getattribute('tadey') and get back 1. The getattribute method would be most useful when the attribute name is in a variable. >>> x = 'tadey' >>> getattr(i,x) 1 I hope this helps. > > > > Thanks, Tadey > > > _______________________________________________ > 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 nas-pytut at python.ca Fri Nov 21 18:18:25 2003 From: nas-pytut at python.ca (Neil Schemenauer) Date: Fri Nov 21 18:16:04 2003 Subject: [Tutor] string.unprintable? In-Reply-To: <00e201c3b075$e8966b20$6401a8c0@xp> References: <BBE3A19A.12118%clay@shirky.com> <00e201c3b075$e8966b20$6401a8c0@xp> Message-ID: <20031121231824.GA4737@mems-exchange.org> On Fri, Nov 21, 2003 at 09:24:55PM -0000, Alan Gauld wrote: > You can either use a nested loop or more usefully a regular > expression: > > import re,string > > regex = "[%s]" % string.printable > > printable = re.compile(regex) You need to escape: regex = "[%s]" % re.escape(string.printable) Haven't tested that either though. Cheers, Neil From krazie_mu_boi at hotmail.com Fri Nov 21 18:22:41 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Fri Nov 21 18:22:46 2003 Subject: [Tutor] Livewires Robot-5 Message-ID: <SEA2-F32v3rQ3OBaxSl00007a76@hotmail.com> I know I should have been more specific: okay, I kinda understand how I can add stuff in to my list. The problem is: WAT do I add? >From: Gregor Lingl <glingl@aon.at> >To: Leung Cris <krazie_mu_boi@hotmail.com> >CC: tutor@python.org >Subject: Re: [Tutor] Livewires Robot-5 >Date: Sat, 22 Nov 2003 00:02:13 +0100 > > > >Leung Cris schrieb: > > > I'm working on Livewires' worksheet 5 -- Robot > > (http://www.livewires.org.uk/python/pdf/5-robots.pdf) . I'm 3/4 of the > > way through this sheet, and I've got a player moving with a robot > > chasing it. But now, I'm stuck on " a List of Robot" . They are saying > > something 'bout placing robots inside a list -- but I don't get it!!! > > Please help. > >Hi Leung! > >I think you are stuck at this point: > >About the only thing you might need to know is that the way to add a new >item to a list is to say something like >my_list.append(new_item) . > >You can only understand this, if you know something about lists, which >is one sort of sequence or collection (of objects, eg. robots) >in Python. Fortunately there are several Livewires "reference sheets" on >certain fundamental topics of Python programming. >One of them is Refernce sheet A, lists. There (on page 2) you will learn >how to "append" objects to lists. >I recommend that you work through this one an you will easily master >your robot problem. It's located here: > >http://www.livewires.org.uk/python/pdf/A-lists.pdf > >HTH > >Gregor > > > > > _________________________________________________________________ > > ¨Ï¥Î MSN Messenger¡A»PªB¤Í¦b½u¤W²á¤Ñ: http://messenger.microsoft.com/tc > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _________________________________________________________________ ¨Ï¥Î¥þ²y¥Î¤á³Ì¦hªº¹q¤l¶l¥óªA°È MSN Hotmail¡G http://www.hotmail.com From glingl at aon.at Fri Nov 21 19:23:47 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Nov 21 19:25:55 2003 Subject: [Tutor] Livewires Robot-5 In-Reply-To: <SEA2-F32v3rQ3OBaxSl00007a76@hotmail.com> References: <SEA2-F32v3rQ3OBaxSl00007a76@hotmail.com> Message-ID: <3FBEAC93.30905@aon.at> Leung Cris schrieb: > I know I should have been more specific: okay, I kinda understand how > I can add stuff in to my list. The problem is: WAT do I add? As far as I see, your task is to create several robots, which are not in collision with each other and to store them in a list. This list is to be called robots robots = [] # initially empty for i in range(number_of_robots_to_create): # number_of_robots_to_create # for instance may be 5 newrobot = Robot() # a new one ## here check if there are collisions ## with robots already created, something SIMILAR TO ok = False while not ok: ok = True for oldrobot in robots: if oldrobot.collides(newrobot): ok = False if not ok: # there was a collision ## put newrobot in a new place ..... ## ok is still False here, so the loop has to be done again ## here we come, if there was no collision (ok is True here) ## so the robot is ok and we append it to our list of robots: robots.append(newrobot) ## Now all our robots are ready to do something: for robot in robots: ### do something ... ## if you want a specific robot to do something, you have ## to call him via his "index", (you said you know lists from ## reference A, didn't you? E. g.: robots[2].x, robots[2].y = 150, 250 this changes position of robots[2], actually the third robot in robots ... please note, that I don't know the robots worksheet very well, so I did only outline an idea of what and how to do... Regards, Gregor > >> From: Gregor Lingl <glingl@aon.at> >> To: Leung Cris <krazie_mu_boi@hotmail.com> >> CC: tutor@python.org >> Subject: Re: [Tutor] Livewires Robot-5 >> Date: Sat, 22 Nov 2003 00:02:13 +0100 >> >> >> >> Leung Cris schrieb: >> >> > I'm working on Livewires' worksheet 5 -- Robot >> > (http://www.livewires.org.uk/python/pdf/5-robots.pdf) . I'm 3/4 of the >> > way through this sheet, and I've got a player moving with a robot >> > chasing it. But now, I'm stuck on " a List of Robot" . They are saying >> > something 'bout placing robots inside a list -- but I don't get it!!! >> > Please help. >> >> Hi Leung! >> >> I think you are stuck at this point: >> >> About the only thing you might need to know is that the way to add a new >> item to a list is to say something like >> my_list.append(new_item) . >> >> You can only understand this, if you know something about lists, which >> is one sort of sequence or collection (of objects, eg. robots) >> in Python. Fortunately there are several Livewires "reference sheets" on >> certain fundamental topics of Python programming. >> One of them is Refernce sheet A, lists. There (on page 2) you will learn >> how to "append" objects to lists. >> I recommend that you work through this one an you will easily master >> your robot problem. It's located here: >> >> http://www.livewires.org.uk/python/pdf/A-lists.pdf >> >> HTH >> >> Gregor >> >> > >> > _________________________________________________________________ >> > ¨Ï¥Î MSN Messenger¡A»PªB¤Í¦b½u¤W²á¤Ñ: >> http://messenger.microsoft.com/tc >> > >> > _______________________________________________ >> > Tutor maillist - Tutor@python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> > > _________________________________________________________________ > ¨Ï¥Î¥þ²y¥Î¤á³Ì¦hªº¹q¤l¶l¥óªA°È MSN Hotmail¡G http://www.hotmail.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Fri Nov 21 19:28:14 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 21 19:28:23 2003 Subject: [Tutor] 3 simple, pithy and short questions (fwd) In-Reply-To: <3FBE9B67.2050601@venix.com> Message-ID: <Pine.LNX.4.44.0311211535180.28305-100000@hkn.eecs.berkeley.edu> > > 1.) Where is the difference between "processing" some functon (let say > > "str" function) like str(a) and like a.__str__() ?? > > > > See two examples below: > > > > > >>>>a = "ww" > >>>>str(a) > > > > 'ww' > > > > > >>>>a.__str__() > > > > 'ww' Hi Tadey, The only difference between: str(a) and a.__str__() is one of usage, of the intended audience. The first one: str(a) is intended for us programmers to use. __str__(), on the other hand, is intended to be used by Python: the underscores are there to highlight this function as slightly "special" or "magical" to the system, and you often shouldn't have to look at it too closely. In fact, a while back, numbers did not have __str__() defined for them. In Python 1.52, for example: ### [dyoo@tesuque dyoo]$ python1.5 Python 1.5.2 (#1, Jan 31 2003, 10:58:35) [GCC 2.96 20000731 (Red Hat Linux 7.3 2 on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> x = 42 >>> str(x) '42' >>> x.__str__() Traceback (innermost last): File "<stdin>", line 1, in ? AttributeError: 'int' object has no attribute '__str__' ### In the old days, __str__() didn't work on numbers, although str() did, because str() had some special cases hardcoded in it to handle the numbers. In recent years, the __str__() method was added to numbers to make them more uniform with the other Python types and classes. So now __str__() should work on everything, and underneath the surface, str() may even call __str__() to get a string representation of an object. But it's still a lot better to avoid calling the magic method __str__() directly, and use str() instead. > > 2.) What hash function does ?? I noticed, that in case if some random > > string is assigned to variable, it returns some long/huge number .... > > > > See example below: > > > > > >>>>b = "r" > >>>>hash(b) > > > > 1707142003 > > The dictionary gets use the hash values in finding the object to be > retrieved. In some languages dictionaries would be called hash tables. > The key used for storing something in a dictionary needs to support the > computation of a hash value. That large "hash" value is used as part of an computer science technique called "hashing". Hashing is not unique to computer science though: take a close look at your English dictionary: it uses similar principles! Hashing works very similarly to how dictionaries work: a English dictionary has 26 categories based on the first letter of each word, so each word maps to a particular category. 'Alphabet' -----> 'A' 'Python' -----> 'P' The categories are there to make it faster to look things up: when we want to look for a definition, instead of having to look through the whole dictionary from scratch, we can just pick the right chapter. We still do have to go through some pages, but it's a lot better than starting from page 1. Hashing works on the same principle, but instead of using 26 categories, we can use a whole lot more. And, just as in a real dictionary they're keyed, but not by first letter, but by "hash value". So: ### >>> hash('Alphabet') -1438023159 >>> hash('Python') -539294296 ### The number isn't random: we'll get the same number every time: ### >>> hash("Alphabet") -1438023159 >>> hash("alphabet") 1273818537 ### Capitalization does matter, though. In order to transform hash values into categories, we do a little mathematical trick: we can divide the hash value by the number of categories we're keeping track, and take the remainder: the remainder will be the ultimate category number, or "hash bucket", for that item. If we use 26 categories, for example, then: ### >>> hash("Alphabet") % 26 25 >>> hash("Python") % 26 18 >>> hash("tayiper") % 26 11 ### Python doesn't necessarily use 26 hash bucket categories. But it uses quite a few. The goal of a good hash function is to try to evenly distribute things among all of the categories, so as to make a nicely balanced dictionary that makes it easy to look things up quickly. The Python dictionary type itself will use hash() quite extensively to construct an efficient structure. That being said, you probably don't have to worry about all this kind of hash() stuff: most people do not explicitely call hash(), and let Python itself take of the busywork. > > 3.) About __getattribute__ function: In help it is "represented" by > > a.getattribute('name') <=> a.name But whatever I typed, I couldn't get > > some "reasonable" output, meaning I always got an error message ... Some things have 'attributes', and other things have 'indices'. It turns out that tuples, like: a = ("ww", "rr", "gggg") can be indexed by position number, but they're not accessible by attribute. ### >>> a = ("ww", "rr", "gggg") >>> a[0] 'ww' >>> a[2] 'gggg' ### Attributes and indices serve a similar function, but they are subtly different. Indicing is used on things that are arranged in sequential order, like lists and tuples. Attributes are used on things that don't quite have a prearranged order. For example, if we were to represent a person as an object: ### >>> class Person: ... def __init__(self, name, age): ... self.name = name ... self.age = age ... >>> bart = Person('Bart Simpson', 10) >>> lisa = Person('Lisa Simpson', 8) ### then we can define --- and later look up --- attributes of each person: ### >>> bart.name 'Bart Simpson' >>> lisa.age 8 ### But if we try to get indices out of them, we shouldn't expect much: ### >>> bart[0] Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: Person instance has no attribute '__getitem__' >>> lisa[1] Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: Person instance has no attribute '__getitem__' ### And if we think about it, we really shouldn't expect indicing to just work! When we say bart[0], are we trying to get at the name, or age, or... ? Python will not try to guess what we mean. Likewise, if we have a list of things: ### >>> even_numbers = range(0, 20, 2) >>> even_numbers [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] ### It makes sense to take indices: ### >>> even_numbers[5] 10 >>> even_numbers[3] 6 ### but taking attributes is less successful: ### >>> even_numbers.5 File "<stdin>", line 1 even_numbers.5 ^ SyntaxError: invalid syntax ### as attributes are not really supposed to be numbers: attributes are not positional in nature. (It is possible to force the system to add numeric attributes... but you are not supposed to know that. *grin*) So the usage of attributes and indicies is meant to be different. Lists do have some attributes, but they don't correspond to the elements in the collection, but rather, to actions that we can perform on lists: ### >>> dir(even_numbers) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> >>> >>> even_numbers.reverse <built-in method reverse of list object at 0x812c38c> >>> >>> even_numbers.reverse() >>> >>> even_numbers [18, 16, 14, 12, 10, 8, 6, 4, 2, 0] ### So lists have attribute that correspond to methods like reverse() or extend() or pop(). Tuples support even fewer attributes, and many of them are there only to support Python: ### >>> l = (42, 43) >>> dir(l) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', '__setattr__', '__str__'] ### The double-underscored attributes here also correspond to methods, but they're not meant to be called by us directly. Anyway, hope this clears some things up. It looks like you're exploring the Python language by using help(). But are you also looking through a tutorial? Talk to you later! From dyoo at hkn.eecs.berkeley.edu Fri Nov 21 19:32:22 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 21 19:32:27 2003 Subject: [Tutor] 3 simple, pithy and short questions (fwd) In-Reply-To: <Pine.LNX.4.44.0311211535180.28305-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0311211629120.28305-100000@hkn.eecs.berkeley.edu> > In recent years, the __str__() method was added to numbers to make them > more uniform with the other Python types and classes. Hi everyone, Yikes, I'm totally wrong here! Numbers still don't have __str__(). I should have double checked my assertions about this. So we can call str() on numbers, but not __str__(). I misremembered the extent to which the numbers were unified with the other types. My apologies! From op73418 at mail.telepac.pt Fri Nov 21 19:41:25 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Nov 21 19:39:45 2003 Subject: [Tutor] 3 simple, pithy and short questions (fwd) In-Reply-To: <Pine.LNX.4.44.0311211235540.10753-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311211235540.10753-100000@hkn.eecs.berkeley.edu> Message-ID: <lcbtrv8k6t3tohogo9jjalprldglfnvpgq@4ax.com> L. Kvam already said the more important things, let me just add some notes. >Hello ... > >I discovered in-built help as late as now (or I know there was some help, >but didn't know how to use it eficiently), so it is really helpfull ... >though sometimes a little indistinct for "pure" begginer ... > >So I have a few very simple, pithy and short questions: > >1.) Where is the difference between "processing" some functon (let say >"str" function) like str(a) and like a.__str__() ?? > >See two examples below: > >>>> a = "ww" >>>> str(a) >'ww' > >>>> a.__str__() >'ww' > In 99% of the times none whatsoever. The rest 1% are corner cases where there is in fact a difference. For example a.__str__() may return something while str(a) raises an exception. As I said these are corner cases so I won't even list them :-) >3.) About __getattribute__ function: In help it is "represented" by >a.getattribute('name') <=> a.name But whatever I typed, I couldn't get >some "reasonable" output, meaning I always got an error message ... > First you've left out the double __ on both sides - very important. Also, pay attention to the docstring: "a.__getattribute__('name') <=> a.name" The '' surrounding name should tell you that __getattribute__ expects a *string* as an argument. __getattribute__, if defined, is called for *every* attribute access, e.g. a.attribute <=> a.__getattribute__("attribute") So we can do something like: >>> class Test(object): ... def __getattribute__(self, attrib): ... return "This is a test." ... >>> a = Test() >>> a.test 'This is a test.' >>> a.dlwhdehkugqswdmv 'This is a test.' >>> a.__getattribute__ 'This is a test.' Having seen this last one, see if you can understand the following: >>> a.__getattribute__("test") Traceback (most recent call last): File "<interactive input>", line 1, in ? TypeError: 'str' object is not callable Don't worry if you can't now, you'll get there :-) But this goes to show that if you implement __getattribute__ you better be *very very careful* With my best regards, G. Rodrigues From dyoo at hkn.eecs.berkeley.edu Fri Nov 21 19:41:10 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Nov 21 19:41:47 2003 Subject: [Tutor] Numbers do support __str__() in recent versions of Python In-Reply-To: <Pine.LNX.4.44.0311211629120.28305-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0311211633280.28305-100000@hkn.eecs.berkeley.edu> On Fri, 21 Nov 2003, Danny Yoo wrote: > > > In recent years, the __str__() method was added to numbers to make them > > more uniform with the other Python types and classes. > > Hi everyone, > > > Yikes, I'm totally wrong here! Numbers still don't have __str__(). Hi everyone, I'm definitely having an off day. I'm wrong again. *grin* Ok, let's do this: ### [dyoo@tesuque dyoo]$ python1.5 Python 1.5.2 (#1, Jan 31 2003, 10:58:35) [GCC 2.96 20000731 (Red Hat Linux 7.3 2 on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> x = 42 >>> x.__str__() Traceback (innermost last): File "<stdin>", line 1, in ? AttributeError: 'int' object has no attribute '__str__' [dyoo@tesuque dyoo]$ python2.2 Python 2.2.1 (#1, Sep 3 2002, 14:52:01) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = 42 >>> x.__str__() '42' ### So numbers do have __str__() now, after all. I need to explain why I blundered: I did not pay close enough attention to the error message when I tested this out earlier: ### >>> 42.__str__() File "<stdin>", line 1 42.__str__() ^ SyntaxError: invalid syntax ### This fails, but not because numbers don't support __str__(), but because PYthon is parsing this out as a floating point value that isn't proper syntax! ### >>> 42.3 42.299999999999997 >>> 42.4 42.399999999999999 >>> 42.__str__() File "<stdin>", line 1 42.__str__() ^ SyntaxError: invalid syntax ### I should have payed closer attention to the error message: I mistook the SyntaxError for an AttributeError, and that led me astray. Anyway, if we add parentheses here, we get rid of the ambiguity, and, as I should have said earlier: ### >>> (42).__str__() '42' ### Numbers do support __str__(). Again, my apologies for giving totally off advice. I think I need a vacation... *grin* Good luck! From op73418 at mail.telepac.pt Fri Nov 21 19:49:04 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Nov 21 19:47:27 2003 Subject: [Tutor] 3 simple, pithy and short questions (fwd) In-Reply-To: <Pine.LNX.4.44.0311211629120.28305-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311211535180.28305-100000@hkn.eecs.berkeley.edu> <Pine.LNX.4.44.0311211629120.28305-100000@hkn.eecs.berkeley.edu> Message-ID: <2hctrv01go5vqu3ntv2untob1rch4isdg4@4ax.com> On Fri, 21 Nov 2003 16:32:22 -0800 (PST), you wrote: > >> In recent years, the __str__() method was added to numbers to make them >> more uniform with the other Python types and classes. > >Hi everyone, > > >Yikes, I'm totally wrong here! Numbers still don't have __str__(). I >should have double checked my assertions about this. So we can call str() >on numbers, but not __str__(). I misremembered the extent to which the >numbers were unified with the other types. > They don't? >>> int.__str__ <slot wrapper '__str__' of 'int' objects> >>> (1).__str__ <method-wrapper object at 0x011C3A70> >>> (1).__str__() '1' Tested in 2.3. With my best regards, G. Rodrigues From glingl at aon.at Fri Nov 21 20:00:47 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Nov 21 20:02:46 2003 Subject: [Fwd: Re: [Tutor] Livewires Robot-5] Message-ID: <3FBEB53F.8040909@aon.at> Indentation of my previous post was completely damaged, (don't know why) I try it once more: robots = [] # initially empty for i in range(number_of_robots_to_create): # number_of_robots_to_create # for instance may be 5 newrobot = Robot() # a new one ## here check if there are collisions ## with robots already created, something SIMILAR TO ok = False while not ok: ok = True for oldrobot in robots: if oldrobot.collides(newrobot): ok = False if not ok: # there was a collision ## put newrobot in a new place ..... ## ok is still False here, so the loop has to be done again ## here we come, if there was no collision (ok is True here) ## so the robot is ok and we append it to our list of robots: robots.append(newrobot) ## Now all our robots are ready to do something: for robot in robots: ### do something ... hope it will work now ... Regards, Gregor From thomi at imail.net.nz Fri Nov 21 20:15:58 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Fri Nov 21 20:16:06 2003 Subject: [Tutor] creating read only attributes Message-ID: <200311221415.58760.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi guys, I've been looking at some Delphi recently, and you can create read only attributes, which behave like variables. consider the following code: type TTest = class private testvar = integer; public property Test: integer read testvar; constructor Create; end; Now, while I *hate* Delphi code with a vengeance, this is pretty cool; I can not do something like this: t := TTest.Create; writeln(t.Test); i.e.- the "Test" property looks and behaves exactly like a normal variable, except that it is read-only in this case. The property can even be the result of a function, like so: type TTest = class private function test: integer; public property Test: integer read test; constructor Create; end; And it is still used like 'Test" as a normal variable. This has the obvious advantage of being able to change the code within a class, without having to change external code which implements these features. (does that make sense)? I'm sure there's a way to do this in python, but I haven't found it yet. A common usage I've seen is having method names like "set_text" and "get_text", but these still behave like functions. You cannot do something like this: t.set_text = 123.456 well, you could, but it wouldn't do what you expected.... Can someone please point me in the right direction? what's the magic keyword I'm missing? Thanks in advance ;) - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/vrjO2tSuYV7JfuERAhRXAJsGHQGFrmKDrqsIv6JJpjZAxAKaJgCgkocD 99fLKNgcd7AYxPksyUqRq+4= =NN6Y -----END PGP SIGNATURE----- From raven at phoenyx.net Fri Nov 21 20:58:45 2003 From: raven at phoenyx.net (Carl D Cravens) Date: Fri Nov 21 20:58:49 2003 Subject: [Tutor] Regex's and "best practice" Message-ID: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> Hello. I'm a Unix sysadmin and developer with a background in C (a few years ago) and more recently Perl and shell scripting. I'm rather proficient with Perl, but I get frustrated with it when I have to deal with references and in trying to build modules. I've recently started learning Python... I'm just about finished with the Tutorial, and I've been converting a 90-line Perl script I'd written a few years ago to see how Python handles it. Now, this script doesn't show off Python's strengths... all it does is read through a standard Unix mailbox and print out From: and Subject: in a compact format. (Actually, basically the same index format as Pine.) So it's doing a lot of string manipulation and pattern matching. Here's my question. The From: line can appear in basically four forms, and I have a little chain of s///'s that try to find the "real name", and barring that, use the address, stripping out extra junk. Here's the Perl snippet... (the "From: " has been stripped and the remainder is in $line) ## three formats to deal with (a bare address falls through) ## <address> , Name <address>, (Name) address $line ~= s/(^<)(.*)(>$)/$2/ || $line =~ s/<.*>// || $line ~=s/(.*)(\()(.*)(\))(.*)/$3/; idpatt = [ re.compile( '(^<)(.*)(>$)' ), re.compile( '<.*>' ), re.compile( '(.*)(\()(.*)(\))(.*)' ) ] idrepl = ['\\2', '', '\\3'] oldline = line for idpt,idrp in zip( idpatt, idrepl ): line = idpt.sub( idrp, line ) if oldline != line: break Not nearly as compact and simple as the Perl statement. Is this pretty much the best I can do? The OR's were very convenient in Perl... in Python, I have to do relatively large amount of work to get the same effect. (And I don't think it's necessary... I could let Python evaluate all threee sub()'s, even when further evaluation won't find anything to match.) That would reduce the last block to... for idpt,idrp in zip( idpatt, idrepl ): line = idpt.sub( idrp, line ) ...which doesn't look so bad, but it keeps processing the sub()'s even after a match has been made. Is there something obvious I'm missing, or is this a fair solution to the problem? Thanks! -- Carl D Cravens (raven@phoenyx.net) Talk is cheap because supply inevitably exceeds demand. From llwyble at cox.net Fri Nov 21 20:59:43 2003 From: llwyble at cox.net (Larry) Date: Fri Nov 21 20:59:40 2003 Subject: [Tutor] A volume control (: In-Reply-To: <20031121204549.4c28fa27.klappnase@freenet.de> References: <20031121065100.WLOA5790.lakemtao08.cox.net@widgeteye.homeip.net> <20031121204549.4c28fa27.klappnase@freenet.de> Message-ID: <20031122015935.CCCM5790.lakemtao08.cox.net@widgeteye.homeip.net> On Fri, 21 Nov 2003 20:45:49 +0100 Michael Lange <klappnase@freenet.de> wrote: > On Fri, 21 Nov 2003 00:51:27 -0600 > Larry <llwyble@cox.net> wrote: > > > > > Well, I have been working on this and got this far but I think I > > screwed up Because I can't figure out how to set the initial volume > > on the slider instead of it going back to 0 (zero) everytime I start > > it. I wanted to use: > > > > Current_vol = mixer.get(ossaudiodev.SOUND_MIXER_VOLUME) > > > > To get the current volume of the mixer. But I didn't consider this > > until I got this far and I don't think my slider code is going to > > allow an initial setting of the slider. Or is it? Arg... > > > > > Hi Larry, > > I think you should use a Tkinter.DoubleVar for the volume settings > which you can bind to the Scale widget(in case the volume is a float > value, I don't know about ossaudiodev, if it is an integer of course > you should use a Tkinter.IntVar()). > If you set the value of this variable to the current volume before the > scale is created I think it should work: > > > #!/usr/local/bin/python > > > > > > from Tkinter import * > > > > import ossaudiodev > > mixer = ossaudiodev.openmixer() > > > > class VOLUME(Frame): > > def print_value(self, val): > > ival = int(val) > > a = (ival,ival) > > mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, a) > > > > def createWidgets(self): > > self.slider = Scale(self, from_=0, to=100, > > orient=HORIZONTAL, > > length="3i", > > command=self.print_value, > variable=self.Current_vol) This didn't set the current volume. I'm not really sure what it does. The variable word is a global name. It's coming after the call to print. And even if I put it before the call to print, it doesn't change the setting of the scale on startup. It still starts at zero. I'm not completely sure what to do with 'variable'. (: Where can I read about 'variable' and the relationship with 'IntVar()' I'm pretty green at this and I don't quite grasp what's going on here. Thanks > > self.QUIT = Button(self, text='QUIT', foreground='red', > > command=self.quit) > > > > self.slider.pack(side=LEFT) > > self.QUIT.pack(side=LEFT, fill=BOTH) > > > > def __init__(self, master=None): > > Frame.__init__(self, master) > > Pack.config(self) > #get the current volume setting: > self.Current_vol = IntVar() > self.Current_vol.set(mixer.get(ossaudiodev.SOUND_MIXER_VOLUME )) > self.createWidgets() > > > > test = VOLUME() > > test.mainloop() > Like I said, I don't know what mixer.get() returns, (I haven't even > ossaudiodev installed), but I think this should do the trick to set > the initial volume. > > Cheers > > Michael > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------------------------- [Thy] kiss is comfortless as frozen water to a starved snake. -William Shakespeare, Troilus and Cressida From littledanehren at yahoo.com Fri Nov 21 21:27:06 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Fri Nov 21 21:27:11 2003 Subject: [Tutor] creating read only attributes In-Reply-To: <200311221415.58760.thomi@imail.net.nz> Message-ID: <20031122022706.94517.qmail@web41806.mail.yahoo.com> --- Thomi Richards wrote: > Hi guys, > > > I've been looking at some Delphi recently, and you > can create read only > attributes, which behave like variables. consider > the following code: > > type TTest = class > private > testvar = integer; > public > property Test: integer read testvar; > constructor Create; > end; > > > Now, while I *hate* Delphi code with a vengeance, > this is pretty cool; I can > not do something like this: > > t := TTest.Create; > writeln(t.Test); > > i.e.- the "Test" property looks and behaves exactly > like a normal variable, > except that it is read-only in this case. > > The property can even be the result of a function, > like so: > > > type TTest = class > private > function test: integer; > public > property Test: integer read test; > constructor Create; > end; > > And it is still used like 'Test" as a normal > variable. This has the obvious > advantage of being able to change the code within a > class, without having to > change external code which implements these > features. (does that make sense)? > > I'm sure there's a way to do this in python, but I > haven't found it yet. > > A common usage I've seen is having method names like > "set_text" and > "get_text", but these still behave like functions. > You cannot do something > like this: > > t.set_text = 123.456 > > well, you could, but it wouldn't do what you > expected.... > > Can someone please point me in the right direction? > what's the magic keyword > I'm missing? > > > Thanks in advance ;) > > - -- > Thomi Richards, > http://once.sourceforge.net/ There is no native thing to do this, but it can probably be done using __setattr__, but I can't do it without getting an infinite recursion. However, I don't see why you really need to do this. It is a convention to not change things that are in allcaps, so if someone wants to write a working application, they probably won't do that. In general, creating private variables is considered unpythonic, so it is probably the same for these immutable variables. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From klappnase at freenet.de Fri Nov 21 23:04:04 2003 From: klappnase at freenet.de (Michael Lange) Date: Fri Nov 21 23:10:25 2003 Subject: [Tutor] A volume control (: In-Reply-To: <20031122015935.CCCM5790.lakemtao08.cox.net@widgeteye.homeip.net> References: <20031121065100.WLOA5790.lakemtao08.cox.net@widgeteye.homeip.net> <20031121204549.4c28fa27.klappnase@freenet.de> <20031122015935.CCCM5790.lakemtao08.cox.net@widgeteye.homeip.net> Message-ID: <20031122050404.76a71edf.klappnase@freenet.de> On Fri, 21 Nov 2003 19:59:43 -0600 Larry <llwyble@cox.net> wrote: > > > This didn't set the current volume. I'm not really sure what it does. > The variable word is a global name. It's coming after the call to print. > And even if I put it before the call to print, it doesn't change the setting > of the scale on startup. It still starts at zero. I'm not completely sure > what to do with 'variable'. (: > > Where can I read about 'variable' and the relationship with 'IntVar()' > > I'm pretty green at this and I don't quite grasp what's going on here. > > Thanks > > Hmmm, what's wrong here.... I've written a little test script to see how the variable works: ############################# from Tkinter import * class Scale_Test: def __init__(self, master): self.a = IntVar() self.a.set(49) self.s = Scale(master, from_=100, to=0, length=200, width=20,\ variable=self.a, command=self.scale_cmd) self.s.pack() def scale_cmd(self, event=None): print self.a.get() def main(): r = Tk() t = Scale_Test(r) r.mainloop() main() ############################## This does obviously what it should: on startup the Scale widget gets set to 49 and when the Scale is moved the variable changes its value. Now, what happens in your script? > #!/usr/local/bin/python > > > from Tkinter import * > > import ossaudiodev > mixer = ossaudiodev.openmixer() > > class VOLUME(Frame): > def print_value(self, val): > ival = int(val) > a = (ival,ival) > mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, a) > > def createWidgets(self): > self.slider = Scale(self, from_=0, to=100, > orient=HORIZONTAL, > length="3i", > command=self.print_value, variable=self.Current_vol) > > self.QUIT = Button(self, text='QUIT', foreground='red', command=self.quit) > > self.slider.pack(side=LEFT) > self.QUIT.pack(side=LEFT, fill=BOTH) > > def __init__(self, master=None): > Frame.__init__(self, master) > Pack.config(self) #get the current volume setting: self.Current_vol = IntVar() self.Current_vol.set(mixer.get(ossaudiodev.SOUND_MIXER_VOLUME)) > self.createWidgets() > > test = VOLUME() > test.mainloop() Maybe the problem is here: >>> self.Current_vol.set(mixer.get(ossaudiodev.SOUND_MIXER_VOLUME)) Are you sure that mixer.get(ossaudiodev.SOUND_MIXER_VOLUME) returns an integer? With the set method you used a 2-tuple: >>> a = (ival,ival) >>> mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, a) so maybe mixer.get(etc.) returns a tuple with the left- and right channel values. (like I said before, I don't know anything about ossaudiodev). You might find out this if you change your __init__ like this: > def __init__(self, master=None): > Frame.__init__(self, master) > Pack.config(self) #get the current volume setting: self.Current_vol = IntVar() cv = mixer.get(ossaudiodev.SOUND_MIXER_VOLUME) print type(cv) self.Current_vol.set(cv) > self.createWidgets() Good luck to you Michael From thomi at imail.net.nz Fri Nov 21 23:19:10 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Fri Nov 21 23:19:16 2003 Subject: [Tutor] creating read only attributes In-Reply-To: <20031122022706.94517.qmail@web41806.mail.yahoo.com> References: <20031122022706.94517.qmail@web41806.mail.yahoo.com> Message-ID: <200311221719.10966.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, > > However, I > don't see why you really need to do this. It is a > convention to not change things that are in allcaps, > so if someone wants to write a working application, > they probably won't do that. In general, creating > private variables is considered unpythonic, so it is > probably the same for these immutable variables. > Isn't one of the basic tenants of OO that objects should be like "magic black boxes", and their inner workng should be invisable to outside observers? It seems to me that private variables are very important for this reason... The same goes for read-only attributes..... OK, so we could all use lots of methods, but if you ask me, a whole heap od methods called "set_a", "set_b", "set_c" etc. etc. is ugly... (the pyGTK classes come to mind). Wouldn't it be nice to be able to treat these attributes as read-only (or write-only), and have them behave as normal variables, rather than having to wrap functions around them? Thanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/vuO+2tSuYV7JfuERAnl2AJoDjE8lrqB/0Jj3Y0pJzI0fi/LmewCfbHf6 4xLupw8zuji7L1qms6X5COo= =bBVP -----END PGP SIGNATURE----- From llwyble at cox.net Fri Nov 21 23:21:15 2003 From: llwyble at cox.net (Larry) Date: Fri Nov 21 23:21:12 2003 Subject: [Tutor] A volume control (: In-Reply-To: <20031122050404.76a71edf.klappnase@freenet.de> References: <20031121065100.WLOA5790.lakemtao08.cox.net@widgeteye.homeip.net> <20031121204549.4c28fa27.klappnase@freenet.de> <20031122015935.CCCM5790.lakemtao08.cox.net@widgeteye.homeip.net> <20031122050404.76a71edf.klappnase@freenet.de> Message-ID: <20031122042109.DEOS4890.lakemtao07.cox.net@widgeteye.homeip.net> On Sat, 22 Nov 2003 05:04:04 +0100 Michael Lange <klappnase@freenet.de> wrote: > On Fri, 21 Nov 2003 19:59:43 -0600 > Larry <llwyble@cox.net> wrote: > > > > > > This didn't set the current volume. I'm not really sure what it > > does. The variable word is a global name. It's coming after the call > > to print. And even if I put it before the call to print, it doesn't > > change the setting of the scale on startup. It still starts at > > zero. I'm not completely sure what to do with 'variable'. (: > > > > Where can I read about 'variable' and the relationship with > > 'IntVar()' > > > > I'm pretty green at this and I don't quite grasp what's going on > > here. > > > > Thanks > > > > > > > Hmmm, > > what's wrong here.... > > I've written a little test script to see how the variable works: > ############################# > > from Tkinter import * > > class Scale_Test: > def __init__(self, master): > self.a = IntVar() > self.a.set(49) > self.s = Scale(master, from_=100, to=0, length=200, width=20,\ > variable=self.a, command=self.scale_cmd) > self.s.pack() > > def scale_cmd(self, event=None): > print self.a.get() > > > def main(): > r = Tk() > t = Scale_Test(r) > r.mainloop() > > main() > > ############################## > > This does obviously what it should: on startup the Scale widget gets > set to 49 and when the Scale is moved the variable changes its value. > > Now, what happens in your script? > > > #!/usr/local/bin/python > > > > > > from Tkinter import * > > > > import ossaudiodev > > mixer = ossaudiodev.openmixer() > > > > class VOLUME(Frame): > > def print_value(self, val): > > ival = int(val) > > a = (ival,ival) > > mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, a) > > > > def createWidgets(self): > > self.slider = Scale(self, from_=0, to=100, > > orient=HORIZONTAL, > > length="3i", > > command=self.print_value, > variable=self.Current_vol) > > > > self.QUIT = Button(self, text='QUIT', foreground='red', > > command=self.quit) > > > > self.slider.pack(side=LEFT) > > self.QUIT.pack(side=LEFT, fill=BOTH) > > > > def __init__(self, master=None): > > Frame.__init__(self, master) > > Pack.config(self) > #get the current volume setting: > self.Current_vol = IntVar() > self.Current_vol.set(mixer.get(ossaudiodev.SOUND_MIXER_VOLUME > )) > > self.createWidgets() > > > > test = VOLUME() > > test.mainloop() > > Maybe the problem is here: > > >>> self.Current_vol.set(mixer.get(ossaudiodev.SOUND_MIXER_VOLUME)) > > Are you sure that mixer.get(ossaudiodev.SOUND_MIXER_VOLUME) returns an > integer? With the set method you used a 2-tuple: > > >>> a = (ival,ival) > >>> mixer.set(ossaudiodev.SOUND_MIXER_VOLUME, a) You are right of course. I didn't even think of it. Too much going on today. But yes it returns a 2-tuple. Arg Thanks. I'll go back with that firmly in mind. (: > so maybe mixer.get(etc.) returns a tuple with the left- and right > channel values.(like I said before, I don't know anything about > ossaudiodev). > > You might find out this if you change your __init__ like this: > > > def __init__(self, master=None): > > Frame.__init__(self, master) > > Pack.config(self) > #get the current volume setting: > self.Current_vol = IntVar() > cv = mixer.get(ossaudiodev.SOUND_MIXER_VOLUME) > print type(cv) > self.Current_vol.set(cv) > > self.createWidgets() > > Good luck to you > > Michael > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- -------------------------------------------- [Thy] kiss is comfortless as frozen water to a starved snake. -William Shakespeare, Troilus and Cressida From alan.gauld at blueyonder.co.uk Sat Nov 22 04:10:56 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Nov 22 04:12:36 2003 Subject: [Tutor] creating read only attributes References: <200311221415.58760.thomi@imail.net.nz> Message-ID: <011c01c3b0d8$89a0d7f0$6401a8c0@xp> > I've been looking at some Delphi recently, and you can create > read only attributes, which behave like variables. > consider the following code: > > type TTest = class > private > testvar = integer; > public > property Test: integer read testvar; > constructor Create; > end; > I'm sure there's a way to do this in python, > but I haven't found it yet. Python recently borrowed the idea of properties from Delphi. Check the docs for how to declare a "property" in Python (introduced in v2.2 I think). Its not identical to Delphi but very close. Having said that I've never used them. The extra work needed to create them isn't worth the payback. The reason Delphi has them is primarily to allow you to expose your own object attributes within Delphi's GUI builder. The Delphi Property Inspector will only show attributes declared as properties. And will only allow you to change properties with a write mechanism defined. Since Python doesn't have such an IDE requirement I've never seen a need for Properties in Python, except to save a couple of keystrokes. Alan G. From op73418 at mail.telepac.pt Sat Nov 22 07:06:04 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Nov 22 07:04:29 2003 Subject: [Tutor] creating read only attributes In-Reply-To: <200311221415.58760.thomi@imail.net.nz> References: <200311221415.58760.thomi@imail.net.nz> Message-ID: <l8kurv4k1clblso1o29bo0065krtsknh2d@4ax.com> On Sat, 22 Nov 2003 14:15:58 +1300, you wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >Hi guys, > > [snipped] > >I'm sure there's a way to do this in python, but I haven't found it yet. > Use properties -- look in the doc, under language reference, customizing attribute access. Then read this: http://zephyrfalcon.org/labs/beginners_mistakes.html I'll quote the important part: """ Mistake 2: writing "language X" code in Python This is a mistake that is almost unavoidable. You come from, say, Pascal, and try your hand at Python. The first code you write will probably look like Pascal with a Python syntax. You are writing Pascal code in Python. Some notorious symptoms of "language X" code, and the languages that may cause them: - You're really paranoid about data hiding (some would call this "encapsulation"), and/or write getters and setters for all object attributes. (Java, C++, Delphi) - You overuse properties (one of the shiny new features in Python 2.2). (Java, Delphi, maybe Visual Basic, C++?) """ With my best regards, G. Rodrigues From mrmrmr50 at yahoo.com Sat Nov 22 09:46:26 2003 From: mrmrmr50 at yahoo.com (mike re-v) Date: Sat Nov 22 09:46:30 2003 Subject: [Tutor] python and snack Message-ID: <20031122144626.37338.qmail@web21203.mail.yahoo.com> please help #!/usr/bin/python from Tkinter import * root = Tk() import tkSnack#!/usr/bin/python from Tkinter import * root = Tk() import tkSnack tkSnack.initializeSnack(root) mysound = tkSnack.Sound() mysound1 = tkSnack.Sound() mysound2 = tkSnack.Sound() afile = open('/home/re-v/good.wav','w') mysound.read('/home/re-v/clm/doggrowl.wav') mysound1.read('/home/re-v/clm/dogbark.wav') mysound2.read('/home/re-v/sound/scream.wav') mysound.play() mysound1.play() mysound2.play() this is the problem#>>>>>afile.write(mysound2)<<<<< root.mainloop() GOAL There are three sound files which are opened and played. Since thay are not blocked they play at the same time. I'd like to not only play thru the speakers, which the code does now{this is nice for interactive editing}, I'd also like to be able to save the sound in a file there is a method in snack .write mysound.write('foo.wav') however the 'play at the same time feature is needed. Thanks re-v __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From marta_andrea at libero.it Fri Nov 21 18:30:59 2003 From: marta_andrea at libero.it (Andrea Valle) Date: Sat Nov 22 10:37:47 2003 Subject: [Tutor] snack classes In-Reply-To: <3CE41F04.4060508@fastmail.fm> Message-ID: <DNEFLBNHCGCPPIGNHGILIEFFDEAA.marta_andrea@libero.it> Dear all, I'm tryin' to use Snack soundkit. That's really interesting. But I'm not a programmer. As I wanted to implement some simple audio manipulation, I created a class Sig from the Sound class of Snack, i.e.: class Sig (Sound): But I am not able to use all the methods of Sound with Sig. It seems that I need some reference to tkSnack. Can anyone kindly explain what happens and how to do? Thanks a lot as usual and sorry if it's evident. -a- From sigurd at 12move.de Sat Nov 22 10:50:53 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sat Nov 22 10:55:23 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> (Carl D. Cravens's message of "Fri, 21 Nov 2003 19:58:45 -0600 (CST)") References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> Message-ID: <m3vfpcl933.fsf@hamster.pflaesterer.de> On 22 Nov 2003, Carl D Cravens <- raven@phoenyx.net wrote: > Here's my question. The From: line can appear in basically four forms, > and I have a little chain of s///'s that try to find the "real name", and > barring that, use the address, stripping out extra junk. Here's the Perl > snippet... (the "From: " has been stripped and the remainder is in $line) > ## three formats to deal with (a bare address falls through) > ## <address> , Name <address>, (Name) address > $line ~= s/(^<)(.*)(>$)/$2/ || > $line =~ s/<.*>// || > $line ~=s/(.*)(\()(.*)(\))(.*)/$3/; Without a little bit cheating you will have more verbose code with Python. But that's nothing new nor should it be a hindrance (if the number of lines doesn't differ too much). [solution with re.sub] > Not nearly as compact and simple as the Perl statement. Compact yes. > Is this pretty much the best I can do? The OR's were very convenient in You could at first use search() instead of sub(). That would mean you had to rewrite the regexps a bit. Second you could use named groups (a nice thing in Python) instead of the numbers. Third you could write one or two functions which give you the terseness of Perl. First the functions: --8<---------------cut here---------------start------------->8--- # reg.py import re def assemble(regs): return [re.compile(reg).search for reg in regs] def s(reglist, string, grp): for rcs in reglist: m = rcs(string) if m: return m.group(grp) return string --8<---------------cut here---------------end--------------->8--- assemble() builds a list of regexp objects with the search method. s() takes such a list, a string to be searched and the name of the group you want to get returned. If nothing is found the string is returned. As soon as a match occurs the function returns. --8<---------------cut here---------------start------------->8--- # reg2.py from reg import * regs = assemble(['(^<)(?P<name>.*)(>$)', '(?P<name>.*)<.*>', '(.*)(\()(?P<name>.*)(\))(.*)']) for line in open($file): line = s(regs, line, 'name') --8<---------------cut here---------------end--------------->8--- assemble() is here called with a list of three regexps; the group which is of interest has been namend 'name'. The construct (?P<group>...) gives the name 'group' to a group. The second regexp had to be rewritten a bit. Then our file is opened and every line is tried with our regexps. [...] > Is there something obvious I'm missing, or is this a fair solution to the > problem? No your solution is a fair one IMO mine is only an alternative. It's a matter of taste what you prefer. Karl -- Please do *not* send copies of replies to me. I read the list From pythontutor at venix.com Sat Nov 22 11:15:25 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Nov 22 11:16:02 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> Message-ID: <3FBF8B9D.4000008@venix.com> Carl D Cravens wrote: > Hello. I'm a Unix sysadmin and developer with a background in C (a few ..... > ## three formats to deal with (a bare address falls through) > ## <address> , Name <address>, (Name) address > $line ~= s/(^<)(.*)(>$)/$2/ || > $line =~ s/<.*>// || > $line ~=s/(.*)(\()(.*)(\))(.*)/$3/; > > > idpatt = [ re.compile( '(^<)(.*)(>$)' ), > re.compile( '<.*>' ), > re.compile( '(.*)(\()(.*)(\))(.*)' ) ] > > idrepl = ['\\2', '', '\\3'] > > oldline = line > for idpt,idrp in zip( idpatt, idrepl ): > line = idpt.sub( idrp, line ) > if oldline != line: > break > > Not nearly as compact and simple as the Perl statement. > Is this pretty much the best I can do? The OR's were very convenient in > Perl... in Python, I have to do relatively large amount of work to get the > same effect. (And I don't think it's necessary... I could let Python > evaluate all threee sub()'s, even when further evaluation won't find > anything to match.) That would reduce the last block to... > > for idpt,idrp in zip( idpatt, idrepl ): > line = idpt.sub( idrp, line ) > > ...which doesn't look so bad, but it keeps processing the sub()'s even > after a match has been made. > > Is there something obvious I'm missing, or is this a fair solution to the > problem? > > Thanks! > > -- > Carl D Cravens (raven@phoenyx.net) > Talk is cheap because supply inevitably exceeds demand. I would call it a fair solution. Perl is very hard to beat on the regex front simply because regular expressions are in the language, not a module. For a sysadmin, I think the win with python is the ease of writing reusable modules that are tailored for your system. I presumme you understand Python's if __name__ == '__main__': idiom. This allows a python script to detect that it is being run as a "command" rather than being imported. So any python script can do double duty, it's a useful command file AND it is importable to provide useful subroutines/objects for other scripts. This is much better than copying and pasting code from one file to another. -- 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 22 15:50:30 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Nov 22 15:52:23 2003 Subject: [Tutor] creating read only attributes References: <20031122022706.94517.qmail@web41806.mail.yahoo.com> <200311221719.10966.thomi@imail.net.nz> Message-ID: <013301c3b13a$440873d0$6401a8c0@xp> > > they probably won't do that. In general, creating > > private variables is considered unpythonic, so it is > > probably the same for these immutable variables. > Isn't one of the basic tenants of OO that objects should > be like "magic black boxes", and their inner workng > should be invisable to outside observers? No, its something that has been tagged on to OO in relatively recent times. All the early OO languages allowed public access to atttibutes but discouraged it by convention. I think Smalltalk 78 was the first OO language to enforce data hiding (sometimes erroneously called encapsulation) but many OOP languages before and since have got on just fine without it. > The same goes for read-only attributes..... OK, so we > could all use lots of methods, but if you ask me, > a whole heap od methods called "set_a", "set_b", A read only attribute is a constant. There are coding conventions for this but actually the ability to define a constant variabkle is something I'd like in Python - but given Pythons way of working - all variables are references - I just don't see how it could be done consistently in the language. So coding conventions are the best substitute. Alan G. From alan.gauld at blueyonder.co.uk Sat Nov 22 15:53:41 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Nov 22 15:55:42 2003 Subject: [Tutor] creating read only attributes References: <200311221415.58760.thomi@imail.net.nz> <l8kurv4k1clblso1o29bo0065krtsknh2d@4ax.com> Message-ID: <013a01c3b13a$b6510b50$6401a8c0@xp> > - You're really paranoid about data hiding (some would call this > "encapsulation"), and/or write getters and setters for all object > attributes. (Java, C++, Delphi) Actually this is bad practice in Delphi too! You should only do that for properties and properties should only be useed for components that will be used from the IDE in a drag n drop style during design. ie For things you want to expose in the OBject Inspector tools. Alan G. (Who is also a Delphi programmer! :-) From littledanehren at yahoo.com Sat Nov 22 16:35:09 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Nov 22 16:37:30 2003 Subject: [Tutor] creating read only attributes In-Reply-To: <200311221719.10966.thomi@imail.net.nz> Message-ID: <20031122213509.32719.qmail@web41811.mail.yahoo.com> > Hi, > > Isn't one of the basic tenants of OO that objects > should be like "magic black > boxes", and their inner workng should be invisable > to outside observers? It > seems to me that private variables are very > important for this reason... > I've never heard of that. I thought objects were supposed to do things automatically, but were still supposed to be transparent. There is no need to watch over your programmers and make sure they don't change the internals of an object. Someone, I'm not sure who, said about Python's lack of private variables "We're all consenting adults here." > The same goes for read-only attributes..... OK, so > we could all use lots of > methods, but if you ask me, a whole heap od methods > called "set_a", "set_b", > "set_c" etc. etc. is ugly... (the pyGTK classes come > to mind). Wouldn't it be > nice to be able to treat these attributes as > read-only (or write-only), and > have them behave as normal variables, rather than > having to wrap functions > around them? > > > Thanks, > - -- > Thomi Richards, > http://once.sourceforge.net/ Who's suggesting using a lot of methods? I was suggesting that you could define __setattr__ in a class to make it so that certain attributes weren't setable. pyGTK probably has to make all of those functions because of a poor wrapper to C, not because they wanted some things to be private. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From gerrit at nl.linux.org Sat Nov 22 17:31:16 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat Nov 22 17:31:56 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> Message-ID: <20031122223116.GA19009@nl.linux.org> Carl D Cravens wrote: > Subject: [Tutor] Regex's and "best practice" > I've recently started learning Python... I'm just about finished with the > Tutorial, and I've been converting a 90-line Perl script I'd written a few > years ago to see how Python handles it. > > Now, this script doesn't show off Python's strengths... all it does is > read through a standard Unix mailbox and print out From: and Subject: in a > compact format. (Actually, basically the same index format as Pine.) So > it's doing a lot of string manipulation and pattern matching. You may want to use an entirely different approach to the problem. You don't need regular expressions at all. A number of high-level libraries are available for this problem: the mailbox module, the email module, e.g. The following code won't work because it's fake, but the solution may look similar to this: import email, mailbox for mail in mailbox.UnixMailbox(email.message_from_file): print email.Utils.parse_addr(mail["From"])[1], mail["Subject"] I haven't tested this and it probably won't work, but you can find the documentation to the email and mailbox modules in the library documentation. They are very useful modules. You don't need any regular expression. I myself tend to avoid them as much of possible, but Perl has a different philosophy ;). What you are doing, is translating Perl to Python. But it doesn't become Python then, it becomes translated Perl. Note that I don't know anything about tranlasting programs since a prerequisite of porting is knowing at least 2 languages (I don't), but I read that this mistake is made my PT2-people (Python as a Second Language ;) so I just note it here. yours, Gerrit. -- There are 10^11 stars in the galaxy. That used to be a huge number. But it's only a hundred billion. It's less than the national deficit! We used to call them astronomical numbers. Now we should call them economical numbers. -- Ricard Feynmann, Physics Today, February 1989 -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Kom in verzet tegen dit kabinet: http://www.sp.nl/ From thomi at imail.net.nz Sat Nov 22 17:45:02 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Nov 22 17:45:30 2003 Subject: [Tutor] creating read only attributes In-Reply-To: <013a01c3b13a$b6510b50$6401a8c0@xp> References: <200311221415.58760.thomi@imail.net.nz> <l8kurv4k1clblso1o29bo0065krtsknh2d@4ax.com> <013a01c3b13a$b6510b50$6401a8c0@xp> Message-ID: <200311231145.02773.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Thank you all for your insightful reples... I'll go play with python some more now ;) Even if it might be the "wrong thing to do", I still think it's worthwhile trying to apply concepts present in other languages to python. Anyway, thanks all the same ;) - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/v+bu2tSuYV7JfuERAj7fAKCFrmqWDqcO6SokHbpOYBFS5ren+QCfVYNs PiYmFNT8SBq5gqZXe6P3Rgk= =v0iD -----END PGP SIGNATURE----- From littledanehren at yahoo.com Sat Nov 22 17:47:50 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sat Nov 22 17:47:55 2003 Subject: [Tutor] Numbers do support __str__() in recent versions of Python In-Reply-To: <Pine.LNX.4.44.0311211633280.28305-100000@hkn.eecs.berkeley.edu> Message-ID: <20031122224750.8278.qmail@web41802.mail.yahoo.com> --- Danny Yoo wrote: > Numbers do support __str__(). Again, my apologies > for giving totally off > advice. I think I need a vacation... *grin* > > > Good luck! I think you're supposed to do str(number) instead of (number).__str__() Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From sigurd at 12move.de Sat Nov 22 18:14:35 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sat Nov 22 18:16:18 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <20031122223116.GA19009@nl.linux.org> (Gerrit Holl's message of "Sat, 22 Nov 2003 23:31:16 +0100") References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> <20031122223116.GA19009@nl.linux.org> Message-ID: <m3ptfk6lsb.fsf@hamster.pflaesterer.de> On 22 Nov 2003, Gerrit Holl <- gerrit@nl.linux.org wrote: > You may want to use an entirely different approach to the problem. > You don't need regular expressions at all. A number of high-level That may be. But if you need performance for a simple task then regexps can be the right tool. [...] > library documentation. They are very useful modules. You don't > need any regular expression. I myself tend to avoid them as much > of possible, but Perl has a different philosophy ;). What you are I won't say that in Python you should avoid regexps. You may only need them less as in Perl. But here they seem perfectly right. Karl -- Please do *not* send copies of replies to me. I read the list From klappnase at freenet.de Sat Nov 22 18:11:37 2003 From: klappnase at freenet.de (Michael Lange) Date: Sat Nov 22 18:34:18 2003 Subject: [Tutor] python and snack In-Reply-To: <20031122144626.37338.qmail@web21203.mail.yahoo.com> References: <20031122144626.37338.qmail@web21203.mail.yahoo.com> Message-ID: <20031123001137.273e9639.klappnase@freenet.de> On Sat, 22 Nov 2003 06:46:26 -0800 (PST) mike re-v <mrmrmr50@yahoo.com> wrote: > please help > #!/usr/bin/python > > from Tkinter import * > root = Tk() > import tkSnack#!/usr/bin/python > > from Tkinter import * > root = Tk() > import tkSnack > tkSnack.initializeSnack(root) > > mysound = tkSnack.Sound() > mysound1 = tkSnack.Sound() > mysound2 = tkSnack.Sound() > afile = open('/home/re-v/good.wav','w') > mysound.read('/home/re-v/clm/doggrowl.wav') > mysound1.read('/home/re-v/clm/dogbark.wav') > mysound2.read('/home/re-v/sound/scream.wav') > > > mysound.play() > > > mysound1.play() > > mysound2.play() > this is the problem#>>>>>afile.write(mysound2)<<<<< > root.mainloop() > > > GOAL > There are three sound files which are opened and > played. Since thay are not blocked they play at the > same time. I'd like to not only play thru the > speakers, which the code does now{this is nice for > interactive editing}, I'd also like to be able to save > the sound in a file > there is a method in snack .write > mysound.write('foo.wav') however the 'play at the same > time feature is needed. > Thanks > re-v > I suppose you want to mix the 3 "mysounds" together into "afile", right? Have you tried the tkSnack.Sound.mix() method ? I must admit that I have not, but it looks like it might be the right thing for you. Good luck Michael From klappnase at freenet.de Sat Nov 22 18:26:47 2003 From: klappnase at freenet.de (Michael Lange) Date: Sat Nov 22 18:34:25 2003 Subject: [Tutor] snack classes In-Reply-To: <DNEFLBNHCGCPPIGNHGILIEFFDEAA.marta_andrea@libero.it> References: <3CE41F04.4060508@fastmail.fm> <DNEFLBNHCGCPPIGNHGILIEFFDEAA.marta_andrea@libero.it> Message-ID: <20031123002647.72841fd6.klappnase@freenet.de> On Sat, 22 Nov 2003 00:30:59 +0100 "Andrea Valle" <marta_andrea@libero.it> wrote: Hi Andrea, > Dear all, > I'm tryin' to use Snack soundkit. That's really interesting. But I'm not a > programmer. > As I wanted to implement some simple audio manipulation, I created a class > Sig from the Sound class of Snack, i.e.: > class Sig (Sound): maybe you could be more explicit about what you want your class "Sig" to do. > But I am not able to use all the methods of Sound with Sig. if you want to use all methods of the "Sound" class, why do you need class "Sig" ? > It seems that I need some reference to tkSnack. If you haven't already, take a look at the Snack manual at Snack's homepage: www.speech.kth.se/snack > Can anyone kindly explain what happens and how to do? like I said above, please tell us more details. If you post your code and maybe some error messages and a description of what you expected your code to do, we might be able to give you better help. Good luck Michael From bvinger at postmaster.co.uk Sat Nov 22 19:10:01 2003 From: bvinger at postmaster.co.uk (Ben Vinger) Date: Sat Nov 22 19:10:46 2003 Subject: [Tutor] sending both a filename and an argument from the command line Message-ID: <PM.23818.1069546201@pmweb7.uk1.bibliotech.net> Hi It seems I can send either a file(s), or arguments to a python script, but not both: I want to do: python ip.py myfile -i myargument or even: cat myfile | python ip.py -i myargument Neither works, although if I do cat myfile | python ip.py - myargument the program begins working and even prints out some correct output before aborting with: IOError: [Errno 2] No such file or directory: 'myargument' Is there a way to accomplish this? Thanks Ben ___________________________________________________ Reduce your company's IT costs today with Officemaster. Sign up for a free trial! http://www.officemaster.net From dyoo at hkn.eecs.berkeley.edu Sat Nov 22 19:55:36 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Nov 22 19:55:46 2003 Subject: [Tutor] sending both a filename and an argument from the command line In-Reply-To: <PM.23818.1069546201@pmweb7.uk1.bibliotech.net> Message-ID: <Pine.LNX.4.44.0311221628340.20023-100000@hkn.eecs.berkeley.edu> On Sun, 23 Nov 2003, Ben Vinger wrote: > It seems I can send either a file(s), or arguments to a python script, > but not both: > > I want to do: > > python ip.py myfile -i myargument Hi Ben, This should work, although probably not exactly as you might expect. The 'optparse' module is responsible for parsing out the command line arguments: http://www.python.org/doc/lib/module-optparse.html When we say something like: python ip.py myfile -i myargument Python itself has no idea how the words 'myfile', '-i', or 'myargument' should be interpreted. As far as Python is concerned, they are all only strings: ### [dyoo@tesuque dyoo]$ cat test_args.py import sys print sys.argv [dyoo@tesuque dyoo]$ python test_args.py myfile -i myargument ['test_args.py', 'myfile', '-i', 'myargument'] ### The 'optparse' module takes sys.argv, and is the subsystem responsible for interpreting each command line argument. It appears that your program wants to use '-i' as an option. 'optparse' provides tools for supporting options: ### [dyoo@tesuque dyoo]$ cat test.py #!/usr/local/bin/python2.3 """A small script to test out optparse.""" import optparse import sys parser = optparse.OptionParser() parser.add_option('-i') options, argv = parser.parse_args(sys.argv) print options print "The rest of my argv variables are:", argv ### Let's see how this works: ### [dyoo@tesuque dyoo]$ ./test.py foobar -i myargument <Values at 0x400e6ecc: {'i': 'myargument'}> The rest of my argv variables are: ['./test.py', 'foobar'] ### Optparse doesn't interpret the command line arguments that it doesn't understand, so it leaves those alone for us to handle. If you want your program to be able to handle something like: python ip.py - myargument where '-' stands for standard in, then we can use 'optparse' in combination with the 'fileinput' module. http://www.python.org/doc/lib/module-fileinput.html For example, say that we want to write a program that uppercases (or lowercases) whatever files we name on the command line. ### #!/usr/local/bin/python2.3 """Another small script to test out optparse.""" import optparse import sys import fileinput def main(): action, file = parseOptions() for line in file: sys.stdout.write(action(line)) def parseOptions(): """Parses out command line options, and returns a line action and the files it should perform that action over.""" parser = optparse.OptionParser() parser.add_option('-c', '--case', dest='case', default='u', help='[u/l] (u)ppercase or (l)owercase') options, argv = parser.parse_args() if options.case == 'u': return upperLine, fileinput.input(argv) else: return lowerLine, fileinput.input(argv) def upperLine(line): return line.upper() def lowerLine(line): return line.lower() if __name__ == '__main__': main() ### Here's an example of it in action: ### [dyoo@tesuque dyoo]$ head test_optparse.py | ./test_optparse.py --case=u #!/USR/LOCAL/BIN/PYTHON2.3 """A SMALL SCRIPT TO TEST OUT OPTPARSE.""" IMPORT OPTPARSE IMPORT SYS IMPORT FILEINPUT DEF MAIN(): ACTION, FILE = PARSEOPTIONS() [dyoo@tesuque dyoo]$ head test_optparse.py | ./test_optparse.py --case=l #!/usr/local/bin/python2.3 """a small script to test out optparse.""" import optparse import sys import fileinput def main(): action, file = parseoptions() ### So 'optparse' and 'fileinput' should be powerful enough to handle the command line arguments you want to parse. If you have more questions, please feel free to ask. Good luck! From david at graniteweb.com Sat Nov 22 21:37:25 2003 From: david at graniteweb.com (David Rock) Date: Sat Nov 22 21:38:29 2003 Subject: [Tutor] sending both a filename and an argument from the command line In-Reply-To: <PM.23818.1069546201@pmweb7.uk1.bibliotech.net> References: <PM.23818.1069546201@pmweb7.uk1.bibliotech.net> Message-ID: <20031123023725.GA10421@wdfs.graniteweb.com> * Ben Vinger <bvinger@postmaster.co.uk> [2003-11-23 00:10]: > Hi > It seems I can send either a file(s), or arguments to a python script, > but not both: > I want to do: > > python ip.py myfile -i myargument > or even: > cat myfile | python ip.py -i myargument > > Neither works, although if I do > > cat myfile | python ip.py - myargument > > the program begins working and even prints out some correct output > before aborting with: > > IOError: [Errno 2] No such file or directory: 'myargument' > > Is there a way to accomplish this? Most modules that parse commandlines (like getopt) expect that the arguments come first, then the filenames. So python ip.py myfile -i myargument should be python ip.py -i myargument myfile piping data into a python app needs some special handling so that it can understand what you are trying to give it. cat myfile | python ip.py - myargument This probably works because it thinks "-" is a filename that represents stdin. Without seeing your code, I can't be sure. The way I usually handle this kind of argument/filename processing is a combination of the getopt and fileinput modules. http://www.python.org/doc/current/lib/module-getopt.html http://www.python.org/doc/current/lib/module-fileinput.html -- 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/20031122/486f482f/attachment.bin From alan.gauld at blueyonder.co.uk Sun Nov 23 04:16:25 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 23 04:18:15 2003 Subject: [Tutor] sending both a filename and an argument from the command line References: <PM.23818.1069546201@pmweb7.uk1.bibliotech.net> Message-ID: <002301c3b1a2$7853c500$6401a8c0@xp> > It seems I can send either a file(s), or arguments to a python script, but not both: > I want to do: > > python ip.py myfile -i myargument Python usage is: python [option] ... [-c cmd | file | -] [arg] ... so you need to rearrange your line slightly: python -i ip.py myargument The option '-i' must come before the filename and the arguments to the file must come immediately after the filename. Alan G. From marta_andrea at libero.it Sun Nov 23 05:34:28 2003 From: marta_andrea at libero.it (Andrea Valle) Date: Sun Nov 23 05:44:54 2003 Subject: R: [Tutor] snack classes In-Reply-To: <20031123002647.72841fd6.klappnase@freenet.de> Message-ID: <DNEFLBNHCGCPPIGNHGILOEGADEAA.marta_andrea@libero.it> Hi Michael (and all), thanks and sorry: This is a code sample -------------- from Tkinter import * from tkSnack import * root=Tk() initializeSnack(root) # As required by Snack from math import * class Sig(Sound): def __init__(self): self.sec=2 self.length=44100*self.sec def sine(self): l=self.length for x in range(l): y=int(10000*sin(float(x)*50)) self.sample(x,y) return self As you can see, I'd like to use the Sig class derived from the Sound class to make some sample manipulation, i.e. the function sine create a sinusoidal signal, etc.. The sample method of Sound is really powerful. But: >>> s=Sig() >>> s.sine() Traceback (most recent call last): File "<pyshell#1>", line 1, in ? s.sine() File "C:/Programmi/python 2.2.1/modello2.py", line 23, in sine self.sample(x,y) File "C:\PROGRA~1\PYTHON~1.1\tkSnack.py", line 288, in sample return _cast(self.tk.call((self.name, 'sample', index) + opts)) AttributeError: Sig instance has no attribute 'tk' >>> ? Thanks and best -a- From bvinger at postmaster.co.uk Sun Nov 23 06:39:58 2003 From: bvinger at postmaster.co.uk (Ben Vinger) Date: Sun Nov 23 06:40:50 2003 Subject: [Tutor] sending both a filename and an argument from the command line Message-ID: <PM.8714.1069587598@pmweb7.uk1.bibliotech.net> Hi OK, thanks to that advice, it works, but behaves strangely. (it prints the correct output, but also some comments and code to the console) #!/usr/bin/env python # example how to take a filename and an ip address as command line arguments # python ip.py capture.txt --ip 66.218.71.109 import os, sys, fileinput, optparse from optparse import OptionParser parser = OptionParser() parser.add_option("--ip", dest="ip address to test", help="example: python ip.py capture.txt --ip 66.218.71.109") options, argv = parser.parse_args(sys.argv) for line in fileinput.input(argv): if line.find(sys.argv[3]) > 0: print line The output of python ip.py capture.txt --ip 66.218.71.109 looks like this (note the unwanted lines from the script): # python ip.py capture.txt --ip 66.218.71.109 parser.add_option("--ip", dest="ip address to test", help="example: python ip.py capture.txt --ip 66.218.71.10 9") 47742.225111 192.168.1.200 -> 66.218.71.109 TCP 5237 > http [FIN, ACK] Seq=3976725456 Ack=3429041443 Win=65287 Len=0 Thanks Ben On Sat, 22 Nov 2003 16:55:36 -0800 (PST) , Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: ___________________________________________________ Take your business online with Officemaster. Sign up for a free trial today! http://www.officemaster.net From arkamir at softhome.net Fri Nov 21 19:27:46 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Sun Nov 23 13:05:01 2003 Subject: [Tutor] Cookie help Message-ID: <1069460866.7005.5.camel@quercus> Hey everyone I'm having some troubles retrieving cookies. The script im using is: #/usr/bin/python import os import Cookie cookies = Cookie.SimpleCookie() cookies.load(os.environ['id']) value = cookies['id'].value print 'Content-type: text/html\n' print value I set the cookie in another script. They are set as a SimpleCookie with the values of username and id. The problem is the script returns an error. (I don't quite have access to the error logs, at least yet). Any help would be appreciated From clay at shirky.com Sun Nov 23 13:37:53 2003 From: clay at shirky.com (Clay Shirky) Date: Sun Nov 23 13:38:06 2003 Subject: [Tutor] string.unprintable? In-Reply-To: <00e201c3b075$e8966b20$6401a8c0@xp> Message-ID: <BBE668B1.1235A%clay@shirky.com> > if printable.search(line): > # do it here. > else: > # or not Right, though this is different loop logic than the operation calls for. This is "If a line has any printable characters, do something", but I need "If a line has any unprintable characters, do something", which means building a big weird regex. I had hoped that there would be string.unprintable, or some easy way to derive it from string.printable, but it looks like the regex is the way to go. -c From raven at phoenyx.net Sun Nov 23 13:39:25 2003 From: raven at phoenyx.net (Carl D Cravens) Date: Sun Nov 23 13:39:32 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <m3vfpcl933.fsf@hamster.pflaesterer.de> References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> <m3vfpcl933.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.58.0311231227200.17524@lists.wirebird.com> On Sat, 22 Nov 2003, Karl [iso-8859-1] Pfl=E4sterer wrote: > Without a little bit cheating you will have more verbose code with > Python. But that's nothing new nor should it be a hindrance (if the > number of lines doesn't differ too much). I recognize that... took me awhile to get used to, though. It's been a long time since I've done serious C coding, and I've forgotten just how much "magic" and assumption there is in Perl. When I first started with Python (just a week ago), I was dumbfounded that an end-of-file condition raised an exception and terminated the program if it wasn't handled. Didn't exactly seem convenient at all. Of course, I then discovered that various modules dealt with reading files more elegantly. 'import this' puts a lot of things in perspective. And fileinput is pretty handy. > You could at first use search() instead of sub(). Seems that doing two regex operations instead of a simple string comparison and a regex operation is both easier to code and simpler to execute. > That would mean you had to rewrite the regexps a bit. Second you could > use named groups (a nice thing in Python) instead of the numbers. > Third you could write one or two functions which give you the terseness > of Perl. Terseness in the main code, yes... but overall I'd have to write more code to develop functions which don't get used anywhere but here. I'm not following your code... I need to go read about groups. My primary purpose in posting was to be sure that I wasn't missing some "obvious" solution. -- Carl D Cravens (raven@phoenyx.net) Press any key to continue or any other key to quit. From raven at phoenyx.net Sun Nov 23 13:43:11 2003 From: raven at phoenyx.net (Carl D Cravens) Date: Sun Nov 23 13:43:15 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <3FBF8B9D.4000008@venix.com> References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> <3FBF8B9D.4000008@venix.com> Message-ID: <Pine.LNX.4.58.0311231240360.17524@lists.wirebird.com> On Sat, 22 Nov 2003, Lloyd Kvam wrote: > I would call it a fair solution. Perl is very hard to beat on the regex > front simply because regular expressions are in the language, not a module. It seems that they could be a bit less clunky. It's counter-intuitive that match() and search() allow including flags, but to use flags with sub() you have to compile() the regex first. Just something I'll have to get used to. > For a sysadmin, I think the win with python is the ease of writing reusable > modules that are tailored for your system. I presumme you understand Python's > if __name__ == '__main__': I've only been doing this for a few days, so I haven't run across this. Sounds useful, though, and I'll keep it in mind. -- Carl D Cravens (raven@phoenyx.net) Toto, I don't think we're online anymore... From raven at phoenyx.net Sun Nov 23 13:50:41 2003 From: raven at phoenyx.net (Carl D Cravens) Date: Sun Nov 23 13:50:56 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <20031122223116.GA19009@nl.linux.org> References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> <20031122223116.GA19009@nl.linux.org> Message-ID: <Pine.LNX.4.58.0311231243190.17524@lists.wirebird.com> On Sat, 22 Nov 2003, Gerrit Holl wrote: > You may want to use an entirely different approach to the problem. > You don't need regular expressions at all. A number of high-level > libraries are available for this problem: the mailbox module, > the email module, e.g. Yes, but that avoids the point of the exercise... to convert one of my Perl scripts to Python to see how they compare. I wrote the original script back in '86 on Perl 4. I don't think there were any public mail libraries (modules didn't exist with Perl 4) at the time, or I'd have just taken that approach with the Perl script as well. > What you are doing, is translating Perl to Python. But it doesn't become > Python then, it becomes translated Perl. Which was the point of my original post... to see if I was missing something obvious to the experienced Python coder. But let's drop down a level and say I'm writing a mailbox module. I'd probably still be using regexes, because trying to extract what I'm looking for without them would be rather tedious. -- Carl D Cravens (raven@phoenyx.net) Dogs crawl under fences, Software crawls under Windows. From littledanehren at yahoo.com Sun Nov 23 14:32:50 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Nov 23 14:32:56 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <Pine.LNX.4.58.0311231243190.17524@lists.wirebird.com> Message-ID: <20031123193250.66125.qmail@web41804.mail.yahoo.com> Carl D Cravens wrote: > On Sat, 22 Nov 2003, Gerrit Holl wrote: > > > You may want to use an entirely different approach > to the problem. > > You don't need regular expressions at all. A > number of high-level > > libraries are available for this problem: the > mailbox module, > > the email module, e.g. > > Yes, but that avoids the point of the exercise... to > convert one of my > Perl scripts to Python to see how they compare. > > I wrote the original script back in '86 on Perl 4. > I don't think there > were any public mail libraries (modules didn't exist > with Perl 4) at the > time, or I'd have just taken that approach with the > Perl script as well. > > > What you are doing, is translating Perl to Python. > But it doesn't become > > Python then, it becomes translated Perl. > > Which was the point of my original post... to see if > I was missing > something obvious to the experienced Python coder. > > But let's drop down a level and say I'm writing a > mailbox module. I'd > probably still be using regexes, because trying to > extract what I'm > looking for without them would be rather tedious. > > -- > Carl D Cravens (raven@phoenyx.net) > Dogs crawl under fences, Software crawls under > Windows. There is a major difference in the philosophies of Perl and Python. Among other things, the Pearl doesn't have nearly as many standard libraries as Python does because they believe that things should be in seperate, user-made libraries, or just reimplimented in the individual program. With Python, unless you have a specific goal of creating a faster library or something (in which case you'd probably use C anyway), it really doesn't make sense to reimpliment things. The availability of these libraries should be taken into account when considering how easy it would be to make one of these programs. If there is no similar library in Perl, that doesn't mean you should write the Python program poorly. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From sigurd at 12move.de Sun Nov 23 14:49:59 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sun Nov 23 14:53:49 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <Pine.LNX.4.58.0311231227200.17524@lists.wirebird.com> (Carl D. Cravens's message of "Sun, 23 Nov 2003 12:39:25 -0600 (CST)") References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> <m3vfpcl933.fsf@hamster.pflaesterer.de> <Pine.LNX.4.58.0311231227200.17524@lists.wirebird.com> Message-ID: <m3y8u6ubdd.fsf@hamster.pflaesterer.de> On 23 Nov 2003, Carl D Cravens <- raven@phoenyx.net wrote: > On Sat, 22 Nov 2003, Karl [iso-8859-1] Pfl?sterer wrote: >> Without a little bit cheating you will have more verbose code with >> Python. But that's nothing new nor should it be a hindrance (if the >> number of lines doesn't differ too much). > I recognize that... took me awhile to get used to, though. It's been a > long time since I've done serious C coding, and I've forgotten just how > much "magic" and assumption there is in Perl. When I first started That magic is one of the strengths of Perl but also a great weakness. You can write fast code (perhaps directly on the command line) but if that code happens to live in file and has to be maintained that magic can cause great headaches. [...] >> That would mean you had to rewrite the regexps a bit. Second you could >> use named groups (a nice thing in Python) instead of the numbers. >> Third you could write one or two functions which give you the terseness >> of Perl. > Terseness in the main code, yes... but overall I'd have to write more code > to develop functions which don't get used anywhere but here. Once only code is clearly not the greatest strength of Python. But if you used such an idiom more often you put that code in your private lib and import that where you need it. A little example where I would never think about using Python. I have a log file (from my News server with entries from rejected postings); as I pull news from more than one server there may be severall entries for the same message (same M-ID). To shorten the log I use awk like that: awk -F"\t" '{ if (mid[$8]++ == 0) print $0 }' The magic that associative arrays are created automagically and that the default value for an entry is 0 makes that task in awk extremly easy and short. I think in Perl you would write it nearly the same way. That's convenient on the command line but who cares for one or two more lines in a source file? Short code doesn't necessarily mean fast code (mostly it's the opposite). > I'm not following your code... I need to go read about groups. They can be very convenient if you have deeper nesting. > My primary purpose in posting was to be sure that I wasn't missing some > "obvious" solution. You didn't (at least IMO). Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Sun Nov 23 17:04:16 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 23 17:04:24 2003 Subject: [Tutor] sending both a filename and an argument from the command line In-Reply-To: <PM.8714.1069587598@pmweb7.uk1.bibliotech.net> Message-ID: <Pine.LNX.4.44.0311231352330.17654-100000@hkn.eecs.berkeley.edu> On Sun, 23 Nov 2003, Ben Vinger wrote: > > OK, thanks to that advice, it works, but behaves strangely. (it prints > the correct output, but also some comments and code to the console) > parser.add_option("--ip", dest="ip address to test", > help="example: python ip.py capture.txt --ip 66.218.71.109") Hi Ben, The 'dest' doesn't stand for "description", but "destination". We use it to tell Python what to name to use when it is storing the option. Try: parser.add_option("--ip", dest="ip", help="example: python ip.py capture.txt --ip 66.218.71.109") Take a look again at: http://www.python.org/doc/lib/optparse-store-action.html if you feel shaky on any of the parameters that add_option() can take. > options, argv = parser.parse_args(sys.argv) > > for line in fileinput.input(argv): > > if line.find(sys.argv[3]) > 0: > > print line The point of using optparse is to avoid having to touch sys.argv[3], for how do we know that the fourth parameter is the ip address parameter? What if the user does something like this: python ip.py --ip 66.218.71.109 capture.txt Once we parse our arguments using parse_args(), we can say something like: options.ip and that should get us the IP address. Take advantage of the work that optparse is doing for you. *grin* > The output of > > python ip.py capture.txt --ip 66.218.71.109 > > looks like this (note the unwanted lines from the script): Ah! Go back and edit the line: > for line in fileinput.input(argv): 'argv' probably still contains the name of the 'ip.py' script at the very beginning! So you'll probably want to slice argv[0] out. Something like: for line in fileinput.input(argv[1:]): should keep it from including itself as part of the input stream. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Nov 23 17:07:03 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 23 17:07:07 2003 Subject: [Tutor] Cookie help In-Reply-To: <1069460866.7005.5.camel@quercus> Message-ID: <Pine.LNX.4.44.0311231404250.17654-100000@hkn.eecs.berkeley.edu> On Fri, 21 Nov 2003, Conrad Koziol wrote: > Hey everyone I'm having some troubles retrieving cookies. The script im > using is: > > #/usr/bin/python > > import os > import Cookie > > cookies = Cookie.SimpleCookie() > cookies.load(os.environ['id']) > value = cookies['id'].value > print 'Content-type: text/html\n' > print value > > I set the cookie in another script. They are set as a SimpleCookie with > the values of username and id. The problem is the script returns an > error. (I don't quite have access to the error logs, at least yet). Any > help would be appreciated Hi Conrad, I think we'll need better error messages. Try adding this line right before the 'import os' line: ### import cgitb ### 'cgitb' is the 'CGI Traceback' module: if anything bad happens during the script, cgitb will intercept the error and try displaying a good error report to your browser. You can find out more about cgitb here: http://www.python.org/doc/lib/module-cgitb.html Good luck to you! From dyoo at hkn.eecs.berkeley.edu Sun Nov 23 17:11:42 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Nov 23 17:11:47 2003 Subject: [Tutor] Cookie help In-Reply-To: <Pine.LNX.4.44.0311231404250.17654-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0311231410240.17654-100000@hkn.eecs.berkeley.edu> > I think we'll need better error messages. Try adding this line right > before the 'import os' line: > > ### > import cgitb > ### Hi Conrad, Whoops. We need one more line in there: ### import cgitb cgitb.enable() ### Forgot to turn the darn thing on... *grin* Good luck to you! From klappnase at freenet.de Sun Nov 23 19:25:54 2003 From: klappnase at freenet.de (Michael Lange) Date: Sun Nov 23 19:32:24 2003 Subject: R: [Tutor] snack classes In-Reply-To: <DNEFLBNHCGCPPIGNHGILOEGADEAA.marta_andrea@libero.it> References: <20031123002647.72841fd6.klappnase@freenet.de> <DNEFLBNHCGCPPIGNHGILOEGADEAA.marta_andrea@libero.it> Message-ID: <20031124012554.04fe5193.klappnase@freenet.de> On Sun, 23 Nov 2003 11:34:28 +0100 "Andrea Valle" <marta_andrea@libero.it> wrote: > > As you can see, I'd like to use the Sig class derived from the Sound class > to make some sample manipulation, i.e. the function sine create a sinusoidal > signal, etc.. The sample method of Sound is really powerful. Hi Andrea, I put your code in a little script to try what happens: from Tkinter import * from tkSnack import * from math import * class Sig(Sound): def __init__(self): self.sec=2 self.length=44100*self.sec def sine(self): l=self.length for x in range(l): y=int(10000*sin(float(x)*50)) self.sample(x,y) return self def test(): root=Tk() initializeSnack(root) s = Sig() s.sine() root.mainloop() test() Running this in IDLE leads to: Traceback (most recent call last): File "/usr/local/share/test.py", line 28, in -toplevel- test() File "/usr/local/share/test.py", line 25, in test s.sine() File "/usr/local/share/test.py", line 18, in sine self.sample(x,y) File "/usr/lib/python2.2/site-packages/tkSnack.py", line 288, in sample return _cast(self.tk.call((self.name, 'sample', index) + opts)) AttributeError: Sig instance has no attribute 'tk' Well, of course there's no attribute "tk" in Sig, look at __init__: self.sec=2 self.length=44100*self.sec there are in fact only two integers there. So let's change this a little: from Tkinter import * from tkSnack import * from math import * class Sig(Sound): def __init__(self): Sound.__init__(self) self.sec=2 self.length=44100*self.sec def sine(self): l=self.length for x in range(l): y=int(10000*sin(float(x)*50)) self.sample(x,y) return self def test(): root=Tk() initializeSnack(root) s = Sig() s.sine() root.mainloop() test() Running in IDLE results in: Traceback (most recent call last): File "/usr/local/share/test.py", line 27, in -toplevel- test() File "/usr/local/share/test.py", line 24, in test s.sine() File "/usr/local/share/test.py", line 17, in sine self.sample(x,y) File "/usr/lib/python2.2/site-packages/tkSnack.py", line 288, in sample return _cast(self.tk.call((self.name, 'sample', index) + opts)) TclError: Index out of bounds Ah, we've come farther :) "Index out of bounds" seems to tell us that we were trying to access data that don't exist - of course our SIG object doesn't contain any data yet. So let's feed some data to Sig: from Tkinter import * from tkSnack import * from math import * class Sig(Sound): def __init__(self): Sound.__init__(self) self.sec=2 self.length=44100*self.sec self.load('/home/pingu/phonoripper/test_2.wav') def sine(self): l=self.length for x in range(l): y=int(10000*sin(float(x)*50)) self.sample(x,y) return self def test(): root=Tk() initializeSnack(root) s = Sig() s.sine() root.mainloop() test() No more error messages! However except of computing a while not much happens, so let's finally do it something: from Tkinter import * from tkSnack import * from math import * class Sig(Sound): def __init__(self): Sound.__init__(self) self.sec=2 self.length=44100*self.sec self.load('/home/pingu/phonoripper/test_2.wav') def sine(self): l=self.length for x in range(l): y=int(10000*sin(float(x)*50)) self.sample(x,y) return self def test(): root=Tk() initializeSnack(root) s = Sig() s2 = s.sine() s2.play() s2.write('/home/pingu/phonoripper/sig_test.wav') root.mainloop() test() Success, it computes a while, beeps 2 seconds and writes a file that when opened beeps 2 seconds again. I'm afraid I'm not one of the "gurus" here, so I can't explain about class definitions very well, but I hope this helped anyway. Cheers Michael From carroll at tjc.com Sun Nov 23 20:50:32 2003 From: carroll at tjc.com (Terry Carroll) Date: Sun Nov 23 20:50:38 2003 Subject: [Tutor] Preserving timestamps when DLing with ftplib / gzip? Message-ID: <Pine.LNX.4.44.0311231742320.2066-100000@violet.rahul.net> I have an application that uses a series of files that I need to refresh from an FTP server once in a while, to stay current. When I do this manually, I use ncftp to FTP the six files, which are in gzip form, and then gunzip them to another directory. When I do this, the downloded .gz files have the same timestamp that they had on the server, and then the uncompressed files also have that same timestamp. Rather than do this manually, I'm trying to use python to do this. It's fairly straightforward, I find, to use the ftplib and gzip modules to do the transfer and decompress, respectively, but both the FTP'd files and the uncompressed files have the current timestamp, not the one from the server. This is to be expected, since in both cases, I'm just opening the output files from within python. I'd like to preserve that timestamp, the same way that the ncftp/gunzip manual process does. Is there a way to do this? I suppose I'd first have to somehow use ftplib to find out the timestamp on the remote file, and then use some sort of interface to set it on the files I create, right? Or should I just give up on this and just invoke ncftp and gunzip from my program? I'm running WinXP. -- Terry Carroll Santa Clara, CA carroll@tjc.com From raven at phoenyx.net Sun Nov 23 21:13:22 2003 From: raven at phoenyx.net (Carl D Cravens) Date: Sun Nov 23 21:13:28 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <20031123193250.66125.qmail@web41804.mail.yahoo.com> References: <20031123193250.66125.qmail@web41804.mail.yahoo.com> Message-ID: <Pine.LNX.4.58.0311232007520.22937@lists.wirebird.com> On Sun, 23 Nov 2003, Daniel Ehrenberg wrote: > There is a major difference in the philosophies of > Perl and Python. Among other things, the Pearl doesn't > have nearly as many standard libraries as Python does > because they believe that things should be in > seperate, user-made libraries, or just reimplimented > in the individual program. I really don't think I can agree with this. The core Perl5 install comes with a great number of modules. cpan.org is overflowing with modules of all kinds. In looking at switching to Python for larger projects, one of my worries has been a _lack_ of modules to draw on compared to Perl. > With Python, unless you have a specific goal of creating a faster > library or something (in which case you'd probably use C anyway), it > really doesn't make sense to reimpliment things. The availability of > these libraries should be taken into account when considering how easy > it would be to make one of these programs. If there is no similar > library in Perl, that doesn't mean you should write the Python program > poorly. My goal is to learn Python, not to create a solution to a problem. The program I chose to reproduce just happened to do something an existing module already does. If I used that module, I'd be defeating the purpose of writing the program, which is to learn how to process text from a file and see how it compares to what I already know in Perl. If I let a module do all the work for me, I do not learn what I set out to learn. -- Carl D Cravens (raven@phoenyx.net) Hey, I ran Windows the other day, and it didn't crash! From raven at phoenyx.net Sun Nov 23 21:15:55 2003 From: raven at phoenyx.net (Carl D Cravens) Date: Sun Nov 23 21:15:59 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <m3y8u6ubdd.fsf@hamster.pflaesterer.de> References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com> <m3vfpcl933.fsf@hamster.pflaesterer.de> <Pine.LNX.4.58.0311231227200.17524@lists.wirebird.com> <m3y8u6ubdd.fsf@hamster.pflaesterer.de> Message-ID: <Pine.LNX.4.58.0311232014230.22937@lists.wirebird.com> Thanks for everyone's input on this. I believe my question was answered adequately. Now I just need a bigger project to work on. Thanks! -- Carl D Cravens (raven@phoenyx.net) The modems canno' stand the strain, captain! From alan.gauld at blueyonder.co.uk Sun Nov 23 23:59:03 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 23 23:58:59 2003 Subject: [Tutor] Regex's and "best practice" References: <Pine.LNX.4.58.0311211941470.4267@lists.wirebird.com><20031122223116.GA19009@nl.linux.org> <Pine.LNX.4.58.0311231243190.17524@lists.wirebird.com> Message-ID: <004901c3b247$ae5b7f80$6401a8c0@xp> > I wrote the original script back in '86 on Perl 4. I don't think there > were any public mail libraries (modules didn't exist with Perl 4) at the > time, or I'd have just taken that approach with the Perl script as well. I assume you mean '96? Perl wasn't around in 86, let alone Perl 4. And in '96 Python already had a basic email handling capability... :-) Batteries included etc. > But let's drop down a level and say I'm writing a mailbox module. I'd > probably still be using regexes, because trying to extract what I'm > looking for without them would be rather tedious. Probably, although you might decide to do it in raw C... :-) But seriously the Pythonic route is to use the module not the regex. regex's are used heavily in Perl because its so good at them, but they are just not used as often in Python because there is often an alternative approach, usually involving a parsing module of some sort... Alan G. "When all you have is a hammer every problem looks like a nail." From dyoo at hkn.eecs.berkeley.edu Mon Nov 24 02:45:19 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 24 02:45:37 2003 Subject: [Tutor] Regex's and "best practice" [libraries and finding third-party resources] In-Reply-To: <Pine.LNX.4.58.0311232007520.22937@lists.wirebird.com> Message-ID: <Pine.LNX.4.44.0311232326250.31981-100000@hkn.eecs.berkeley.edu> > > There is a major difference in the philosophies of Perl and Python. > > Among other things, Perl doesn't have nearly as many standard > > libraries as Python does because they believe that things should be in > > seperate, user-made libraries, or just reimplimented in the individual > > program. > > I really don't think I can agree with this. The core Perl5 install > comes with a great number of modules. cpan.org is overflowing with > modules of all kinds. Hi Carl, Very true; if we had to name one real strength in Perl, we'd have to name the CPAN. Good programmers know when to reuse code, and that's something that's universal, regardless of what programming language we're using. The Perl community has done a lot to cultivate that kind of centralized code sharing, and it's something we can admire and seek to emulate. > In looking at switching to Python for larger projects, one of my worries > has been a _lack_ of modules to draw on compared to Perl. If the Standard Library: http://www.python.org/doc/lib/ lacks some functionality that you're looking for, there are repositories for third-party modules that you can explore. PyPi is one of the evolving repositories for Python code: http://www.python.org/pypi There's also the venerable "Vaults of Parnassus": http://www.vex.net/parnassus/ Finally, there's another repository for "Useless" code that you might have some fun with: http://www.uselesspython.com/ Please feel free to ask more questions. Good luck! From dyoo at hkn.eecs.berkeley.edu Mon Nov 24 02:59:30 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 24 02:59:36 2003 Subject: [Tutor] Regex's and "best practice" In-Reply-To: <Pine.LNX.4.58.0311231240360.17524@lists.wirebird.com> Message-ID: <Pine.LNX.4.44.0311232351210.31981-100000@hkn.eecs.berkeley.edu> > > I would call it a fair solution. Perl is very hard to beat on the > > regex front simply because regular expressions are in the language, > > not a module. > > It seems that they could be a bit less clunky. It's counter-intuitive > that match() and search() allow including flags, but to use flags with > sub() you have to compile() the regex first. Hi Carl, It is possible to include flags as part of the pattern. Here's one example that does a case-insensitive substitution: ### >>> re.sub("Z(?i)", " ", "ThisziszaZtest") 'This is a test' ### This is similar to the Perl code: my $msg = "ThisziszaZtest"; $msg =~ s/Z/ /ig; and most of the other familiar Perl flags should work with Python's regular expressions too. We can find information about the rest of the (?...) flags here: http://www.python.org/doc/lib/re-syntax.html > > For a sysadmin, I think the win with python is the ease of writing > > reusable modules that are tailored for your system. I presumme you > > understand Python's if __name__ == '__main__': > > I've only been doing this for a few days, so I haven't run across this. > Sounds useful, though, and I'll keep it in mind. Since you've done some Perl programming already, you might find this useful: http://diveintopython.org/ It's Mark Pilgrim's Python tutorial, geared toward experienced programmers; I think you'll enjoy it. Best of wishes to you! From comber at cix.co.uk Tue Nov 18 05:51:17 2003 From: comber at cix.co.uk (Edward Comber) Date: Mon Nov 24 03:12:25 2003 Subject: [Tutor] Accessing the name of an instance variable In-Reply-To: <qj1frvof6e9k1oika0trrai9k4dih6mcsm@4ax.com> Message-ID: <BEEOLJNPLOPIONOMGLAACEHGCIAA.comber@cix.co.uk> To explain why I want to this sort of thing - I have derived a simple language for my partners to use in our medical practice by subclassing the Python container classes. They don't program themselves but can easily handle these classes which extract and manipulate groups of patients depending on diseases. A definition takes the form of.. non_smoker_group = DiseaseCode(['1371','137L','137P0','137S','137T']) which extracts matching patients from the DB. I want them to be able to do some simple debugging by outputting the contents of the containers preceded by the container name, so they can check that the codes they have used are correct (by doing a lookup in another DB). I can do this of course by explicitly stating the container name: describe_disease_group('non_smokerR',non_smoker_group) but it would be nicer and more fool-proof to incorporate it in container behaviour like non_smoker_group.describe() Eddie. -----Original Message----- From: Goncalo Rodrigues [mailto:op73418@mail.telepac.pt] Sent: 16 November 2003 14:33 To: Edward Comber; tutor@python.org Subject: Re: [Tutor] Accessing the name of an instance variable On Sun, 16 Nov 2003 13:53:41 -0000, you wrote: >Thanks Goncalo. I have sorted something out with the below, but it won't >work from another module (see further below). > >The purpose is to print a description of the objects created for third party >users of my code. > >Eddie. > >class A: > def __init__(self,x,y): > self.one = x > self.two = y > > def describe(self): > print 'Describing' > this_instance = id(self) > for name, instance in globals().items(): # vars() > print name > if isinstance(instance,A): > if id(instance) == this_instance: > print 'Description of', name > >#pp.pprint(read_code_helper.helper.description(self)) > print self.one, self.two > >if __name__ == '__main__' : > > a = A(1,2) > b = A(1001,1002) > > a.describe() > b.describe() > > >import get_name > >a = get_name.A(1,2) > >a.describe() #dosen't pick up the name, presumably a scoping issue. > > Yes, I forgot to add that globals is really only *module-level* globals. From comber at cix.co.uk Tue Nov 18 10:36:01 2003 From: comber at cix.co.uk (Edward Comber) Date: Mon Nov 24 03:12:47 2003 Subject: [Tutor] Accessing the name of an instance variable In-Reply-To: <48bkrvoq6i6ap4t35okj3fks3p2eeil3or@4ax.com> Message-ID: <BEEOLJNPLOPIONOMGLAAAEHJCIAA.comber@cix.co.uk> ah, yes. But the point of it all is to get the actual variable name. This is so when the contents of the container is printed the variable name as it appears in the program is also printed for debugging (or proof-reading would be better description). I think what I will do is write it all in a simple one-module script so the variable names are available via globals(). That will do for proof-reading. Eddie. -----Original Message----- From: Goncalo Rodrigues [mailto:op73418@mail.telepac.pt] Sent: 18 November 2003 14:52 To: Edward Comber; tutor@python.org Subject: Re: [Tutor] Accessing the name of an instance variable On Tue, 18 Nov 2003 10:51:17 -0000, you wrote: >To explain why I want to this sort of thing - I have derived a simple >language for my partners to use in our medical practice by subclassing the >Python container classes. They don't program themselves but can easily >handle these classes which extract and manipulate groups of patients >depending on diseases. > >A definition takes the form of.. > >non_smoker_group = DiseaseCode(['1371','137L','137P0','137S','137T']) > >which extracts matching patients from the DB. > >I want them to be able to do some simple debugging by outputting the >contents of the containers preceded by the container name, so they can check >that the codes they have used are correct (by doing a lookup in another DB). Excellent. > >I can do this of course by explicitly stating the container name: > >describe_disease_group('non_smokerR',non_smoker_group) > >but it would be nicer and more fool-proof to incorporate it in container >behaviour like > >non_smoker_group.describe() > Great but what does that got to do with messing with globals? Let me go back a little and repost the example you posted a while back: class A: def __init__(self,x,y): self.one = x self.two = y def describe(self): print 'Describing' this_instance = id(self) for name, instance in globals().items(): # vars() print name if isinstance(instance,A): if id(instance) == this_instance: print 'Description of', name The describe method, as you code it, is very bizarre. What you seem to be doing is to go through the global names to *find the instance itself* and then print a description. Don't do that, there is no need! The first argument being called self is a clue... :-) Bear with me a little. When you do the following #Create an A instance. a = A(1, 2) #Describe it. a.describe() The last line is equivalent to: A.describe(a) So that, as you can see, when the describe method is called the self argument is set to the instance itself. So describe can be coded just as def describe(self): print "Describing" print "Description of", self No need to grovel through the globals to find the instance, since the instance is supplied as... self :-) Just one more note: It is better for a method like describe to return "something that can be printed" (a string) instead of print-ing directly. That way you can combine describe with other methods, compose fancier descriptions, etc. def describe(self): return "Describing\n" + "Description of " + repr(self) etc., etc. If you need more help just holler. With my best regards, G. Rodrigues P.S: Consider reading the tutorial coming with every Python distro or reading some of the online tutorials to learn more about objects, for example, A. Gauld's is great. He is also on this list so you can always try to squeeze more information out of him if my attempts at explanation are too unnerving :-) From alan.gauld at freenet.co.uk Wed Nov 19 04:45:21 2003 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 24 03:13:01 2003 Subject: [Tutor] Re: informaton about some specific variable locaton ... does computer needs two informations ??? References: <01d501c3ad97$d09a5cb0$c54648d9@mz9s680eu689tz> <002f01c3adc3$6d7be550$6401a8c0@xp> <006c01c3ae72$58c66e50$ae4648d9@mz9s680eu689tz> Message-ID: <005201c3ae81$d9402620$6401a8c0@xp> ----- Original Message ----- From: "Tadey" <tayiper@volja.net> To: "Alan Gauld" <alan.gauld@freenet.co.uk> Sent: Wednesday, November 19, 2003 7:53 AM Subject: informaton about some specific variable locaton ... does computer needs two informations ??? > I have read some book about programming languages in general, and in chapter > about variables, it says something like (I had to translate it from > Slovenian - as accurate as I could) > > > START < > > Access to certain location in memory is possible by addressing this location > ... > Adress could be the name of "variable" (Note: with variable, here meaning > just a number which could change - more like in math, not programming term > variable) or "pointer" ("index", "indicator"). In programming languages the > name of "variable" (again math term) could means value, which is stored on > this location, from which we read this value, or it means the adress of > location, where we want to store (assign) the new value. ??? equivocality > ??? > > (Note -> the important part) The name of "pointer" also could represent > value or adress, but not the (Note: probably adress of ...) location, where > this pointer indicates to, but but location, where the value of pointer is > stored. ??? equivocality again ??? > > > END OF TEXT < > > > So, as I understand this tex wants to say, that when for example assigning > number (value) 4 to valiable a (a = 4), there are actually two informations, > which are important, which computer stores ... > > one is: > - that on location a, value 4 is stored ... > > and second: > - that this specific physical location in memory is "called", "assigned" as > variable a (by us) ... Absolutely correct. However how variables are implemented varies a lot between programming languages. Python, internally, uses a dictionary for variables. So a variable name is simply a lookup key to a dictionary and the value is whatever is held against that key. You can think of an assignment a = 42 As being almost the same as Variables['a'] = 42 Where Variables is the Python variable dictionary. Its not quite as simple as that but not much more complicated either. However languages like C actually allocate a bit of computer memory to a variable so that int a = 42; actually allocates enough memory to hold an integer and binds the name 'a' to its address. Then the assinment actually sets that menory location to hold 42. > ... which is something, computer should also remember to recognize some > location as "named" as a ("the value of pointer"), beside knowing the value > of that location. This hopefully explains why C has a notion of pointers as well as variables, because a variable can be defined to hold a memory address. That address can be the address of another variable. int* b = a Allocates enough memory to hold an address and binds the name 'b' to that address, it then fills the address with the address of 'a'. Python doesn't need to do that since variables are dictionary keys so that all variables are in effect pointers to the real data (which can be of any type). > Please, tell me, if I am right, ... some variables > like, a, b, c, d, etc. are fixed, default - meaning that a or b or c always > points to only one, and only one certain physical location in memory) ?!? In languages like C that's true, in Python (and some other languages) it is slightly different. To be honest trying to think of variables at that level of detail as a beginner is probably just confusing. In my tutorial I use the example of a postal sorting office. The data is what gets put in the boxes and the variables are the labels stuck on the front of the boxes. Data in a box without a label gets thrown in the garbage. That's a pretty accurate illustration of how Python does things. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From krazie_mu_boi at hotmail.com Wed Nov 19 20:13:09 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Mon Nov 24 03:13:11 2003 Subject: [Tutor] Python game - robot Message-ID: <Sea2-F54wXbY8UvYl2G00003df1@hotmail.com> I'm 3/4 through programming this game - a player in the middle, robots chase you. Player touch robot, player dies. Robot touch each other, they die. But I got stuck to the part where they "teach" you how to make multiple robots. They said use an empty list, but I simply don't get it. This is from the livewire package :www.livewires.org.uk/python . Worksheet 5- robot. _________________________________________________________________ ¦b±zªº¦æ°Ê¸Ë¸m¤W¶Ç°e±µ¦¬ Hotmail ¶l¥ó¡A½Ð²¾¦Ü: http://zh-asiasms.mobile.msn.com From jgrubich at fieldmuseum.org Thu Nov 20 15:48:38 2003 From: jgrubich at fieldmuseum.org (JGrubich) Date: Mon Nov 24 03:13:22 2003 Subject: [Tutor] (no subject) Message-ID: <a0600200dbbe2d903a49d@[10.10.25.250]> Hi, I'm just starting programming and I really like the ease of python. Unfortunately I'm so inept yet that I can't figure out how to get my program to accept string arguments and them print them out....it will only take numbers? Do I need to import something first to allow keyboard input in the form of words... -- ================================================================== Justin Grubich, PhD Div. of Fishes The Field Museum of Natural History 1400 S. Lakeshore Dr. Chicago, IL 60605, USA phone: 312-665-7755 fax: 312-665-7932 e-mail: jgrubich@fmnh.org ================================================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031120/d895f69e/attachment.html From alan.gauld at freenet.co.uk Fri Nov 21 01:52:00 2003 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Nov 24 03:13:32 2003 Subject: [Tutor] Re: 3 simple, pithy and short questions, releated to previous answers of yours ... References: <003b01c3afe7$e4dfe350$154f48d9@mz9s680eu689tz> Message-ID: <008c01c3affb$f6edaf50$6401a8c0@xp> Tadey, > So to "allocate" my questions reasonably, I am sending question > about in-built help to Danny Yoo, the other guy from Python Tutor > (you probably know him) ... You are better to semd all questions to the tutor list. That way anyone on the list can answer so if Danny or I are busy or unavailable you get an answer quicker. Also other beginners can learn from the answers to your questions. Finally, by getting answers from more than one person you get different points of view which sometimes helps you see the answer quicker. > 1.) What is the difference (in general) between [] and () brackets. In general [] indicates a list and () a tuple. a tuple is very like a list except you cannot change the contents once created. This allows us to use a tuple as the lookup key to a dictionary(see below) > For example in for loops with range function in examples bellow there > are the same results. range() always returns a list. However you can do for n in (1,2,3) or for n in [1,2,3] and there is no difference because for lopps over a *collection* (or sequence) and lists, tuples, strings (and since v2,2 dictionaries) are all sequences in Python. > I understand also that one creates an arrow of object in string > (or something like that), other creates the list, but could you explain > shortlly the (practical) difference ?!? Sorry, not sure wjat you mean there. Can you reword it? Or give an example? > P.S., And there are also {} brackets - what is their part {} indicate a dictionary. That is a collection of pairs of data. One ite in the pair is the lookup key, the other the return value. In a real dictionary the lookup wouldbe a word and the value the meaning. But in programming the lookup can be any *immutable*(or unchangeable) value and the "definition" data can be anything at all. So: [] => a list () => a tuple {} => a dictionary To add to the confusion, we use [] to access the data for all three! t = (1,2,3) L = [4,5,6] d = {7:8,9:0} print t[0],L[0],d[7] # prints 1 4 8 And of course we use () to hold the arguments to functions and to group mathematical terms in an expression. (5+6) * 3 etc... > So I made some more examples of that kind of code and something > seemed clear - that number 4 means, that loop is "jumping-over 4" from 1 to 10. That's right, the last argument in range() is the size of step between values. > 3.) I noticed, that examples below (after typing print a, and print b) > give identical results, so is it really so, that there is no difference, > creating string or tuple, if using brackets, or if not ?? > s = 1,2,3 ... and ... s = (1, 2, 3) > b = "ww", "aa" ... and ... b = ("ww", "aa") There are some subtle differences but in the main tuples can hold anything whereas strings can only hold characters. Othewise they are very similar. This might be where you get a better answer from another tutor member. (I'm off to catch a plane in 15 minutes!) Take care, Alan G. From clay at ernie.webservepro.com Fri Nov 21 10:04:17 2003 From: clay at ernie.webservepro.com (Clay Shirky) Date: Mon Nov 24 03:13:39 2003 Subject: [Tutor] string.unprintable? Message-ID: <BBE393A1.120DC%clay@ernie.webservepro.com> I want to loop over a file with some printable and some binary lines, printing the former. What I really want is for line in file("spam"): if string.unprintable in line: continue print line but there is no string.unprintable, and if not string.printable in line for some reason matches everything in the file, even though I've .strip()ed the line aready. -clay From xuw6 at univmail.cis.mcmaster.ca Fri Nov 21 22:26:01 2003 From: xuw6 at univmail.cis.mcmaster.ca (W. Xu) Date: Mon Nov 24 03:13:44 2003 Subject: [Tutor] Why I can't use scipy.plt.plot? Message-ID: <web-9985507@cgpsrv2.cis.mcmaster.ca> I installed Python-2.2.3, win32all-162, wxPythonWIN32-2.4.2.4u-Py22, Numeiric-22.0.win32-py2.2, SciPy-0.2.0_alpha_210.4077.win32-py2.2 but when I used scipy.plt.plot, an system error came out. I am just learning how to use plt and gplt, and not necessarily use plt. Thank you From lkvam at venix.com Sat Nov 22 10:14:08 2003 From: lkvam at venix.com (Lloyd Kvam) Date: Mon Nov 24 03:13:49 2003 Subject: [Tutor] Re: Numbers do support __str__() in recent versions of Python In-Reply-To: <Pine.LNX.4.44.0311211633280.28305-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311211633280.28305-100000@hkn.eecs.berkeley.edu> Message-ID: <3FBF7D40.70405@venix.com> Danny Yoo wrote: > > On Fri, 21 Nov 2003, Danny Yoo wrote: > Numbers do support __str__(). Again, my apologies for giving totally off > advice. I think I need a vacation... *grin* > > Good luck! > > Danny, I don't know how you find the time for your long, detailed responses. My shorter note took nearly twenty minutes. You are nearly always right on the mark. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From kpp9c at virginia.edu Mon Nov 24 03:02:53 2003 From: kpp9c at virginia.edu (kevin parks) Date: Mon Nov 24 03:13:54 2003 Subject: [Tutor] silly remedial question Message-ID: <9B2F7D6C-1E54-11D8-A7C6-003065555ABC@virginia.edu> Hi folks! I am trying to do something that seems rather simple, but perhaps is something i haven't done before or forgot... I have a function that does something to sequence and returns a sequence. Now i call that function a bunch of times one a whole bunch of lists and i get my output which is very nice. Problem is, that i want to make that output more humanly readable form by first printing the name of the list variable followed by a ' = ' and then the items in the list. so if sequence input_01 = [22, 25, 31] and i write something that returns the mod 12 equivalent of each item in a new list [10, 1, 7] i can print [22, 25, 31] and [10, 1, 7] but how can i get it to say : input_01 = [22, 25, 31], [10, 1, 7] Without saying: print 'input_01 =', input_01 for each input list. I can print the input and output lists no problem, but how do you tell python to print the variable itself.. I don't want to do this by hand as i have a huge bunch of list that i have to do this to that are already sitting in a text file. Not sure i made this clear or not... cheers, kevin From kp8 at mac.com Mon Nov 24 03:12:02 2003 From: kp8 at mac.com (kevin parks) Date: Mon Nov 24 03:14:03 2003 Subject: [Tutor] silly remedial question Message-ID: <E219154B-1E55-11D8-A7C6-003065555ABC@mac.com> Hi folks! I am trying to do something that seems rather simple, but perhaps is something i haven't done before or forgot... I have a function that does something to sequence and returns a sequence. Now i call that function a bunch of times one a whole bunch of lists and i get my output which is very nice. Problem is, that i want to make that output more humanly readable form by first printing the name of the list variable followed by a ' = ' and then the items in the list. so if sequence input_01 = [22, 25, 31] and i write something that returns the mod 12 equivalent of each item in a new list [10, 1, 7] i can print [22, 25, 31] and [10, 1, 7] but how can i get it to say : input_01 = [22, 25, 31], [10, 1, 7] Without saying: print 'input_01 =', input_01 for each input list. I can print the input and output lists no problem, but how do you tell python to print the variable itself.. I don't want to do this by hand as i have a huge bunch of list that i have to do this to that are already sitting in a text file. Not sure i made this clear or not... cheers, kevin --^---------------------------------------- k p 8 at m a c . c o m From the_investor at ziplip.com Mon Nov 24 03:24:14 2003 From: the_investor at ziplip.com (the_investor) Date: Mon Nov 24 03:25:32 2003 Subject: [Tutor] Starting with Python Message-ID: <FTLVBZHVPUDXPTPTECH2MLH1AMB5KDGJAIEMKKFY@ziplip.com> Hello all! I am a beginner to the Python languasge and after spending many hours behind the screen with MS Excel I have finally came to the realisation that I need to take the next step by learning a computer language. I started with VB.NET but likened it to me sitting in a pilot's seat - and I don't know anything but flying bar flapping my arms!! So far I have floated around many of the beginner's stuff and can somewhat confidently state that I know a little of the basics. Now for the reason of this post... I want to take the next big leap by giving myself a *difficult* assignment on changing a simple spreadsheet that I created many moons ago and forming it into a Python program. Unfortunately there is a heap of stuff out there and someone like me can get caught up chasing their tail just in finding a suitable IDE! Anyhow, in closing... Let's say, for now, I wish to create a simple line chart from a static table plotting X & Y values (something which is simple for me to do in Excel)... where best to dive into (databases? wx?...)? Or have I totally dove into the deep end!!!! Thanks, R From intatia at paradise.net.nz Mon Nov 24 03:52:44 2003 From: intatia at paradise.net.nz (Intatia) Date: Mon Nov 24 03:54:02 2003 Subject: [Tutor] (no subject) In-Reply-To: <a0600200dbbe2d903a49d@[10.10.25.250]> References: <a0600200dbbe2d903a49d@[10.10.25.250]> Message-ID: <3FC1C6DC.6090503@paradise.net.nz> >>> a = raw_input() Hello World! >>> print a Hello World! That should give you some ideas:) JGrubich wrote: > Hi, I'm just starting programming and I really like the ease of python. > Unfortunately I'm so inept yet that I can't figure out how to get my > program to accept string arguments and them print them out....it will > only take numbers? Do I need to import something first to allow > keyboard input in the form of words... > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Mon Nov 24 07:46:52 2003 From: project5 at redrival.net (Andrei) Date: Mon Nov 24 07:49:28 2003 Subject: [Tutor] Re: Starting with Python References: <FTLVBZHVPUDXPTPTECH2MLH1AMB5KDGJAIEMKKFY@ziplip.com> Message-ID: <11xu5rrrbolpn$.1rseklz84whg6.dlg@40tude.net> the_investor wrote on Mon, 24 Nov 2003 00:24:14 -0800 (PST): Hi, <snip> > I want to take the next big leap by giving myself a *difficult* assignment > on changing a simple spreadsheet that I created many moons ago and forming > it into a Python program. > > Unfortunately there is a heap of stuff out there and someone like me can > get caught up chasing their tail just in finding a suitable IDE! For minimal fuss: SciTE (http://scintilla.org) or the PythonWin IDE if you're on Windows (get the ActiveState Python distro because it includes PythonWin and very good docs (http://activestate.com/Products/ActivePython/ and click on the big red Download button in the upper left part of the screen). > Let's say, for now, I wish to create a simple line chart from a static > table plotting X & Y values (something which is simple for me to do in > Excel)... For this kind of really simple stuff, nothing beats spreadsheets, even if it were just for the overhead of typing commas en parentheses in Python which you don't have to do in a spreadsheet - right tool for the right job and all that. That being said, if we're talking about data you don't type in yourself and the graph is part of a larger application which does other processing too, you should look into one of the plotting packages. > where best to dive into (databases? wx?...)? Start small, no databases -Python data structures are sufficient- and no wxPy. Learn Python basics with one of the tutorials (http://www.python.org/topics/learn/non-prog.html) - it's an easy language to pick up. Given your example, I'd first learn to implement the mathematical part of a spreadsheet in Python and only then worry about plotting the results. Once you know how things work in Python, go and try the plotting packages. The ones I know of are wxPyPlot (http://www.cyberus.ca/~g_will/wxPython/wxpyplot.html), Chaco (http://www.scipy.org/site_content/chaco/intro) and Gnuplot from SciPy (http://www.scipy.org/site_content/tutorials/plot_tutorial). Gnuplot would be a good starting point I think if you don't want to get into GUI stuff, it's easier than learning wxPython. > Or have I totally dove into the deep end! Plotting with Python is not as easy as it is with a spreadsheet because the to a spreadsheet plotting is a primary function - a few clicks and you've got a plot, but to Python it isn't. Not that it's hard to do, but it requires more manual work initially. Oh, almost forgot: there's a Python shell called Psi which *does* have some built-in plotting abilities. Perhaps it's a good way to learn Python and do plotting at the same time. You can find it here: http://www.chez.com/spinecho/pypsi/pagpypsi.htm. -- 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 bvinger at postmaster.co.uk Mon Nov 24 08:46:38 2003 From: bvinger at postmaster.co.uk (Ben Vinger) Date: Mon Nov 24 08:46:44 2003 Subject: [Tutor] sending both a filename and an argument from the command line Message-ID: <PM.26539.1069681598@pmweb15.uk1.bibliotech.net> Danny Thanks, it was all as you said, and now works fine. It's amazing to get fine advice like this for free! Ben ___________________________________________________ Web-based office space for rent. Free trial! http://www.officemaster.net From Janssen at rz.uni-frankfurt.de Mon Nov 24 09:25:43 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Nov 24 09:25:58 2003 Subject: [Tutor] silly remedial question In-Reply-To: <E219154B-1E55-11D8-A7C6-003065555ABC@mac.com> References: <E219154B-1E55-11D8-A7C6-003065555ABC@mac.com> Message-ID: <Pine.A41.4.56.0311241451290.80860@hermes-22.rz.uni-frankfurt.de> On Mon, 24 Nov 2003, kevin parks wrote: > I can print the input and output lists no problem, but how do you tell > python to print the variable itself.. You can do it for *function* via their __name__ attribute: def f(): pass print f.__name__ but variables havn't got such a attribute (they have no attributes at all - it makes no sense to speak of an "attribute of a variable"). I believe, it's not possible, to retrieve to name of a variable. You should better store your list within a dictionary (i.e. a mapping from keys to values, in this case from names to lists): d = { "name1": []; "name2": []; ..... } Now your task is easy: for key in d.keys(): print key, print d[key] In case you can't rebuild your lists into a dictionary, you can (mis)use the globals-dictionary: d = globals() for key in d: if type(d[key]) == type([]): print key, print d[key] this will print out every list within global namespace (type "globals()" on an interactive prompt, to get an idea what this means). Since the globals-dictionary contains every list that is assinged it might print out unwanted stuff. Regard this as a "bad hack" and try to write programs, that don't need to get the "name of a variable". Michael From glingl at aon.at Mon Nov 24 11:37:33 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Nov 24 12:10:08 2003 Subject: [Tutor] silly remedial question In-Reply-To: <Pine.A41.4.56.0311241451290.80860@hermes-22.rz.uni-frankfurt.de> References: <E219154B-1E55-11D8-A7C6-003065555ABC@mac.com> <Pine.A41.4.56.0311241451290.80860@hermes-22.rz.uni-frankfurt.de> Message-ID: <3FC233CD.3080304@aon.at> Michael Janssen schrieb: >On Mon, 24 Nov 2003, kevin parks wrote: > > > >>I can print the input and output lists no problem, but how do you tell >>python to print the variable itself.. >> >> > >You can do it for *function* via their __name__ attribute: > >def f(): > pass > >print f.__name__ > > And even this may result in strange effects: >>> def f(): print "Hi!" >>> f.__name__ 'f' >>> def f(): print "Hi!" >>> f() Hi! >>> f.__name__ 'f' >>> g = f >>> g() Hi! >>> g.__name__ 'f' >>> del f >>> f() Traceback (most recent call last): File "<pyshell#29>", line 1, in -toplevel- f() NameError: name 'f' is not defined >>> g() Hi! >>> g.__name__ 'f' >>> This is so, because in Python different names can refer to the same object. So the question "which name refers to this object?" may have no unique answer. However there *is* a construct in Python, which can retrieve the string representation of names, namely keyword arguments of a function. It goes like this: >>> def pwn(**kwargs): # print with name for w in kwargs: print w, "=", kwargs[w] >>> a=2 >>> b=5 >>> c=[4,9,11] >>> pwn(a=a,b=b,c=c,d=[-1,0,1]) a = 2 c = [4, 9, 11] b = 5 d = [-1, 0, 1] >>> This performs more or less automatically what Michael suggested in a previous post. The only problem may be, that the order of the output is arbitrary, except you implement some sorting routine inside pwn, which is appropriate to your needs. Regards, Gregor From glingl at aon.at Mon Nov 24 12:06:34 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Nov 24 12:47:12 2003 Subject: [Tutor] silly remedial question Message-ID: <3FC23A9A.1090209@aon.at> Michael Janssen schrieb: >On Mon, 24 Nov 2003, kevin parks wrote: > > > >>I can print the input and output lists no problem, but how do you tell >>python to print the variable itself.. >> >> > >You can do it for *function* via their __name__ attribute: > >def f(): > pass > >print f.__name__ > > And even this may result in strange effects: >>> def f(): print "Hi!" >>> f() Hi! >>> f.__name__ 'f' >>> g = f >>> g() Hi! >>> g.__name__ 'f' >>> del f >>> f() Traceback (most recent call last): File "<pyshell#29>", line 1, in -toplevel- f() NameError: name 'f' is not defined >>> g() Hi! >>> g.__name__ 'f' >>> This is so, because in Python different names can refer to the same object. So the question "which name refers to this object?" may have no unique answer. However there *is* a construct in Python, which can retrieve the string representation of names, namely keyword arguments of a function. It goes like this: >>> def pwn(**kwargs): # print with name for w in kwargs: print w, "=", kwargs[w] >>> a=2 >>> b=5 >>> c=[4,9,11] >>> pwn(a=a,b=b,c=c,d=[-1,0,1]) a = 2 c = [4, 9, 11] b = 5 d = [-1, 0, 1] >>> This performs more or less automatically what Michael suggested in a previous post. The only problem may be, that the order of the output is arbitrary, except you implement some sorting routine inside pwn, which is appropriate to your needs. Regards, Gregor From dieck.s at dsoftware.de Mon Nov 24 03:45:38 2003 From: dieck.s at dsoftware.de (Stefan Dieck) Date: Mon Nov 24 13:43:10 2003 Subject: [Tutor] Writing BINARY-CONTENT Message-ID: <OFELLIKBJNEKFBIGDFFIIEDHCAAA.dieck.s@dsoftware.de> >> a = open('c:\\test.me', 'wb') # opens a file for binary writing >This is correct for writing binary. Are you sure that the program or editor >you're using to check this isn't opening the file in text mode (with 'r' >instead of 'rb')? Yes I'm sure to open in binary mode There is a huge problem around this: If I want write 256 "different" bytes. Python put 257 bytes to the File. On reading, the lenght is 256 bytes to work with. (-1) It seems like the size I expect, but the file on the disk has more bytes. (not really good for binaries) But such a behavior can corrupt my data. Isn't there a better or a fixed method to open and handle binaries? Thx, Stefan From dyoo at hkn.eecs.berkeley.edu Mon Nov 24 13:48:41 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 24 13:52:53 2003 Subject: [Tutor] Why I can't use scipy.plt.plot? In-Reply-To: <web-9985507@cgpsrv2.cis.mcmaster.ca> Message-ID: <Pine.LNX.4.44.0311241045150.23219-100000@hkn.eecs.berkeley.edu> On Fri, 21 Nov 2003, W. Xu wrote: > I installed Python-2.2.3, win32all-162, wxPythonWIN32-2.4.2.4u-Py22, > Numeiric-22.0.win32-py2.2, SciPy-0.2.0_alpha_210.4077.win32-py2.2 > > but when I used scipy.plt.plot, an system error came out. I am just > learning how to use plt and gplt, and not necessarily use plt. Hello, This is somewhat of a specialized question; we may be able to help you, but you may have better results if you ask help from the folks at the SciPy User mailing list: http://www.scipy.org/site_content/MailList The folks there all should have experience installing SciPy, so they're probably the best people to ask about your installation problem. When you ask the SciPy folks, can you be more specific what you mean by a system error? Do a cut-and-paste of the error message; this will help make it easier to figure out what is happening. Good luck to you! From mlong at datalong.com Mon Nov 24 14:08:19 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Mon Nov 24 14:08:27 2003 Subject: [Tutor] Question about Classes In-Reply-To: <3FC23A9A.1090209@aon.at> References: <3FC23A9A.1090209@aon.at> Message-ID: <.151.203.32.149.1069700899.squirrel@datalong.com> In an effort to understand how classes work I have created 2 classes. After importing the class I get the following error: >>> reload(Contact) <module 'Contact' from 'Contact.pyc'> >>> p=Contact.Contact(firstName='Joe', lastName='Blow') >>> p.showContactInfo() 'Joe Blow' >>> p.addEmail('mlong','datalong') Traceback (most recent call last): File "<stdin>", line 1, in ? File "Contact.py", line 10, in addEmail self.emails.append(seq) AttributeError: Contact instance has no attribute 'emails' My question is how do I initialize the variables in the class Email? Here are the class definitions: class Email: def __init__(self): self.emails=[] def showEmail(self): return self.emails def addEmail(self, email, type): seq = (type, email) self.emails.append(seq) class Contact(Email): def __init__(self ,firstName='' ,lastName='' ): """ Initial object """ self.firstName=firstName self.lastName=lastName def updateContact(self ,firstName ,lastName ): """ Save Contact Information """ self.firstName=firstName self.lastName=lastName def showContactInfo(self): return self.firstName + ' ' + self.lastName Thanks, Mike From gustabares at verizon.net Mon Nov 24 16:32:50 2003 From: gustabares at verizon.net (Gustavo Tabares) Date: Mon Nov 24 16:33:09 2003 Subject: [Tutor] Question about Classes In-Reply-To: <.151.203.32.149.1069700899.squirrel@datalong.com> References: <3FC23A9A.1090209@aon.at> <.151.203.32.149.1069700899.squirrel@datalong.com> Message-ID: <200311241632.50975.gustabares@verizon.net> Matt, By subclassing the class "Email", you are overwriting the __init__ function in the Email class. This means that the instance of Contact has no clue about the statement: self.emails = [] in the Email class. You can try placing this statement in the __init__ of Contact, or make it all one class, or whatever else you might think of. Gus On Monday 24 November 2003 14:08, mlong@datalong.com wrote: > In an effort to understand how classes work I have created 2 classes. After > > importing the class I get the following error: > >>> reload(Contact) > > <module 'Contact' from 'Contact.pyc'> > > >>> p=Contact.Contact(firstName='Joe', lastName='Blow') > >>> p.showContactInfo() > > 'Joe Blow' > > >>> p.addEmail('mlong','datalong') > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "Contact.py", line 10, in addEmail > self.emails.append(seq) > AttributeError: Contact instance has no attribute 'emails' > > My question is how do I initialize the variables in the class Email? > > > Here are the class definitions: > > class Email: > def __init__(self): > self.emails=[] > > def showEmail(self): > return self.emails > > def addEmail(self, email, type): > seq = (type, email) > self.emails.append(seq) > > > class Contact(Email): > def __init__(self > ,firstName='' > ,lastName='' > ): > """ Initial object """ > self.firstName=firstName > self.lastName=lastName > > def updateContact(self > ,firstName > ,lastName > ): > """ Save Contact Information """ > self.firstName=firstName > self.lastName=lastName > > def showContactInfo(self): > return self.firstName + ' ' + self.lastName > > > Thanks, > Mike > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From gustabares at verizon.net Mon Nov 24 16:34:00 2003 From: gustabares at verizon.net (Gustavo Tabares) Date: Mon Nov 24 16:34:14 2003 Subject: [Tutor] Question about Classes Message-ID: <200311241634.00535.gustabares@verizon.net> And that's Mike, not Matt. Sorry:) Gus From magnus at thinkware.se Mon Nov 24 16:35:12 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Nov 24 16:35:25 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUHJlc2VydmluZyB0aW1lc3RhbXBzIHdoZW4gRExpbmcgd2l0aCBmdHBsaWIgLyBnemlwPw==?= Message-ID: <think001_3fc274b478e04@webmail.thinkware.se> Terry Carroll wrote: > Is there a way to do this? I suppose I'd first have to somehow use ftplib > to find out the timestamp on the remote file, and then use some sort of > interface to set it on the files I create, right? That sounds reasonable. (Maybe there is a shortcut I don't know.) I don't know of a better way to get times than to do a directory listing and parsing the output. Did I miss something? To set times on the local side, use the os module: >>> import os >>> help(os.utime) Help on built-in function utime: utime(...) utime(path, (atime, utime)) utime(path, None) Set the access and modified time of the file to the given values. If the second form is used, set the access and modified times to the current time. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Mon Nov 24 16:43:36 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Nov 24 16:43:43 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gV3JpdGluZyBCSU5BUlktQ09OVEVOVA==?= Message-ID: <think001_3fc27aa7c48ab@webmail.thinkware.se> Stefan Dieck <dieck.s@dsoftware.de> wrote: > If I want write 256 "different" bytes. Python put 257 bytes to the File. > On reading, the lenght is 256 bytes to work with. (-1) > > It seems like the size I expect, but the file on the disk has more bytes. > (not really good for binaries) Really? This is Python 2.3.2 on Win NT: >>> f = file('x.bin', 'wb') >>> f.write('x'*25) >>> f.close() >>> import os >>> os.system('DIR') [snip] 03-11-24 22:37 25 x.bin [snip] 0 How are you writing data to the file? Can you show some code? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Mon Nov 24 17:08:41 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Nov 24 17:08:46 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gc3RyaW5nLnVucHJpbnRhYmxlPw==?= Message-ID: <think001_3fc27d864323d@webmail.thinkware.se> Clay Shirky <clay@ernie.webservepro.com> wrote: > if not string.printable in line > > for some reason matches everything in the file, even though I've .strip()ed > the line aready. Of course! string.printable is just a string with all the printable characters. "if not string.printable in line:" means "If the content of string.printable is not a substring of the string referred to as 'line'." >>> import string >>> print string.printable 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-/:;<=>?@[\]^_`{|}~ ♂♀ >>> string.printable in "Hello" False >>> string.printable not in "Hello" True >>> I think you want something like "If all of the characters in the line are in string.printable I want to print the line". That seems to require a loop... One version would be this: >>> def printIfPrintable(line): .. ok = True .. for char in line: .. if char not in string.printable: .. ok = False .. if ok: .. print line .. >>> printIfPrintable('Hello there') Hello there >>> printIfPrintable('Hello there\0x0f') >>> Here's a shorter version using reduce and list comprehension. >>> def printIfPrintable(line): .. import operator .. if reduce(operator.mul, [(x in string.printable) for x in line]): .. print line .. >>> printIfPrintable('Hello there') Hello there >>> printIfPrintable('Hello there\0x0f') >>> Without reduce: >>> def printIfPrintable(line): .. if [x for x in line if x in string.printable]==list(line): .. print line .. >>> printIfPrintable('Hello there\0x0f') >>> printIfPrintable('Hello there') Hello there >>> -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Mon Nov 24 17:24:31 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Nov 24 17:24:45 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUXVlc3Rpb24gYWJvdXQgQ2xhc3Nlcw==?= Message-ID: <think001_3fc28227024b6@webmail.thinkware.se> Hi Mike! Mike wrote: > In an effort to understand how classes work I have created 2 classes. One of the first thing you should know about classes is that inheritance means "is-a". In other words, by letting "Contact" inherit "Email" as you did in your code, you are claiming that a Contact is a kind of Email. I don't think you really see the world like that. I certainly don't. ;) This kind of misuse of class mechanisms will only cause grief. A contact might *have* emails. That implies composition, or an aggregate, that is, the person could have an emails attribute. Since the Email class seems to collect emails (plural), it seems it would be better to call is "Emails". If you use it through an "emails" attribute in the Contact, it seems a bit redundant to repeat the word "email" in the method names. (I think this long names just occured because your mistake with inheritance.) class Emails: def __init__(self): self._emails=[] def show(self): return self._emails def add(self, email, type): self._emails.append((type, email)) > class Contact(Email): > def __init__(self > ,firstName='' > ,lastName='' > ): > """ Initial object """ > self.firstName=firstName > self.lastName=lastName self.emails = Emails() > > def updateContact(self > ,firstName > ,lastName > ): > """ Save Contact Information """ > self.firstName=firstName > self.lastName=lastName > > def showContactInfo(self): > return self.firstName + ' ' + self.lastName Now you can do: p.emails.add('x', 'yyy') and p.emails.show() -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo at hkn.eecs.berkeley.edu Mon Nov 24 17:30:25 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 24 17:31:01 2003 Subject: [Tutor] Writing BINARY-CONTENT In-Reply-To: <OFELLIKBJNEKFBIGDFFIIEDHCAAA.dieck.s@dsoftware.de> Message-ID: <Pine.LNX.4.44.0311241421420.23219-100000@hkn.eecs.berkeley.edu> On Mon, 24 Nov 2003, Stefan Dieck wrote: > >> a = open('c:\\test.me', 'wb') # opens a file for binary writing > > >This is correct for writing binary. Are you sure that the program or > > editor you're using to check this isn't opening the file in text mode > > (with 'r' instead of 'rb')? > Yes I'm sure to open in binary mode > > There is a huge problem around this: > > If I want write 256 "different" bytes. Python put 257 bytes to the > File. On reading, the lenght is 256 bytes to work with. (-1) Hi Stefan, Hmmm... that sounds strange! Let's test this. ### >>> f = open("test_binary.bin", "wb") >>> for i in range(256): ... f.write(chr(i)) ... >>> f.close() >>> f = open('test_binary.bin', 'rb') >>> data = f.read() >>> len(data) 256 ### > It seems like the size I expect, but the file on the disk has more > bytes. (not really good for binaries) ### >>> import os >>> os.system('ls -l test_binary.bin') -rw-r--r-- 1 dyoo users 256 Nov 24 14:22 test_binary.bin 0 ### On my end, this appears to work consistantly. > But such a behavior can corrupt my data. Sure. But let's take another glance at the program that's doing the writing, just to make sure we're not missing something silly. *grin* Can you show us what program you used to write those bytes to disk? Perhaps a stray byte is getting passed into write()? Also, show us also how you're measuring the file size afterwards. With that information, One of us can then try to duplicate the problem on our end. Good luck to you! From magnus at thinkware.se Mon Nov 24 17:45:07 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Mon Nov 24 17:48:04 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gU3RhcnRpbmcgd2l0aCBQeXRob24=?= Message-ID: <think001_3fc2870b3a6d6@webmail.thinkware.se> > I am a beginner to the Python languasge and after spending many hours behind the screen with MS Excel I have finally came to the realisation that I need to take the next step by learning a computer language. I can certainly see your point! :) Excel is very useful for some things, but you tend to hit walls when you want to break out of its bonds. Welcome to the free world! :) > Let's say, for now, I wish to create a simple line chart from a static table plotting X & Y values (something which is simple for me to do in Excel).. where best to dive into (databases? wx?...)? This depends a lot on what you want to do with the plot. Andrei gave you some suggestions mainly for on-screen plotting, but if you want to make your plots available on the web, or put in some document, it's probably better to use a tool that creates a file, for instance a GIF or (better) PNG file. See for instance http://www.hpl.hp.com/personal/Yasushi_Saito/pychart/index.html For line charts, see http://www.hpl.hp.com/personal/Yasushi_Saito/pychart/doc/node2.html Just as with Excel, it's important not to reinvent the wheel! :) A complication with Python compared to Excel in a case like this is that you get som many different options to do these peripheral things that aren't in the core of Python. But you only need to learn one way if that way does what you need! :) See also http://starship.python.net/crew/jhauser/plot-res.html and http://www.thinkware.se/cgi-bin/thinki.cgi/PythonForImaging -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From thinkuknowme2007 at yahoo.com Mon Nov 24 19:08:27 2003 From: thinkuknowme2007 at yahoo.com (Udz) Date: Mon Nov 24 19:08:32 2003 Subject: [Tutor] convert to exe? Message-ID: <20031125000827.79647.qmail@web60203.mail.yahoo.com> hey, well this is sorta a stupid question, but i just started to program, so i dont know much. im learning python from an online source, but theres something i dont get. the interpreter works fine for all program testing purposes, but what after that? how do i convert the .py file to an executable .exe application that other people will be able to use? and whoever is going to explain this to me, do it in simple terms, im not exactly what ud call the ultimate computer genius. thanx, Udz --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031124/5cf26016/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Nov 24 19:51:00 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Nov 24 19:51:07 2003 Subject: [Tutor] convert to exe? In-Reply-To: <20031125000827.79647.qmail@web60203.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0311241645230.23744-100000@hkn.eecs.berkeley.edu> On Mon, 24 Nov 2003, Udz wrote: > im learning python from an online source, Hi Udz, Just wondering, what page are you learning from? > but theres something i dont get. the interpreter works fine for all > program testing purposes, but what after that? how do i convert the .py > file to an executable .exe application that other people will be able to > use? You can try to convince all of your friends to install Python... but if that doesn't work, you still have some options. You can use a utility called py2exe: http://py2exe.sourceforge.net/ That utility can bundle up your Python programs into .exe executables. Good luck to you! From the_investor at ziplip.com Mon Nov 24 20:23:30 2003 From: the_investor at ziplip.com (the_investor) Date: Mon Nov 24 20:24:50 2003 Subject: [Tutor] Starting with Python Message-ID: <KGAJPQPXCHKCOBOJCHAOBZAPL5EIFRB4LXKKGAH0@ziplip.com> Thanks Andrei and Magnus for your help!! Andrei: I tried downloading psi-55-py23.exe file on that PSI website but I get an error message when I try to load it (something about it being corrupt)... I downloaded the source zip file, but am unsure on how to run it/use it. Magnus: I use WinXP and I would like to download the PyChart stuff, but the files seem to be only Linux based... is there a win32 file for this charting module? Thanks, Ryan From mlong at datalong.com Mon Nov 24 22:53:20 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Mon Nov 24 22:53:30 2003 Subject: [Tutor] Question about Classes In-Reply-To: <200311241632.50975.gustabares@verizon.net> References: <3FC23A9A.1090209@aon.at><.151.203.32.149.1069700899.squirrel@datalong .com> <200311241632.50975.gustabares@verizon.net> Message-ID: <.151.203.32.149.1069732400.squirrel@datalong.com> > Matt, > > By subclassing the class "Email", you are overwriting the __init__ function > in the Email class. This means that the instance of Contact has no clue about This is good information. So I have to be carefull when subclassing to handle all properties. From mlong at datalong.com Mon Nov 24 22:55:20 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Mon Nov 24 22:55:29 2003 Subject: [Tutor] Question about Classes In-Reply-To: <200311241634.00535.gustabares@verizon.net> References: <200311241634.00535.gustabares@verizon.net> Message-ID: <.151.203.32.149.1069732520.squirrel@datalong.com> > And that's Mike, not Matt. > > > Sorry:) Not a problem. You can call me whatever you like...just don't call me late for dinner :)) > > Gus > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mlong at datalong.com Mon Nov 24 23:14:09 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Mon Nov 24 23:14:19 2003 Subject: [Tutor] Question about Classes In-Reply-To: <think001_3fc28227024b6@webmail.thinkware.se> References: <think001_3fc28227024b6@webmail.thinkware.se> Message-ID: <.151.203.32.149.1069733649.squirrel@datalong.com> Hi Magnus, > Hi Mike! > > One of the first thing you should know about classes is that > inheritance means "is-a". In other words, by letting "Contact" > inherit "Email" as you did in your code, you are claiming that > a Contact is a kind of Email. I don't think you really see the > world like that. I certainly don't. ;) This kind of misuse of > class mechanisms will only cause grief. Thanks for "is-a" explanation. My gut told me that this would be some sort of abuse of classes but I am new to OO programing and really don't "grok" it yet. I rationalize my abuse by calling it a learning exercise. :) > > A contact might *have* emails. That implies composition, or > an aggregate, that is, the person could have an emails attribute. So if I wanted to reuse the email functionality in another type of object how would I do this? For example if have a contact(person entity) class as well as a company(business entity) class. > Since the Email class seems to collect emails (plural), it seems > it would be better to call is "Emails". If you use it through > an "emails" attribute in the Contact, it seems a bit redundant > to repeat the word "email" in the method names. (I think this > long names just occured because your mistake with inheritance.) > > class Emails: > def __init__(self): > self._emails=[] > > def show(self): > return self._emails > > def add(self, email, type): > self._emails.append((type, email)) > >> class Contact(Email): >> def __init__(self >> ,firstName='' >> ,lastName='' >> ): >> """ Initial object """ >> self.firstName=firstName >> self.lastName=lastName > self.emails = Emails() >> >> def updateContact(self >> ,firstName >> ,lastName >> ): >> """ Save Contact Information """ >> self.firstName=firstName >> self.lastName=lastName >> >> def showContactInfo(self): >> return self.firstName + ' ' + self.lastName > > Now you can do: > > p.emails.add('x', 'yyy') > > and > > p.emails.show() You lost me here. In the preceding section you define _email and yet you refer to email in this last bit. Does the underscore perform some sort of magic? Cheers, Mike From vrisiva at yahoo.com Tue Nov 25 03:07:09 2003 From: vrisiva at yahoo.com (Vrisiva V) Date: Tue Nov 25 03:07:17 2003 Subject: [Tutor] python for terminal emulator Message-ID: <20031125080709.82299.qmail@web21509.mail.yahoo.com> Hello All, Is python language a correct choice to convert and port a terminal emulation software (existing in "C" language ) for communicating with an IBM mainframe ?? It is in the MS-Windows OS platform and needs to be ported to the Gnu/Linux OS platform but will it work if the client has another OS/s running on his system ?? thanks for your time, Vrisiva V --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031125/bbfe248f/attachment.html From project5 at redrival.net Tue Nov 25 07:09:57 2003 From: project5 at redrival.net (Andrei) Date: Tue Nov 25 07:12:33 2003 Subject: [Tutor] Re: Starting with Python References: <KGAJPQPXCHKCOBOJCHAOBZAPL5EIFRB4LXKKGAH0@ziplip.com> Message-ID: <7wjkof06z3s5$.1gw2eiggfw86y$.dlg@40tude.net> the_investor wrote on Mon, 24 Nov 2003 17:23:30 -0800 (PST): > Thanks Andrei and Magnus for your help!! > > Andrei: I tried downloading psi-55-py23.exe file on that PSI website > but I get an error message when I try to load it (something about > it being corrupt)... I downloaded the source zip file, but am unsure > on how to run it/use it. You will need recent versions of both Python and wxPython installed to run the source. You can just extract it somewhere and run it (doubleclick on psi.py or whatever the main file is). If it has a setup.py, you need to open a command prompt and run "python setup.py install", which will probably put it in the Lib\site-packages subdirectory of your Python dir. If it still doesn't work, you should probably contact the author as I'm not familiar enough with it to do troubleshooting. > Magnus: I use WinXP and I would like to download the PyChart stuff, but > the files seem to be only Linux based... is there a win32 file for this > charting module? Have a look at the second question from the PyChart FAQ (http://www.hpl.hp.com/personal/Yasushi_Saito/pychart/faq.html). If you need to compile, there's a free C++ IDE/compiler for Windows called Dev-C++ at (http://www.bloodshed.net/dev/devcpp.html). It's pretty easy to use and if you're lucky you can compile by just clicking on a button. If you're unlucky you'll have to hunt for compiled binaries or debug C code. -- 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 op73418 at mail.telepac.pt Tue Nov 25 07:49:43 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Nov 25 07:48:06 2003 Subject: [Tutor] convert to exe? In-Reply-To: <20031125000827.79647.qmail@web60203.mail.yahoo.com> References: <20031125000827.79647.qmail@web60203.mail.yahoo.com> Message-ID: <ngj6sv82ihi7h196o7ht9qm4evdoplm0oc@4ax.com> On Mon, 24 Nov 2003 16:08:27 -0800 (PST), you wrote: >hey, > >well this is sorta a stupid question, but i just started to program, so i dont know much. im learning python from an online source, but theres something i dont get. the interpreter works fine for all program testing purposes, but what after that? how do i convert the .py file to an executable .exe application that other people will be able to use? and whoever is going to explain this to me, do it in simple terms, im not exactly what ud call the ultimate computer genius. >thanx, > >Udz > There are no compilers for the Python language (yet). What happens is that the code (the code in your source file .py) is translated to an intermediate language, and then that translation is run by another program, which you can view as simulating a computer - heck, it's even called a Virtual Machine (VM). Other languages like Perl or Java do the same. In practice, what this means is that to run your .py file in a computer, it must have the Python interpreter installed. There are tools, however, that can *bundle and wrap* your source file together with the interpreter and any extra libraries it needs into an executable binary. Look up py2exe http://py2exe.sourceforge.net/ With my best regards, G. Rodrigues From okana at doruk.net.tr Tue Nov 25 15:24:12 2003 From: okana at doruk.net.tr (Okan Asik) Date: Tue Nov 25 08:24:44 2003 Subject: [Tutor] Image Viewer Message-ID: <3FC3BA6C.6080004@doruk.net.tr> I need to create an image viewer(fcheck like, which makes slide show). Is Python the right tool for this. I want to make a very very small application just for seeing images, slide-show. How hard to create this apps with Python ? Which path i must follow :) Thank you From magnus at thinkware.se Tue Nov 25 09:47:25 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Nov 25 09:47:34 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUXVlc3Rpb24gYWJvdXQgQ2xhc3Nlcw==?= Message-ID: <think001_3fc365d2318fc@webmail.thinkware.se> > Thanks for "is-a" explanation. My gut told me that this would be some sort of abuse > of classes but I am new to OO programing and really don't "grok" it yet. Seems your instincts are right then. > So if I wanted to reuse the email functionality in another type of object how would > I do this? For example if have a contact(person entity) class as well as a > company(business entity) class. The only thing I needed to do here was to put "self.emails = Emails()" in Contact.__init__. It's trivial to put that in Company.__init__ as well. But you are actually mentioning a well known pattern. It's been analyzed by Marting Fowler in his book "Analysis Patterns". You have to think about your model in terms of "is a kind of", "has" and "contains" etc, and design you model based on that. I'll dodge a bit by saying that this is not really a Python issues... ;) > > Since the Email class seems to collect emails (plural), it seems > > it would be better to call is "Emails". If you use it through > > an "emails" attribute in the Contact, it seems a bit redundant > > to repeat the word "email" in the method names. (I think this > > long names just occured because your mistake with inheritance.) > > > > class Emails: > > def __init__(self): > > self._emails=[] > > > > def show(self): > > return self._emails > > > > def add(self, email, type): > > self._emails.append((type, email)) > > > >> class Contact(Email): > >> def __init__(self > >> ,firstName='' > >> ,lastName='' > >> ): > >> """ Initial object """ > >> self.firstName=firstName > >> self.lastName=lastName > > self.emails = Emails() Note the line above! > >> > >> def updateContact(self > >> ,firstName > >> ,lastName > >> ): > >> """ Save Contact Information """ > >> self.firstName=firstName > >> self.lastName=lastName > >> > >> def showContactInfo(self): > >> return self.firstName + ' ' + self.lastName > > > > Now you can do: > > > > p.emails.add('x', 'yyy') > > > > and > > > > p.emails.show() > > You lost me here. In the preceding section you define _email and yet you refer to > email in this last bit. Does the underscore perform some sort of magic? No magic at all. I assumed p to be a Contact, just as in your code. _emails is an attribute in the *Emails* class, containing a list. emails is an attribute in the *Contact* class, containg an instance of the Emails class. I use a leading underscore to give a hint that this is an internal attribute that you shouldn't access directly. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Nov 25 09:59:02 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Nov 25 09:59:07 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gU3RhcnRpbmcgd2l0aCBQeXRob24=?= Message-ID: <think001_3fc36d1e255b0@webmail.thinkware.se> > Magnus: I use WinXP and I would like to download the PyChart stuff, but the files seem to be only Linux based... is there a win32 file for this charting module? I see nothing Linux specific in the file. Normal unzip programs like winzip can open a gnu-zipped tar file. See the FAQ for further info. http://www.hpl.hp.com/personal/Yasushi_Saito/pychart/faq.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Nov 25 10:05:19 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Nov 25 10:05:36 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gSW1hZ2UgVmlld2VyIA==?= Message-ID: <think001_3fc36ebb8758c@webmail.thinkware.se> > I need to create an image viewer(fcheck like, which makes slide show). > Is Python the right tool for this. I want to make a very very small > application just for seeing images, slide-show. How hard to create this > apps with Python ? Which path i must follow :) Thank you It depends on what you mean by small... I'm sure you can write a fairly small python script that does this, but if you want to distribute it to people who don't have Python installed, and want to give them a simple executable, it will be big, since it will include both the Python runtime environment and the libraries you need. Another relevant factor is operating system. Python is probably one of the better choices if you want platform independence. Have a look at PIL: http://www.pythonware.com/products/pil/ -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Nov 25 10:49:01 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Nov 25 10:49:08 2003 Subject: =?ISO-8859-1?B?UmU6IFJFOiBbVHV0b3JdIEFjY2Vzc2luZyB0aGUgbmFtZSBvZiBhbiBpbnN0YW5jZSB2YXJpYWJsZQ==?= Message-ID: <think001_3fc376fa5ddb3@webmail.thinkware.se> > ah, yes. But the point of it all is to get the actual variable name. But an object doesn't have a variable name. The name is just what someone on the outside calls the object. a = DiseaseCode(['1371','137L','137P0','137S','137T']) b = a c = b Now you have three names for the same object. Different names might occur in different scopes. The global scope should be avoided as much as possible, and the local scopes are just that--local. They are meaningless outside the functions or classes where they are defined. Object might also exist without being directly referenced by variables. l = [] l.append(DiseaseCode(['1371','137L','137P0','137S','137T'])) I think you need to rethink this. I'm sure you can make something that will do what you intended for globals in a module, but I'm pretty sure this will become useless as your system grows. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Nov 25 11:03:17 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Nov 25 11:03:23 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gc2lsbHkgcmVtZWRpYWwgcXVlc3Rpb24g?= Message-ID: <think001_3fc37a9480058@webmail.thinkware.se> Hi Kevin! If you have lots of similar objects that you are going to treat in a uniform way, don't give them a variable each. Put them in a list or a dictionary. E.g.: d = {'input_1': [234, 234, 123], 'input_2': [21,345,12], ... } input_names = d.keys() input_names.sort() for input_name in input_names: print input_name, '=', d[input_name], ',', f(d[input_name]) Using a list, you'll only access them via integer numbers. Using a dictionary you will access them via names, but you can't preserve the order you placed them into the dictionary. Dictionaries are basically unordered. (See http://www.python.org/doc/current/lib/typesmapping.html). To preserve both a name and an order, you could use a tuple in a list: l = [('input_1', [234, 234, 123]), ('input_2', [21,345,12]), ... ] for input_name, value in l: print input_name, '=', value, ',', f(value) -----Ursprungligt meddelande----- Fr?n: kevin parks <kpp9c@virginia.edu> Skickat: 2003-11-24 09:02:53 Till: tutor@python.org ?mne: [Tutor] silly remedial question > Hi folks! > > I am trying to do something that seems rather simple, but perhaps is > something i haven't done before or forgot... > > I have a function that does something to sequence and returns a > sequence. Now i call that function a bunch of times one a whole bunch > of lists and i get my output which is very nice. Problem is, that i > want to make that output more humanly readable form by first printing > the name of the list variable followed by a ' = ' and then the items in > the list. > > so if sequence input_01 = [22, 25, 31] and i write something that > returns the mod 12 equivalent of each item in a new list [10, 1, 7] > > i can print [22, 25, 31] and [10, 1, 7] > but how can i get it to say : > > input_01 = [22, 25, 31], [10, 1, 7] > > Without saying: > > print 'input_01 =', input_01 > > for each input list. > > I can print the input and output lists no problem, but how do you tell > python to print the variable itself.. I don't want to do this by hand > as i have a huge bunch of list that i have to do this to that are > already sitting in a text file. > > Not sure i made this clear or not... > > > cheers, > > kevin > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Tue Nov 25 13:07:06 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Nov 25 13:07:14 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUmU6IDMgc2ltcGxlLCBwaXRoeSBhbmQgc2hvcnQgcXVlc3Rpb25zLCByZWxlYXRlZCB0byBwcmV2aW91cyBhbnN3ZXJzIG9mIHlvdXJzIC4uLg==?= Message-ID: <think001_3fc391c75fd85@webmail.thinkware.se> > a tuple is very like a list except you cannot change the contents > once created. E.g. >>> l = [1,2,3] >>> l[1]=5 >>> l [1, 5, 3] >>> t = (1,2,3) >>> t[1]=5 Traceback (most recent call last): File "<pyshell#70>", line 1, in -toplevel- t[1]=5 TypeError: object doesn't support item assignment > This allows us to use a tuple as the lookup key to a > dictionary(see below) A tuple is also somewhat faster and uses a little less memory. But in practice, we typically use lists when we have a sequence of similar objects, like a list of email addresses, or a list of names of people. Tuples are often used for structures, for instance if you want to keep a name, an email address and an age for a person as a collection, you might do something like someone = ('Doug Duckling', 'doug@example.com', 43) As you might have guessed by now, it's fairly common with lists of tuples. people = [ ('Doug Duckling', 'doug@example.com', 43), ('Dan Duckling', 'da@example.com', 42), ('Fred Duckling', 'fred@example.com', 41) ] With this construct, you can easily add people to the list, or remove them from it, but a "people tuple" can't have itmes appended to it etc. Of course, you can change Fred's age like this... # Fred's birthday fred = people[2] people[2] = (fred[0], fred[1], fred[2]+1) ..but then you have not motified the last tuple in the list. You have replaced it with a brand new tuple object with similar content. > > I understand also that one creates an arrow of object in > string You mean array? The generic term used in Python is sequence. Typically, arrays in computer languages imply a certain type of implementation. The word array also has a mathematical meaning, but only for numbers I guess... Sequence is considered a less technical, broader term that described the common qualities of lists, tuples and strings etc. A string is (like the tuple and list) also a sequence, but as Alan said, it's restricted to containing characters (which are strings with a length of one, which means that I just gave a circular definition, sorry! ;) Like the tuple, strings are immutable. >>> s = "abc" >>> s[1] 'b' >>> s[1] = 'B' Traceback (most recent call last): File "<pyshell#73>", line 1, in -toplevel- s[1] = 'B' TypeError: object doesn't support item assignment > So: > [] => a list > () => a tuple > {} => a dictionary To be picky, a tuple is really created by putting commas between objects, like this: >>> x = 1,2,3 Sometimes we need to use () to avoid ambiguities. For instance... >>> t = 1,2,3*4 >>> t (1, 2, 12) >>> t = (1,2,3)*4 >>> t (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3) or >>> def f(x): print x >>> f(1,2,3) Traceback (most recent call last): File "<pyshell#85>", line 1, in -toplevel- f(1,2,3) TypeError: f() takes exactly 1 argument (3 given) >>> f((1,2,3)) (1, 2, 3) >>> > To add to the confusion, we use [] to access the data for all > three! > > t = (1,2,3) > L = [4,5,6] > d = {7:8,9:0} > > print t[0],L[0],d[7] # prints 1 4 8 This works the same with strings. You can also use slices. >>> l = range(65,80) >>> t = tuple(l) >>> s = "".join([chr(x) for x in l]) >>> print l [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79] >>> print t (65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79) >>> print s ABCDEFGHIJKLMNO >>> print l[3:10] [68, 69, 70, 71, 72, 73, 74] >>> print t[3:10] (68, 69, 70, 71, 72, 73, 74) >>> print s[3:10] Or even... DEFGHIJ >>> print l[3:10:3] [68, 71, 74] >>> print t[3:10:3] (68, 71, 74) >>> print s[3:10:3] DGJ > That's right, the last argument in range() is the size of step > between values. Compare with the last slicing examples above. (I think this was introduced in Python 2.3.) > > 3.) I noticed, that examples below (after typing print a, and > print b) > > give identical results, so is it really so, that there is no > difference, > > creating string or tuple, if using brackets, or if not ?? > > s = 1,2,3 ... and ... s = (1, 2, 3) > > b = "ww", "aa" ... and ... b = ("ww", "aa") As I wrote above, it's the commas that make the tuple. You can find out the type of an object with the (suprise) type() function. >>> type(l) <type 'list'> >>> type(t) <type 'tuple'> >>> type(s) <type 'str'> -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tayi177 at hotmail.com Tue Nov 25 13:43:01 2003 From: tayi177 at hotmail.com (David) Date: Tue Nov 25 13:43:36 2003 Subject: [Tutor] Sample9.py and Sample9.pyc & seting path to Python open files ... Message-ID: <BAY8-DAV12JaqezRSry00002f9d@hotmail.com> Hello ... 1.) I noticed, that after I have imported some random module (in this case, module I made) there appear an additional file in Python\Saves directory, where my modules are stored ... The module I imported was Sample9.py (green icon), process it. and just after last line the new file Sample9.pyc appeared (more or less red icon) ... It has also different content compare to "original" file, some sort of "program language" I do not recognize ... Sample9.py print "tadej" multiplier = input("Which multiplier do you want? Pick a number ") for j in range(1,13): print "%d x %d = %d" % (j, multiplier, j * multiplier) Sample9.pyc ;? ~???c @ sE d GHe d ? Z x- e d d ? D] Z d e e e e f GHq! Wd S( s tadejs, Which multiplier do you want? Pick a number i i s %d x %d = %dN( s inputs multipliers ranges j( s js multiplier( ( s/ D:\Program Files\Python\Lib\idlelib\Saves\gg.pys ? s What is that *.pyc file is ?? What is it used for (just assuming something has changed in it during processing, compare to "original" .py file) ?? 2.) Just before writting this mail, when I was trying to make some more complex "read/write" file operatons, I always get an error: IOError [Errno 2] No such file or directory: 'Sample.py' A also tryed with sys.path.append("D:\\PROGRAM~1\Python) function, which worked fine previous time, when Python didn't "know" the right path, and there was IOError again. Further, to be more certain I also tryed sys.path.append("D:\\PROGRAM~1\Lib\idlelib\Saves\) - the directory, where I store my sample files, ... and there was the same error again. Please tell me, what am I doing wrong ?? 3.) And only one question directly releated to programming: I finished with Alan Gauld's tutorial (than you again, Alan - it's really the best option for non-programmer to start with), so to continue, I am learning from 4 new tutorials (not at the same time), one from techiwarehouse.com, second is Dive into Python, third is "An Informal Introduction to Python" from www.python.org and fourth is Josh Cogliati's "Python for Non-Programmers" So in the one from techiwarehouse.com, there is an explanation of so-called Logical operators: and, or, and not. I do not understand explanation of and operator: Firts it says: For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10. and then: Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as "true." >>> x = 5 >>> x and 1 1 >>> y = 0 >>> y and 1 0 So, how do we get 1 and 0 here ?? Probably they are not meaning "true" or "false", cause when I typed ... >>> x = 1 >>> x and 2 2 ... it gives value 2 !! I assume it is releated to "Any nonzero number is interpreted as "true.", but I can't get it 100 % ... Thanks for any answer, Tadey -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031125/57cb6f7f/attachment.html From paul at entropia.co.uk Tue Nov 25 12:06:23 2003 From: paul at entropia.co.uk (paul@entropia.co.uk) Date: Tue Nov 25 13:53:40 2003 Subject: [Tutor] tripping up zip Message-ID: <3FC38C0F.3376.1280223@localhost> Dear list, I've been trying to make a quick backup script, but its failing to add some files to the archive. Any idea where I'm going wrong? ## path module by http://www.jorendorff.com/articles/python/path/ ## win xp pro Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 from path import path import zipfile f = path('C:\Documents and Settings\XP Pro\My Documents\personal') nuzip = zipfile.ZipFile('C:\ziptests\ziptest.zip','w') ## this is a document I added to test things and ## it appears in the final archive ## but fails in the for loop and is listed as doing so x='C:\\Documents and Settings\\XP Pro\\My Documents\\personal\\INDIA TRAVEL ITENARY.doc' nuzip.write(x,x,zipfile.ZIP_DEFLATED) files = 0 folders = 0 failed ='' failures= 0 bax = f.walkdirs() for topfiles in f: if topfiles.isfile(): # print topfiles files = files + 1 try: nuzip.write(topfiles,topfiles,zipfile.ZIP_DEFLATED) except: failed=failed+topfiles.name + ' \n' failures = failures + 1 ## this will sweep the sub directories if I ever get it working ##for folder in bax: ### folders = folders + 1 ### for filer in folder: ## if filer.isfile(): ## #print filer ## files = files + 1 ## #try: ## #nuzip.write(filer,filer,zipfile.ZIP_DEFLATED) ## #except: ## #failed=failed+filer.name + ' \n' ## #failures = failures + 1 nuzip.printdir() nuzip.close() print 'there are %d folders and %d files with %d failures' %(folders, files, failures) print 'The following failed: ' print failed OUTPUT IN SHELL: File Name Modified Size C:/Documents and Settings/XP Pro/My Documents/personal/INDIA TRAVEL ITENARY.doc 2003-10-04 21:47:41 54784 C:/Documents and Settings/XP Pro/My Documents/personal/Backup of REF CHECK TEMPLATE.wbk 2003-08-12 14:50:00 58368 C:/Documents and Settings/XP Pro/My Documents/personal/cologne.doc 2003-09-13 10:10:21 65536 C:/Documents and Settings/XP Pro/My Documents/personal/Email to Jim Harvey.doc 2003-03-24 06:43:34 19456 C:/Documents and Settings/XP Pro/My Documents/personal/handover arrangements draft.doc 2003-03-31 12:08:02 77312 C:/Documents and Settings/XP Pro/My Documents/personal/invite.jpg 2003-03-20 15:19:06 63175 C:/Documents and Settings/XP Pro/My Documents/personal/leafletdave.doc 2003-03- 31 11:48:06 45056 C:/Documents and Settings/XP Pro/My Documents/personal/NMCK REF CHECK TEMPLATE.doc 2003-08-14 08:56:29 63488 C:/Documents and Settings/XP Pro/My Documents/personal/REF CHECK TEMPLATE.doc 2003-08-12 14:50:11 58368 there are 0 folders and 21 files with 13 failures The following failed: !ebookers flight 4.url gy cv.doc GY Resignation .doc INDIA TRAVEL ITENARY.doc INDIA TRAVEL ITENARY2.doc INDIA TRAVEL ITENARY3.doc invoice.pdf PARIS FRANCE ITERNARY.doc PERFORMANCE APPRAISAL FORM.doc Reg net password details.doc SUe PERFORMANCE APPRAISAL FORM.doc Thumbs.db which.txt without the try clause I got this: Traceback (most recent call last): File "C:\Python23\Lib\mybackup.py", line 22, in -toplevel- nuzip.write(filer,filer,zipfile.ZIP_DEFLATED) File "C:\Python23\Lib\zipfile.py", line 412, in write self.fp.write(zinfo.FileHeader()) File "C:\Python23\Lib\zipfile.py", line 166, in FileHeader return header + self.filename + self.extra UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 12: ordinal not in range(128) From paul at entropia.co.uk Tue Nov 25 13:42:22 2003 From: paul at entropia.co.uk (paul@entropia.co.uk) Date: Tue Nov 25 13:57:46 2003 Subject: [Tutor] tripping up zip Message-ID: <3FC3A28E.16723.17FE315@localhost> Dear list, I've been trying to make a quick backup script, but its failing to add some files to the archive. Any idea where I'm going wrong? Works fine using nt4/Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 ## path module by http://www.jorendorff.com/articles/python/path/ ## win xp pro Python 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)] on win32 from path import path import zipfile f = path('C:\Documents and Settings\XP Pro\My Documents\personal') nuzip = zipfile.ZipFile('C:\ziptests\ziptest.zip','w') ## this is a document I added to test things and ## it appears in the final archive ## but fails in the for loop and is listed as doing so x='C:\\Documents and Settings\\XP Pro\\My Documents\\personal\\INDIA TRAVEL ITENARY.doc' nuzip.write(x,x,zipfile.ZIP_DEFLATED) files = 0 folders = 0 failed ='' failures= 0 bax = f.walkdirs() for topfiles in f: if topfiles.isfile(): # print topfiles files = files + 1 try: nuzip.write(topfiles,topfiles,zipfile.ZIP_DEFLATED) except: failed=failed+topfiles.name + ' \n' failures = failures + 1 ## this will sweep the sub directories if I ever get it working ##for folder in bax: ### folders = folders + 1 ### for filer in folder: ## if filer.isfile(): ## #print filer ## files = files + 1 ## #try: ## #nuzip.write(filer,filer,zipfile.ZIP_DEFLATED) ## #except: ## #failed=failed+filer.name + ' \n' ## #failures = failures + 1 nuzip.printdir() nuzip.close() print 'there are %d folders and %d files with %d failures' %(folders, files, failures) print 'The following failed: ' print failed OUTPUT IN SHELL: File Name Modified Size C:/Documents and Settings/XP Pro/My Documents/personal/INDIA TRAVEL ITENARY.doc 2003-10-04 21:47:41 54784 C:/Documents and Settings/XP Pro/My Documents/personal/Backup of REF CHECK TEMPLATE.wbk 2003-08-12 14:50:00 58368 C:/Documents and Settings/XP Pro/My Documents/personal/cologne.doc 2003-09-13 10:10:21 65536 C:/Documents and Settings/XP Pro/My Documents/personal/Email to Jim Harvey.doc 2003-03-24 06:43:34 19456 C:/Documents and Settings/XP Pro/My Documents/personal/handover arrangements draft.doc 2003-03-31 12:08:02 77312 C:/Documents and Settings/XP Pro/My Documents/personal/invite.jpg 2003-03-20 15:19:06 63175 C:/Documents and Settings/XP Pro/My Documents/personal/leafletdave.doc 2003-03- 31 11:48:06 45056 C:/Documents and Settings/XP Pro/My Documents/personal/NMCK REF CHECK TEMPLATE.doc 2003-08-14 08:56:29 63488 C:/Documents and Settings/XP Pro/My Documents/personal/REF CHECK TEMPLATE.doc 2003-08-12 14:50:11 58368 there are 0 folders and 21 files with 13 failures The following failed: !ebookers flight 4.url gy cv.doc GY Resignation .doc INDIA TRAVEL ITENARY.doc INDIA TRAVEL ITENARY2.doc INDIA TRAVEL ITENARY3.doc invoice.pdf PARIS FRANCE ITERNARY.doc PERFORMANCE APPRAISAL FORM.doc Reg net password details.doc SUe PERFORMANCE APPRAISAL FORM.doc Thumbs.db which.txt without the try clause I got this: Traceback (most recent call last): File "C:\Python23\Lib\mybackup.py", line 22, in -toplevel- nuzip.write(filer,filer,zipfile.ZIP_DEFLATED) File "C:\Python23\Lib\zipfile.py", line 412, in write self.fp.write(zinfo.FileHeader()) File "C:\Python23\Lib\zipfile.py", line 166, in FileHeader return header + self.filename + self.extra UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 12: ordinal not in range(128) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031125/b59d12b3/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Tue Nov 25 14:45:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 25 14:46:02 2003 Subject: [Tutor] Sample9.py and Sample9.pyc & seting path to Python open files ... In-Reply-To: <BAY8-DAV12JaqezRSry00002f9d@hotmail.com> Message-ID: <Pine.LNX.4.44.0311251100490.8195-100000@hkn.eecs.berkeley.edu> On Tue, 25 Nov 2003, David wrote: > 1.) I noticed, that after I have imported some random module (in this > case, module I made) there appear an additional file in Python\Saves > directory, where my modules are stored ... > > The module I imported was Sample9.py (green icon), process it. and just > after last line the new file Sample9.pyc appeared (more or less red > icon) ... > > It has also different content compare to "original" file, some sort of > "program language" I do not recognize ... Hi Tadey, Yes. That second file that you're seeing, with the '.pyc' extention, is a Python "bytecode-compiled" file. Before Python starts to run a program, it takes a step to read the whole program, digest it, and turn it into an internal "bytecode" format that's simpler for it to understand. Think of a cow that ruminates: Python does something similar to rumination. For example, the relatively simple function: ### >>> def hello(): ... print "Hello world!" ... ### is processed by Python, and digested into a set of relatively simple "bytecode" instructions: ### >>> import dis >>> dis.dis(hello) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_CONST 1 ('Hello world!') 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE ### The 'bytecodes' here are very primitive instructions, but they capture everything that our original hello() function is doing. Usually, Python keeps these bytecodes only for as long as a program is running. But since it actually takes a bit of work for Python to convert our text program into primitive bytecodes, sometimes Python will try to save the bytecodes to disk, if it feels it'll be useful in the future. For example, it'll write the bytecodes out to disk if we do a module 'import': module libraries are heavily used, so it makes sense to save the .pyc file to disk to save some work. You never have to explictely tell Python to byte-compile a Python file though. It also shouldn't hurt if you delete a .pyc file, because it's simply a processed version of your '.py' files. But in general, you shouldn't need to worry too much about them. > 2.) Just before writting this mail, when I was trying to make some more > complex "read/write" file operatons, I always get an error: > > IOError [Errno 2] No such file or directory: 'Sample.py' What kind of reading and writing operation are you doing? Show us the code, and we can take a look. In particular, it'll help if we see the line that the error message is pointing at. Are you trying to write to a text file? And if so, why 'Sample.py'? The list 'sys.path' does not control where a file is to be opened: it does not change the present working directory. Instead, it's meant to tell Python a bunch of locations where it can find modules to 'import'. It shouldn't be involved with any file 'open()'ing that you're doing, though, so I'm not sure if you should be using sys.path. I think we'll need to see more of your program, though, before saying more. I actually have to go at the moment, but the other tutors may handle your third question about logical operators. Talk to you later! From mlong at datalong.com Tue Nov 25 15:36:30 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Tue Nov 25 15:37:21 2003 Subject: [Tutor] Question about Classes In-Reply-To: <think001_3fc365d2318fc@webmail.thinkware.se> References: <think001_3fc365d2318fc@webmail.thinkware.se> Message-ID: <.161.91.247.12.1069792590.squirrel@datalong.com> > But you are actually mentioning a well known pattern. It's been analyzed > by Marting Fowler in his book "Analysis Patterns". > > You have to think about your model in terms of "is a kind of", "has" > and "contains" etc, and design you model based on that. I'll dodge a > bit by saying that this is not really a Python issues... ;) So if the goal is to maximize code reuse, would the correct solution require that the Emails class be placed in another module that can then be imported whenever the Emails functionality is required or is there a better way to do this? Thanks, Mike From chris at heisel.org Tue Nov 25 15:55:32 2003 From: chris at heisel.org (Chris Heisel) Date: Tue Nov 25 15:55:38 2003 Subject: [Tutor] Automated Breadcrumb -- help for a PHP user Message-ID: <3FC3C1C4.40308@heisel.org> Hi, I'm a n00b to python coming from PHP land. I'd like to create an automated breadcrumb script that would inspect the URL and create an appropriate bread crumb navigation set. In PHP I'd so something like function makeBread($url) { $path_parts = explode('/', $url); echo('<p class="trail">'); foreach ($path_parts as $key => $value) { $where_at = $where_at + $value; echo('<a href="$where_at">'.$where_at.'</a>'); } } I'd put this function in an external file include() it and make a call with: <?php makeBread($PHP_SELF) ?> (Disclaimer: this code is really ugly its just an example...) I'd like to do this in Python and make it a cgi-bin file so I could have something like this: <!--#include virtual="/cgi-bin/bread.py" --> But I'm not sure where to start. How can I pass the URL of the page making the include call to the script? One its there I'm sure I can muddle through some flow control structures and what not to massage the URL into the various breadcrumb pieces... Any help would be greatly appreciated. Thanks in advance, Chris From magnus at thinkware.se Tue Nov 25 16:11:26 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Nov 25 16:11:35 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gUXVlc3Rpb24gYWJvdXQgQ2xhc3Nlcw==?= Message-ID: <think001_3fc3c280e87c5@webmail.thinkware.se> > So if the goal is to maximize code reuse, would the correct solution require that > the Emails class be placed in another module that can then be imported whenever the > Emails functionality is required or is there a better way to do this? It's ALWAYS a goal to keep things simple. If the class is as simple that Email class, it's hardly worth a lot of administrative efforts making it a deliverable in itself that needs to be maintained. In contrast to Java, it's not a typical Python idiom to place each class in its own module. Since Python is a higher level language than Java, Python modules with only one class would tend to be rather small. It's normal to place related classes together in a module. On one hand, it's always good to do things right at once, but on the other hand, what's right in one situation is wrong in another, and things change over time. Trying to solve thing in a "good for the future" way often means that you spend time and energy making your system more complicated for no good reason. Finding the right balance between planning ahead and staying simple and flexible is something you will have to learn over time. A great thing with Python is that it's so flexible. I'd put the Email(s) class with the Contact class in a shared module. You can import that in some other program and just use the Email class. If it grows, and you feel it should have a module on it's own, it's time to refactor your code and break it out. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From alan.gauld at blueyonder.co.uk Tue Nov 25 16:32:35 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 25 16:32:07 2003 Subject: [Tutor] (no subject) References: <a0600200dbbe2d903a49d@[10.10.25.250]> Message-ID: <006301c3b39b$a4e8aa40$6401a8c0@xp> > to get my program to accept string arguments and them print them > out....it will only take numbers? Do I need to import something > first to allow keyboard input in the form of words... I guess you are using input()? Try using raw_input() instead. This is explained in the Simple Sequences page of mny tutor. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mlong at datalong.com Tue Nov 25 16:55:47 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Tue Nov 25 16:56:20 2003 Subject: [Tutor] Question about Classes In-Reply-To: <think001_3fc3c280e87c5@webmail.thinkware.se> References: <think001_3fc3c280e87c5@webmail.thinkware.se> Message-ID: <.161.91.247.12.1069797347.squirrel@datalong.com> > Finding the right balance between planning ahead and staying > simple and flexible is something you will have to learn over > time. > > A great thing with Python is that it's so flexible. I'd put > the Email(s) class with the Contact class in a shared module. > You can import that in some other program and just use the > Email class. If it grows, and you feel it should have a module > on it's own, it's time to refactor your code and break it out. Your explanation is very good. You have helped me to better understand how to use classes and modules. Thank you, Mike From dyoo at hkn.eecs.berkeley.edu Tue Nov 25 16:56:15 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Nov 25 16:56:30 2003 Subject: [Tutor] Automated Breadcrumb -- help for a PHP user In-Reply-To: <3FC3C1C4.40308@heisel.org> Message-ID: <Pine.LNX.4.44.0311251328170.29460-100000@hkn.eecs.berkeley.edu> On Tue, 25 Nov 2003, Chris Heisel wrote: > I'd like to do this in Python and make it a cgi-bin file so I could have > something like this: > <!--#include virtual="/cgi-bin/bread.py" --> Hi Chris, This looks like a Server Side Include (SSI) directive. http://httpd.apache.org/docs-2.0/howto/ssi.html http://httpd.apache.org/docs-2.0/mod/mod_include.html According to the second document, it is possible to pass parameters to bread.py: we can add a query string to the end. For example: <!--#include virtual="/cgi-bin/bread.py?path=/foo/bar" --> will call bread.py, and pass 'path' as a CGI parameter. But according to that second page, you can also grab at the 'URI' path by looking at the environment variable 'DOCUMENT_URI'. I'm guessing that DOCUMENT_URI is equivalent to $PHP_SELF. If so, then we can take full advanage of that! Here's a small cgi that just prints out the document uri: ### #!/usr/local/bin/python2.3 import cgitb cgitb.enable() import os print "Content-type: text/plain\n\n" print os.environ['DOCUMENT_URI'] ### If you just include this cgi by using the SSI directive, you should see that the cgi program now knows about the document uri. > One its there I'm sure I can muddle through some flow control structures > and what not to massage the URL into the various breadcrumb pieces... Sounds good! You may find: http://www.python.org/doc/lib/module-urlparse.html useful; it will already handle what you did with PHP's explode() function. But if you really want a close equivalent to explode(), you can use a string's split() method: ### >>> 'hello-world-this-is-a-test'.split('-') ['hello', 'world', 'this', 'is', 'a', 'test'] ### Good luck to you! From alan.gauld at blueyonder.co.uk Tue Nov 25 17:05:34 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 25 17:05:03 2003 Subject: [Tutor] Question about Classes References: <3FC23A9A.1090209@aon.at><.151.203.32.149.1069700899.squirrel@datalong.com> <200311241632.50975.gustabares@verizon.net> Message-ID: <00a401c3b3a0$40245cd0$6401a8c0@xp> > By subclassing the class "Email", you are overwriting the __init__ function > in the Email class. This means that the instance of Contact has no clue about > the statement: > > self.emails = [] > > in the Email class. You can try placing this statement in the __init__ of > Contact, or make it all one class, or whatever else you might think of. Or call the Email init function within the Contact init: Email.__init__(self) This is normally good practice when creating subclasses anyhow. Initialise the parent then do the local initialisation. > > class Email: > > def __init__(self): > > self.emails=[] > > > > > > class Contact(Email): > > def __init__(self > > ,firstName='' > > ,lastName='' > > ): > > """ Initial object """ Email.__init__(self) > > self.firstName=firstName > > self.lastName=lastName > > Alan G. From alan.gauld at blueyonder.co.uk Tue Nov 25 17:13:52 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 25 17:13:20 2003 Subject: [Tutor] convert to exe? References: <20031125000827.79647.qmail@web60203.mail.yahoo.com> Message-ID: <00ca01c3b3a1$693121c0$6401a8c0@xp> > well this is sorta a stupid question, but i just started to program, Nope, not stupid, in fact it comes up regularly. > the interpreter works fine for all program testing purposes, It works fine for running your final programs too, its only a problem if you need to share your [rograms with someone who doesn't have Python installed. Java and Visual Basic have this problem too and they get round it by making everyone install the VB DLL and the JVM. So you could be like Sun and Microsoft and insist that everyone installs Python if they want to use your programs. You could even include Python on the distribution CD... If you really must make an exe there are a coupkle of programs for doing so but neither are easy for beginners so you'll need to be patient a wee while yet till you get a bit more experience, then go find py2exe or Gordon McMillan's installer. Personally I use the Java approach! Alan G. From mlong at datalong.com Tue Nov 25 17:33:44 2003 From: mlong at datalong.com (mlong@datalong.com) Date: Tue Nov 25 17:33:54 2003 Subject: [Tutor] Question about Classes In-Reply-To: <00a401c3b3a0$40245cd0$6401a8c0@xp> References: <3FC23A9A.1090209@aon.at><.151.203.32.149.1069700899.squirrel@datalong .com><200311241632.50975.gustabares@verizon.net> <00a401c3b3a0$40245cd0$6401a8c0@xp> Message-ID: <.161.91.247.12.1069799624.squirrel@datalong.com> > Or call the Email init function within the Contact init: > > Email.__init__(self) > > This is normally good practice when creating subclasses anyhow. > Initialise the parent then do the local initialisation. Cool... From alan.gauld at blueyonder.co.uk Tue Nov 25 18:00:36 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 25 18:00:06 2003 Subject: [Tutor] Question about Classes References: <think001_3fc28227024b6@webmail.thinkware.se> <.151.203.32.149.1069733649.squirrel@datalong.com> Message-ID: <00d301c3b3a7$f01e8c30$6401a8c0@xp> > > Since the Email class seems to collect emails (plural), it seems > > it would be better to call is "Emails". If you use it through > > an "emails" attribute in the Contact, ... > > class Emails: > > def __init__(self): > > self._emails=[] _emails is an attribute of the Email class. > > def show(self): > > def add(self, email, type): > > > >> class Contact(Email): > >> def __init__(self... > >> self.firstName=firstName > >> self.lastName=lastName > > self.emails = Emails() emails is an attribute of the Contact class > > p.emails.add('x', 'yyy') Which adds an entry to the Emails class in the p contact > You lost me here. In the preceding section you > define _email and yet you refer to email in this > last bit. Does the underscore perform some sort of magic? Not really its just a convention to indicate in internal member of a class. The real point is that Magnis has declared two different variables, one in the Emails class(_emails) and one in the Contact class(emails). HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld PS. Welcome back to the tutor list Magnus From alan.gauld at blueyonder.co.uk Tue Nov 25 18:05:03 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 25 18:04:31 2003 Subject: [Tutor] python for terminal emulator References: <20031125080709.82299.qmail@web21509.mail.yahoo.com> Message-ID: <00db01c3b3a8$8f366450$6401a8c0@xp> > Is python language a correct choice to convert and port > a terminal emulation software (existing in "C" language ) > for communicating with an IBM mainframe ?? I wouldn't have automatically have thought of Python, but for a terminal emulator it should actually be OK. However... > It is in the MS-Windows OS platform and needs to be > ported to the Gnu/Linux OS platform but will it work > if the client has another OS/s running on his system ?? > thanks for your time, Are you sure you need this? If it's a 3270 emulator then x3270 is free on Linux. If it's for OS/400 I think there is a free terminal for that too... Also C code is pretty easy to port to from Unix/Linux so it might actually be easier to port than translate. (Going the other way is what's hard!) However having translated it to Pyhon it should run pretty well on any platform... Alan G. From alan.gauld at blueyonder.co.uk Tue Nov 25 18:11:14 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Nov 25 18:10:41 2003 Subject: [Tutor] Image Viewer References: <3FC3BA6C.6080004@doruk.net.tr> Message-ID: <00e401c3b3a9$6ca6edf0$6401a8c0@xp> > I need to create an image viewer(fcheck like, which makes slide show). > Is Python the right tool for this. I want to make a very very small > application just for seeing images, slide-show. How hard to create this > apps with Python ? Which path i must follow :) Thank you Very easy in Tkinter. (I suspect about as easy in wxPython, but I know it less well). Just create a widget that can accept Image objects. (Canvas or Text widgets say) For each image file (bmp, jpg or GIF) you want to display create an Image object and insert it into the widget. (Removing the previous entry first!) Put some navigation controls on the app for first,next, previous, last etc, maybe a browse button. That should do the trick. Quite a nice first GUI project in fact. If you want to do more sophisticated manipulation or display other formats check out either PIL or pyMagick(?) (an interface to ImageMagick) My tutor has a very short intro to Tkinter (GUI programming) that would be enough for this project I suspect. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From project5 at redrival.net Tue Nov 25 19:29:15 2003 From: project5 at redrival.net (Andrei) Date: Tue Nov 25 19:31:48 2003 Subject: [Tutor] Re: Image Viewer References: <3FC3BA6C.6080004@doruk.net.tr> <00e401c3b3a9$6ca6edf0$6401a8c0@xp> Message-ID: <16j3ip19wtfhl.o7xptwonsk3b$.dlg@40tude.net> Alan Gauld wrote on Tue, 25 Nov 2003 23:11:14 -0000: >> I need to create an image viewer(fcheck like, which makes slide > show). >> Is Python the right tool for this. I want to make a very very > small >> application just for seeing images, slide-show. How hard to > create this >> apps with Python ? Which path i must follow :) Thank you > > Very easy in Tkinter. (I suspect about as easy in wxPython, > but I know it less well). Just create a widget that can accept > Image objects. (Canvas or Text widgets say) <snip> There is an image viewer written in wxPy: http://web.tiscali.it/agriggio/cornice.html It even says "full-screen view" and "slideshow" in the features list. If you're in it because you need results fast (as opposed to: for learning Python/some GUI toolkit), you might want to improve Cornice instead of rolling your own. -- 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 arkamir at softhome.net Tue Nov 25 19:45:01 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Nov 25 19:45:39 2003 Subject: [Tutor] cookie error messages Message-ID: <1069807501.7959.5.camel@quercus> This is the error message, I think it means that id cannot be found. I looked throught the list and found that there were 2 cookies with the name of id. I tried it with username, and some random letters and it returned the same error. Also anyone now of a compact version of python for windows. Like under 100 megs. I copied one that was a couple years old and it turned out to be like 2.5 gigs uncompressed, though i think one of the files was corrupted. I don't have admin to install it since its going on the school network, and I'm the only one using it. :) The following error occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /home/conrad/public_html/cgi-bin/thread.py 5 import re 6 import insertthread 7 import retrievecookies 8 import cgitb 9 retrievecookies undefined /home/conrad/public_html/cgi-bin/retrievecookies.py 7 cgitb.enable() 8 9 value = os.environ['id'] 10 11 #print "Content-type: text/html\n" value undefined, os = <module 'os' from '/usr/lib/python2.2/os.pyc'>, os.environ = {'HTTP_COOKIE': 'id="((\'JCm8o0RJIu\',),)"; user...': '127.0.0.1', 'DOCUMENT_ROOT': '/var/www/html'} ? in __getitem__(self={'HTTP_COOKIE': 'id="((\'JCm8o0RJIu\',),)"; user...': '127.0.0.1', 'DOCUMENT_ROOT': '/var/www/html'}, key='id') KeyError: id __doc__ = 'Mapping key not found.' __getitem__ = <bound method KeyError.__getitem__ of <exceptions.KeyError instance>> __init__ = <bound method KeyError.__init__ of <exceptions.KeyError instance>> __module__ = 'exceptions' __str__ = <bound method KeyError.__str__ of <exceptions.KeyError instance>> args = ('id',) From okana at doruk.net.tr Tue Nov 25 22:14:58 2003 From: okana at doruk.net.tr (Okan Asik) Date: Tue Nov 25 20:14:59 2003 Subject: [Tutor] IDE Message-ID: <3FC41AB2.5010203@doruk.net.tr> What's the most common IDE you people using while writing your own programs ? From intatia at paradise.net.nz Tue Nov 25 20:28:43 2003 From: intatia at paradise.net.nz (Intatia) Date: Tue Nov 25 20:29:56 2003 Subject: [Tutor] IDE In-Reply-To: <3FC41AB2.5010203@doruk.net.tr> References: <3FC41AB2.5010203@doruk.net.tr> Message-ID: <3FC401CB.1090900@paradise.net.nz> Not sure if it counts, but I use vim, old habits die hard, first computer I had with internet used vi for email:) That's in linux anyway, in winblows I use the activestate one. Okan Asik wrote: > What's the most common IDE you people using while writing your own > programs ? > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From gustabares at verizon.net Tue Nov 25 20:42:21 2003 From: gustabares at verizon.net (Gustavo Tabares) Date: Tue Nov 25 20:42:34 2003 Subject: [Tutor] IDE In-Reply-To: <3FC41AB2.5010203@doruk.net.tr> References: <3FC41AB2.5010203@doruk.net.tr> Message-ID: <200311252042.21647.gustabares@verizon.net> In Linux I prefer to use vim, but when I'm working on Windows I prefer just to use IDLE. The only probably with IDLE is that it's slow when compared to vim for Windows Gus On Tuesday 25 November 2003 22:14, Okan Asik wrote: > What's the most common IDE you people using while writing your own > programs ? > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From littledanehren at yahoo.com Tue Nov 25 22:15:33 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Nov 25 22:15:45 2003 Subject: [Tutor] Automated Breadcrumb -- help for a PHP user In-Reply-To: <3FC3C1C4.40308@heisel.org> Message-ID: <20031126031533.58801.qmail@web41811.mail.yahoo.com> Chris Heisel wrote: > Hi, > > I'm a n00b to python coming from PHP land. > > I'd like to create an automated breadcrumb script > that would inspect the > URL and create an appropriate bread crumb navigation > set. > > In PHP I'd so something like > function makeBread($url) { > $path_parts = explode('/', $url); > echo('<p class="trail">'); > foreach ($path_parts as $key => $value) { > $where_at = $where_at + $value; > echo('<a > href="$where_at">'.$where_at.'</a>'); > } > } > If I understand what that does correctly, it's probably something like this: def makeBread(url): path_parts = url.split('/') output = '<p class="trail">' where_at = '' for value in path_parts: where_at += value output += '<a href="%s">%s</a>' % (where_at, where_at) return output > I'd put this function in an external file include() > it and make a call with: > <?php > makeBread($PHP_SELF) > ?> > (Disclaimer: this code is really ugly its just an > example...) > > I'd like to do this in Python and make it a cgi-bin > file so I could have > something like this: > <!--#include virtual="/cgi-bin/bread.py" --> > > But I'm not sure where to start. How can I pass the > URL of the page > making the include call to the script? > > One its there I'm sure I can muddle through some > flow control structures > and what not to massage the URL into the various > breadcrumb pieces... > > Any help would be greatly appreciated. > > Thanks in advance, > > Chris It looks kind of like you're trying to write PHP in Python. There's nothing wrong with PHP, but it is not that popular to try to emulate other languages. (If you still want to, try the replcode module at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217, but it doesn't handle CGI automatically.) For advanced website templating, you should try CherryPy, or Zope's DTML. DTML does a good job of seperating style and coding, and CherryPy is very good object system and is easy to use. If you still want to use your weird comment syntax, a regexp would probably be necessary, but I don't know anything further. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From tayi177 at hotmail.com Wed Nov 26 00:00:03 2003 From: tayi177 at hotmail.com (David) Date: Wed Nov 26 00:00:13 2003 Subject: [Tutor] Re: Sample9.py and Sample9.pyc & seting path to Python open files ... Message-ID: <BAY8-DAV43LkEtpgWtf00003512@hotmail.com> Danny, you are right !! I have unfortunatelly mixed-up some terms/operations, IMPORTING file (or module) with .py extension, reading lines which are in that (somename.py) file, with sys.path.append("D:\\PROGRAM~1\Lib\idlelib\Saves\somefile.py) method, and READING file (I suppose ? with any extension ? - or .txt files for certain), with inp = open("somename.txt","r") method ... But anyway the problem, that I could not OPEN that file (not import module), with inp = open ... method still exist ... It says, as mentioned in previous mail: No such file or directory: 'somename.txt' The thing is, that I could open files, write/read in/from them yesterday, da before yestarday, etc., but today, I just couldn't do it anymore (used the same inp = open ... method). I also tryed to copy different copys of this file to all "essential" Python directoryes, D:\Program Files\Python\Lib\idlelib\Saves\, D:\Program Files\Python\, even in D:\Windows directory (and just in case in C:\Windows too), but always got that error message ... About Danny written: "Show us the code, and we can take a look" - honestly, it doesn't deserve to be called "code". There are just some basic "learning lines", just to become familiar with read/write functions, options, etc., so I think, it wouldn't mean any help to you. I was just attending to write something more "complex". And also I haven't got poblems processing this code, but already opening file, so I assume the problem is not in the code ... Thanks again -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031126/5dac5a88/attachment.html From fleming.j at comcast.net Wed Nov 26 00:06:45 2003 From: fleming.j at comcast.net (john fleming) Date: Wed Nov 26 00:05:25 2003 Subject: [Tutor] IDE In-Reply-To: <3FC41AB2.5010203@doruk.net.tr> References: <3FC41AB2.5010203@doruk.net.tr> Message-ID: <3FC434E5.8050704@comcast.net> Okan Asik wrote: > What's the most common IDE you people using while writing your own > programs ? > I have used emacs in linux and windows. If you want to try it in windows I suggest using Xemacs because it comes with python mode configured. But I learned a few things about wxPython by using boa constructor. It has an editing mode that lists properties that can be changed and you can edit your program by changing things there, and watching the result on your app. The seperate files for PyApp and Pyframe portions of the program I found confusing though and prefer to write the main framework of a program with one file until I get a better understanding of where to put things. John F From the_investor at arach.net.au Wed Nov 26 03:25:04 2003 From: the_investor at arach.net.au (The Investor) Date: Wed Nov 26 03:25:39 2003 Subject: [Tutor] clear IDLE Message-ID: <OIEJKFFKPKECFLDGAJMKGEEOCCAA.the_investor@arach.net.au> Here's a simple question: How do you clear previous IDLE errors? I've run a few programs and have all these exception errors on my IDLE screen and I am wondering if it is possible to clear them so that I have a fresh clean IDLE space without closing and reopening it again. It's so simple it's probably staring me right in the face! Ryan --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.543 / Virus Database: 337 - Release Date: 21/11/2003 From the_investor at arach.net.au Wed Nov 26 03:27:56 2003 From: the_investor at arach.net.au (Ryan Sheehy) Date: Wed Nov 26 03:28:05 2003 Subject: [Tutor] clear IDLE Message-ID: <OIEJKFFKPKECFLDGAJMKMEEOCCAA.the_investor@arach.net.au> Here's a simple question: How do you clear previous IDLE errors? I've run a few programs and have all these exception errors on my IDLE screen and I am wondering if it is possible to clear them so that I have a fresh clean IDLE space without closing and reopening it again. It's so simple it's probably staring me right in the face! Ryan --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.543 / Virus Database: 337 - Release Date: 21/11/2003 From paul at entropia.co.uk Wed Nov 26 03:22:29 2003 From: paul at entropia.co.uk (paul@entropia.co.uk) Date: Wed Nov 26 03:37:35 2003 Subject: [Tutor] multiple posts re zipfile Message-ID: <3FC462C5.5975.46EBB74@localhost> Apologies to the list, my ISP was a little broken yesterday so I kept getting undelivered mail messages. I'm not sure the ones that got through mentioned that the script works fine on NT4/ python2.2.2 Cheers Paul Butler From dyoo at hkn.eecs.berkeley.edu Wed Nov 26 03:40:50 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 26 03:40:55 2003 Subject: [Tutor] Re: Sample9.py and Sample9.pyc & seting path to Python open files ... In-Reply-To: <BAY8-DAV43LkEtpgWtf00003512@hotmail.com> Message-ID: <Pine.LNX.4.44.0311260010590.9375-100000@hkn.eecs.berkeley.edu> > About Danny written: "Show us the code, and we can take a look" - > honestly, it doesn't deserve to be called "code". There are just some > basic "learning lines", just to become familiar with read/write > functions, options, etc., so I think, it wouldn't mean any help to you. Hi Tadey, You're being too hard on yourself. Let us decide the usefulness or uselessness of the program for ourselves. There are good reasons for showing us the code. For one, it helps you practice giving good bug reports. *grin* Seriously, from a purely practical perspective, if you don't show us your program, all we can do is make vague guesses at what is causing the problem. At the moment, I have to wildly guess that there's a problem in the line that open()s the file, but that's as far as I can see without seeing. > I was just attending to write something more "complex". > > And also I haven't got poblems processing this code, but already opening > file, so I assume the problem is not in the code ... Yes, that's what you're assuming. But, frankly, if you don't have problems in your program, then that program should be working perfectly. The first rule about debugging is not to assume, without strong proof, that code is correct. And even if the problem isn't in the code itself, once we see what you've done so far, then given the context of the problem, we can give you better suggestions to further diagnose things. For example, if you had shown us something like the line: f = open("hello.txt") then that would have immediately given us some avenues of attacking the problem. Perhaps the current working directory is different today than yesterday. If that's the problem, then we'd ask what would happen if we hardcode the absolute path name during the open(), like: f = open("D:/Program Files/Python/Lib/idlelib/Saves/hello.txt") Or if you had shown us something like: f = open("D:\Program Files\Python\Lib\idlelib\Saves\hello.txt") then we could have warned you about the potential problems with backslashes in strings. Programming is a difficult thing: it's both a high-level and low-level activity, and bugs can come in from both directions. Summarizing the situtation --- that you're getting an error message when opening a file --- is a great thing to do. But equally good is to show the lines that are causing the problem. I apologize about being pedantic about this. *grin* But when you're asking for help, you need to show us what you're doing. There's a real value to showing us what you've typed, and how Python responds to your program. And aon't worry if the code is "simple", because that's perfectly ok to us: we like looking at simple code. Best of wishes to you! From alan.gauld at blueyonder.co.uk Wed Nov 26 04:57:19 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 26 04:56:39 2003 Subject: [Tutor] Re: Sample9.py and Sample9.pyc & seting path to Python openfiles ... References: <BAY8-DAV43LkEtpgWtf00003512@hotmail.com> Message-ID: <016801c3b403$ae4317c0$6401a8c0@xp> > And also I haven't got poblems processing this code, but > already opening file, so I assume the problem is not in the code ... The usual problem here is that the program is looking in a different place to the file location. Try hard coding the entire file path into the open statement. Oh yes, and check with explorer that the file does actually exist and that you have permission to open it! Alan g. From chris at heisel.org Wed Nov 26 10:22:12 2003 From: chris at heisel.org (Chris Heisel) Date: Wed Nov 26 10:22:22 2003 Subject: [Tutor] Automated Breadcrumb -- help for a PHP user In-Reply-To: <20031126031533.58801.qmail@web41811.mail.yahoo.com> References: <20031126031533.58801.qmail@web41811.mail.yahoo.com> Message-ID: <3FC4C524.7050007@heisel.org> I aplogize, I didn't mean to indicate that I wanted to write PHP in python, I'm trying to migrate to python because I enjoy the elegance of the language, I should have clarified my question a bit. I'm used to the PHP environment where I can access a page's URL and other attributes by accessing the various global system arrays. I have not done any traditional CGI programming, so I'm not sure about how to pass information, such as an HTML page's URI, to my python script. I'd love to use some of the frameworks you mentioned but I'm in a corporate environment designing a system for other Web producers who will be editing pages via BBEdit and then uploading to the server, so I'm trying to keep the set up as simple as possible. Danny's answer was helpful because its sent me down the cgi path and I'm doing some RTFM about cgi and the various variables available... So apologies all around, I should have clarieid that I wasn't used to the python way of accessing global page variables when being used as a CGI script, and not that I was confused about the language constructs to output the trail... Chris Daniel Ehrenberg wrote: > Chris Heisel wrote: > >>Hi, >> >>I'm a n00b to python coming from PHP land. >> >>I'd like to create an automated breadcrumb script >>that would inspect the >>URL and create an appropriate bread crumb navigation >>set. >> >>In PHP I'd so something like >>function makeBread($url) { >> $path_parts = explode('/', $url); >> echo('<p class="trail">'); >> foreach ($path_parts as $key => $value) { >> $where_at = $where_at + $value; >> echo('<a >>href="$where_at">'.$where_at.'</a>'); >> } >>} >> > > If I understand what that does correctly, it's > probably something like this: > > def makeBread(url): > path_parts = url.split('/') > output = '<p class="trail">' > where_at = '' > for value in path_parts: > where_at += value > output += '<a href="%s">%s</a>' % (where_at, > where_at) > return output > > >>I'd put this function in an external file include() >>it and make a call with: >><?php >>makeBread($PHP_SELF) >>?> >>(Disclaimer: this code is really ugly its just an >>example...) >> >>I'd like to do this in Python and make it a cgi-bin >>file so I could have >>something like this: >><!--#include virtual="/cgi-bin/bread.py" --> >> >>But I'm not sure where to start. How can I pass the >>URL of the page >>making the include call to the script? >> >>One its there I'm sure I can muddle through some >>flow control structures >>and what not to massage the URL into the various >>breadcrumb pieces... >> >>Any help would be greatly appreciated. >> >>Thanks in advance, >> >>Chris > > > It looks kind of like you're trying to write PHP in > Python. There's nothing wrong with PHP, but it is not > that popular to try to emulate other languages. (If > you still want to, try the replcode module at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217, > but it doesn't handle CGI automatically.) For advanced > website templating, you should try CherryPy, or Zope's > DTML. DTML does a good job of seperating style and > coding, and CherryPy is very good object system and > is easy to use. If you still want to use your weird > comment syntax, a regexp would probably be necessary, > but I don't know anything further. > > Daniel Ehrenberg > > __________________________________ > Do you Yahoo!? > Free Pop-Up Blocker - Get it now > http://companion.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From roman at kataisk.zaural.ru Wed Nov 26 10:25:24 2003 From: roman at kataisk.zaural.ru (Roman A. Lagunov) Date: Wed Nov 26 10:25:12 2003 Subject: [Tutor] clear IDLE In-Reply-To: <OIEJKFFKPKECFLDGAJMKMEEOCCAA.the_investor@arach.net.au> (Ryan Sheehy's message of "Wed, 26 Nov 2003 16:27:56 +0800") References: <OIEJKFFKPKECFLDGAJMKMEEOCCAA.the_investor@arach.net.au> Message-ID: <87u14rdue3.fsf@kataisk.zaural.ru> >>>>> "RS" ==> Ryan Sheehy writes: RS> Here's a simple question: How do you clear previous IDLE errors? RS> I've run a few programs and have all these exception errors on my IDLE RS> screen and I am wondering if it is possible to clear them so that I have a RS> fresh clean IDLE space without closing and reopening it again. In IDLE 1.0 which shipping whith python2.3 you can use 'Restart Shell' in 'Shell' menu item. -- Roman From roman at kataisk.zaural.ru Wed Nov 26 10:21:49 2003 From: roman at kataisk.zaural.ru (Roman A. Lagunov) Date: Wed Nov 26 10:25:23 2003 Subject: [Tutor] IDE In-Reply-To: <3FC41AB2.5010203@doruk.net.tr> (Okan Asik's message of "Tue, 25 Nov 2003 22:14:58 -0500") References: <3FC41AB2.5010203@doruk.net.tr> Message-ID: <87y8u3duk2.fsf@kataisk.zaural.ru> >>>>> "OA" ==> Okan Asik writes: OA> What's the most common IDE you people using while writing your own OA> programs ? Take a look at IPython. Description: An enhanced interactive Python shell IPython is an enhanced interactive Python shell. It can be used as a replacement for the standard Python shell, or it can be used as a complete working environment for scientific computing (like Matlab or Mathematica) when paired with the standard Python scientific and numerical tools. It supports dynamic object introspections, numbered input/output prompts, a macro system, session logging, session restoring, complete system shell access, verbose and colored traceback reports, auto-parentheses, auto-quoting, and is embeddedable in other Python programs. You can find it in http://ipython.scipy.org/ I think it's not a really IDE, but it's usefull for me. Btw, IPython works on Linux and Windows. -- Roman From guillermo.fernandez at epfl.ch Wed Nov 26 11:02:50 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Wed Nov 26 11:02:56 2003 Subject: [Tutor] readline under linux Message-ID: <3FC4CEAA.4020002@epfl.ch> Hi, i downloaded Python 2.3 a while ago, compiled it and installed it with no problem. Still, I tried to use the readline module: >>> import readline Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel- import readline ImportError: No module named readline I am running under linux, so i was expecting the module readline to be avalaible. I'm I wrong about this avaibility? Or is there any dependencies to satisfy that I've missed? Or maybe a special option at compile time that I did not set? Thanks, Guille From mhansen at cso.atmel.com Wed Nov 26 11:45:15 2003 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed Nov 26 11:44:02 2003 Subject: [Tutor] Re: IDE In-Reply-To: <E1AOv0y-00015B-7x@mail.python.org> References: <E1AOv0y-00015B-7x@mail.python.org> Message-ID: <3FC4D89B.5040400@cso.atmel.com> I've been reading The Pragmatic Programmer.(I think someone on this list mentioned it, so I fired it up in O'Reilly's Safari.) It strongly recommends finding a powerful editor to help make you more productive. IMHO, VIM & EMACS are probably the top two. There's a holy war between fans of each editor. I think they are both powerful tools. If you don't like one, try the other. You'll probably need to invest a few days to get used to the one you choose to learn, but it sounds like you can be much more productive once you get over the learning curve. I tried emacs 3 times over the years, and it never clicked with me. YMMV. When I came across the part about editors in The Pragmatic Programmer, I decided to take a look at VIM. So far, it's making more sense to me than EMACS. Both EMACS and VIM are very powerful. They try to keep your hands on the keyboard instead of the mouse which should result in you being more productive. There's lots of cool features in both editors that also help in productivity. I recommend that you try EMACS or VIM. It'll help you in Python and nearly any other programming language you decide to use. BTW, I believe that development on XEMACS has stopped, and most of the features that were in XEMACS are now in EMACS. "A surprising number of people we've met use the Windows notepad utility to edit their source code. This is like using a teaspoon as a shovel" - The Pragmatic Programmer Mike > > Subject: > Re: [Tutor] IDE > From: > john fleming <fleming.j@comcast.net> > Date: > Tue, 25 Nov 2003 21:06:45 -0800 > To: > Okan Asik <okana@doruk.net.tr> > > > Okan Asik wrote: > >> What's the most common IDE you people using while writing your own >> programs ? >> > I have used emacs in linux and windows. If you want to try it in > windows I suggest using Xemacs because it comes with python mode > configured. But I learned a few things about wxPython by using boa > constructor. It has an editing mode that lists properties that can be > changed and you can edit your program by changing things there, and > watching the result on your app. The seperate files for PyApp and > Pyframe portions of the program I found confusing though and prefer to > write the main framework of a program with one file until I get a > better understanding of where to put things. > > John F > > From magnus at thinkware.se Wed Nov 26 13:28:39 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Nov 26 13:28:47 2003 Subject: =?ISO-8859-1?B?VGhlIEFORC9PUiBwYXJ0IFJlOiBbVHV0b3JdIFNhbXBsZTkucHkgYW5kIFNhbXBsZTkucHljICYgc2V0aW5nIHBhdGggdG8gUHl0aG9uIG9wZW4gZmlsZXMgLi4u?= Message-ID: <think001_3fc4c77e0b18d@webmail.thinkware.se> > So in the one from techiwarehouse.com, there is an explanation of so-called Logical operators: and, or, and not. I do not understand explanation of and operator: In Boolean arithmetic, there are only two values, True (let's call that 1 for the moment) and False, let's call that 0 for now. There are also three operators, AND (we'll call that *), OR (let's call that +) and finally NOT (let's call that !). This arithemtic is based on a philosophical concept of logic and truth. IF the battery works, AND the light bulb is working AND I turn it on, my lamp will emit light. Written as an equation: emit_light = battery_works AND light_bulb_works AND turned_on Or rephrased: IF the battery does NOT work OR the light bulb is NOT working or I do NOT turn it on, the lamp will NOT emit light. Written as an equation: NOT emit_light = (NOT battery_works) OR (NOT light_bulb_works) OR (NOT turned_on) (Actually, this transformation from AND to NOT/OR is called de Morgans theorem, but that doesn't matter now.) In general: True AND True = True True AND False = False False AND True = False False AND False = False True AND True = True True AND False = False False AND True = False False AND False = False NOT True = False NOT False = True Written with the shorter notation I suggested above, we get: 1 * 1 = 1 1 * 0 = 0 0 * 1 = 0 0 * 0 = 0 1 + 1 = 1 1 + 0 = 1 0 + 1 = 1 0 + 0 = 0 !1 = 0 !0 = 1 As you see, AND behaves exactly like multiplication, and OR is very close to addition, with the little quirk that 1 + 1 = 0. Note that this is not normal binary arithmetic, where 1 + 1 = 10. Still, it's close enough to normal arithemtic for 1, 0 and *, + to become popular symbols for True, False and AND, OR. If you generalize the equations above, and let X or Y represent values that can be either True or False, we can say that if X is true: X AND Y = Y X OR Y = X if X is false: X AND Y = X X OR Y = Y Are you following this? It's a generalization of 1 AND 1 = 1 1 AND 0 = 0 0 AND 1 = 0 0 AND 0 = 0 1 OR 1 = 1 1 OR 0 = 1 0 OR 1 = 1 0 OR 0 = 0 If Boolean theory, this assumes that X is either true or false. In some programming languages, such as Python, this concept has been extended a bit. Basically, in Python, 0, 0j, 0.0, "", [], (), {}, None and instances of classes where the __nonzero__ method returns a false value are false. All (?) other values are true. So, this... >>> 0 or 5 5 ..is completely in line with George Boole. Five is one of many representations of True, and 0 is one of several representations of False, so what is says above is "False AND True = True" That's completely correct. A possible problem occurs if you have to completely unfounded idea that all truths are equal, and that all incarnations of false are equal, since for instance >>> (0 or 5) == (0 or 3) False One truth isn't always identical another... (Or as another George put it: "All animals are equal, but some are more equal than others." ;) In the case of comparisions (<, <=, ==, !=, > and >=) Python returns the values True (which is basically 1 on disguise) and False (which is basically 0 in disguise). In previous versions it returned 1 and 0. The not-operator also returns True or False. >>> not 0 True >>> 1 == '' False >>> not "Hello" False >>> 5 < 3 False It would be very odd if "1 == 1" would return 42 or some other arbitrary value, but in the case of AND and OR, it's very useful to use the generalization I mentioned above: if X is true: X AND Y = Y X OR Y = X if X is false: X AND Y = X X OR Y = Y This enables us to use AND and OR as very compact versions of if statements that we can put inside expressions. For instance, if we have a variable X that can either contain an integer on the value None, and we want to treat None as 0 from a mathermatical perspective, we can write something like... R = ((X or 0) + Y) * Z ..instead of... if X: R = (X + Y) * Z else: R = Y * Z Or, if you are displaying email messages, you could use something like... print subject or "<no subject>" ..instead of... if subject: print subject else: print "<no subject>" I think it's less common that the and-operator is used like this in Python, but for instance, you could do... y = (x >= 0 and x) * 5 ..instead of... if x > 0: y = x > 5 else: y = 0 -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus at thinkware.se Wed Nov 26 14:18:55 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Wed Nov 26 14:19:02 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQXV0b21hdGVkIEJyZWFkY3J1bWIgLS0gaGVscCBmb3IgYSBQSFAgdXNlcg==?= Message-ID: <think001_3fc4f95a3e3e2@webmail.thinkware.se> > But I'm not sure where to start. How can I pass the URL of the page > making the include call to the script? You don't have to pass it in to the script (as a parameter). The script can simply read the environment variables. import os uri=os.environ['REQUEST_URI'] The following CGI script will show all the environment variables that are set: #!/usr/bin/python -u import os print "Content-type: text/plain\n\n" env_keys = os.environ.keys(); env_keys.sort() for key in env_keys: print "%s=%s" % (key, os.environ[key]) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From chris at heisel.org Wed Nov 26 14:55:59 2003 From: chris at heisel.org (Chris Heisel) Date: Wed Nov 26 14:56:04 2003 Subject: [Tutor] Automated Breadcrumb -- help for a PHP user In-Reply-To: <think001_3fc4f95a3e3e2@webmail.thinkware.se> References: <think001_3fc4f95a3e3e2@webmail.thinkware.se> Message-ID: <3FC5054F.7090507@heisel.org> I wanted to thank everyone for their help, I've successfully finished my first (non-hello-world) Python program. I'd love any feedback that you all have about ways I might improve it and make it more Python-like... Thanks again, Chris <CODE> def nameHandler(name): if 'index.html' == name: name = '' return name elif name.endswith('.html'): name = 'Content' return name else: name = name.capitalize() return name def valueChecker(value): if '' == value: pass else: return value def breadMaker(url, basedir, basedir_name, glue): path_parts = url.split('/') #path_parts has an empty first item we need to fix it here href = basedir output = '<p class="trail"><a href="%s">%s</a> %s ' % (basedir, basedir_name, glue) for value in path_parts: name = nameHandler(value) if '' == name: continue #if its a blank string try again if value.endswith('.html'): href = href+value else: href = href+value+'/' if 'Content' == name: output += '<a href="%s">%s</a>' % (href, name) else: output += '<a href="%s">%s</a> %s ' % (href, name, glue) output = output+'</p>' return output print "Content-type: text/plain\n\n" path = os.environ['DOCUMENT_URI'] basedir = '/' basedir_name = 'AJC Sports Plus' trail = breadMaker(path, basedir, basedir_name, '>') print trail From dyoo at hkn.eecs.berkeley.edu Wed Nov 26 15:39:52 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Nov 26 15:40:02 2003 Subject: [Tutor] readline under linux In-Reply-To: <3FC4CEAA.4020002@epfl.ch> Message-ID: <Pine.LNX.4.44.0311261225170.1611-100000@hkn.eecs.berkeley.edu> On Wed, 26 Nov 2003, Guillermo Fernandez Castellanos wrote: > Traceback (most recent call last): > File "<pyshell#0>", line 1, in -toplevel- > import readline > ImportError: No module named readline > > I am running under linux, so i was expecting the module readline to be > avalaible. Hi Guillermo, Although you have the readline library installed, you might not have the readline 'development' files that Python needs when it compiles support for readline. Many Linux distributions will decouple the development stuff from the main library, so you may need to install the readline-devel stuff first, and then recompile Python. > I'm I wrong about this avaibility? Or is there any dependencies to > satisfy that I've missed? Or maybe a special option at compile time that > I did not set? You most likely won't have to do anything special with './configure'. Python 2.3 should be able to autodetect readline once the development stuff is in place. If you're running a RPM-based distribution, like Redhat, look for something like 'readline-devel' from your Linux installation CD. Similarly, if you're using a Debian-based system, look for 'readline-dev'. Good luck to you! From alan.gauld at blueyonder.co.uk Wed Nov 26 15:43:37 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Nov 26 15:42:49 2003 Subject: [Tutor] Re: IDE References: <E1AOv0y-00015B-7x@mail.python.org> <3FC4D89B.5040400@cso.atmel.com> Message-ID: <018701c3b45d$f7b72900$6401a8c0@xp> > I've been reading The Pragmatic Programmer. An excellent book for the intermediate level programmer. > recommends finding a powerful editor to help make you more productive. > IMHO, VIM & EMACS are probably the top two. Yes, my only disagreement with them is that they suggest sticking with one. I use both emacs and vim for different things. vim is great for fast edits to existing text - its search tools are peerless. Emacs is better for creating new text and for making large scale changes over many files (its macro capabilities are much better than vim) > BTW, I believe that development on XEMACS has stopped, and most of the > features that were in XEMACS are now in EMACS. Really? I must check that out. Xemacs was well ahead of emacs for a spell. Alan g. From littledanehren at yahoo.com Wed Nov 26 15:59:24 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Nov 26 15:59:28 2003 Subject: [Tutor] wxPython window flashes open and closed Message-ID: <20031126205925.53563.qmail@web41804.mail.yahoo.com> I'm trying to learn wxPython. I made a simple hello world app but it just flashes open and closed. Here's the code: import wx class window(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Hi") if __name__ == '__main__': x = window() x.Show(True) I'm using Debian GNU/Linux and Python 2.3.2, but I don't think that should matter. Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From littledanehren at yahoo.com Wed Nov 26 16:46:29 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Nov 26 16:46:34 2003 Subject: [Tutor] readline under linux In-Reply-To: <Pine.LNX.4.44.0311261225170.1611-100000@hkn.eecs.berkeley.edu> Message-ID: <20031126214629.44863.qmail@web41801.mail.yahoo.com> Danny Yoo wrote: > Similarly, if you're using a > Debian-based system, look > for 'readline-dev'. > > > Good luck to you! Actually, it's called libreadline4-dev, so it can be installed by typing apt-get install libreadline4-dev. __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From littledanehren at yahoo.com Wed Nov 26 17:14:40 2003 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Nov 26 17:14:45 2003 Subject: [Tutor] Automated Breadcrumb -- help for a PHP user In-Reply-To: <3FC5054F.7090507@heisel.org> Message-ID: <20031126221440.50184.qmail@web41813.mail.yahoo.com> Chris Heisel wrote: > def nameHandler(name): > if 'index.html' == name: > name = '' > return name > elif name.endswith('.html'): > name = 'Content' > return name > else: > name = name.capitalize() > return name I don't understand why you have those multiple returns when they all return the same variable. I'd do it more like this: def nameHandler(name): if name == 'index.html': handled = '' elif name.endswith('.html'): handled = 'Content' else: handled = name.capitalize() return handled > > def valueChecker(value): > if '' == value: > pass > else: > return value > You don't really need this, as I'll explain below, but if you still wanted it, you should probably write def valueChecker(value): if value: return value It works slightly differently, but for strings, it's the same. Basically it returns None for '' and any other empty value (yours only returned None for '') and returns the input value for everything else. > def breadMaker(url, basedir, basedir_name, glue): > path_parts = url.split('/') > #path_parts has an empty first item we need to fix > it here That's not a bug. That's how it's supposed to work, but not necessarily what you wanted. For almost every purpose, there will never be two adjacent /s, so this should work as you want it to: path_parts = url.split('/')[1:] But if you want to filter out all empty strings, there are two ways to do this: list comprehensions and filters. path_parts = filter(None, url.split('/')) #basically filters out all of the things that would return None on valueChecker path_parts = filter(valueChecker, url.split('/')) #actually uses valueChecker path_parts = [ x for x in url.split('/') if x ] #List comprehension. > > href = basedir > output = '<p class="trail"><a href="%s">%s</a> > %s ' % (basedir, > basedir_name, glue) > > for value in path_parts: > name = nameHandler(value) > if '' == name: > continue #if its a blank string try again > > if value.endswith('.html'): > href = href+value > else: > href = href+value+'/' > You should probably use += in those previous few lines, and also add value to it outside of the if statement. Actually, the if statement could be completely gotten rid of: x = int(value.endswith('.html')) href = href + value + x*'/' Multiplying a string times zero gives ''. > if 'Content' == name: > output += '<a href="%s">%s</a>' % (href, > name) > else: > output += '<a href="%s">%s</a> %s ' % > (href, name, glue) > > output = output+'</p>' > return output > > > print "Content-type: text/plain\n\n" > path = os.environ['DOCUMENT_URI'] > > basedir = '/' > basedir_name = 'AJC Sports Plus' > > trail = breadMaker(path, basedir, basedir_name, '>') > print trail Daniel Ehrenberg __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From thinkuknowme2007 at yahoo.com Wed Nov 26 18:59:26 2003 From: thinkuknowme2007 at yahoo.com (Udz) Date: Wed Nov 26 18:59:31 2003 Subject: [Tutor] distutil setup script Message-ID: <20031126235926.16801.qmail@web60206.mail.yahoo.com> i'm having trouble using a distutil setup script with py2exe. using the example given on their site, i created a setup script. however, when i go to run the script from command prompt (python setup-script.py py2exe ----- i think thats the right command), i get the following error: File "setup-script.py", line 8 scripts=["thing.py"], ^ SyntaxError: invalid syntax This is my setup script: #setup-script from distutils.core import setup import py2exe setup(name = "thing" scripts=["thing.py"], ) I have no clue what i'm doing wrong(yes, i'm a newbie, could u tell?), i tried messing around with it a bit, but it gives me a syntax error each time. so yes, I need help with that. thanx to any and every one that does help me, Udz --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031126/b4db1563/attachment.html From op73418 at mail.telepac.pt Wed Nov 26 19:39:03 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Nov 26 19:37:10 2003 Subject: [Tutor] distutil setup script In-Reply-To: <20031126235926.16801.qmail@web60206.mail.yahoo.com> References: <20031126235926.16801.qmail@web60206.mail.yahoo.com> Message-ID: <iqhasv0r803ds7p9ads60f5irdr579mh33@4ax.com> On Wed, 26 Nov 2003 15:59:26 -0800 (PST), you wrote: >i'm having trouble using a distutil setup script with py2exe. using the example given on their site, i created a setup script. however, when i go to run the script from command prompt (python setup-script.py py2exe ----- i think thats the right command), i get the following error: > > File "setup-script.py", line 8 > scripts=["thing.py"], > ^ >SyntaxError: invalid syntax > >This is my setup script: > >#setup-script >from distutils.core import setup >import py2exe >setup(name = "thing" ^^^^^^^^^^^^ Isn't a comma missing here? > scripts=["thing.py"], >) > It should be: setup(name = "thing", scripts=["thing.py"],) Best, G. Rodrigues From thinkuknowme2007 at yahoo.com Wed Nov 26 22:44:05 2003 From: thinkuknowme2007 at yahoo.com (Udz) Date: Wed Nov 26 22:44:11 2003 Subject: [Tutor] help? Message-ID: <20031127034405.5513.qmail@web60207.mail.yahoo.com> well, after i fixed my little mistake (thanx G.Rodriguez, I made a stupid mistake.), i ran py2exe, and it appeared to work right, it built the dir that it was supposed to, and compiled the .dll and .exe file. the only problem is, the program doesnt work. i know that the solution is sitting right in front of me, but i can't figure it out. was i supposed to alter the code somehow to qualify it for compilation (or whatever py2exe does)? yes, i'm stuck, so if anyone could help me that'd be great. thanx to any and everyone that tries to help, Udz --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031126/20770582/attachment-0001.html From karl.fast at pobox.com Wed Nov 26 23:18:42 2003 From: karl.fast at pobox.com (Karl Fast) Date: Wed Nov 26 23:18:49 2003 Subject: [Tutor] wxPython window flashes open and closed In-Reply-To: <20031126205925.53563.qmail@web41804.mail.yahoo.com>; from littledanehren@yahoo.com on Wed, Nov 26, 2003 at 12:59:24PM -0800 References: <20031126205925.53563.qmail@web41804.mail.yahoo.com> Message-ID: <20031126221842.A25721@signal.lights.com> > I'm trying to learn wxPython. I made a simple hello world app but it > just flashes open and closed. Here's the code: I had the same problem. You need to redirect stdout/stderr to a file. By default it goes to a console window, but this disappears immediately after the program exits. So if you've got a fatal error that causes your program to die before it gets started, well, you'll never see it. This message describes the problem and the solution. Worked for me. http://lists.wxwindows.org/archive/wxPython-users/msg07054.html From venkatbabukr at yahoo.com Thu Nov 27 05:10:04 2003 From: venkatbabukr at yahoo.com (Venkatesh Babu) Date: Thu Nov 27 05:10:37 2003 Subject: [Tutor] Creating Parent and child threads Message-ID: <20031127101004.42492.qmail@web41411.mail.yahoo.com> Hi, I have a question related to thread programming in Python. In my program, I am creating a set of threads which I call parent threads because each of them in turn is spawning one or more threads (child threads), starting all these child threads simultaneously and waiting for these child threads to terminate. Now my problem is: The program works fine as long as there are few parent threads but as the number of parent threads becomes, more my program hangs. I guess a dead lock is happening but I'm not able to figure out what is causing this. Is it due to any mistake in the program or something else? The program code is shown below: import threading class ChildThread(threading.Thread): task = None def __init__(self, task): threading.Thread.__init__(self) self.task = task def run(self): self.task() return class ParentThread(threading.Thread): children = None def __init__(self, tasks): threading.Thread.__init__(self) self.children = list([]) for t in tasks: self.children.append(ChildThread(t)) def run(self): for c in self.children: c.start() for c in self.children: c.join() return Given this, if I create say 3 parent threads each of which spawn 3 child threads: ex: for i in range(3): mts.append(ParentThread([f1, f2, f3])) # f1, f2 and f3 are functions for t in mts: t.start() then few threads execute properly and the remaining aren't executing. their _Thread__started has a value 1 but then why are the threads not executing? Please help me in finding out what is the mistake? and sorry for long mail. Thank you, Venkatesh __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From guillermo.fernandez at epfl.ch Thu Nov 27 05:18:31 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez Castellanos) Date: Thu Nov 27 05:18:37 2003 Subject: [Tutor] readline under linux In-Reply-To: <Pine.LNX.4.44.0311261225170.1611-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0311261225170.1611-100000@hkn.eecs.berkeley.edu> Message-ID: <3FC5CF77.3080900@epfl.ch> Hi, >Although you have the readline library installed, you might not have the >readline 'development' files that Python needs when it compiles support >for readline. Many Linux distributions will decouple the development >stuff from the main library, so you may need to install the readline-devel >stuff first, and then recompile Python. > > Actually I compiled Python a while ago, so I did not think about checking the ./configure again... I did as Daniel sugested: $ ./configure |grep read [thread support snip] checking for readlink... yes checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... no I suppose from here that the readline-devel stuf is not installed. The problem is that I'm not root on my machine, and the sysadmin is not very oppened to install new packages. Do you think it would be posible for me to compile the dev stuff into my account and use it for compilation? I've already done it for other librairies (sqlite for instance) but I've never tried with only the developmentpart of a library, and I'm afraid I could break up some other things... Otherwise, I checked and I did not even see the readline.py file in my /home/myself/lib/python23/, but I guess it's normal if it did not compile... Thanks, Guille From tayi177 at hotmail.com Thu Nov 27 05:44:18 2003 From: tayi177 at hotmail.com (David) Date: Thu Nov 27 05:45:15 2003 Subject: [Tutor] inp. outp. - part 2 & variable - dictionary difference ... Message-ID: <BAY8-DAV45gfelcBAvT000044a7@hotmail.com> Hello ... About my yesterday question: I just noticed two "interesting" issues (probably releated only to my configuration): 1.) First I found out, after trying few times, closing Python, and opening it again, that sometimes it open file (for reading/writting), and sometimes just don't, arbitrary, meaning that its not like I couldn't open the file always I try, therefore the most logical conclusion would be - I miss-spelled the code, but no: I 100 % tryed with identical input, I double, triple-checked the "code" ... I use the method below, from Alan's tutorial (don't know, probably the only one method for read/write files) ... I also checked files (on Alan's suggestion), if the are accidentally set as "read-only", I even unchecked "archive" (but that wouldn't explain why I could open them yesteday) ... with no benefit - as I said sometimes just can, and sometimes just can't (I second case I get "no such file or directory: 'somename.txt'" error message) !! >>> inp = open("lll.txt","r") # made both files just before opening Python ... >>> outp = open("ggg","w") ... for line in inp.readlines(): # for intendation here, I am not sure if its right, cause I couldn't check it ... ... outp.write(line) # before sending this mail, because of all mentioned above ... >>> inp.close() >>> outp.close() So, I was surely surprised yesterday, when (after "restarting" Python) trying to open the very same file, it was normally opened with the same method, with same text (input): >>> inp = open("lll.txt","r") >>> outp = open("ggg","w") ... but today after closing Python, shuting down PC (sleeping 8 hours) and trying to do the same thing again - there was the same (familiar) - "no such file or directory: 'somename.txt'" error message !! I have also tryed what Danny suggested, some other method to open file, and typed: >>> inp = open("D:/Program Files/Python/Lib/idlelib/Saves/ggg.txt") ... and the file was opened normally !! ... but in the very next line (of course after typing inp.close() ), with inp = open("somefile.txt","r") method: >>> inp = open("lll.txt","r") ... the was "no such file or directory" error message again !! 2.) Second about reading/writing from/into file, I noticed (yesterday, when I had luck and I could open file), that Python doesn't want to write from one file to another, which is non-empty (though maybe also just in my case) and also in file, which was already modified (something written in), changed from outside Python, during current session (of course, I used inp(close) before modified it) and even if this file was modified, and I later deleted that "new added" text (again maybe just in my case). 2.) Then I would really like to know, if I open some file, already process some line, and then miss-spell something, and some error message appears - do I need to close both (inp and out) files, and start from the beginning, or could I continue from the line before that error message ?? 3.) And as the last question, Alan.G's answer on my question about "difference between different types of brackets", was: "{} indicate a dictionary. ... One item in the pair is the lookup key, the other the return value." I am just curious - where is some "elemental" difference between dictionary (in practical use) and simple variable, cause "One item in the pair is the lookup key, the other the return value." - more or less resemble on variable deffiniton ... Example: instance = "Actual usage of class" (here we have variable and its actual value, stored in some location in RAM) ... so here one item is also some sort of "lookup key", and the other "the return value" ... Sorry, I really have more "theoretical" questions now on the beginning of learning how to programm, but it (answers here on Tutor list) really help me to imagine how everything works. P.S., I save all the answers I get, and you couldn't imagine (or you probably do, but I just said so, cause it sounds nice), how helpfull is having you answers saved somewhere, and when something is not so clear, just open those files, and see what was doing wrong ... Thank you all, Tadey -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031127/b1e8be68/attachment.html From intatia at paradise.net.nz Thu Nov 27 06:36:51 2003 From: intatia at paradise.net.nz (Intatia) Date: Thu Nov 27 06:38:09 2003 Subject: [Tutor] Disable output buffer with some tkinter thrown in. Message-ID: <3FC5E1D3.1000600@paradise.net.nz> I am doing a little python scripting for kmuddy, a mud client, this involves receiving, having a look at, and occasionaly sending stuff back. What is sent/received is always plain text through stdin and stdout. Firstly when I first started off I came across a problem where everything I sent back (via a print statement) came up only after the script had finished, a quick post on the kmuddy led me to using sys.stdout.flush() after each print statement, but it was also mentioned that in other languages it's possible to disable the output buffer entirely. Mentioned in perl: ,$|=1; and in C/C++ as: setvbuf (stdout, 0, _IONBF, 0); How do I do this in python? Secondly I am running into a similar problem when using Tkinter, createing a root window and inserting labels. It creates the Tkinter window but then it just sits there without the labels being added in, closing the tkinter window produces the following traceback : Traceback (most recent call last): Script info has finished with return code 1. <<<--This line is from kmuddy File "/home/intatia/script/infomation.py", line 7, in ? Label(root, tex="Hello").grid(row=0, column=0) File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 2370, in __init__ Widget.__init__(self, master, 'label', cnf, kw) File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1835, in __init__ self.tk.call( _tkinter.TclError: can't invoke "label" command: application has been destroyed This script works perfectly and as expected when run by itself from the command line. I can only assume it is running into the same problem as the print statements were, some sort of output buffer? Any ideas? Thoughts? Musings? Random gueses?:) Python 2.3 on Mandrake9.1 kmuddy 0.6rc2 As an explanation on what I'm doing as a whole, I'm aiming at creating a script that intercepts says/goss/clantell/tell (Communication from other players) into window for easier (and slower) reading. And perhaps eventually putting in the capacity to reply on the appropriate channel. Thanks:) From intatia at paradise.net.nz Thu Nov 27 06:53:38 2003 From: intatia at paradise.net.nz (Intatia) Date: Thu Nov 27 06:57:34 2003 Subject: [Tutor] Disable output buffer with some tkinter thrown in. In-Reply-To: <3FC5E1D3.1000600@paradise.net.nz> References: <3FC5E1D3.1000600@paradise.net.nz> Message-ID: <3FC5E5C2.3050306@paradise.net.nz> Hrm, I seem to have got the Tkinter problem sorted, a minor shifting of this and that etc etc, will work on it more in the morning. <<snip>> From missive at hotmail.com Thu Nov 27 10:14:48 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Nov 27 10:14:55 2003 Subject: [Tutor] Re: Creating Parent and child threads Message-ID: <BAY2-F11JYuD6WSgJJW00015bbd@hotmail.com> >Now my problem is: The program works fine as long as >there are few parent threads but as the number of >parent threads becomes, more my program hangs. I guess >a dead lock is happening but I'm not able to figure >out what is causing this. Is it due to any mistake in >the program or something else? > Not sure... works for me. I rewrote your code a bit... import threading class ChildThread(threading.Thread): def __init__(self, task): threading.Thread.__init__(self) self.task = task def run(self): self.task() return class ParentThread(threading.Thread): def __init__(self, tasks): threading.Thread.__init__(self) self.children = [] for t in tasks: self.children.append(ChildThread(t)) def run(self): for c in self.children: c.start() for c in self.children: c.join() return def f1(): print 'f1' def f2(): for c in range(2): print 'f2' def f3(): for c in range(3): print 'f3' def main(): PARENT_THREADS = 3 CHILD_THREADS = 1 mts = [] for i in range(PARENT_THREADS): mts.append(ParentThread([f1, f2, f3]*CHILD_THREADS)) for t in mts: t.start() if __name__ == '__main__': main() When I bumped PARENT_THREADS up to about 3000 I ran out of memory, but with PARENT_THREADS at 300 and CHILD_THREADS at 100 it was able to finish without deadlocking. What are you actually doing in f1 f2 and f3. Maybe that is the problem... _________________________________________________________________ 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 Thu Nov 27 10:44:15 2003 From: karl.fast at pobox.com (Karl Fast) Date: Thu Nov 27 10:45:17 2003 Subject: [Tutor] IDE In-Reply-To: <3FC401CB.1090900@paradise.net.nz>; from intatia@paradise.net.nz on Wed, Nov 26, 2003 at 02:28:43PM +1300 References: <3FC41AB2.5010203@doruk.net.tr> <3FC401CB.1090900@paradise.net.nz> Message-ID: <20031127094415.A8763@signal.lights.com> > > What's the most common IDE you people using while writing your own > > programs ? > > Not sure if it counts, but I use vim I use VIM too, but I'm relatively new to VIM and haven't got it all down. Is there a tutorial on using VIM to develop in python? I've pulled some useful scripts from vim.org for folding and commenting and a few other things. This has improved the situation considerably, but I still feel like I'm missing important things. People ask "What IDE do you use?" and the reponse is usually "VI(M) or (x)Emacs." But I haven't found a comprehensive tutorial on how to effectively use VIM with python. --karl From venkatbabukr at yahoo.com Thu Nov 27 13:36:13 2003 From: venkatbabukr at yahoo.com (Venkatesh Babu) Date: Thu Nov 27 13:36:18 2003 Subject: [Tutor] Re: Creating Parent and child threads In-Reply-To: <BAY2-F11JYuD6WSgJJW00015bbd@hotmail.com> Message-ID: <20031127183613.93840.qmail@web41415.mail.yahoo.com> Hi, Unfortunately this modified code is also not working here. I am not getting same output every time I execute this piece of code. Thus, I've just pasted the output produced during one such executions. The Output is shown below: Note: I've saved the code in Test.py and imported Test at the prompt. Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import threading >>> import Test >>> f1 f3 f3 f3 f2 f2 >>> threading.enumerate() [<_MainThread(MainThread, started)>, <ParentThread(Thread-1, started)>, <ParentThread(Thread-5, started)>, <ChildThread(Thread-2, started)>, <ChildThread(Thread-3, started)>, <ParentThread(Thread-9, started)>, <ChildThread(Thread-8, started)>] >>> These threads donot show any activity for long time and I am finally stopping all these threads explicitly. Also few parent threads aren't having all their child threads created. Why is this happening? Now, since this problem is not happening with you, is this problem related to any configuration settings? Regarding my implementation of functions f1, f2, f3: They were also simple functions just printing some arbitrary string. Thank you, Venkatesh --- Lee Harr <missive@hotmail.com> wrote: > > Not sure... works for me. > > I rewrote your code a bit... > > > import threading > > > class ChildThread(threading.Thread): > def __init__(self, task): > threading.Thread.__init__(self) > self.task = task > > def run(self): > self.task() > return > > class ParentThread(threading.Thread): > def __init__(self, tasks): > threading.Thread.__init__(self) > self.children = [] > for t in tasks: > self.children.append(ChildThread(t)) > > def run(self): > for c in self.children: > c.start() > for c in self.children: > c.join() > return > > > def f1(): > print 'f1' > > > def f2(): > for c in range(2): > print 'f2' > > > def f3(): > for c in range(3): > print 'f3' > > > def main(): > PARENT_THREADS = 3 > CHILD_THREADS = 1 > > mts = [] > for i in range(PARENT_THREADS): > mts.append(ParentThread([f1, f2, > f3]*CHILD_THREADS)) > > for t in mts: > t.start() > > > if __name__ == 'Test': > main() > > > > When I bumped PARENT_THREADS up to about 3000 I ran > out of memory, > but with PARENT_THREADS at 300 and CHILD_THREADS at > 100 it was able > to finish without deadlocking. > > What are you actually doing in f1 f2 and f3. Maybe > that is the problem... > > _________________________________________________________________ > STOP MORE SPAM with the new MSN 8 and get 2 months > FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From magnus at thinkware.se Thu Nov 27 13:49:41 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Thu Nov 27 13:49:54 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gRGlzYWJsZSBvdXRwdXQgYnVmZmVyIHdpdGggc29tZSB0a2ludGVyIHRocm93biBpbi4=?= Message-ID: <think001_3fc63e7d790ac@webmail.thinkware.se> > Firstly when I first started off I came across a problem where everything I sent > back (via a print statement) came up only after the script had finished, a quick > post on the kmuddy led me to using sys.stdout.flush() after each print > statement, but it was also mentioned that in other languages it's possible to > disable the output buffer entirely. > Mentioned in perl: ,$|=1; > and in C/C++ as: setvbuf (stdout, 0, _IONBF, 0); > How do I do this in python? You can skip buffering for a whole python process using "python -u" (or #!/usr/bin/env python -u etc) or by setting the environment variable PYTHONUNBUFFERED. You could also replace sys.stdout with some other stream like wrapper which does a flush after every call. Something like this (not really tested) might work...but there are probably problems that could pop up. For instance, I don't think it will work in IDLE, since sys.stdout is already replaced with some funny object there which doesn't like to be flushed. (This could be considered a bug in IDLE though.) >>> class Unbuffered: .. def __init__(self, stream): .. self.stream = stream .. def write(self, data): .. self.stream.write(data) .. self.stream.flush() .. def __getattr__(self, attr): .. return getattr(self.stream, attr) .. >>> import sys >>> sys.stdout=Unbuffered(sys.stdout) >>> print 'Hello' Hello Here, we replace sys.stdout with an object that will make a flush after every write, but will delegate everything else to the buffer it was initiated with. Of course, this is (if it works :) a more generic solution that can be used for a lot more than flushing buffers. For instance, it could turn your output into pig latin or convert text to some different code page. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From thinkuknowme2007 at yahoo.com Thu Nov 27 14:28:23 2003 From: thinkuknowme2007 at yahoo.com (Udz) Date: Thu Nov 27 14:28:26 2003 Subject: [Tutor] program doesnt work Message-ID: <20031127192823.40767.qmail@web60210.mail.yahoo.com> well, after i fixed my little mistake (thanx G.Rodriguez, I made a stupid mistake.), i ran py2exe, and it appeared to work right, it built the dir that it was supposed to, and compiled the .dll and .exe file. the only problem is, the program doesnt work. The window just kinda pops up, then disappears without doing anything. i know that the solution is sitting right in front of me, but i can't figure it out. was i supposed to alter the code somehow to qualify it for compilation (or whatever py2exe does)? yes, i'm stuck, so if anyone could help me that'd be great. thanx to any and everyone that tries to help, Udz --------------------------------- Do you Yahoo!? Free Pop-Up Blocker - Get it now -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031127/8829a8b7/attachment.html From carroll at tjc.com Thu Nov 27 16:55:52 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Nov 27 16:55:57 2003 Subject: [Tutor] Toolkit for Tkinter? Message-ID: <Pine.LNX.4.44.0311271349330.6100-100000@violet.rahul.net> I want to do more in the way of GUI programming, and Tkinter kind of frustrates me in the level of detail it requires. I've heard about Wax, both on this list and at its web site <http://zephyrfalcon.org/moin.cgi/Wax>, but that's an interface into wxPython. I'd like to stay in Tkinter, rather than learning a whole new GUI toolkit like wxPython. I don't use Python professionally, this is just for my own use for my occasional programming at home, so I'm looking for a no-cost option, being a cheap bastard. So, does anyone know of anything comparable to Wax for Tkinter? (Happy Thanksgiving to the USAians on the list.) -- Terry Carroll Santa Clara, CA carroll@tjc.com From missive at hotmail.com Thu Nov 27 18:55:17 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Nov 27 18:55:37 2003 Subject: [Tutor] Re: Creating Parent and child threads Message-ID: <BAY2-F46u4eMxfp2C8t00016f7b@hotmail.com> >Unfortunately this modified code is also not working >here. I am not getting same output every time I >execute this piece of code. Thus, I've just pasted the >output >produced during one such executions. > I think that is expected when working with threads. >The Output is shown below: > >Note: I've saved the code in Test.py and imported Test >at the prompt. > >Python 2.2.2 (#1, Feb 24 2003, 19:13:11) >[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 >Type "help", "copyright", "credits" or "license" for >more information. > >>> import threading > >>> import Test I don't see how this could be... if you have the code I posted in the module Test, then you would have to do ... import Test Test.main() or are you actually running some other code? > >>> f1 >f3 >f3 >f3 >f2 >f2 > > >>> threading.enumerate() >[<_MainThread(MainThread, started)>, ><ParentThread(Thread-1, started)>, ><ParentThread(Thread-5, started)>, ><ChildThread(Thread-2, started)>, ><ChildThread(Thread-3, started)>, ><ParentThread(Thread-9, started)>, ><ChildThread(Thread-8, started)>] > >>> > >These threads donot show any activity for long time >and I am finally stopping all these threads >explicitly. Also few parent threads aren't having all >their child threads created. Why is this happening? > >Now, since this problem is not happening with you, is >this problem related to any configuration settings? > >Regarding my implementation of functions f1, f2, f3: >They were also simple functions just printing some >arbitrary string. > I guess I recommend posting to the main python list (I view it as comp.lang.python on usenet) Make sure to include the exact code you are using and the details of your system (python and os versions and how you are running the code -- like if you are in IDLE or konsole or gnome terminal) along with the output you are getting and the output that you expect to get. _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From alan.gauld at blueyonder.co.uk Thu Nov 27 17:50:13 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Nov 27 19:08:31 2003 Subject: [Tutor] IDE References: <3FC41AB2.5010203@doruk.net.tr> <3FC401CB.1090900@paradise.net.nz> <20031127094415.A8763@signal.lights.com> Message-ID: <000001c3b543$c7831a00$6401a8c0@xp> > > > What's the most common IDE you people using while writing your own > > > programs ? > > > > Not sure if it counts, but I use vim > > I use VIM too, but I'm relatively new to VIM and haven't got it all > down. > > Is there a tutorial on using VIM to develop in python? Really its more about learning to use the vi editor. VIM is "Vi Improved" and to get the best you really need to know vi. The best tutor for vi that I know is called teachvi (also sometimes found as learnvi) and is a Unix shell script based tutor in 5 parts but you need a way to run Bourne shell scripts - ether Linux or Cygwin will do. It really explains the vi philosophy such that once you get it the vi commands become totally intuitive and you start to be able to guess what they will be without looking them up. Once you know vi the menu system in Vim provides much of the rest, plus reading the help pages on the extras like folding and splitting windows and using visual blocks for cut n paste etc. VIM also includes facilities for calling a compiler, which could be a python command window so at a push of a button you can run your script. But the usual way I do it is just have two windows open, one with vim and the other a simple OS prompt. Once you type the run command in once simple command recall means its two button pushes to run it again - and you know that the behaviour will be exactly like the production version, which isn't always true of an IDE. HTH Alan G. From speno at isc.upenn.edu Thu Nov 27 19:20:28 2003 From: speno at isc.upenn.edu (John P Speno) Date: Thu Nov 27 19:20:37 2003 Subject: [Tutor] Toolkit for Tkinter? In-Reply-To: <Pine.LNX.4.44.0311271349330.6100-100000@violet.rahul.net> References: <Pine.LNX.4.44.0311271349330.6100-100000@violet.rahul.net> Message-ID: <20031128002028.GA3384@isc.upenn.edu> On Thu, Nov 27, 2003 at 01:55:52PM -0800, Terry Carroll wrote: > So, does anyone know of anything comparable to Wax for Tkinter? Dunno how comparable it is, but have you seen the Python megawidgets? http://pmw.sourceforge.net/ From clickron at webtv.net Fri Nov 28 13:56:17 2003 From: clickron at webtv.net (Ron A) Date: Fri Nov 28 13:56:22 2003 Subject: [Tutor] special character ( =?iso-8859-1?q?=F1?= ) Message-ID: <2794-3FC79A51-4890@storefull-3196.bay.webtv.net> I have python 2.2.2. Is there an easy way to type ? (n with tilde) or other special characters?. Ron A From alan.gauld at blueyonder.co.uk Fri Nov 28 14:40:17 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Nov 28 14:39:53 2003 Subject: [Tutor] Toolkit for Tkinter? References: <Pine.LNX.4.44.0311271349330.6100-100000@violet.rahul.net> Message-ID: <002d01c3b5e7$738d2a90$6401a8c0@xp> > I want to do more in the way of GUI programming, and Tkinter kind of > frustrates me in the level of detail it requires. I assume you have looked at the Python MegaWidgets(PMW) package? It's a set of extra widgets built on top of Tk. It includes some extra dialogs, validated entry widgets, message bar, notebooks with tabs, scrolled canvas, scrolled list, time counter, etc. > occasional programming at home, so I'm looking for a no-cost option, PMW is free. Its described in Grayson's Tkinter book. Alan g. From abli at freemail.hu Fri Nov 28 17:40:15 2003 From: abli at freemail.hu (Abel Daniel) Date: Fri Nov 28 17:40:18 2003 Subject: [Tutor] Re: IDE In-Reply-To: <3FC4D89B.5040400@cso.atmel.com> (Mike Hansen's message of "Wed, 26 Nov 2003 09:45:15 -0700") References: <E1AOv0y-00015B-7x@mail.python.org> <3FC4D89B.5040400@cso.atmel.com> Message-ID: <E1APrHb-0000Bp-00@hooloovoo> Mike Hansen <mhansen@cso.atmel.com> writes: > BTW, I believe that development on XEMACS has stopped, and most of the > features that were in XEMACS are now in EMACS. well, according to http://xemacs.org/About/XEmacsVsGNUemacs.html : There are currently irreconcilable differences in the views about technical, programming, design and organizational matters between Richard Stallman (RMS) and the XEmacs development team which provide little hope for a merge to take place in the short-term future. The fact that emacs is getting features xemacs had before doesn't mean that xemacs development stopped or that there is a merger going on. (They might be reimplemented in emacs. Copying features isn't 'merging') -- Abel Daniel From missive at hotmail.com Fri Nov 28 19:15:55 2003 From: missive at hotmail.com (Lee Harr) Date: Fri Nov 28 19:16:02 2003 Subject: [Tutor] Re: Creating Parent and child threads Message-ID: <BAY2-F25aAKyCkoqfO300019cc9@hotmail.com> > > I guess I recommend posting to the main python list > > (I view it as comp.lang.python on usenet) > > > > Make sure to include the exact code you are > > using and the details of your system (python and os > > versions and how you are running the code -- like if > > you are in IDLE or konsole or gnome terminal) > > along with the output you are getting and > > the output that you expect to get. > > >If u don't mind, can u suggest some other mailing >lists to which I can send my question, coz right now I >can't access news groups. > http://python.org/community/lists.html comp.lang.python is also known as python-list http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From klappnase at freenet.de Fri Nov 28 20:40:34 2003 From: klappnase at freenet.de (Michael Lange) Date: Fri Nov 28 20:47:03 2003 Subject: [Tutor] Toolkit for Tkinter? In-Reply-To: <Pine.LNX.4.44.0311271349330.6100-100000@violet.rahul.net> References: <Pine.LNX.4.44.0311271349330.6100-100000@violet.rahul.net> Message-ID: <20031129024034.316bb8a7.klappnase@freenet.de> On Thu, 27 Nov 2003 13:55:52 -0800 (PST) Terry Carroll <carroll@tjc.com> wrote: > I want to do more in the way of GUI programming, and Tkinter kind of > frustrates me in the level of detail it requires. > > I've heard about Wax, both on this list and at its web site > <http://zephyrfalcon.org/moin.cgi/Wax>, but that's an interface into > wxPython. I'd like to stay in Tkinter, rather than learning a whole new > GUI toolkit like wxPython. > > I don't use Python professionally, this is just for my own use for my > occasional programming at home, so I'm looking for a no-cost option, being > a cheap bastard. > > So, does anyone know of anything comparable to Wax for Tkinter? > > (Happy Thanksgiving to the USAians on the list.) > I've seen that Pmw has been suggested. Another collection of Megawidgets is Tix < http://tix.sourceforge.net >. If you want to use Tix, there's even a gui builder available at < http://page.sourceforge.net >; it's surely a matter of personal flavor, but I prefer Tix to Pmw, however if you are using MSWindows i've heard that some people had problems getting it installed (for me it worked without problems). Cheers Michael From klappnase at freenet.de Fri Nov 28 20:54:30 2003 From: klappnase at freenet.de (Michael Lange) Date: Fri Nov 28 21:01:00 2003 Subject: [Tutor] special character ( =?ISO-8859-1?Q?=F1?= ) In-Reply-To: <2794-3FC79A51-4890@storefull-3196.bay.webtv.net> References: <2794-3FC79A51-4890@storefull-3196.bay.webtv.net> Message-ID: <20031129025430.1ad0605a.klappnase@freenet.de> On Fri, 28 Nov 2003 13:56:17 -0500 (EST) clickron@webtv.net (Ron A) wrote: > I have python 2.2.2. Is there an easy way to type ? (n with tilde) or > other special characters?. > I am afraid that I'm not an encoding expert, but I guess you have the same problems as I have with german special characters. In this case it depends on *where* you want to print it: In IDLE(python 2.2.3): >>> print '?' UnicodeError: ASCII encoding error: ordinal not in range(128) If that is what happens to you, see what I get in a unix shell: >>> print "?" ? If you just suffer from IDLE's limitations try idlefork : < http://idlefork.sourceforge.net > It's IDLE with a few extra features; as far as I know it replaces the "original" IDLE since python 2.3 . cheers Michael From tayi177 at hotmail.com Sat Nov 29 14:24:21 2003 From: tayi177 at hotmail.com (Tadey & Ivan) Date: Sat Nov 29 14:24:27 2003 Subject: [Tutor] inp. outp. & variable - dictionary difference ... Message-ID: <BAY8-DAV59AJVigEhxe00002cc6@hotmail.com> Hello ... I was having some problems lately with my hotmail email storage, so I probably deleted all new mails I got, or I even didn't get none (I had full box for some time too), so don't be mad if I am sending this mail second time, but I would really like to see any answer, if there was some (if there was, no need to put it on mailing list, just please forward me the answer, if it is possible) ... I just noticed two "interesting" issues (probably releated only to my configuration): 1.) First I found out, after trying few times, closing Python, and opening it again, that sometimes it open file (for reading/writting), and sometimes just don't, arbitrary, meaning that its not like I couldn't open the file always I try, therefore the most logical conclusion would be - I miss-spelled the code, but no: I 100 % tryed with identical input, I double, triple-checked the "code" ... I use the method below, from Alan's tutorial (don't know, probably the only one method for read/write files) ... I also checked files (on Alan's suggestion), if the are accidentally set as "read-only", I even unchecked "archive" (but that wouldn't explain why I could open them yesteday) ... with no benefit - as I said sometimes just can, and sometimes just can't (I second case I get "no such file or directory: 'somename.txt'" error message) !! >>> inp = open("lll.txt","r") # made both files just before opening Python ... >>> outp = open("ggg","w") ... for line in inp.readlines(): # for intendation here, I am not sure if its right, cause I couldn't check it ... ... outp.write(line) # before sending this mail, because of all mentioned above ... >>> inp.close() >>> outp.close() So, I was surely surprised yesterday, when (after "restarting" Python) trying to open the very same file, it was normally opened with the same method, with same text (input): >>> inp = open("lll.txt","r") >>> outp = open("ggg","w") ... but today after closing Python, shuting down PC (sleeping 8 hours) and trying to do the same thing again - there was the same (familiar) - "no such file or directory: 'somename.txt'" error message !! I have also tryed what Danny suggested, some other method to open file, and typed: >>> inp = open("D:/Program Files/Python/Lib/idlelib/Saves/ggg.txt") ... and the file was opened normally !! ... but in the very next line (of course after typing inp.close() ), with inp = open("somefile.txt","r") method: >>> inp = open("lll.txt","r") ... the was "no such file or directory" error message again !! 2.) Second about reading/writing from/into file, I noticed (yesterday, when I had luck and I could open file), that Python doesn't want to write from one file to another, which is non-empty (though maybe also just in my case) and also in file, which was already modified (something written in), changed from outside Python, during current session (of course, I used inp(close) before modified it) and even if this file was modified, and I later deleted that "new added" text (again maybe just in my case). 2.) Then I would really like to know, if I open some file, already process some line, and then miss-spell something, and some error message appears - do I need to close both (inp and out) files, and start from the beginning, or could I continue from the line before that error message ?? 3.) And as the last question, Alan.G's answer on my question about "difference between different types of brackets", was: "{} indicate a dictionary. ... One item in the pair is the lookup key, the other the return value." I am just curious - where is some "elemental" difference between dictionary (in practical use) and simple variable, cause "One item in the pair is the lookup key, the other the return value." - more or less resemble on variable deffiniton ... Example: instance = "Actual usage of class" (here we have variable and its actual value, stored in some location in RAM) ... so here one item is also some sort of "lookup key", and the other "the return value" ... Sorry, I really have more "theoretical" questions now on the beginning of learning how to programm, but it (answers here on Tutor list) really help me to imagine how everything works. P.S., I save all the answers I get, and you couldn't imagine (or you probably do, but I just said so, cause it sounds nice), how helpfull is having you answers saved somewhere, and when something is not so clear, just open those files, and see what was doing wrong ... Thank you all, Tadey -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031129/840ccb84/attachment.html From gerrit at nl.linux.org Sat Nov 29 15:12:43 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Sat Nov 29 15:13:18 2003 Subject: [Tutor] Python game - robot In-Reply-To: <Sea2-F54wXbY8UvYl2G00003df1@hotmail.com> References: <Sea2-F54wXbY8UvYl2G00003df1@hotmail.com> Message-ID: <20031129201243.GA9281@nl.linux.org> Leung Cris wrote: > I'm 3/4 through programming this game - a player in the middle, robots > chase you. Player touch robot, player dies. Robot touch each other, they > die. But I got stuck to the part where they "teach" you how to make > multiple robots. They said use an empty list, but I simply don't get it. > This is from the livewire package :www.livewires.org.uk/python . Worksheet > 5- robot. I don't see which part of which tutorial you mean, but I think I know your question - if not, maybe you can clarify it. I'm guessing here. Is it true that, until know, you created robots just with code like foo = Robot() bar = Robot() ? But know you want to create X different robots...? If so, you can do so like this: L = [] for i in range(X): L.append(Robot()) This creates X robots without a "name". They can be accessed through the list: L[0], L[1], L[2], etc. They do not have a name binding in your namespace: the only reference to their objects is through the list L. Maybe this answered your question or maybe this helps you in answering your question. If not, clarifying your question may help... yours, Gerrit. -- 15. If any one take a male or female slave of the court, or a male or female slave of a freed man, outside the city gates, he shall be put to death. -- 1780 BC, Hammurabi, Code of Law -- Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From carroll at tjc.com Sat Nov 29 20:21:07 2003 From: carroll at tjc.com (Terry Carroll) Date: Sat Nov 29 20:21:15 2003 Subject: [Tutor] Toolkit for Tkinter? In-Reply-To: <002d01c3b5e7$738d2a90$6401a8c0@xp> Message-ID: <Pine.LNX.4.44.0311291716590.18889-100000@violet.rahul.net> On Fri, 28 Nov 2003, Alan Gauld wrote: > I assume you have looked at the Python MegaWidgets(PMW) package? I hadn't, thanks. John Speno also pointed that out, I'm having a look at it. Thanks also to Michael Lange who pointed out Tix and PAGE. For anyone else following, here's a summary of the relevant URLs: Tix: http://tix.sourceforge.net/ PAGE: http://page.sourceforge.net/ PMW: http://pmw.sourceforge.net/ -- Terry Carroll Santa Clara, CA carroll@tjc.com From python at experiencedstudents.com Sat Nov 29 21:35:26 2003 From: python at experiencedstudents.com (Az) Date: Sat Nov 29 21:35:25 2003 Subject: [Tutor] python mailing list Message-ID: <00d401c3b6ea$9cca6c20$6400a8c0@a0> python mailing list From hameedkhaan at yahoo.com Sun Nov 30 12:30:27 2003 From: hameedkhaan at yahoo.com (Hameed Khan) Date: Sun Nov 30 12:30:51 2003 Subject: [Tutor] help about thread programming Message-ID: <20031130173027.4586.qmail@web20411.mail.yahoo.com> Hi, i try to consult python documentation for thread and threading module. i look at few scripts. but didn't get any idea of threading. i am really fedup of it now. and i dont want to give up. i will try to search on google. but if any one of you can write a simple threading script with explanation then it will be very valuable for me. and i will try to learn from it. waiting for your replies and advices. Thanks, Hameed Khan __________________________________ Do you Yahoo!? Free Pop-Up Blocker - Get it now http://companion.yahoo.com/ From karl.fast at pobox.com Sun Nov 30 17:48:32 2003 From: karl.fast at pobox.com (Karl Fast) Date: Sun Nov 30 17:48:39 2003 Subject: [Tutor] help about thread programming In-Reply-To: <20031130173027.4586.qmail@web20411.mail.yahoo.com>; from hameedkhaan@yahoo.com on Sun, Nov 30, 2003 at 09:30:27AM -0800 References: <20031130173027.4586.qmail@web20411.mail.yahoo.com> Message-ID: <20031130164832.A2154@signal.lights.com> > i try to consult python documentation for thread and threading > module. Try the threads and processes chapter in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Threads I have found Doug Fort's basic thread control recipe to be useful: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 --karl From alan.gauld at blueyonder.co.uk Sun Nov 30 19:40:35 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Nov 30 19:40:38 2003 Subject: [Tutor] inp. outp. & variable - dictionary difference ... References: <BAY8-DAV59AJVigEhxe00002cc6@hotmail.com> Message-ID: <001b01c3b7a3$bbe3b300$6401a8c0@xp> > 1.) First I found out, after trying few times, closing Python, and > opening it again, that sometimes it open file (for reading/writting), > and sometimes just don't, I'm guessing but how do you start Python? Could it be that you are sometimes starting it from the folder that the filesw are stored in and sometimres from some place else? Python will look in "the current directory" for the files if you don't provide the full path. > I have also tryed what Danny suggested, some other method to open file, : > > >>> inp = open("D:/Program Files/Python/Lib/idlelib/Saves/ggg.txt") ... > and the file was opened normally !! > > ... but in the very next line (of course after typing inp.close() ), with > inp = open("somefile.txt","r") method: Note you used the full path first time but a relatoive path second time. Suggests you were not in D:/Program Files/Python/Lib/idlelib/Saves when you started Python. > 2.) Second about reading/writing from/into file, I noticed ... > that Python doesn't want to write from one file to another, > which is non-empty I think what you mean here is that Python wipes out what was previously in the file? Thats what 'w' does. If you use 'a' it will append the new data after the existing: outp = ('ggg.txt','a') > miss-spell something, and some error message appears - do I need to > close both (inp and out) files, and start from the beginning, > or could I continue from the line before that error message ?? Depends on the error but for now its probably safer to close both files and start over. > 3.) And as the last question, Alan.G's answer on my question about > "difference between different types of brackets", was: > > "{} indicate a dictionary. ... One item in the pair is the lookup key, > the other the return value." > > I am just curious - where is some "elemental" difference between > dictionary (in practical use) and simple variable, Very observant. In fact Python uses dictionaries internally to store variables. That is a variable is just a key in a dictionary that Python uses internally and the value corresponding to the key is the variables value. In fact the dir() function lets you see the keys of the local dictionary (Or whichever dictionary/module you specify): >>> import sys >>> dir() ......lists local names... >>> dir(sys) .... lists names in sys module.... In both cases its just printing out the keys of the internal dictionaries Python is using. Thus >>> sys.stdout is a reference to a name in the dictionary used for the sys module, and sys in turn is a name in the local module. Alan G. From krazie_mu_boi at hotmail.com Sun Nov 30 21:25:08 2003 From: krazie_mu_boi at hotmail.com (Leung Cris) Date: Sun Nov 30 21:25:13 2003 Subject: [Tutor] mouse_buttons() Message-ID: <Sea2-F27mYDKFJ2I13p00018274@hotmail.com> How do I use that function? It's from Livewires . It returns three values, the middle , right, and left button. Depending on whether it is clicked, it will return a 0 or 1. But how do I get it so that when I click on the screen, it will stop? I've triedthis: while 1: mouse_buttons() if mouse_buttons() == 1 break but... it doens't work _________________________________________________________________ ¨Ï¥Î¥þ²y¥Î¤á³Ì¦hªº¹q¤l¶l¥óªA°È MSN Hotmail¡G http://www.hotmail.com