From john at fouhy.net Tue Nov 1 00:09:36 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 1 Nov 2005 12:09:36 +1300 Subject: [Tutor] Tainted characters and CGI In-Reply-To: <20051031204448.GT1791@johnsons-web.com> References: <20051031204448.GT1791@johnsons-web.com> Message-ID: <5e58f2e40510311509s1c2771dbk@mail.gmail.com> On 01/11/05, Tim Johnson wrote: > Hello: > I need to tighten my handling of CGI transmissions. > I particular, I need to develop a strategy of safely dealing > with "tainted" characters. A friend of mine has written a module that may be useful to you: """ zstr is an extension of the Python str class that has a built-in mechanism for escaping the string for use in different contexts. Most importantly, a zstr object keeps track of its current display state, making the escaping operations idempotent. ... The main intent for zstr is to help with CGI and web-related code. CGI programming involves a lot of string manipulation. For any given string, there might be a user input version of it, an HTML-escaped version of it, a SQL-escaped version of it, and possibly other customised escaped versions for things like filtering certain HTML tags but letting others through. """ Link: http://www.mcs.vuw.ac.nz/~jester/zstr/ -- John. From hugonz-lists at h-lab.net Tue Nov 1 00:13:57 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 31 Oct 2005 17:13:57 -0600 Subject: [Tutor] (no subject) In-Reply-To: <30CB82E83CB76D4584C5D7CEE3A4013E04ED4586@THEARCHITECT.ambac.abklan.net> References: <30CB82E83CB76D4584C5D7CEE3A4013E04ED4586@THEARCHITECT.ambac.abklan.net> Message-ID: <4366A535.7020008@h-lab.net> Do you need time to see the output? Then why don't you just use time.sleep(5) after each command? Hugo Roberts, Alice wrote: > Well, I'm looking into os.spawnl with os.P_WAIT, now. > > Thanks, > From tim at johnsons-web.com Tue Nov 1 00:25:53 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 31 Oct 2005 14:25:53 -0900 Subject: [Tutor] Tainted characters and CGI In-Reply-To: <5e58f2e40510311509s1c2771dbk@mail.gmail.com> References: <20051031204448.GT1791@johnsons-web.com> <5e58f2e40510311509s1c2771dbk@mail.gmail.com> Message-ID: <20051031232553.GW1791@johnsons-web.com> * John Fouhy [051031 14:16]: > On 01/11/05, Tim Johnson wrote: > > Hello: > > I need to tighten my handling of CGI transmissions. > > I particular, I need to develop a strategy of safely dealing > > with "tainted" characters. > > A friend of mine has written a module that may be useful to you: Hey - great tip! I will be checking this out thoroughly. Thanks (great word "idempotent") tim > """ > zstr is an extension of the Python str class that has a built-in > mechanism for escaping the string for use in different contexts. Most > importantly, a zstr object keeps track of its current display state, > making the escaping operations idempotent. > ... > The main intent for zstr is to help with CGI and web-related code. CGI > programming involves a lot of string manipulation. For any given > string, there might be a user input version of it, an HTML-escaped > version of it, a SQL-escaped version of it, and possibly other > customised escaped versions for things like filtering certain HTML > tags but letting others through. > """ > > Link: http://www.mcs.vuw.ac.nz/~jester/zstr/ > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From Barry.Carroll at psc.com Tue Nov 1 02:07:57 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 31 Oct 2005 17:07:57 -0800 Subject: [Tutor] Talking to UDPServer Message-ID: Greetings: I am writing a browser-based interface to a server program which extends SocketServer.UDPServer. The program listens on a well-known socket, receiving commands, verifying them and using their content to drive our test hardware, returning status to the client. The current client interface is a command line interface that allows the user to type in a command and sends it to the server, receives the status response and displays it for the user. My job is to duplicate the client functionality in a set of web pages. My problem is that, while I can find documentation on UDPServer, I cannot find anything on how a remote client talks to the server. How is this done in Python? Can someone point me to a how-to, tutorial or the like? Thanks in advance. Barry -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051031/fe22c5d7/attachment.html From ajikoe at gmail.com Tue Nov 1 02:14:49 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 1 Nov 2005 02:14:49 +0100 Subject: [Tutor] while/if/elif/else loops In-Reply-To: <43669C73.7030804@gmail.com> References: <43669C73.7030804@gmail.com> Message-ID: Let's comment something: 1. If you have error please show us your error message. 2. When you code python be aware of indention, be persistent for example use tab space 4. 3. import should be on the top of your code. 4. to choose random between integer 1 or 0 use randint(0,1) 5. your last code use Print it should be print (small letter please). Cheers, pujo On 10/31/05, Zameer Manji wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA512 > > I'm new to programming and python. I've have recently been experimenting > with while/if/elif/else loops and I've created a simple number guessing > game. Now I want to create a coin tossing game, but I don't know how to > structure it in python. The code I already have (but it's not working) > is below. > > > #Coin Toss Game > > print "This game will simulate 100 coin tosses and then tell you the > number of head's and tails" > > import random > > tosses = 0 > heads = 0 > tails = 0 > > while tosses = 100<0: > coin = randrange(1) > tosses +=1 > if coin == 0: > heads +=1 > print "Heads" > else: > tails +=1 > Print "Tails" > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.2 (MingW32) > > iQEVAwUBQ2accw759sZQuQ1BAQqoyQgAsmVhRidMC1/WpQms6fChX+z62DWSpmRW > qiY9F7bZAYZusyNsHHDUpuTAYdI0LXxgLVmYBKDz3tKhVCbEZTn9FUwgw5A2thYy > I5o82tWXZnIpgmFIN2AysAj2dCI4mSfi/IJjE5JvG+IFELWigMb9Pf6tap4HiB71 > IBayql8MN1XrA2zv8fXQs35zVwxnBUSvAHZuUBLi4hDcPxY/d71X/JHqfqpf3svS > ClzUlYqLhXld+39/aiRFKOXHyVCnfsEUcAXB45r110Q3K+7KegwgX4Js8qL5dA66 > d74HlLMb6Cp6G5AlNdQoKDin8jlMloxeQpb60hS+HmnBwkEFukyNHA== > =QMuB > -----END PGP SIGNATURE----- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051101/a6d06dd9/attachment.htm From kent37 at tds.net Tue Nov 1 02:55:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 31 Oct 2005 20:55:34 -0500 Subject: [Tutor] Talking to UDPServer In-Reply-To: References: Message-ID: <4366CB16.3030907@tds.net> Carroll, Barry wrote: > I am writing a browser-based interface to a server program which extends > SocketServer.UDPServer. The program listens on a well-known socket, > receiving commands, verifying them and using their content to drive our > test hardware, returning status to the client. The current client > interface is a command line interface that allows the user to type in a > command and sends it to the server, receives the status response and > displays it for the user. My job is to duplicate the client > functionality in a set of web pages. > > My problem is that, while I can find documentation on UDPServer, I > cannot find anything on how a remote client talks to the server. How is > this done in Python? Can someone point me to a how-to, tutorial or the > like? Are you trying to write a browser-based client, or a Python client? As far as I know, it is not possible to write a browser client in Python, or a browser UDP client. You can write a UDP client in Python, I think you have to use the socket module directly. Kent -- http://www.kentsjohnson.com From singingxduck at gmail.com Tue Nov 1 03:40:49 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon, 31 Oct 2005 21:40:49 -0500 Subject: [Tutor] : [Slightly OT] Using Python to intercept audio from a program Message-ID: <4366D5B1.2070508@gmail.com> Hello all, A week or two ago I sent in a few emails regarding using threads in automating conversion between wav's and mp3's using lame. However, the program I use to generate these wav's, Audacity (a great program, btw), can't record directly from another program, but instead catches all audio directed at the speakers. Being the person I am, I'm never patient enough to sit there and do nothing else while I record these wav's, so I do other things in the background. Unfortunately, with the current setup, any sounds generated by these background activities end up in the wav files. So I asked on the audacity-help mailing list whether audacity has the capability to record directly from another program, and the answer, sadly, was no. At least, not for Windows. So what I would like to do is attempt the same with Python, though right now I have only the vaguest of ideas on how to proceed. If anyone could point me in the right direction, I would be very grateful. Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051031/e9e4c9be/attachment.html From johan at accesstel.co.za Tue Nov 1 02:34:31 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 01 Nov 2005 03:34:31 +0200 Subject: [Tutor] Talking to UDPServer In-Reply-To: References: Message-ID: <4366C627.8090403@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051101/f3e42a23/attachment.html From singingxduck at gmail.com Tue Nov 1 04:20:08 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon, 31 Oct 2005 22:20:08 -0500 Subject: [Tutor] : [Slightly OT] Using Python to intercept audio from a program Message-ID: <4366DEE8.20002@gmail.com> By the way, if it makes a difference, the program I intend to attempt this with is Rhapsody , a part of the RealPlayer collection of media software. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From amonroe at columbus.rr.com Tue Nov 1 04:10:34 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 31 Oct 2005 22:10:34 -0500 Subject: [Tutor] while/if/elif/else loops In-Reply-To: <43669C73.7030804@gmail.com> References: <43669C73.7030804@gmail.com> Message-ID: <331093283819.20051031221034@columbus.rr.com> > while tosses = 100<0: I didn't run the program, but this immediately caught my eye as looking kind of suspect. Was it a typo? Most programs usually have a need for comparisons of equal, or greater/less, but it's really rare to need both combined in one statement... Also if you really _do_ want to check two things being equal, don't forget to use double equal ( == ). Alan From dyoo at hkn.eecs.berkeley.edu Tue Nov 1 05:34:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 31 Oct 2005 20:34:05 -0800 (PST) Subject: [Tutor] help with prime number program In-Reply-To: <4365FC11.4050303@tds.net> Message-ID: On Mon, 31 Oct 2005, Kent Johnson wrote: > Norman Silverstone wrote: > > I am a beginner so, I hope what I give, makes sense. In it's simplest > > form what is wrong with :- > > > > n = input("Enter a number") > > if n % 2 != 0 and n % 3 != 0: > > print n, " Is a prime number" > > > This only gives the correct answer if n < 25. You can't test against a > fixed list of divisors, there will always be a non-prime whose divisors > are not in your list. Kent's comment is actually a paraphrase of Euclid's "There are an infinite number of primes" argument used in mathematics. *grin* http://mathworld.wolfram.com/EuclidsTheorems.html From steve at rueb.com Tue Nov 1 05:52:18 2005 From: steve at rueb.com (Steve Bergman) Date: Mon, 31 Oct 2005 22:52:18 -0600 Subject: [Tutor] Turning kwargs into scalars Message-ID: <4366F482.2030807@rueb.com> Say I have a function: def f(self, **kwargs) : and I want to take the key/value pairs and create a set of variables with the names of the keys. For example, if I say: f(x=5, y=2) I want to create local variables 'x' and 'y' in the function, with values of 5 and 2 respectively. How could I do this? Thanks, Steve Bergman From ml.cyresse at gmail.com Tue Nov 1 07:15:42 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Tue, 1 Nov 2005 19:15:42 +1300 Subject: [Tutor] Random Q on Python's internals? Message-ID: Hi all, I was perusing the standard library, and was wondering if anyone knew how the internals of Python work, roughly or no. Basically, I assume os.pipe() resides in a DLL somewhere, yet when I open up Python24.DLL in PEexplorer I can't find mention of pipes anywhere... am I looking the right place? Regards, Liam Clarke From dyoo at hkn.eecs.berkeley.edu Tue Nov 1 07:16:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 31 Oct 2005 22:16:56 -0800 (PST) Subject: [Tutor] Turning kwargs into scalars In-Reply-To: <4366F482.2030807@rueb.com> Message-ID: On Mon, 31 Oct 2005, Steve Bergman wrote: > Say I have a function: > > def f(self, **kwargs) : > > and I want to take the key/value pairs and create a set of variables > with the names of the keys. > > For example, if I say: > > f(x=5, y=2) > > I want to create local variables 'x' and 'y' in the function, with > values of 5 and 2 respectively. Hi Steve, It's technically possible to do this in Python, but it's not advised to do it, just because it becomes difficult to control what local variables will be created. That can make debugging very hard. It also wrecks havoc with lint-like programs like pychecker: http://pychecker.sourceforge.net/. I guess I'm trying to say: are you really sure you want to do this? *grin* We can access those values through the kwargs dictionary though; is this sufficient? It's a very rare case where we want to really make local variable names in such a dynamic way; perhaps there's another approach to the problem you're solving? If you can show us more of what you're trying to do, we can give more suggestions. Best of wishes! From alan.gauld at freenet.co.uk Tue Nov 1 07:26:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 1 Nov 2005 06:26:27 -0000 Subject: [Tutor] while/if/elif/else loops References: <43669C73.7030804@gmail.com> Message-ID: <003a01c5dead$30bcdf80$0a01a8c0@xp> > import random > > > while tosses = 100<0: > coin = randrange(1) You need to preped random: coin = random.randrange(1) Otherwise it looks OKAlthough.... > tosses +=1 > if coin == 0: > heads +=1 > print "Heads" You might want to output the count too print heads, " heads" Or maybe at the end just print a summary... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Tue Nov 1 07:31:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 31 Oct 2005 22:31:44 -0800 (PST) Subject: [Tutor] Random Q on Python's internals? In-Reply-To: Message-ID: > I was perusing the standard library, and was wondering if anyone knew > how the internals of Python work, roughly or no. > > Basically, I assume os.pipe() resides in a DLL somewhere, yet when I > open up Python24.DLL in PEexplorer I can't find mention of pipes > anywhere... Hi Liam, os.pipe() comes from the block of code near the top of os.py: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/os.py?rev=1.58.2.4&view=markup where it starts to talk to platform-specific modules like 'nt' and 'posix'. The 'os.py' module is a sponge that absorbs the content of platform-specific modules in an attempt to make things look platform independent. *grin* pipe() really comes from the posix/nt module, whose implementation can be found here: http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/posixmodule.c?view=markup Best of wishes! From norman at littletank.org Tue Nov 1 11:37:58 2005 From: norman at littletank.org (Norman Silverstone) Date: Tue, 01 Nov 2005 10:37:58 +0000 Subject: [Tutor] while/if/elif/else loops In-Reply-To: <43669C73.7030804@gmail.com> References: <43669C73.7030804@gmail.com> Message-ID: <1130841478.29704.3.camel@localhost.localdomain> > #Coin Toss Game > > print "This game will simulate 100 coin tosses and then tell you the > number of head's and tails" > > import random > > tosses = 0 > heads = 0 > tails = 0 > > while tosses = 100<0: > coin = randrange(1) > tosses +=1 > if coin == 0: > heads +=1 > print "Heads" > else: > tails +=1 > Print "Tails" This problem was covered only a few days ago and I suggest the replies are looked up. Incidentally coin = random.randrange(1) can surely only return 0 and, if one is to look at a random result between heads and tails then coin should = random.randrange(2). Norman From ml.cyresse at gmail.com Tue Nov 1 13:22:55 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Wed, 2 Nov 2005 01:22:55 +1300 Subject: [Tutor] Random Q on Python's internals? In-Reply-To: References: Message-ID: Thanks Danny. On 11/1/05, Danny Yoo wrote: > > > > I was perusing the standard library, and was wondering if anyone knew > > how the internals of Python work, roughly or no. > > > > Basically, I assume os.pipe() resides in a DLL somewhere, yet when I > > open up Python24.DLL in PEexplorer I can't find mention of pipes > > anywhere... > > Hi Liam, > > > os.pipe() comes from the block of code near the top of os.py: > > http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Lib/os.py?rev=1.58.2.4&view=markup > > where it starts to talk to platform-specific modules like 'nt' and > 'posix'. The 'os.py' module is a sponge that absorbs the content of > platform-specific modules in an attempt to make things look platform > independent. *grin* > > pipe() really comes from the posix/nt module, whose implementation can be > found here: > > http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/posixmodule.c?view=markup > > > Best of wishes! > > From bgailer at alum.rpi.edu Tue Nov 1 17:17:14 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 01 Nov 2005 08:17:14 -0800 Subject: [Tutor] Turning kwargs into scalars In-Reply-To: <4366F482.2030807@rueb.com> References: <4366F482.2030807@rueb.com> Message-ID: <6.1.2.0.0.20051101081145.03566f58@mail.mric.net> At 08:52 PM 10/31/2005, Steve Bergman wrote: >Say I have a function: >def f(self, **kwargs) : FWIW you don't have a function at this point. You have a def statement which must be followed by at least one indented statement, which in turn must be executed. Then you have a function. >and I want to take the key/value pairs and create a set of variables with >the names of the keys. >For example, if I say: >f(x=5, y=2) >I want to create local variables 'x' and 'y' in the function, with values >of 5 and 2 respectively. >How could I do this? This is an FAQ. It can be done. However there are better ways to accomplish the same thing. Namely use the dictionary kwargs and look things up by key. Would you give an example of what you'd do with variables x and y after creating them? From singletoned at gmail.com Tue Nov 1 17:55:25 2005 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 1 Nov 2005 16:55:25 +0000 Subject: [Tutor] Rename files with numbers In-Reply-To: References: <1130776390.085587.116270@g43g2000cwa.googlegroups.com> <1130784747.373637.108040@g14g2000cwa.googlegroups.com> <1130789205.862429.10090@g43g2000cwa.googlegroups.com> <20051031220841.GF2575@kitchen.client.attbi.com> Message-ID: <34bb7f5b0511010855u60848244p@mail.gmail.com> The best free app I've found for this is MusicBrainz [www.musicbrainz.com]. This has a huge database of obsessively correct details of albums which can be formatted in anyway you choose. It can automatically recognise which song an MP3 is! This is a similar script I wrote to renumber files in sequential order. It assumes that everything before the first underscore can be replaced. from path import path import re def renumberfiles(filesdir, startnum=1): d = path(filesdir) print d x = startnum for f in d.files(): fname = f.name.split('_', 1) fname = str(x).zfill(2) + "_" + fname[-1] fname = re.sub(r" ",r"_",fname) fname = re.sub(r"__",r"_",fname) x = x + 1 print f.name, "==>", f.rename(f.parent + "\\" + fname) print fname As you can see, I use the path module rather than os.path. it's a much more intuitive way of handling files. http://www.jorendorff.com/articles/python/path/ Ed On 01/11/05, Dave Benjamin wrote: > On Mon, 31 Oct 2005, Micah Elliott wrote: > > > On Oct 31, Micah Elliott wrote: > >> Now I need to go beautify my collection. :-) > > > > While a fun exercise, there are probably already dozens (or > > thousands?) of utilities in existence that do this and much more. > > Seconded. I initially considered writing a script to rename a huge pile of > MP3 files, but halfway through, I thought, "there's *got* to be a better > way". I found this app: http://www.softpointer.com/tr.htm > > Bought it the next day. Holy crap, what a gigantic timesaver. It looks up > albums based on track lengths, downloads titles from freedb and Amazon, > does ID3 tagging, renaming, moves files into separate directories... I > busted through about 20 gigs of MP3s in three days. I kid you not. > > If this is just a fun toy Python project, don't let me discourage you, but > if you have more than a handful of albums to rename, trust me. This > problem has been solved. > > Here's a list of apps, including Tag&Rename, that can query freedb: > http://www.freedb.org/freedb_aware_apps.php > > -- > .:[ dave benjamin: ramen/[sp00] ]:. > \\ "who will clean out my Inbox after I'm dead[?]" - charles petzold > -- > http://mail.python.org/mailman/listinfo/python-list > From singletoned at gmail.com Tue Nov 1 17:56:26 2005 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 1 Nov 2005 16:56:26 +0000 Subject: [Tutor] Rename files with numbers In-Reply-To: <34bb7f5b0511010855u60848244p@mail.gmail.com> References: <1130776390.085587.116270@g43g2000cwa.googlegroups.com> <1130784747.373637.108040@g14g2000cwa.googlegroups.com> <1130789205.862429.10090@g43g2000cwa.googlegroups.com> <20051031220841.GF2575@kitchen.client.attbi.com> <34bb7f5b0511010855u60848244p@mail.gmail.com> Message-ID: <34bb7f5b0511010856q9daffe4s@mail.gmail.com> Sorry, wrong list. Many apologies. Ed On 01/11/05, Ed Singleton wrote: > The best free app I've found for this is MusicBrainz [www.musicbrainz.com]. > > This has a huge database of obsessively correct details of albums > which can be formatted in anyway you choose. It can automatically > recognise which song an MP3 is! > > This is a similar script I wrote to renumber files in sequential > order. It assumes that everything before the first underscore can be > replaced. > > from path import path > import re > > def renumberfiles(filesdir, startnum=1): > d = path(filesdir) > print d > x = startnum > for f in d.files(): > fname = f.name.split('_', 1) > fname = str(x).zfill(2) + "_" + fname[-1] > fname = re.sub(r" ",r"_",fname) > fname = re.sub(r"__",r"_",fname) > x = x + 1 > print f.name, "==>", > f.rename(f.parent + "\\" + fname) > print fname > > As you can see, I use the path module rather than os.path. it's a > much more intuitive way of handling files. > > http://www.jorendorff.com/articles/python/path/ > > Ed > > On 01/11/05, Dave Benjamin wrote: > > On Mon, 31 Oct 2005, Micah Elliott wrote: > > > > > On Oct 31, Micah Elliott wrote: > > >> Now I need to go beautify my collection. :-) > > > > > > While a fun exercise, there are probably already dozens (or > > > thousands?) of utilities in existence that do this and much more. > > > > Seconded. I initially considered writing a script to rename a huge pile of > > MP3 files, but halfway through, I thought, "there's *got* to be a better > > way". I found this app: http://www.softpointer.com/tr.htm > > > > Bought it the next day. Holy crap, what a gigantic timesaver. It looks up > > albums based on track lengths, downloads titles from freedb and Amazon, > > does ID3 tagging, renaming, moves files into separate directories... I > > busted through about 20 gigs of MP3s in three days. I kid you not. > > > > If this is just a fun toy Python project, don't let me discourage you, but > > if you have more than a handful of albums to rename, trust me. This > > problem has been solved. > > > > Here's a list of apps, including Tag&Rename, that can query freedb: > > http://www.freedb.org/freedb_aware_apps.php > > > > -- > > .:[ dave benjamin: ramen/[sp00] ]:. > > \\ "who will clean out my Inbox after I'm dead[?]" - charles petzold > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From Barry.Carroll at psc.com Tue Nov 1 19:34:47 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 1 Nov 2005 10:34:47 -0800 Subject: [Tutor] Talking to UDPServer Message-ID: Johan, et al: Yes, that is exactly what I want. I need to write a program that communicates with an existing server, using the UDP protocol. This is my first time writing such a program, and I need help getting started. Thanks again. Barry _____ From: Johan Geldenhuys [mailto:johan at accesstel.co.za] Sent: Monday, October 31, 2005 5:35 PM To: Carroll, Barry Cc: 'tutor at python.org' Subject: Re: [Tutor] Talking to UDPServer Maybe you could tel us if you already have the server listening on the socket that you expec connections on? If, yes, do you want an example of how a client connects to that socket? Johan Carroll, Barry wrote: Greetings: I am writing a browser-based interface to a server program which extends SocketServer.UDPServer. The program listens on a well-known socket, receiving commands, verifying them and using their content to drive our test hardware, returning status to the client. The current client interface is a command line interface that allows the user to type in a command and sends it to the server, receives the status response and displays it for the user. My job is to duplicate the client functionality in a set of web pages. My problem is that, while I can find documentation on UDPServer, I cannot find anything on how a remote client talks to the server. How is this done in Python? Can someone point me to a how-to, tutorial or the like? Thanks in advance. Barry _____ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051101/7b8fd222/attachment.htm From Barry.Carroll at psc.com Tue Nov 1 19:52:58 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 1 Nov 2005 10:52:58 -0800 Subject: [Tutor] while/if/elif/else loops Message-ID: Greetings: I tried running first just the expression, then the statement. Here are the results: >>> tosses = 100<0 >>> tosses False >>> while tosses = 100<0: File "", line 1 while tosses = 100<0: ^ SyntaxError: invalid syntax >>> Coming from the C/C++ world as I do, I was a little surprised by the error. C accepts the assignment expression and uses the result as the while condition, so that the loop never executes. Nice to see that Python avoids that trap. Regards, Barry > Date: Mon, 31 Oct 2005 22:10:34 -0500 > From: "R. Alan Monroe" > Subject: Re: [Tutor] while/if/elif/else loops > To: tutor at python.org > Message-ID: <331093283819.20051031221034 at columbus.rr.com> > Content-Type: text/plain; charset=us-ascii > > > > while tosses = 100<0: > > I didn't run the program, but this immediately caught my eye as > looking kind of suspect. Was it a typo? Most programs usually > have a need for comparisons of equal, or greater/less, but it's really > rare to need both combined in one statement... > > Also if you really _do_ want to check two things being equal, don't > forget to use double equal ( == ). > > Alan > From kent37 at tds.net Tue Nov 1 19:55:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 01 Nov 2005 13:55:51 -0500 Subject: [Tutor] Talking to UDPServer In-Reply-To: References: Message-ID: <4367BA37.4000706@tds.net> Carroll, Barry wrote: > Yes, that is exactly what I want. I need to write a program that > communicates with an existing server, using the UDP protocol. This is > my first time writing such a program, and I need help getting started. Here is an example from Python Network Programming, by John Goerzen. It opens a UDP port, sends a message, then echoes any received text to the console. There is no higher-level support built in to Python, you just open a datagram socket and push data out. Google for "Python udp" for more examples. Kent #!/usr/bin/env python # UDP Example - Chapter 2 import socket, sys, time host = sys.argv[1] textport = sys.argv[2] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(textport) except ValueError: # That didn't work. Look it up instread. port = socket.getservbyname(textport, 'udp') s.connect((host, port)) print "Enter data to transmit: " data = sys.stdin.readline().strip() s.sendall(data) s.shutdown(1) print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." while 1: buf = s.recv(2048) if not len(buf): break print "Received: %s" % buf From johan at accesstel.co.za Tue Nov 1 20:38:57 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 01 Nov 2005 21:38:57 +0200 Subject: [Tutor] Talking to UDPServer In-Reply-To: <4367BA37.4000706@tds.net> References: <4367BA37.4000706@tds.net> Message-ID: <4367C451.8070303@accesstel.co.za> I've done some network programming mostly with TCP and I don't think that the way the client connects to the server is a lot different (if any), The only difference is when you must decide the protcol family. "socket.SOCK_DGRAM" will be for UDP and "socket.SOCK_STREAM" will be for TCP. After this, the client can connect the same way. Here is a simpler sample than the one Kent gave: """ from socket import * HOST = 'localhost' PORT = 3001 BUFSIZ = 1024 ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) # change here for UDP tcpCliSock.connect(ADDR) while 1: data = raw_input('>') # Enter text to be transmitted to the server. if not data: break tcpClisock.send(data) data = tcpCliSock.recv(BUFSIZ) if not data: break print data tcpCliSock.close() """ HTH, Johan Kent Johnson wrote: > Carroll, Barry wrote: > >> Yes, that is exactly what I want. I need to write a program that >> communicates with an existing server, using the UDP protocol. This >> is my first time writing such a program, and I need help getting >> started. > > > Here is an example from Python Network Programming, by John Goerzen. > It opens a UDP port, sends a message, then echoes any received text to > the console. There is no higher-level support built in to Python, you > just open a datagram socket and push data out. Google for "Python udp" > for more examples. > > Kent > > #!/usr/bin/env python > # UDP Example - Chapter 2 > > import socket, sys, time > > host = sys.argv[1] > textport = sys.argv[2] > > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > try: > port = int(textport) > except ValueError: > # That didn't work. Look it up instread. > port = socket.getservbyname(textport, 'udp') > > s.connect((host, port)) > print "Enter data to transmit: " > data = sys.stdin.readline().strip() > s.sendall(data) > s.shutdown(1) > print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." > while 1: > buf = s.recv(2048) > if not len(buf): > break > print "Received: %s" % buf > > From zmerch at 30below.com Tue Nov 1 20:44:09 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Tue, 01 Nov 2005 14:44:09 -0500 Subject: [Tutor] Does a module for DirectFB exist? Message-ID: <5.1.0.14.2.20051101144204.047d34e0@mail.30below.com> DirectFB is short for Direct Frame Buffer, and allows access to a graphical frame buffer system in *nix (and I think maybe MacOSX) from a text prompt without going through X. Anyone know of a module to access this through Python? I've googled for it, but didn't know if anyone here knew about something along these lines. Thanks, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | A new truth in advertising slogan SysAdmin, Iceberg Computers | for MicroSoft: "We're not the oxy... zmerch at 30below.com | ...in oxymoron!" From Barry.Carroll at psc.com Tue Nov 1 21:06:29 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 1 Nov 2005 12:06:29 -0800 Subject: [Tutor] Talking to UDPServer Message-ID: Kent, Johan: Thank you. These examples will be a great help. I also found some links via Google (I always forget that resource for some reason). I have enough to go forward, now. Barry > -----Original Message----- > From: Johan Geldenhuys [mailto:johan at accesstel.co.za] > Sent: Tuesday, November 01, 2005 11:39 AM > To: Kent Johnson > Cc: Carroll, Barry; 'tutor at python.org' > Subject: Re: [Tutor] Talking to UDPServer > > I've done some network programming mostly with TCP and I don't think > that the way the client connects to the server is a lot different (if > any), The only difference is when you must decide the protcol family. > "socket.SOCK_DGRAM" will be for UDP and "socket.SOCK_STREAM" will be for > TCP. After this, the client can connect the same way. > > Here is a simpler sample than the one Kent gave: > > """ > from socket import * > > HOST = 'localhost' > PORT = 3001 > BUFSIZ = 1024 > ADDR = (HOST, PORT) > > tcpCliSock = socket(AF_INET, SOCK_STREAM) # change here for UDP > tcpCliSock.connect(ADDR) > > while 1: > data = raw_input('>') # Enter text to be transmitted to the server. > if not data: break > tcpClisock.send(data) > data = tcpCliSock.recv(BUFSIZ) > if not data: break > print data > > tcpCliSock.close() > """ > HTH, > > Johan > > > Kent Johnson wrote: > > > Carroll, Barry wrote: > > > >> Yes, that is exactly what I want. I need to write a program that > >> communicates with an existing server, using the UDP protocol. This > >> is my first time writing such a program, and I need help getting > >> started. > > > > > > Here is an example from Python Network Programming, by John Goerzen. > > It opens a UDP port, sends a message, then echoes any received text to > > the console. There is no higher-level support built in to Python, you > > just open a datagram socket and push data out. Google for "Python udp" > > for more examples. > > > > Kent > > > > #!/usr/bin/env python > > # UDP Example - Chapter 2 > > > > import socket, sys, time > > > > host = sys.argv[1] > > textport = sys.argv[2] > > > > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > try: > > port = int(textport) > > except ValueError: > > # That didn't work. Look it up instread. > > port = socket.getservbyname(textport, 'udp') > > > > s.connect((host, port)) > > print "Enter data to transmit: " > > data = sys.stdin.readline().strip() > > s.sendall(data) > > s.shutdown(1) > > print "Looking for replies; press Ctrl-C or Ctrl-Break to stop." > > while 1: > > buf = s.recv(2048) > > if not len(buf): > > break > > print "Received: %s" % buf > > > > From disalvo.antonio at gmail.com Tue Nov 1 23:24:10 2005 From: disalvo.antonio at gmail.com (ciclope) Date: Tue, 1 Nov 2005 23:24:10 +0100 Subject: [Tutor] Python and sock Message-ID: Hi, I have a question about the use of a sock server under python. I wanna a little program I'm writing to use a sock server, either version 4 or 5. How can I make it communicating through a such SOCKS server under python, without using a SOCKScap like software, but easily using something like a socket module that implements an interface to those servers? I found a very old implementation for python 1.x (If I remember correctly) but obviously it doesnt work for me. I know I can socksify the sourcecode of the socket module, but before doing this I would know if there is already something. Thanks in Advance PS: sorry for the English, but it isnt my mother language ;-P -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051101/fd19e9d9/attachment.htm From zmanji at gmail.com Tue Nov 1 23:36:11 2005 From: zmanji at gmail.com (Zameer Manji) Date: Tue, 01 Nov 2005 17:36:11 -0500 Subject: [Tutor] while/if/elif/else loops In-Reply-To: References: Message-ID: <4367EDDB.5050609@gmail.com> Ok after looking at everyones replies my program looks like this: #Coin Toss Game #Zameer Manji import random print "This game will simulate 100 coin tosses and then tell you the number of head's and tails" tosses = 0 heads = 0 tails = 0 while tosses<100: if tosses<100: coin = random.randrange(2) tosses +=1 if coin == 0: heads +=1 print "Heads" else: tails +=1 print "Tails" else: print "100 tosses have been simulated. Please wait for your results" print "Out of", tosses, ",", heads, "were heads and", tails, "were tails." This is the results: >>> ================================ RESTART ================================ >>> This game will simulate 100 coin tosses and then tell you the number of head's and tails Heads ... (To save space the results have been stripped) Heads Out of 100 , 48 were heads and 52 were tails. Thank you for your help everyone. From bgailer at alum.rpi.edu Wed Nov 2 04:48:24 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 01 Nov 2005 19:48:24 -0800 Subject: [Tutor] while/if/elif/else loops In-Reply-To: <4367EDDB.5050609@gmail.com> References: <4367EDDB.5050609@gmail.com> Message-ID: <6.1.2.0.0.20051101173656.03558c58@mail.mric.net> At 02:36 PM 11/1/2005, Zameer Manji wrote: >Ok after looking at everyones replies my program looks like this: > >#Coin Toss Game >#Zameer Manji >import random > >print "This game will simulate 100 coin tosses and then tell you the >number of head's and tails" > >tosses = 0 >heads = 0 >tails = 0 > >while tosses<100: > if tosses<100: > coin = random.randrange(2) > tosses +=1 > if coin == 0: > heads +=1 > print "Heads" > else: > tails +=1 > print "Tails" > else: > print "100 tosses have been simulated. Please wait for your results" > >print "Out of", tosses, ",", heads, "were heads and", tails, "were tails." Good progress. Note that if tosses<100 will always succeed, since the while ends when tosses is 100. Therefore the first print statement never happens. Here are some incremental refinements to help you get a taste of programming and Python Refinement 1 put the first print where it will execute. But what is there to wait for? >while tosses<100: > coin = random.randrange(2) > tosses +=1 > if coin == 0: > heads +=1 > print "Heads" > else: > tails +=1 > print "Tails" >print "100 tosses have been simulated. Please wait for your results" >print "Out of", tosses, ",", heads, "were heads and", tails, "were tails." Refinement 2 - use for and range() instead of while: >for tosses in range(100): > coin = random.randrange(2) > if coin == 0: > heads +=1 > print "Heads" > else: > tails +=1 > print "Tails" >etc. Refinement 3 - test result of randrange directly: >for tosses in range(100): > if random.randrange(2): > tails +=1 > print "Tails" > else: > heads +=1 > print "Heads" >etc. Refinement 4 - compute heads once: >for tosses in range(100): > if random.randrange(2): > tails +=1 > print "Tails" > else: > print "Heads" >heads = 100 - tails >etc. Radical Refinement 1 - use list comprehension instead of for. Use the sum function: import random coins = [random.randrange(2) for i in range(100)] print "1 for heads, 0 for tails", coins # 1 for heads, 0 for tails [1, 1, 1, 0, 1, 1, 0, 0, 1, 0 ...] heads = sum(coins) print "Heads %i Tails %i" % (heads, 100-heads) # Heads 64 Tails 36 Have fun groking all there is to programming and Python. From johan at accesstel.co.za Wed Nov 2 09:30:57 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 02 Nov 2005 10:30:57 +0200 Subject: [Tutor] os command In-Reply-To: <435FFE2A.8040105@h-lab.net> References: <435F6FCD.4090704@accesstel.co.za> <435FFE2A.8040105@h-lab.net> Message-ID: <43687941.40303@accesstel.co.za> Sorry for the late reply, But is it necessary to use a child process? I don't want to execute the command in another process. What happens with the parent process and how do I execute my command in the parent process? Thanks Hugo Gonz?lez Monteverde wrote: > Hi, > > os.system will return the errorval of the application. You need to > > 1) get the pid of the child process > 2) kill it using os.kill(os.SIGTERM) > 3) reap the killed process > > This is all in unix/linux, of course. > > what I do (untested, please check order of args and correct usage of > exec): > > pid = os.fork() > > if pid == 0: #child process > os.execvp("tcpdump", "tcpdump", "-n", "-i", "eth0") > > else: #parent > time.sleep(5) > os.kill(pid, os.SIGTERM) > os.waitpid(pid, 0) #wait for process to end > > > > Johan Geldenhuys wrote: > >> I have script that calls a system command that I want to run for 5 >> minutes. >> """ >> import os >> cmd = 'tcpdump -n -i eth0' >> os.system(cmd) >> """ >> >> I can start a timer after the cmd is issued, but I don't know how to >> send a control signal to stop the command after I issued it. This is >> normally from the shell ^c. >> >> This cmd my run in more than one thread on different interfaces and I >> don't whant all of then stopped at once. I think the best way is to >> make a thread for each interface where the cmd can be issued and >> stopped without the danger of stopping he wrong thread. >> >> Can anybody help? >> >> Thanks >> >> Johan >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From johan at accesstel.co.za Wed Nov 2 08:04:40 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 02 Nov 2005 09:04:40 +0200 Subject: [Tutor] Decoding decleration Message-ID: <43686508.3010307@accesstel.co.za> I receive this error when executing a file: "Non-ASCII character '\x8b' in file task.py on line 1, but no encoding declared". Can anybody tell me what the encoding is supposed to look like and is it standard on all files that is trying to use Non-ASCII characters? Thanks, Johan From ajikoe at gmail.com Wed Nov 2 08:17:33 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 2 Nov 2005 08:17:33 +0100 Subject: [Tutor] while/if/elif/else loops In-Reply-To: <4367EDDB.5050609@gmail.com> References: <4367EDDB.5050609@gmail.com> Message-ID: Hello, I see two things can be changed a little bit. 1. redundant: while, if 2. print style at the last statement. see below: #Coin Toss Game #Zameer Manji import random print "This game will simulate 100 coin tosses and then tell you the number of head's and tails" tosses = 0 heads = 0 tails = 0 while tosses<100: coin = random.randrange(2) tosses +=1 if coin == 0: heads +=1 print "Heads" else: tails +=1 print "Tails" print "100 tosses have been simulated. Please wait for your results" print "Out of %s, %s were heads and %s were tails" % (tosses, heads, tails) cheers, pujo On 11/1/05, Zameer Manji wrote: > > Ok after looking at everyones replies my program looks like this: > > #Coin Toss Game > #Zameer Manji > import random > > print "This game will simulate 100 coin tosses and then tell you the > number of head's and tails" > > tosses = 0 > heads = 0 > tails = 0 > > while tosses<100: > if tosses<100: > coin = random.randrange(2) > tosses +=1 > if coin == 0: > heads +=1 > print "Heads" > else: > tails +=1 > print "Tails" > else: > print "100 tosses have been simulated. Please wait for your results" > > print "Out of", tosses, ",", heads, "were heads and", tails, "were tails." > > > This is the results: > > >>> ================================ RESTART > ================================ > >>> > This game will simulate 100 coin tosses and then tell you the number of > head's and tails > Heads > ... (To save space the results have been stripped) > Heads > Out of 100 , 48 were heads and 52 were tails. > > Thank you for your help everyone. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051102/fb25e22b/attachment.htm From johan at accesstel.co.za Wed Nov 2 10:02:45 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 02 Nov 2005 11:02:45 +0200 Subject: [Tutor] Tutorials on the web Message-ID: <436880B5.1020202@accesstel.co.za> Here is a link to a range of tutorials: http://www.awaretek.com/tutorials.html Maybe this wil help some people to know where to find a good tutorial ona specific subject. Johan From vagemulo at yahoo.es Wed Nov 2 14:18:14 2005 From: vagemulo at yahoo.es (rio) Date: Wed, 2 Nov 2005 08:18:14 -0500 (EST) Subject: [Tutor] while/if/elif/else loops In-Reply-To: Message-ID: <20051102131814.48035.qmail@web26604.mail.ukl.yahoo.com> i too am a newbie to programming (except BASIC over 20 years ago!). randrange() didnt seem to be in the random module (pyth2.4.2) random() IS but it doesn;t seem to take arguments. it returns a float between 0.0 and 0.9999, so random.random()*2 means half will be (0.0-0.99999) & half (1.0-1.99999). int() rounds it towards 0. i bet it coulda been simpler or more elegant... but i think i more or less got it working... -------------------begin code---------------------- #Coin Toss Game print "This game will simulate 100 coin tosses and then tell you the number of heads and tails" import random tosses = 0 heads = 0 tails = 0 while tosses < 100: coin = int(random.random()*2) print coin, # prints 0s or 1s instead of heads & tails (to save space) tosses +=1 if coin == 0: heads +=1 else: tails +=1 print print " heads total:", heads print " tails total:", tails --------------------end code----------------------- can i gush? I LOOOOOOVE python! what a great language! IDLE is awesome! this list is awesome! i learn so much every day... brian zmanji at gmail wrote: > I'm new to programming and python. I've have recently been experimenting > with while/if/elif/else loops and I've created a simple number guessing > game. Now I want to create a coin tossing game, but I don't know how to > structure it in python. The code I already have (but it's not working) > is below. > > > #Coin Toss Game > > print "This game will simulate 100 coin tosses and then tell you the > number of head's and tails" > > import random > > tosses = 0 > heads = 0 > tails = 0 > > while tosses = 100<0: > coin = randrange(1) > tosses +=1 > if coin == 0: > heads +=1 > print "Heads" > else: > tails +=1 > Print "Tails" __________________________________________________________ Find your next car at http://autos.yahoo.ca From vagemulo at yahoo.es Wed Nov 2 15:34:56 2005 From: vagemulo at yahoo.es (rio) Date: Wed, 2 Nov 2005 09:34:56 -0500 (EST) Subject: [Tutor] idle shell command recall In-Reply-To: Message-ID: <20051102143456.77743.qmail@web26612.mail.ukl.yahoo.com> is there any way from the idle shell to recall the last line(s) of code entered like or does for DOS prompt or BASH? brian __________________________________________________________ Find your next car at http://autos.yahoo.ca From kent37 at tds.net Wed Nov 2 17:35:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Nov 2005 11:35:32 -0500 Subject: [Tutor] Decoding decleration In-Reply-To: <43686508.3010307@accesstel.co.za> References: <43686508.3010307@accesstel.co.za> Message-ID: <4368EAD4.9080103@tds.net> Johan Geldenhuys wrote: > I receive this error when executing a file: > "Non-ASCII character '\x8b' in file task.py on line 1, but no encoding > declared". > > Can anybody tell me what the encoding is supposed to look like and is it > standard on all files that is trying to use Non-ASCII characters? Python expects source files to be in ASCII unless they contain an encoding declaration. The encoding declaration is a special comment line. It must be the first or second line of the file and have the form # -*- coding: -*- for example # -*- coding: iso-8859-1 -*- The current release allows iso-8859-1 characters and gives a warning as you have seen. A future release will make this an error. For full details see PEP 263: http://www.python.org/peps/pep-0263.html It's not explicit in the PEP but I assume the encoding name can be any name recognized by the Python codecs module; a list is here: http://docs.python.org/lib/standard-encodings.html Kent -- http://www.kentsjohnson.com From kent37 at tds.net Wed Nov 2 19:09:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Nov 2005 13:09:34 -0500 Subject: [Tutor] while/if/elif/else loops In-Reply-To: <20051102131814.48035.qmail@web26604.mail.ukl.yahoo.com> References: <20051102131814.48035.qmail@web26604.mail.ukl.yahoo.com> Message-ID: <436900DE.5070802@tds.net> rio wrote: > i too am a newbie to programming (except BASIC over 20 years ago!). > randrange() didnt seem to be in the random module (pyth2.4.2) Sure it is, check your spelling and make sure you call it random.randrange(): Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> random.randrange(2) 1 > can i gush? I LOOOOOOVE python! what a great language! IDLE is awesome! > this list is awesome! i learn so much every day... Gush away :-) Kent -- http://www.kentsjohnson.com From kent37 at tds.net Wed Nov 2 19:11:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 02 Nov 2005 13:11:19 -0500 Subject: [Tutor] idle shell command recall In-Reply-To: <20051102143456.77743.qmail@web26612.mail.ukl.yahoo.com> References: <20051102143456.77743.qmail@web26612.mail.ukl.yahoo.com> Message-ID: <43690147.4060704@tds.net> rio wrote: > is there any way from the idle shell to recall the last line(s) of code > entered like or does for DOS prompt or BASH? Use the mouse or the arrow keys to put the cursor in the line you want to recall. Press Return and you will get a fresh, editable copy of the line at your current prompt. Kent -- http://www.kentsjohnson.com From py at virtual.demon.co.uk Wed Nov 2 19:15:59 2005 From: py at virtual.demon.co.uk (Graeme) Date: Wed, 02 Nov 2005 18:15:59 +0000 Subject: [Tutor] idle shell command recall In-Reply-To: <20051102143456.77743.qmail@web26612.mail.ukl.yahoo.com> References: <20051102143456.77743.qmail@web26612.mail.ukl.yahoo.com> Message-ID: <4369025F.40704@virtual.demon.co.uk> rio wrote: > is there any way from the idle shell to recall the last line(s) of code > entered like or does for DOS prompt or BASH? Alt + P = History Previous Alt + N = History Next Also in the menu, if you go to Options > Configure IDLE > Keys, you'll find a list of all the available key options. Graeme From ebgreen at customdatasoft.com Wed Nov 2 15:52:49 2005 From: ebgreen at customdatasoft.com (ebgreen@customdatasoft.com) Date: Wed, 02 Nov 2005 09:52:49 -0500 Subject: [Tutor] Style/Conceptual Help Message-ID: <20051102095249.yqsxej0242cgkk00@65.254.38.146> I had posted once before with a TKinter problem that I was having and it was solved in one message so thanks a lot to the List. I now have working code and I would be interested in some input/suggestions on the pythonicness of the way I did things and on style, or anything else you see that I can improve. I have some things that I am already planning as improvements: -Menus - Right now there are none. I need to put some in with all of the options that I want. -Options - Right now there are 4 options that are available (sourcedir, targetdir, deleteold, and extensions) and they are stored in an INI file. I would like to make the options configurable from within the app and potentially use a DB for storage. -Logging - There is none right now and I am a fan of having logs to look back at when there is a problem to diagnose. Here is the code I have so far. Any input would be great. from Tkinter import * import PIL.Image as image import PIL.ImageTk as imagetk import ConfigParser import os import time import shutil from sys import exit def GetEndString(number): '''GetEndString(number) Takes an integer or an integer like string and returns the proper English ordinal ending string for the number. Examples: >>> print GetEndString(1) st >>> print GetEndString(2) nd >>> print GetEndString(3) rd >>> print GetEndString(4) th >>> print GetEndString(11) th >>> print GetEndString(12) th >>> print GetEndString(13) th >>> print GetEndString(130112) th ''' number = str(number) #The ending is different for 11 and 12 teens if number[len(number)-2:] == '11' or number[len(number)-2:] == '12' or number[len(number)-2:] == '13': return "th" #otherwise, the ending is a function of the last digit enddict = {'1':'st', '2':'nd', '3':'rd', '4':'th', '5':'th', '6':'th', '7':'th', '8':'th', '9':'th', '0':'th'} lastdigit = number[-1:] return enddict[lastdigit] class MyApp: def __init__(self, parent): self.myParent = parent self.myContainer1 = Frame(parent) self.myContainer1.configure() self.myContainer1.pack() self.button1 = Button(self.myContainer1) self.button1.configure(text="Copy Pics", font=("Arial Black", "24")) self.button1.pack() self.button1.bind("", self.button1Click) self.button1.bind("", self.button1Motion) self.button1.bind("", self.button1Leave) self.tvStat = StringVar() self.tvStat.set("") self.tvFrom = StringVar() self.tvFrom.set("") self.tvTo = StringVar() self.tvTo.set("") self.tvMid = StringVar() self.tvMid.set("") self.lblStat = Label(self.myContainer1) self.lblStat.configure(textvariable = self.tvStat) self.lblStat.pack() self.lblFrom = Label(self.myContainer1) self.lblFrom.configure(textvariable = self.tvFrom) self.lblFrom.pack() self.lblMid = Label(self.myContainer1) self.lblMid.configure(textvariable = self.tvMid) self.lblMid.pack() self.lblTo = Label(self.myContainer1) self.lblTo.configure(textvariable = self.tvTo) self.lblTo.pack() self.canvas1 = Canvas(self.myContainer1) self.canvas1.configure(width=700, height=300) self.canvas1.pack() def button1Motion(self, event): self.button1.configure(bg="blue", fg="yellow") def button1Leave(self, event): self.button1.configure(bg="#fff", fg="black") def button1Click(self, event): files = {} nameList = [] #Import config information from the ini file configfile = "./GetPics.ini" config = ConfigParser.ConfigParser() try: config.read(configfile) sourcedirloc = config.get("GetPics", "sourcedir") targetdirloc = config.get("GetPics", "targetdir") deleteold = config.get("GetPics", "deleteold") extList = config.get("GetPics", "extensions").lower().split(",") except ConfigParser.NoSectionError, detail: self.tvStat.set("There was an error while reading the ini file: " + str(detail) + os.linesep + "Please correct the problem then try again") return() #OPen the source dir and get a list of the files making the new name and path as you go sourcefiles = os.listdir(sourcedirloc) files = {} for file in sourcefiles: if os.path.splitext(file)[1].lower()[1:] not in extList: continue filepath = sourcedirloc + "/" + file if files.has_key(filepath): #The file is duplicated? pass else: files[filepath] = {} files[filepath]['originalname'] = file files[filepath]['modtuple'] = time.localtime(os.stat(filepath).st_mtime) files[filepath]['size'] = os.stat(filepath).st_size files[filepath]['monthdir'] = targetdirloc + "/" + \ time.strftime('%Y-%m', time.localtime(os.stat(filepath).st_mtime)) files[filepath]['daydir'] = files[filepath]['monthdir'] + "/" + \ time.strftime('%d', time.localtime(os.stat(filepath).st_mtime)) + \ GetEndString(time.strftime('%d', time.localtime(os.stat(filepath).st_mtime))) files[filepath]['newname'] = files[filepath]['daydir'] + "/" + time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(os.stat(filepath).st_mtime)) + os.path.splitext(file)[1] #Now check to see if a file with this name already exists and increment the name if it does n = 1 testName = files[filepath]['newname'] while os.path.isfile(testName) or testName in nameList: testName = os.path.splitext(files[filepath]['newname'])[0] + "-" + str(n) + os.path.splitext(files[filepath]['newname'])[1] n += 1 files[filepath]['newname'] = testName nameList.append(testName) #Copy all of the file to the target dir for file in files.keys(): self.tvStat.set("Copying...") #Check for the dir and create it if needed: if not os.path.isdir(files[file]['monthdir']): self.tvFrom.set("Creating (monthdir) " + files[file]['monthdir']) os.makedirs(files[file]['monthdir']) if not os.path.isdir(files[file]['daydir']): self.tvFrom.set("Creating (daydir) " + files[file]['daydir']) os.makedirs(files[file]['daydir']) #copy the file self.tvFrom.set(file) self.tvMid.set("TO") self.tvTo.set(files[file]['newname']) try: self.DisplayImage(file) except: print "ERROR:", sys.exc_info()[0] shutil.copy2(file, files[file]['newname']) #Go back and remove the sorce files checking that the target file exists first self.tvStat.set("Finished with copies...") self.tvFrom.set("") self.tvMid.set("") self.tvTo.set("") for file in files.keys(): if os.stat(files[file]['newname']).st_size == files[file]['size'] and deleteold.lower() == "true": self.tvStat.set("Deleting file...") self.tvFrom.set(file) os.remove(file) else: self.tvStat.set("There was an error with " + file) self.tvStat.set("Copy done.") self.tvFrom.set(str(len(files)) + " files were copied.") self.tvMid.set("") self.tvTo.set("") def DisplayImage(self, file): im = image.open(file) origx, origy = im.size if origx > origy: ratio = 250./origx else: ratio = 250./origy size = (int(ratio*origx), int(ratio*origy)) out = im.resize(size) pic1 = imagetk.PhotoImage(out) self.canvas1.create_image(350, 150, image = pic1, anchor=CENTER) self.myParent.update_idletasks() self.canvas1.pack() # run it ... root = Tk() myapp = MyApp(root) root.mainloop() From Barry.Carroll at psc.com Wed Nov 2 19:47:20 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 2 Nov 2005 10:47:20 -0800 Subject: [Tutor] Tutorials on the web Message-ID: Johan: The link is helpful indeed. In five minutes I found six tutorials I want to check out for my current project. Thank you. Barry > Message: 5 > Date: Wed, 02 Nov 2005 11:02:45 +0200 > From: Johan Geldenhuys > Subject: [Tutor] Tutorials on the web > To: Tutor > Message-ID: <436880B5.1020202 at accesstel.co.za> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Here is a link to a range of tutorials: > http://www.awaretek.com/tutorials.html > > Maybe this wil help some people to know where to find a good tutorial > ona specific subject. > > Johan From dyoo at hkn.eecs.berkeley.edu Wed Nov 2 20:15:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 2 Nov 2005 11:15:20 -0800 (PST) Subject: [Tutor] Style/Conceptual Help In-Reply-To: <20051102095249.yqsxej0242cgkk00@65.254.38.146> Message-ID: On Wed, 2 Nov 2005 ebgreen at customdatasoft.com wrote: > I would be interested in some input/suggestions on the pythonicness of > the way I did things and on style, or anything else you see that I can > improve. Hi ebgreen, The only big thing I'd point out is that the buttonClick() method of the application is too big. *grin* You may want to extract some of its functionality as separate methods. The overall movement of button1Click appears to be the following: ### Pseudocode ##################### def button1Click(): importConfigurationInformation() getListOfFiles() copyFilesToTargetDirectory() deleteSourceFilesSafely() #################################### I'm boxing things this way initially because the program's comments seem to favor it. The configuration information stuff might want to live in a separate class: I'm not sure if the GUI itself should be so intimately involved with the details of reading off a ConfigParser. One possibility is to do something like this: ################################################################## class Configuration: def __init__(self, configfile): parser = ConfigParser.ConfigParser() parser.read(configfile) self.sourcedirloc = parser.get("GetPics", "sourcedir") self.targetdirloc = parser.get("GetPics", "targetdir") self.deleteold = parser.get("GetPics", "deleteold") self.extList = parser.get("GetPics", "extensions").lower().split(",") ################################################################## (For the moment, I'm stripping out the exception handling just to make this example simple: you'll probably want to add it back later.) If we have something like this Configuration object, then we can use it as: ########################################### def button1Click(self, event): files = {} nameList = [] config = Configuration("./GetPics.ini") #OPen the source dir and get a list of the files making the new name and #path as you go sourcefiles = os.listdir(config.sourcedirloc) ... ########################################### That is, if we're careful about things, we can slowly extract blocks of code into separate classes and methods, and we'll make the code easier to read. The extraction above also makes it easier to see that it might even be possible to reorder the configuration reading part to some time even before buttons are clicked, since it doesn't really pay attention to anything else besides the filename './GetPics.ini'. Hope this helps! From hugonz-lists at h-lab.net Wed Nov 2 22:39:25 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 02 Nov 2005 15:39:25 -0600 Subject: [Tutor] os command In-Reply-To: <43687941.40303@accesstel.co.za> References: <435F6FCD.4090704@accesstel.co.za> <435FFE2A.8040105@h-lab.net> <43687941.40303@accesstel.co.za> Message-ID: <4369320D.9060306@h-lab.net> In UNIX, you use the fork() exec() technique for starting a new process, from the very first process(init) onwards. The os.system() uses a shell to do that, or you may do it yourself (in your script) A "command" is just an executable file running(process), unless you've got a library function that does just that, then you could do what you must without creating a new process. Probably your best bet would be to use the subprocess module. It was designed around the limitations of the previous methods. Take a look at what oyu can do with it at: http://www.python.org/doc/2.4.2/lib/module-subprocess.html For example, the pid of the command would be available at the pid atribute of a subprocess instance. p.pid Hugo Johan Geldenhuys wrote: > Sorry for the late reply, > But is it necessary to use a child process? I don't want to execute the > command in another process. What happens with the parent process and how > do I execute my command in the parent process? > > Thanks > > Hugo Gonz?lez Monteverde wrote: > >> Hi, >> >> os.system will return the errorval of the application. You need to >> >> 1) get the pid of the child process >> 2) kill it using os.kill(os.SIGTERM) >> 3) reap the killed process >> >> This is all in unix/linux, of course. >> >> what I do (untested, please check order of args and correct usage of >> exec): >> >> pid = os.fork() >> >> if pid == 0: #child process >> os.execvp("tcpdump", "tcpdump", "-n", "-i", "eth0") >> >> else: #parent >> time.sleep(5) >> os.kill(pid, os.SIGTERM) >> os.waitpid(pid, 0) #wait for process to end >> >> >> >> Johan Geldenhuys wrote: >> >>> I have script that calls a system command that I want to run for 5 >>> minutes. >>> """ >>> import os >>> cmd = 'tcpdump -n -i eth0' >>> os.system(cmd) >>> """ >>> >>> I can start a timer after the cmd is issued, but I don't know how to >>> send a control signal to stop the command after I issued it. This is >>> normally from the shell ^c. >>> >>> This cmd my run in more than one thread on different interfaces and I >>> don't whant all of then stopped at once. I think the best way is to >>> make a thread for each interface where the cmd can be issued and >>> stopped without the danger of stopping he wrong thread. >>> >>> Can anybody help? >>> >>> Thanks >>> >>> Johan >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> > From rob at customdatasoft.com Thu Nov 3 02:45:40 2005 From: rob at customdatasoft.com (Rob Dowell) Date: Wed, 02 Nov 2005 19:45:40 -0600 Subject: [Tutor] Style/Conceptual Help In-Reply-To: References: Message-ID: <43696BC4.8020803@customdatasoft.com> Thanks for the input Danny. I had already begun to separate the presentation layer from the computation by moving code out of the button click function. Your idea of a separate config class is a good one and I will implement it soon. I'll also begin fragmenting the function that does all the work to make it easier to follow. Thanks again for the input and I will post back here for more advice when I get these changes completed. Oh, and about the email addresses, ebgreen is an account I use when doing email via a web interface (i.e. I'm not at home) and this is my home address. Rob Danny Yoo wrote: >On Wed, 2 Nov 2005 ebgreen at customdatasoft.com wrote: > > > >>I would be interested in some input/suggestions on the pythonicness of >>the way I did things and on style, or anything else you see that I can >>improve. >> >> > >Hi ebgreen, > >The only big thing I'd point out is that the buttonClick() method of the >application is too big. *grin* > > >You may want to extract some of its functionality as separate methods. The >overall movement of button1Click appears to be the following: > >### Pseudocode ##################### >def button1Click(): > importConfigurationInformation() > getListOfFiles() > copyFilesToTargetDirectory() > deleteSourceFilesSafely() >#################################### > >I'm boxing things this way initially because the program's comments seem >to favor it. > > >The configuration information stuff might want to live in a separate >class: I'm not sure if the GUI itself should be so intimately involved >with the details of reading off a ConfigParser. One possibility is to do >something like this: > > >################################################################## >class Configuration: > def __init__(self, configfile): > parser = ConfigParser.ConfigParser() > parser.read(configfile) > self.sourcedirloc = parser.get("GetPics", "sourcedir") > self.targetdirloc = parser.get("GetPics", "targetdir") > self.deleteold = parser.get("GetPics", "deleteold") > self.extList = parser.get("GetPics", > "extensions").lower().split(",") >################################################################## > >(For the moment, I'm stripping out the exception handling just to make >this example simple: you'll probably want to add it back later.) > > >If we have something like this Configuration object, then we can use it >as: > >########################################### >def button1Click(self, event): > files = {} > nameList = [] > config = Configuration("./GetPics.ini") > > #OPen the source dir and get a list of the files making the new name and > #path as you go > sourcefiles = os.listdir(config.sourcedirloc) > ... >########################################### > > >That is, if we're careful about things, we can slowly extract blocks of >code into separate classes and methods, and we'll make the code easier to >read. > >The extraction above also makes it easier to see that it might even be >possible to reorder the configuration reading part to some time even >before buttons are clicked, since it doesn't really pay attention to >anything else besides the filename './GetPics.ini'. > > >Hope this helps! > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > > > From Barry.Carroll at psc.com Thu Nov 3 03:13:26 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Wed, 2 Nov 2005 18:13:26 -0800 Subject: [Tutor] Talking to UDPServer: Follow-up Message-ID: Greetings: After studying the socket examples and tutorials y'all pointed me to, I settled on Examples 19.3 and 19.4 in Alex Martelli's " Python in a Nutshell" as my starting point. They worked fine, of course, right out of the box. My task now is to extend the client script to handle the command syntax that our server program implements. Thanks to everyone who helped. This maillist is my best source of Python information. Barry From dyoo at hkn.eecs.berkeley.edu Thu Nov 3 03:15:46 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 2 Nov 2005 18:15:46 -0800 (PST) Subject: [Tutor] Style/Conceptual Help In-Reply-To: <43696BC4.8020803@customdatasoft.com> Message-ID: On Wed, 2 Nov 2005, Rob Dowell wrote: > Oh, and about the email addresses, ebgreen is an account I use when > doing email via a web interface (i.e. I'm not at home) and this is my > home address. [meta: list administration] Hi Rob, No problem. What you can do, if you want to avoid the moderation queue, is subscribe your other email account to the Tutor list too, and set its options so that it doesn't receive list traffic. That way, our mailing list software will at least know that you're subscribed --- it'll know that you can post to the list, but it won't go out of its way to send messages to you. From johan at accesstel.co.za Thu Nov 3 05:11:09 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 03 Nov 2005 06:11:09 +0200 Subject: [Tutor] os command In-Reply-To: <4369320D.9060306@h-lab.net> References: <435F6FCD.4090704@accesstel.co.za> <435FFE2A.8040105@h-lab.net> <43687941.40303@accesstel.co.za> <4369320D.9060306@h-lab.net> Message-ID: <43698DDD.8030203@accesstel.co.za> Hugo, I see that 'os.execcvp()' doesn't actually make two seperate processes. The advice you gave me works good. I just had to fgure out with what params I should call it. I'm still a bit unsure of how to call the sysem command with more than one argument. This is what I have working now: """ import os, signal, time pid = os.fork() print 'pid; ',pid if pid == 0: #child process #os.execvp('tcpdump', ['tcpdump', '-i modem0 > cap1.txt']) os.execvp('ping', ['ping', '127.0.0.1 -c 30 > cap.txt']) time.sleep(5) kill(pid) def kill(pid, signal=signal.SIGTERM): print "trying to kill pid...", pid os.kill(pid, signal) os.waitpid(pid, 0) print "Killed %d"%pid """ The ping command is executed but the part where it must put the replies in the file is not recognized. How do I use the addisional arguments to be seen? Thanks, Johan Hugo Gonz?lez Monteverde wrote: > In UNIX, you use the fork() exec() technique for starting a new > process, from the very first process(init) onwards. The os.system() > uses a shell > to do that, or you may do it yourself (in your script) > > A "command" is just an executable file running(process), unless you've > got a library function that does just that, then you could do what you > must without creating a new process. > > Probably your best bet would be to use the subprocess module. It was > designed around the limitations of the previous methods. > > Take a look at what oyu can do with it at: > > http://www.python.org/doc/2.4.2/lib/module-subprocess.html > > For example, the pid of the command would be available at the pid > atribute of a subprocess instance. > > p.pid > > Hugo > > Johan Geldenhuys wrote: > >> Sorry for the late reply, >> But is it necessary to use a child process? I don't want to execute >> the command in another process. What happens with the parent process >> and how do I execute my command in the parent process? >> >> Thanks >> >> Hugo Gonz?lez Monteverde wrote: >> >>> Hi, >>> >>> os.system will return the errorval of the application. You need to >>> >>> 1) get the pid of the child process >>> 2) kill it using os.kill(os.SIGTERM) >>> 3) reap the killed process >>> >>> This is all in unix/linux, of course. >>> >>> what I do (untested, please check order of args and correct usage of >>> exec): >>> >>> pid = os.fork() >>> >>> if pid == 0: #child process >>> os.execvp("tcpdump", "tcpdump", "-n", "-i", "eth0") >>> >>> else: #parent >>> time.sleep(5) >>> os.kill(pid, os.SIGTERM) >>> os.waitpid(pid, 0) #wait for process to end >>> >>> >>> >>> Johan Geldenhuys wrote: >>> >>>> I have script that calls a system command that I want to run for 5 >>>> minutes. >>>> """ >>>> import os >>>> cmd = 'tcpdump -n -i eth0' >>>> os.system(cmd) >>>> """ >>>> >>>> I can start a timer after the cmd is issued, but I don't know how >>>> to send a control signal to stop the command after I issued it. >>>> This is normally from the shell ^c. >>>> >>>> This cmd my run in more than one thread on different interfaces and >>>> I don't whant all of then stopped at once. I think the best way is >>>> to make a thread for each interface where the cmd can be issued and >>>> stopped without the danger of stopping he wrong thread. >>>> >>>> Can anybody help? >>>> >>>> Thanks >>>> >>>> Johan >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>> >> > From hugonz-lists at h-lab.net Thu Nov 3 05:51:20 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 02 Nov 2005 22:51:20 -0600 Subject: [Tutor] os command In-Reply-To: <43698DDD.8030203@accesstel.co.za> References: <435F6FCD.4090704@accesstel.co.za> <435FFE2A.8040105@h-lab.net> <43687941.40303@accesstel.co.za> <4369320D.9060306@h-lab.net> <43698DDD.8030203@accesstel.co.za> Message-ID: <43699748.6030504@h-lab.net> Hi Johan Geldenhuys wrote: > Hugo, > > I see that 'os.execcvp()' doesn't actually make two seperate processes. > This is what I have working now: > """ > > import os, signal, time > pid = os.fork() > print 'pid; ',pid > if pid == 0: #child process > #os.execvp('tcpdump', ['tcpdump', '-i modem0 > cap1.txt']) > os.execvp('ping', ['ping', '127.0.0.1 -c 30 > cap.txt']) The following line (sleep)is superluous, as it is no longer your python script after calling exec() Your process (in this case the child process)is replaced with a copy of ping in memory. > time.sleep(5) > kill(pid) > > def kill(pid, signal=signal.SIGTERM): > print "trying to kill pid...", pid > os.kill(pid, signal) > os.waitpid(pid, 0) > print "Killed %d"%pid > """ > > The ping command is executed but the part where it must put the replies > in the file is not recognized. How do I use the addisional arguments to > be seen? > Mmm no, this line: > os.execvp('ping', ['ping', '127.0.0.1 -c 30 > cap.txt']) uses *shell redirection*.. guess who has to interpret the whole > thing.. As you are using no shell, the '>' argument is passed to the ping program, which knows nothing of handling it the way you expect it. What you're doing is equivalent to (in my workstation) root at glorfindel:~# ping 192.168.0.8 ">" cap.txt ping: unknown host > You have to call a shell if you want to use redirection, otherwise you will have to use python to send all of ping's output to a file (which would be a nice exercise, IMHO ;) ) Hugo From hugonz at h-lab.net Thu Nov 3 05:48:49 2005 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 02 Nov 2005 22:48:49 -0600 Subject: [Tutor] os command In-Reply-To: <43698DDD.8030203@accesstel.co.za> References: <435F6FCD.4090704@accesstel.co.za> <435FFE2A.8040105@h-lab.net> <43687941.40303@accesstel.co.za> <4369320D.9060306@h-lab.net> <43698DDD.8030203@accesstel.co.za> Message-ID: <436996B1.3010002@h-lab.net> Hi Johan Geldenhuys wrote: > Hugo, > > I see that 'os.execcvp()' doesn't actually make two seperate processes. > This is what I have working now: > """ > > import os, signal, time > pid = os.fork() > print 'pid; ',pid > if pid == 0: #child process > #os.execvp('tcpdump', ['tcpdump', '-i modem0 > cap1.txt']) > os.execvp('ping', ['ping', '127.0.0.1 -c 30 > cap.txt']) The following line (sleep)is superluous, as it is no longer your python script after calling exec() Your process (in this case the child process)is replaced with a copy of ping in memory. > time.sleep(5) > kill(pid) > > def kill(pid, signal=signal.SIGTERM): > print "trying to kill pid...", pid > os.kill(pid, signal) > os.waitpid(pid, 0) > print "Killed %d"%pid > """ > > The ping command is executed but the part where it must put the replies > in the file is not recognized. How do I use the addisional arguments to > be seen? > Mmm no, this line: > os.execvp('ping', ['ping', '127.0.0.1 -c 30 > cap.txt']) uses *shell redirection*.. guess who has to interpret the whole > thing.. As you are using no shell, the '>' argument is passed to the ping program, which knows nothing of handling it the way you expect it. What you're doing is equivalent to (in my workstation) root at glorfindel:~# ping 192.168.0.8 ">" cap.txt ping: unknown host > You have to call a shell if you want to use redirection, otherwise you will have to use python to send all of ping's output to a file (which would be a nice exercise, IMHO ;) ) Hugo From rob at customdatasoft.com Thu Nov 3 07:55:03 2005 From: rob at customdatasoft.com (Rob Dowell) Date: Thu, 03 Nov 2005 00:55:03 -0600 Subject: [Tutor] Style/Conceptual Help In-Reply-To: References: Message-ID: <4369B447.6090106@customdatasoft.com> Thanks, I'll do that. Danny Yoo wrote: >On Wed, 2 Nov 2005, Rob Dowell wrote: > > > >>Oh, and about the email addresses, ebgreen is an account I use when >>doing email via a web interface (i.e. I'm not at home) and this is my >>home address. >> >> > >[meta: list administration] > >Hi Rob, > >No problem. > >What you can do, if you want to avoid the moderation queue, is subscribe >your other email account to the Tutor list too, and set its options so >that it doesn't receive list traffic. > >That way, our mailing list software will at least know that you're >subscribed --- it'll know that you can post to the list, but it won't go >out of its way to send messages to you. > > > > > > > From johan at accesstel.co.za Thu Nov 3 08:37:14 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 03 Nov 2005 09:37:14 +0200 Subject: [Tutor] Capture command output Message-ID: <4369BE2A.6020200@accesstel.co.za> I've been musy with the os command on how to kill a process. That's been sorted out to an extend. Many thanks for your input. Now I have a question in the same direction: I use os.execpv(cmd, [cmd, args]). That executes the command that have output. This was the best way of getting the pid and killing the process after a certain time. This is my code: import os, signal, time pid = os.fork() print 'pid; ',pid if pid == 0: #child process os.execvp('tcpdump', ['tcpdump', '-np']) # Need syntax to add another arg time.sleep(5) # let it run for 5 seconds kill(pid) # kill the process def kill(pid, signal=signal.SIGTERM): print "trying to kill pid...", pid os.kill(pid, signal) os.waitpid(pid, 0) print "Killed %d"%pid How do I capture that output to a file? Can I use os.popen() or something like that after I did the os.execvp() execution or is there a standard way of putting any output in a file/ Thanks, From ajikoe at gmail.com Thu Nov 3 10:02:32 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 3 Nov 2005 10:02:32 +0100 Subject: [Tutor] avoid eval how??? Message-ID: Hello I have a dynamic functions which created by some algorithms during runtime. These functions are in string type. When I want to use it, I can use eval command. But can someone give me more suggestion about how to handle this problem, I want to avoid eval. Example : L = ['x+sin(x)', '1/(2.2 + pow(2,3)/sin(30)'] Sincerely Yours, pujo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051103/90a9aea7/attachment.htm From kent37 at tds.net Thu Nov 3 11:55:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Nov 2005 05:55:16 -0500 Subject: [Tutor] Capture command output In-Reply-To: <4369BE2A.6020200@accesstel.co.za> References: <4369BE2A.6020200@accesstel.co.za> Message-ID: <4369EC94.4020806@tds.net> Johan Geldenhuys wrote: > I've been musy with the os command on how to kill a process. That's been > sorted out to an extend. Many thanks for your input. > > Now I have a question in the same direction: > > I use os.execpv(cmd, [cmd, args]). That executes the command that have > output. This was the best way of getting the pid and killing the process > after a certain time. > > How do I capture that output to a file? > Can I use os.popen() or something like that after I did the os.execvp() > execution or is there a standard way of putting any output in a file/ Have you tried using subprocess.Popen()? It supports capturing output of the child process and it gives access to the pid of the child. Kent -- http://www.kentsjohnson.com From johan at accesstel.co.za Thu Nov 3 11:58:15 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 03 Nov 2005 12:58:15 +0200 Subject: [Tutor] Capture command output In-Reply-To: <4369EC94.4020806@tds.net> References: <4369BE2A.6020200@accesstel.co.za> <4369EC94.4020806@tds.net> Message-ID: <4369ED47.1010007@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051103/873298d8/attachment-0001.htm From kent37 at tds.net Thu Nov 3 11:59:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Nov 2005 05:59:04 -0500 Subject: [Tutor] O'Reilly on sale at Bookpool Message-ID: <4369ED78.4030902@tds.net> Bookpool.com has all O'Reilly titles on sale 47% off. So if you have been wanting to pick up a copy of Learning Python, Python in a Nutshell or Python Cookbook this is a good time. Kent -- http://www.kentsjohnson.com From lists at janeden.org Thu Nov 3 13:22:27 2005 From: lists at janeden.org (Jan Eden) Date: Thu, 3 Nov 2005 13:22:27 +0100 Subject: [Tutor] Subclassing data attributes Message-ID: Hi, the module Data.py stores a number of data attributes. I'd like to structure the storage of these attributes, either in subclasses or in dictionaries. My first attempt was this: class A: templates['attr1'] = 'string' queries['children'] = ... class B(A): templates['attr2'] = 4 queries['children'] = ... class C(B): templates['attr3'] = 939.121 queries['populate'] = ... Python obviously complains about unknown names 'templates' and 'queries'. So I thought about realizing this with classes: class A: class Templates: attr1 = 'string' ... The problem here is that once an object uses class C.Templates to lookup attr3, it will not consult class A.Templates for attr1. How can I avoid a complete inheritance mess and structure all my data attributes at the same time? Thanks, Jan -- I'd never join any club that would have the likes of me as a member. - Groucho Marx From kent37 at tds.net Thu Nov 3 14:09:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Nov 2005 08:09:35 -0500 Subject: [Tutor] Subclassing data attributes In-Reply-To: References: Message-ID: <436A0C0F.4030208@tds.net> Jan Eden wrote: > Hi, > > the module Data.py stores a number of data attributes. I'd like to structure the storage of these attributes, either in subclasses or in dictionaries. > > My first attempt was this: > > class A: > templates['attr1'] = 'string' > queries['children'] = ... > > class B(A): > templates['attr2'] = 4 > queries['children'] = ... > > class C(B): > templates['attr3'] = 939.121 > queries['populate'] = ... > > Python obviously complains about unknown names 'templates' and 'queries'. I'm not at all clear why you want to do this. Can you give an example of how you would use these classes? If you want the classes to be containers for data you can just use class attributes like this: >>> class A(object): ... attr1 = 'string' ... children = 'children of A' ... >>> class B(A): ... attr2 = 4 ... children = 'children of B' ... >>> A.attr1 'string' >>> A.children 'children of A' >>> B.attr1 'string' >>> B.attr2 4 >>> B.children 'children of B' You might also be interested in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305268 Is either of these close to what you want? Kent -- http://www.kentsjohnson.com From cjw at sympatico.ca Thu Nov 3 15:12:23 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 03 Nov 2005 09:12:23 -0500 Subject: [Tutor] avoid eval how??? In-Reply-To: References: Message-ID: <436A1AC7.5050501@sympatico.ca> Pujo Aji wrote: > Hello > > I have a dynamic functions which created by some algorithms during > runtime. > These functions are in string type. > When I want to use it, I can use eval command. > But can someone give me more suggestion about how to handle this > problem, I want to avoid eval. Why avoid? It seems the simplest way. Colin W. > > Example : > L = ['x+sin(x)', '1/(2.2 + pow(2,3)/sin(30)'] > > > Sincerely Yours, > pujo > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > From mhansen at cso.atmel.com Thu Nov 3 18:42:25 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 03 Nov 2005 10:42:25 -0700 Subject: [Tutor] RSH? Message-ID: <436A4C01.5070100@cso.atmel.com> Anyone know of a way to have Python run a command on a remote machine? In my particular case, I want to run a python program on Windows and run a command on VMS. Would the telnetlib module do it, or is there something better? Mike From ajikoe at gmail.com Thu Nov 3 18:44:11 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 3 Nov 2005 18:44:11 +0100 Subject: [Tutor] RSH? In-Reply-To: <436A4C01.5070100@cso.atmel.com> References: <436A4C01.5070100@cso.atmel.com> Message-ID: try pyro. Cheers, pujo On 11/3/05, Mike Hansen wrote: > > Anyone know of a way to have Python run a command on a remote machine? In > my > particular case, I want to run a python program on Windows and run a > command on > VMS. Would the telnetlib module do it, or is there something better? > > Mike > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051103/15e17c17/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Nov 3 20:13:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 3 Nov 2005 11:13:45 -0800 (PST) Subject: [Tutor] avoid eval how??? In-Reply-To: Message-ID: On Thu, 3 Nov 2005, Pujo Aji wrote: > I have a dynamic functions which created by some algorithms during > runtime. These functions are in string type. When I want to use it, I > can use eval command. But can someone give me more suggestion about how > to handle this problem, I want to avoid eval. Hi Pujo, To do this safely, many programmers will take a parsing + evaluation approach. A parser can take a string, such as: "x + sin(x)" and turn it into a data structure that can be evaluated safely. As a concrete example of what it means to use data structures to represent these dynamic functions: ############################################## class Add: """Represents the addition operator.""" def __init__(self, lhs, rhs): self.lhs, self.rhs = lhs, rhs def evaluate(self, environment): lval = self.lhs.evaluate(environment) rval = self.rhs.evaluate(environment) return lval + rval class Variable: """Represents a variable name.""" def __init__(self, id): self.id = id def evaluate(self, environment): return environment[self.id] ############################################## Let's say that we have a string like: "x + y" We can capture the essence of the meaning there by building the data structure: Add(Variable('x'), Variable('y')) The job of doing the string-to-data-structure thing is pretty automated if we use parser tools like pyparsing. I won't go into parsing at the moment; I'll treat that as a separate topic, but if you want to explore parsers, see: http://pyparsing.sourceforge.net/ Once we have a dynamic function in a data structure format like this, then things aren't so bad. We can "evaluate" that data structure at multiple points: ###### >>> equation = Add(Variable('x'), Variable('y')) >>> equation <__main__.Add instance at 0x403a7e2c> >>> equation.evaluate(dict(x=3, y=4)) 7 >>> equation.evaluate(dict(x=19, y=42)) 61 >>> >>> another = Add(Variable('x'), Add(Variable('y'), Variable('z'))) >>> another.evaluate(dict(x=3, y=4, z=5)) 12 ###### Does this make sense? We can talk about this in more detail if you'd like. From 3dbernard at gmail.com Thu Nov 3 20:16:40 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 3 Nov 2005 14:16:40 -0500 Subject: [Tutor] RSH? In-Reply-To: References: <436A4C01.5070100@cso.atmel.com> Message-ID: <61d0e2b40511031116o4fc31851x2b678730080882ce@mail.gmail.com> I use plink http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html Basically you send a system command (os.system) to the plink executable. The actuall command will take this form: os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, command ) ) Now, if you want to run a python script on the remote machine, you will have to send two commands (afaik). The first one to cd to the python script file, the second to send the python execution command: os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, 'cd /blah/blah/' ) ) os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, 'python scriptname.py' ) ) On 11/3/05, Pujo Aji wrote: > try pyro. > > Cheers, > pujo > > > > On 11/3/05, Mike Hansen wrote: > > Anyone know of a way to have Python run a command on a remote machine? In > my > > particular case, I want to run a python program on Windows and run a > command on > > VMS. Would the telnetlib module do it, or is there something better? > > > > Mike > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 3 20:30:53 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 4 Nov 2005 08:30:53 +1300 Subject: [Tutor] avoid eval how??? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1352@chbnt01.alpha.wd.govt.nz> I recommend using pyparsing or similar parser to parse it; if merely to ensure that it's a valid algorithim. Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Pujo Aji Sent: Thursday, 3 November 2005 10:03 p.m. To: Tutor Subject: [Tutor] avoid eval how??? Hello I have a dynamic functions which created by some algorithms during runtime. These functions are in string type. When I want to use it, I can use eval command. But can someone give me more suggestion about how to handle this problem, I want to avoid eval. Example : L = ['x+sin(x)', '1/(2.2 + pow(2,3)/sin(30)'] Sincerely Yours, pujo A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051104/76ad96a2/attachment.html From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 3 20:31:37 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 4 Nov 2005 08:31:37 +1300 Subject: [Tutor] avoid eval how??? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1353@chbnt01.alpha.wd.govt.nz> Oops, I see I just doubled up on Danny's advice. Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Pujo Aji Sent: Thursday, 3 November 2005 10:03 p.m. To: Tutor Subject: [Tutor] avoid eval how??? Hello I have a dynamic functions which created by some algorithms during runtime. These functions are in string type. When I want to use it, I can use eval command. But can someone give me more suggestion about how to handle this problem, I want to avoid eval. Example : L = ['x+sin(x)', '1/(2.2 + pow(2,3)/sin(30)'] Sincerely Yours, pujo A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051104/1c2cc12a/attachment.htm From johan at accesstel.co.za Thu Nov 3 20:31:16 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 03 Nov 2005 21:31:16 +0200 Subject: [Tutor] printing statement Message-ID: <436A6584.8020802@accesstel.co.za> Hi all, Just a quick question; How do I code this output: """ files dirs ========== """ I want to print something a few space away from the left side or in the middle of the line. Thanks, Johan From dyoo at hkn.eecs.berkeley.edu Thu Nov 3 20:38:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 3 Nov 2005 11:38:58 -0800 (PST) Subject: [Tutor] avoid eval how??? In-Reply-To: <436A1AC7.5050501@sympatico.ca> Message-ID: > > I have a dynamic functions which created by some algorithms during > > runtime. These functions are in string type. When I want to use it, I > > can use eval command. But can someone give me more suggestion about > > how to handle this problem, I want to avoid eval. > > Why avoid? It seems the simplest way. Hi Colin, The problem is that an eval()-like is too powerful for most programmers to use safely. It's danger is not a Python-specific issue, but common to any language that provides an eval() on arbitrary strings. http://en.wikipedia.org/wiki/Eval#Security_risks This aversion to eval() isn't based on some theoretical worry; the PHP folks got hit by exploits that targeted eval-using code just a few months ago. Read the "Security" section of: http://phpxmlrpc.sourceforge.net/#security to see what kind of issues eval() brings when we use it. They hit the same conceptual problem three times before they finally got humble enough to realize that eval() was the wrong tool. We have to learn from their mistakes, or else we'll make them ourselves. *grin* From hugonz-lists at h-lab.net Thu Nov 3 21:35:34 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 03 Nov 2005 14:35:34 -0600 Subject: [Tutor] Capture command output In-Reply-To: <4369ED47.1010007@accesstel.co.za> References: <4369BE2A.6020200@accesstel.co.za> <4369EC94.4020806@tds.net> <4369ED47.1010007@accesstel.co.za> Message-ID: <436A7496.9050703@h-lab.net> Hi, Here's the docs for the popen2 module in python 2.2, the Popen2 object allows you to get the pid. The popen2() call allows you to get the output in a filehandle. http://www.python.org/doc/2.2.3/lib/module-popen2.html You cannot run any function at all in your script after you do the exec call, it is no longer your program, but the one you exec-ed. popen actually runs the subprocess, you don't have to call it manually. Popen is the most used way to get the output, and looks like it is the only one in Python 2.2. Here's an example. >>> import popen2 >>> myobj = popen2.Popen3('/bin/ls') >>> dir(myobj) ['__doc__', '__init__', '__module__', '_run_child', 'childerr', 'fromchild', 'pid', 'poll', 'sts', 'tochild', 'wait'] >>> myobj.pid 3033 >>> output = myobj.fromchild.read() >>> output 'Changelog\nblankcursor\ndaemon.py\ndaemon.pyc\nl_index.txt\nl_sec.txt\nloadlin16c.txt\nloadlin16c.zip\nmypipa\nnewlooper.py\nxorg.conf.new\n' >>> myobj.wait() 0 Johan Geldenhuys wrote: > The version of python that I have is 2.2.2 and I can't upgrade, sorry. > As far as I know this only from version 2.4.2?? > > Johan > > Kent Johnson wrote: > >>Johan Geldenhuys wrote: >> >> >>>I've been musy with the os command on how to kill a process. That's been >>>sorted out to an extend. Many thanks for your input. >>> >>>Now I have a question in the same direction: >>> >>>I use os.execpv(cmd, [cmd, args]). That executes the command that have >>>output. This was the best way of getting the pid and killing the process >>>after a certain time. >>> >>>How do I capture that output to a file? >>>Can I use os.popen() or something like that after I did the os.execvp() >>>execution or is there a standard way of putting any output in a file/ >>> >>> >> >>Have you tried using subprocess.Popen()? It supports capturing output of the child process and it gives access to the pid of the child. >> >>Kent >> >> >> > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From shantanoo at gmail.com Thu Nov 3 21:07:59 2005 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Fri, 4 Nov 2005 01:37:59 +0530 Subject: [Tutor] RSH? In-Reply-To: <61d0e2b40511031116o4fc31851x2b678730080882ce@mail.gmail.com> References: <61d0e2b40511031116o4fc31851x2b678730080882ce@mail.gmail.com> Message-ID: <20051103200759.GA7585@ghar.dhoomketu.net.in> +++ Bernard Lebel [03-11-05 14:16 -0500]: | I use plink | http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html | | Basically you send a system command (os.system) to the plink | executable. The actuall command will take this form: | | os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, command ) ) | | | Now, if you want to run a python script on the remote machine, you | will have to send two commands (afaik). The first one to cd to the | python script file, the second to send the python execution command: | | os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, | 'cd /blah/blah/' ) ) | os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, | 'python scriptname.py' ) ) How about: os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, '/absolute/path/of/python /absolute/path/of/python/script' ) ) Also dirty method: (i,o,e) = os.popen3('telnet hostIP) Where, i = input o = output e = error i.write('...') for sending input. o.readline() and e.readline() for reading data. Shantanoo -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 187 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051104/c36ccffa/attachment.pgp From m.haft at abdn.ac.uk Thu Nov 3 22:34:23 2005 From: m.haft at abdn.ac.uk (Michael Haft) Date: Thu, 3 Nov 2005 21:34:23 -0000 (GMT) Subject: [Tutor] File IO Message-ID: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> Hello, I tried the following code: def readSOMNETM(inputName): input = open(inputName, "r") result = [] for line in input: fields = line.split() data = fields[1] + fields[2] + fields[7] result.append(data) input.close() return result print "Here goes" print "Enter filename:" filename = raw_input("Name:") print readSOMNETM(filename) print "might work" on a file that lookes like this: Monthly Weather Data, LAU73M.MET, converted from: BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW ************************************************************** 1 22.5 0.3 * 54.6 15.1 * 11.9 2 16.1 1.8 * 110 51.1 * 18.1 3 16.4 4.8 * 227.5 94.5 * 36.8 4 19.5 5.9 * 286.3 89 * 45.5 5 36.1 13.2 * 448.5 164.6 * 83 6 36 16.9 * 525.7 208.8 * 105.7 7 37.7 18.2 * 459.7 165.4 * 98.6 8 29.3 18.2 * 463.8 206.8 * 97.9 9 27 14.8 * 277.5 119.5 * 58.7 10 57.6 7.6 * 158.7 72.2 * 31.3 11 23.4 3.9 * 98.3 75.6 * 19.1 12 14 0.7 * 55.5 38 * 12.5 And recieved the following error: Traceback (most recent call last): File "C:\Python24\INProgress.py", line 15, in -toplevel- print readSOMNETM(filename) File "C:\Python24\INProgress.py", line 6, in readSOMNETM data = fields[1] + fields[2] + fields[7] IndexError: list index out of range Essentially I'm trying to write a bit of code that can take any of the fields in the above data i.e. rain temp evap for each month for a hundred or so files like this one and spit out a file at the end that has the data in a different format. Any help would be very much appreciated I need to get this done by the end of next week Thanks Mike From bgailer at alum.rpi.edu Thu Nov 3 22:54:24 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 03 Nov 2005 13:54:24 -0800 Subject: [Tutor] printing statement In-Reply-To: <436A6584.8020802@accesstel.co.za> References: <436A6584.8020802@accesstel.co.za> Message-ID: <6.1.2.0.0.20051103134622.0357e528@mail.mric.net> At 11:31 AM 11/3/2005, Johan Geldenhuys wrote: >Hi all, >Just a quick question; > >How do I code this output: >""" >files dirs >========== >""" > >I want to print something a few space away from the left side or in the >middle of the line. In the Python Library Reference look up 2.3.6.2 String Formatting Operations - % interpolation In general you create a "template" of the desired output with %s (or other conversion type) wherever you want a value substituted. "%-15s%-15s" % ('files', 'dirs') will give "files dirs " "%-15s%-15s" % (filename, directory) will give "funny.doc c:\root " assuming the variabies filename, directory have the values shown. the - means left align, 15 is field width. From bgailer at alum.rpi.edu Thu Nov 3 22:55:56 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 03 Nov 2005 13:55:56 -0800 Subject: [Tutor] printing statement In-Reply-To: <436A6584.8020802@accesstel.co.za> References: <436A6584.8020802@accesstel.co.za> Message-ID: <6.1.2.0.0.20051103135435.0357f280@mail.mric.net> At 11:31 AM 11/3/2005, Johan Geldenhuys wrote: >Hi all, >Just a quick question; FWIW saying that does not help. It takes time to read it, and I can judge the question length by reading the question. The real concern is what does it take to construct an answer. From bgailer at alum.rpi.edu Thu Nov 3 23:01:13 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 03 Nov 2005 14:01:13 -0800 Subject: [Tutor] File IO In-Reply-To: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> References: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> Message-ID: <6.1.2.0.0.20051103135828.0357dba8@mail.mric.net> At 01:34 PM 11/3/2005, Michael Haft wrote: >Hello, > I tried the following code: > >def readSOMNETM(inputName): > input = open(inputName, "r") > result = [] > for line in input: > fields = line.split() # add this; it will show you what line(s) have less than 8 fields if len(fields) < 8: print "Line too short", line continue > data = fields[1] + fields[2] + fields[7] > result.append(data) > input.close() > return result > > >print "Here goes" >print "Enter filename:" >filename = raw_input("Name:") >print readSOMNETM(filename) >print "might work" > >on a file that lookes like this: > >Monthly Weather Data, LAU73M.MET, converted from: >BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 >VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA >MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW >************************************************************** >1 22.5 0.3 * 54.6 15.1 * 11.9 >2 16.1 1.8 * 110 51.1 * 18.1 >3 16.4 4.8 * 227.5 94.5 * 36.8 >4 19.5 5.9 * 286.3 89 * 45.5 >5 36.1 13.2 * 448.5 164.6 * 83 >6 36 16.9 * 525.7 208.8 * 105.7 >7 37.7 18.2 * 459.7 165.4 * 98.6 >8 29.3 18.2 * 463.8 206.8 * 97.9 >9 27 14.8 * 277.5 119.5 * 58.7 >10 57.6 7.6 * 158.7 72.2 * 31.3 >11 23.4 3.9 * 98.3 75.6 * 19.1 >12 14 0.7 * 55.5 38 * 12.5 > > >And recieved the following error: > >Traceback (most recent call last): > File "C:\Python24\INProgress.py", line 15, in -toplevel- > print readSOMNETM(filename) > File "C:\Python24\INProgress.py", line 6, in readSOMNETM > data = fields[1] + fields[2] + fields[7] >IndexError: list index out of range > >Essentially I'm trying to write a bit of code that can take any of the >fields in the above data i.e. rain temp evap for each month for a hundred >or so files like this one and spit out a file at the end that has the data >in a different format. > >Any help would be very much appreciated I need to get this done by the end >of next week From m.haft at abdn.ac.uk Thu Nov 3 23:10:02 2005 From: m.haft at abdn.ac.uk (Mike Haft) Date: Thu, 3 Nov 2005 22:10:02 -0000 (GMT) Subject: [Tutor] File IO In-Reply-To: <6.1.2.0.0.20051103135828.0357dba8@mail.mric.net> References: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> <6.1.2.0.0.20051103135828.0357dba8@mail.mric.net> Message-ID: <1997.84.43.99.200.1131055802.squirrel@www.abdn.ac.uk> I did that and got this: Here goes Enter filename: Name:LAU73M.MET Line too short Monthly Weather Data, LAU73M.MET, converted from: Line too short BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 Line too short ********************************************************************** ['DEWPCALCULATEDHUMID', 'RAINAVTEMPEVAPW', '22.50.311.9', '16.11.818.1', '16.44.836.8', '19.55.945.5', '36.113.283.0', '36.016.9105.7', '37.718.298.6', '29.318.297.9', '27.014.858.7', '57.67.631.3', '23.43.919.1', '14.00.712.5'] might work Its worth pointing out that there are more than eight fields in my actual files, I'm using a shorter version just to test stuff on. Actual fields are: MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW EVAPG EVAPS HUMID VAP DEWP There are 13 so I'll have a play with that for the moment. Thanks for the help Mike > At 01:34 PM 11/3/2005, Michael Haft wrote: >>Hello, >> I tried the following code: >> >>def readSOMNETM(inputName): >> input = open(inputName, "r") >> result = [] >> for line in input: >> fields = line.split() > > # add this; it will show you what line(s) have less than 8 > fields > if len(fields) < 8: > print "Line too short", line > continue > >> data = fields[1] + fields[2] + fields[7] >> result.append(data) >> input.close() From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 3 23:11:36 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 4 Nov 2005 11:11:36 +1300 Subject: [Tutor] File IO Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B135A@chbnt01.alpha.wd.govt.nz> Hi Mike, Same file, eh? >From the docs for split() "If sep is not specified or is None, a different splitting algorithm is applied. First, whitespace characters (spaces, tabs, newlines, returns, and formfeeds) are stripped from both ends. Then, words are separated by arbitrary length strings of whitespace characters. Consecutive whitespace delimiters are treated as a single delimiter ("'1 2 3'.split()" returns "['1', '2', '3']"). Splitting an empty string or a string consisting of just whitespace returns an empty list." So, these lines '1 22.5 0.3 * 54.6 15.1 * 11.9' will yield lists - ['MONTH','RAIN', 'AVTEMP','S10','RAD','SUN','WIND','EVAPW'] ['1','22.5','0.3','*','54.6','15.1','*','11.9'] which is what you're after. >data = fields[1] + fields[2] + fields[7] >IndexError: list index out of range Now, this error. >>> x = [1,2,3] >>> print x[5] will cause the same error. Here's a debugging suggestion, jump in the interactive interpreter, and try this - >>>fields = "Monthly Weather Data, LAU73M.MET, converted from:".split() >>>print fields ["Monthly","Weather","Data","LAU73M.MET","converted", "from:"] >>>print fields[7] IndexError: list index out of range >>>"**************************************************************".split() ['**************************************************************'] That's your problem. In your loop, I'd recommend you check and ignore your header. either - result = [] pastHeader = False for line in input: if not pastHeader: if line.startswith("***********"): pastHeader = True #Will be shortly, anyway. continue #Skip line, go to next. else: #Header has passed. Process line normally. fields = line.split() -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Michael Haft Sent: Friday, 4 November 2005 10:34 a.m. To: tutor at python.org Subject: [Tutor] File IO Hello, I tried the following code: def readSOMNETM(inputName): input = open(inputName, "r") result = [] for line in input: fields = line.split() data = fields[1] + fields[2] + fields[7] result.append(data) input.close() return result print "Here goes" print "Enter filename:" filename = raw_input("Name:") print readSOMNETM(filename) print "might work" on a file that lookes like this: Monthly Weather Data, LAU73M.MET, converted from: BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW ************************************************************** 1 22.5 0.3 * 54.6 15.1 * 11.9 2 16.1 1.8 * 110 51.1 * 18.1 3 16.4 4.8 * 227.5 94.5 * 36.8 4 19.5 5.9 * 286.3 89 * 45.5 5 36.1 13.2 * 448.5 164.6 * 83 6 36 16.9 * 525.7 208.8 * 105.7 7 37.7 18.2 * 459.7 165.4 * 98.6 8 29.3 18.2 * 463.8 206.8 * 97.9 9 27 14.8 * 277.5 119.5 * 58.7 10 57.6 7.6 * 158.7 72.2 * 31.3 11 23.4 3.9 * 98.3 75.6 * 19.1 12 14 0.7 * 55.5 38 * 12.5 And recieved the following error: Traceback (most recent call last): File "C:\Python24\INProgress.py", line 15, in -toplevel- print readSOMNETM(filename) File "C:\Python24\INProgress.py", line 6, in readSOMNETM data = fields[1] + fields[2] + fields[7] IndexError: list index out of range Essentially I'm trying to write a bit of code that can take any of the fields in the above data i.e. rain temp evap for each month for a hundred or so files like this one and spit out a file at the end that has the data in a different format. Any help would be very much appreciated I need to get this done by the end of next week Thanks Mike _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 3 23:16:20 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 4 Nov 2005 11:16:20 +1300 Subject: [Tutor] File IO Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B135B@chbnt01.alpha.wd.govt.nz> Woah, that's way simpler than mine. Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of bob Sent: Friday, 4 November 2005 11:01 a.m. To: m.haft at abdn.ac.uk; tutor at python.org Subject: Re: [Tutor] File IO At 01:34 PM 11/3/2005, Michael Haft wrote: >Hello, > I tried the following code: > >def readSOMNETM(inputName): > input = open(inputName, "r") > result = [] > for line in input: > fields = line.split() # add this; it will show you what line(s) have less than 8 fields if len(fields) < 8: print "Line too short", line continue > data = fields[1] + fields[2] + fields[7] > result.append(data) > input.close() > return result > > >print "Here goes" >print "Enter filename:" >filename = raw_input("Name:") >print readSOMNETM(filename) >print "might work" > >on a file that lookes like this: > >Monthly Weather Data, LAU73M.MET, converted from: >BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 >VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA >MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW >************************************************************** >1 22.5 0.3 * 54.6 15.1 * 11.9 >2 16.1 1.8 * 110 51.1 * 18.1 >3 16.4 4.8 * 227.5 94.5 * 36.8 >4 19.5 5.9 * 286.3 89 * 45.5 >5 36.1 13.2 * 448.5 164.6 * 83 >6 36 16.9 * 525.7 208.8 * 105.7 >7 37.7 18.2 * 459.7 165.4 * 98.6 >8 29.3 18.2 * 463.8 206.8 * 97.9 >9 27 14.8 * 277.5 119.5 * 58.7 >10 57.6 7.6 * 158.7 72.2 * 31.3 >11 23.4 3.9 * 98.3 75.6 * 19.1 >12 14 0.7 * 55.5 38 * 12.5 > > >And recieved the following error: > >Traceback (most recent call last): > File "C:\Python24\INProgress.py", line 15, in -toplevel- > print readSOMNETM(filename) > File "C:\Python24\INProgress.py", line 6, in readSOMNETM > data = fields[1] + fields[2] + fields[7] >IndexError: list index out of range > >Essentially I'm trying to write a bit of code that can take any of the >fields in the above data i.e. rain temp evap for each month for a >hundred or so files like this one and spit out a file at the end that >has the data in a different format. > >Any help would be very much appreciated I need to get this done by the >end of next week _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Barry.Carroll at psc.com Fri Nov 4 00:47:05 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Thu, 3 Nov 2005 15:47:05 -0800 Subject: [Tutor] File IO Message-ID: Mike: I see two issues here: First, do you really want to apply your field selection logic to ALL the lines in each file? It seems to me that the first five lines of the file are header information that you want to ignore. If so, and if all the files have the same format, you can use a loop to throw away the first five lines of the input and start collecting your data on line #6. Another possibility would be to check each line and throw it away if fields[1] cannot be converted into a number. Second, your current logic is assembling the data from each line into a string. Is that what you want? I'm guessing you want to extract the three fields into a three element list. If so, you need to turn the three strings (fields[1], fields[2] and fields[3]) back into list elements. Do this by placing them in square brackets separated by commas: data = [fields[1], fields[2], fields[7]] > ------------------------------ > Date: Thu, 3 Nov 2005 22:10:02 -0000 (GMT) > From: "Mike Haft" > Subject: Re: [Tutor] File IO > To: "bob" > Cc: tutor at python.org > Message-ID: <1997.84.43.99.200.1131055802.squirrel at www.abdn.ac.uk> > Content-Type: text/plain;charset=iso-8859-1 > > I did that and got this: > > Here goes > Enter filename: > Name:LAU73M.MET > Line too short Monthly Weather Data, LAU73M.MET, converted from: > > Line too short BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR > 01/01/1973-31/12/1973 > > Line too short > ********************************************************************** > > ['DEWPCALCULATEDHUMID', 'RAINAVTEMPEVAPW', '22.50.311.9', '16.11.818.1', > '16.44.836.8', '19.55.945.5', '36.113.283.0', '36.016.9105.7', > '37.718.298.6', '29.318.297.9', '27.014.858.7', '57.67.631.3', > '23.43.919.1', '14.00.712.5'] > might work > > Its worth pointing out that there are more than eight fields in my actual > files, I'm using a shorter version just to test stuff on. Actual fields > are: > > MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW > EVAPG EVAPS HUMID VAP DEWP > > There are 13 so I'll have a play with that for the moment. > > Thanks for the help > > Mike > > > > At 01:34 PM 11/3/2005, Michael Haft wrote: > >>Hello, > >> I tried the following code: > >> > >>def readSOMNETM(inputName): > >> input = open(inputName, "r") > >> result = [] > >> for line in input: > >> fields = line.split() > > > > # add this; it will show you what line(s) have less than 8 > > fields > > if len(fields) < 8: > > print "Line too short", line > > continue > > > >> data = fields[1] + fields[2] + fields[7] > >> result.append(data) > >> input.close() From kent37 at tds.net Fri Nov 4 00:56:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Nov 2005 18:56:02 -0500 Subject: [Tutor] File IO In-Reply-To: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> References: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> Message-ID: <436AA392.5090609@tds.net> Michael Haft wrote: > Hello, > I tried the following code: > > def readSOMNETM(inputName): > input = open(inputName, "r") > result = [] > for line in input: > fields = line.split() > data = fields[1] + fields[2] + fields[7] > result.append(data) > input.close() > return result As bob has hinted, you need to skip the headers. If there are always five lines of header they are easy to skip, just do input = open(inputName, "r") for i in range(5): input.next() result = [] for line in input: Kent > > > print "Here goes" > print "Enter filename:" > filename = raw_input("Name:") > print readSOMNETM(filename) > print "might work" > > on a file that lookes like this: > > Monthly Weather Data, LAU73M.MET, converted from: > BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 > VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA > MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW > ************************************************************** > 1 22.5 0.3 * 54.6 15.1 * 11.9 > 2 16.1 1.8 * 110 51.1 * 18.1 > 3 16.4 4.8 * 227.5 94.5 * 36.8 > 4 19.5 5.9 * 286.3 89 * 45.5 > 5 36.1 13.2 * 448.5 164.6 * 83 > 6 36 16.9 * 525.7 208.8 * 105.7 > 7 37.7 18.2 * 459.7 165.4 * 98.6 > 8 29.3 18.2 * 463.8 206.8 * 97.9 > 9 27 14.8 * 277.5 119.5 * 58.7 > 10 57.6 7.6 * 158.7 72.2 * 31.3 > 11 23.4 3.9 * 98.3 75.6 * 19.1 > 12 14 0.7 * 55.5 38 * 12.5 > > > And recieved the following error: > > Traceback (most recent call last): > File "C:\Python24\INProgress.py", line 15, in -toplevel- > print readSOMNETM(filename) > File "C:\Python24\INProgress.py", line 6, in readSOMNETM > data = fields[1] + fields[2] + fields[7] > IndexError: list index out of range > > Essentially I'm trying to write a bit of code that can take any of the > fields in the above data i.e. rain temp evap for each month for a hundred > or so files like this one and spit out a file at the end that has the data > in a different format. > > Any help would be very much appreciated I need to get this done by the end > of next week > > Thanks > > Mike > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Fri Nov 4 01:03:44 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 4 Nov 2005 00:03:44 -0000 Subject: [Tutor] Capture command output References: <4369BE2A.6020200@accesstel.co.za> <4369EC94.4020806@tds.net><4369ED47.1010007@accesstel.co.za> <436A7496.9050703@h-lab.net> Message-ID: <001601c5e0d3$39347e70$0a01a8c0@xp> > You cannot run any function at all in your script after you do the exec > call, it is no longer your program, but the one you exec-ed. popen > actually runs the subprocess, you don't have to call it manually. Popen > is the most used way to get the output, and looks like it is the only > one in Python 2.2. You can do the heavy lifting yourself using a combination of pipe(), fork(), dup2() and exec() from the os module. Pseudo code: # create pipes for stdin/out for our two processes. p1 = pipe() p2 = pipe() # clone the process pid = fork() if pid: # this is the parent process close(p1[1]) close(p2[0]) dup2(p1[0],0) # duplicate stdin dup2(p2[1],1) # stdout else: # in the child close(p1[0]) close(p2[1]) dup2(p2[0],0) # duplicate stdin dup2(p1[1],1) # stdout execv(prog,args) Now we can read and write to the child process using the pipes to access stdin/stdout. This is basically what popen does but also gives us access to the pid of the child process so that we can send a kill message - which was the original requirement!! HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From cjw at sympatico.ca Fri Nov 4 01:30:48 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 03 Nov 2005 19:30:48 -0500 Subject: [Tutor] avoid eval how??? In-Reply-To: References: Message-ID: <436AABB8.5090603@sympatico.ca> Danny Yoo wrote: >>>I have a dynamic functions which created by some algorithms during >>>runtime. These functions are in string type. When I want to use it, I >>>can use eval command. But can someone give me more suggestion about >>>how to handle this problem, I want to avoid eval. >>> >>> >>Why avoid? It seems the simplest way. >> >> > >Hi Colin, > >The problem is that an eval()-like is too powerful for most programmers to >use safely. It's danger is not a Python-specific issue, but common to any >language that provides an eval() on arbitrary strings. > > http://en.wikipedia.org/wiki/Eval#Security_risks > >This aversion to eval() isn't based on some theoretical worry; the PHP >folks got hit by exploits that targeted eval-using code just a few months >ago. Read the "Security" section of: > > http://phpxmlrpc.sourceforge.net/#security > >to see what kind of issues eval() brings when we use it. They hit the >same conceptual problem three times before they finally got humble enough >to realize that eval() was the wrong tool. > >We have to learn from their mistakes, or else we'll make them ourselves. >*grin* > > > Danny, You make some good points here but I suggest that, in the real world, the risks are small. You might consider using exec instead. It would appear that one can specify a restricted environment in which the statement is executed. Colin W. From cjw at sympatico.ca Fri Nov 4 01:34:11 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 03 Nov 2005 19:34:11 -0500 Subject: [Tutor] printing statement In-Reply-To: <6.1.2.0.0.20051103134622.0357e528@mail.mric.net> References: <436A6584.8020802@accesstel.co.za> <6.1.2.0.0.20051103134622.0357e528@mail.mric.net> Message-ID: <436AAC83.6090604@sympatico.ca> bob wrote: >At 11:31 AM 11/3/2005, Johan Geldenhuys wrote: > > >>Hi all, >>Just a quick question; >> >>How do I code this output: >>""" >>files dirs >>========== >>""" >> >>I want to print something a few space away from the left side or in the >>middle of the line. >> >> > >In the Python Library Reference look up 2.3.6.2 String Formatting >Operations - % interpolation > >In general you create a "template" of the desired output with %s (or other >conversion type) wherever you want a value substituted. >"%-15s%-15s" % ('files', 'dirs') will give >"files dirs " >"%-15s%-15s" % (filename, directory) will give >"funny.doc c:\root " >assuming the variabies filename, directory have the values shown. >the - means left align, 15 is field width. > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Have you considered the % formatting operator? See 2.3.6.2 String Formatting Operations in the Library Reference. Colin W. From cjw at sympatico.ca Fri Nov 4 01:47:54 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 03 Nov 2005 19:47:54 -0500 Subject: [Tutor] File IO In-Reply-To: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> References: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> Message-ID: <436AAFBA.2060307@sympatico.ca> Michael Haft wrote: >Hello, > I tried the following code: > >def readSOMNETM(inputName): > input = open(inputName, "r") > result = [] > for line in input: > fields = line.split() > data = fields[1] + fields[2] + fields[7] > result.append(data) > input.close() > return result > > >print "Here goes" >print "Enter filename:" >filename = raw_input("Name:") >print readSOMNETM(filename) >print "might work" > >on a file that lookes like this: > >Monthly Weather Data, LAU73M.MET, converted from: >BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 >VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA >MONTH RAIN AVTEMP S10 RAD SUN WIND EVAPW >************************************************************** >1 22.5 0.3 * 54.6 15.1 * 11.9 >2 16.1 1.8 * 110 51.1 * 18.1 >3 16.4 4.8 * 227.5 94.5 * 36.8 >4 19.5 5.9 * 286.3 89 * 45.5 >5 36.1 13.2 * 448.5 164.6 * 83 >6 36 16.9 * 525.7 208.8 * 105.7 >7 37.7 18.2 * 459.7 165.4 * 98.6 >8 29.3 18.2 * 463.8 206.8 * 97.9 >9 27 14.8 * 277.5 119.5 * 58.7 >10 57.6 7.6 * 158.7 72.2 * 31.3 >11 23.4 3.9 * 98.3 75.6 * 19.1 >12 14 0.7 * 55.5 38 * 12.5 > > >And recieved the following error: > >Traceback (most recent call last): > File "C:\Python24\INProgress.py", line 15, in -toplevel- > print readSOMNETM(filename) > File "C:\Python24\INProgress.py", line 6, in readSOMNETM > data = fields[1] + fields[2] + fields[7] >IndexError: list index out of range > >Essentially I'm trying to write a bit of code that can take any of the >fields in the above data i.e. rain temp evap for each month for a hundred >or so files like this one and spit out a file at the end that has the data >in a different format. > >Any help would be very much appreciated I need to get this done by the end >of next week > >Thanks > >Mike > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > My guess is that you have a line, perhaps the last one in the file, which does not end with '\n'. You might try: def readSOMNETM(inputName): input = open(inputName, "r") result = [] for line in input: fields = line.split() try: data = fields[1] + fields[2] + fields[7] except: print repr(line) print fields raise ValueError result.append(data) input.close() return result Colin W. From dyoo at hkn.eecs.berkeley.edu Fri Nov 4 02:15:14 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 3 Nov 2005 17:15:14 -0800 (PST) Subject: [Tutor] avoid eval how??? In-Reply-To: <436AABB8.5090603@sympatico.ca> Message-ID: > You make some good points here but I suggest that, in the real world, > the risks are small. Hi Colin, But that's the point I'm trying to make; eval() is appropriate only for toy code. In real world code that's exposed to the world, using eval() is usually the wrong thing to do, because it really is dangerous unless we really know what we're doing. eval() is more potent than it appears. We had a thread about this last year: http://mail.python.org/pipermail/tutor/2004-December/033819.html http://mail.python.org/pipermail/tutor/2004-December/033828.html I gave an an example that shows that it's very possible to write an infinite loop (or at least hit Python's stack limit) with a single expression: ###### s = "(lambda loop: loop(loop)) (lambda self: self(self))" eval(s) ###### Note that there are no calls to the builtins, nor any reference to outside free variables. It's just simple function application. Beginners see eval() as an easy all-in-one tool for doing parsing and value conversion. Those who use it indiscriminately don't understand that Python's eval() has enough power to do bad things like infinite loops and calls to os.system(). > You might consider using exec instead. It would appear that one can > specify a restricted environment in which the statement is executed. I think you're talking about 'rexec'. But the folks who finally wrote the Python Standard Library eventually woke up and deprecated rexec. http://www.python.org/doc/lib/module-rexec.html They deprecated it because they could not guarantee a safe, restricted execution environment on top of Python's eval() and exec primitives. I'm not saying that eval() is useless: it does have its uses. And I suppose that it's possible to write sandboxes if we're cautious enough with it. My point, though, is that it is not trivial to make eval()/exec safe. Plenty of smart people have tried it and messed it up. I'm dumb enough not to try. *grin* There are plenty of other alternatives for turning a string into dynamic "code". I'd rather we concentrate on those because such techniques are well known and battle tested. Hope this helps! From cjw at sympatico.ca Fri Nov 4 02:52:45 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 03 Nov 2005 20:52:45 -0500 Subject: [Tutor] avoid eval how??? In-Reply-To: References: Message-ID: <436ABEED.5050303@sympatico.ca> Danny Yoo wrote: >>You make some good points here but I suggest that, in the real world, >>the risks are small. >> >> > >Hi Colin, > >But that's the point I'm trying to make; eval() is appropriate only for >toy code. In real world code that's exposed to the world, using eval() is >usually the wrong thing to do, because it really is dangerous unless we >really know what we're doing. > > >eval() is more potent than it appears. We had a thread about this last >year: > > http://mail.python.org/pipermail/tutor/2004-December/033819.html > http://mail.python.org/pipermail/tutor/2004-December/033828.html > >I gave an an example that shows that it's very possible to write an >infinite loop (or at least hit Python's stack limit) with a single >expression: > >###### >s = "(lambda loop: loop(loop)) (lambda self: self(self))" >eval(s) >###### > >Note that there are no calls to the builtins, nor any reference to outside >free variables. It's just simple function application. > > >Beginners see eval() as an easy all-in-one tool for doing parsing and >value conversion. Those who use it indiscriminately don't understand that >Python's eval() has enough power to do bad things like infinite loops and >calls to os.system(). > > > > >>You might consider using exec instead. It would appear that one can >>specify a restricted environment in which the statement is executed. >> >> > >I think you're talking about 'rexec'. But the folks who finally wrote the >Python Standard Library eventually woke up and deprecated rexec. > > http://www.python.org/doc/lib/module-rexec.html > >They deprecated it because they could not guarantee a safe, restricted >execution environment on top of Python's eval() and exec primitives. > > > Hi Danny, No, I was thinking of exec. The given statement can be executed in a specified environment. You might say "The rogue code can dodge that with an import statement with an import". True, but it seems to me that a user specified __import__ function can protect against this. I have not tried this. >I'm not saying that eval() is useless: it does have its uses. And I >suppose that it's possible to write sandboxes if we're cautious enough >with it. My point, though, is that it is not trivial to make eval()/exec >safe. Plenty of smart people have tried it and messed it up. I'm dumb >enough not to try. *grin* > > > I accept the points you make wrt eval. Colin W. >There are plenty of other alternatives for turning a string into dynamic >"code". I'd rather we concentrate on those because such techniques are >well known and battle tested. > > >Hope this helps! > > > From kent37 at tds.net Fri Nov 4 04:02:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 03 Nov 2005 22:02:34 -0500 Subject: [Tutor] avoid eval how??? In-Reply-To: <436ABEED.5050303@sympatico.ca> References: <436ABEED.5050303@sympatico.ca> Message-ID: <436ACF4A.3080000@tds.net> Colin J. Williams wrote: > No, I was thinking of exec. The given statement can be executed in a > specified environment. > You might say "The rogue code can dodge that with an import statement > with an import". > > True, but it seems to me that a user specified __import__ function can > protect against this. > > I have not tried this. This is a pretty frequent topic on comp.lang.python. There are some pretty devious tricks you can use in exec and eval even when builtins are disabled. The most promising route seems to be to use the Python parser to generate a syntax tree, then to check the tree for only valid node types before evaluating it. For example see this thread for discussion: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d5f4d7e2c397c2ca/5d1af7f9c7b1789b?q=safe+exec+parser&rnum=1#5d1af7f9c7b1789b and this recipe for a _very_limited_ application of the idea: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 Kent -- http://www.kentsjohnson.com From bgailer at alum.rpi.edu Fri Nov 4 06:24:35 2005 From: bgailer at alum.rpi.edu (bob) Date: Thu, 03 Nov 2005 21:24:35 -0800 Subject: [Tutor] File IO In-Reply-To: <436AAFBA.2060307@sympatico.ca> References: <1828.84.43.99.200.1131053663.squirrel@www.abdn.ac.uk> <436AAFBA.2060307@sympatico.ca> Message-ID: <6.1.2.0.0.20051103212100.031dada0@mail.mric.net> [snip] Colin: your replies to 2 e-mails indicate that you have either not read the e-mails or the prior responses. Please consider the work others put into replying before replying. Example: I suggested % formatting in a reply. You replied to that by saying the same thing. From johan at accesstel.co.za Fri Nov 4 07:02:03 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 04 Nov 2005 08:02:03 +0200 Subject: [Tutor] printing statement In-Reply-To: <436AAC83.6090604@sympatico.ca> References: <436A6584.8020802@accesstel.co.za> <6.1.2.0.0.20051103134622.0357e528@mail.mric.net> <436AAC83.6090604@sympatico.ca> Message-ID: <436AF95B.8040300@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051104/f8c0db44/attachment.htm From royb at ubiquity.com.au Fri Nov 4 08:13:49 2005 From: royb at ubiquity.com.au (Roy Bleasdale) Date: Fri, 04 Nov 2005 18:13:49 +1100 Subject: [Tutor] Exit from program early Message-ID: <5.1.0.14.2.20051104172320.021c0950@localhost> Hi In the example below I would like the program to stop if I forgot to provide an argument . Though I could do all my processing indented under the else statement, I was wondering if there was a command that would allow me to halt the program execution early. Regards, Roy # Example program - Test for valid argument import sys if len(sys.argv) < 2: print "opps missing an argument" # Nice if I could stop and exit program here else: print "Argument provided!!" # Looking good so go do some stuff print "Done some stuff" From johan at accesstel.co.za Fri Nov 4 08:16:03 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 04 Nov 2005 09:16:03 +0200 Subject: [Tutor] Exit from program early In-Reply-To: <5.1.0.14.2.20051104172320.021c0950@localhost> References: <5.1.0.14.2.20051104172320.021c0950@localhost> Message-ID: <436B0AB3.1010205@accesstel.co.za> Try using 'sys.exit()' where you want the script to stop if you haven't supplied enough arguments. in you example, it looks like it will go on to the else anyway AND print the string at the end. HTH, Johan Roy Bleasdale wrote: >Hi > >In the example below I would like the program to stop if I forgot to >provide an argument . Though I could do all my processing indented under >the else statement, I was wondering if there was a command that would allow >me to halt the program execution early. > >Regards, > >Roy > > ># Example program - Test for valid argument > >import sys > >if len(sys.argv) < 2: > print "opps missing an argument" > # Nice if I could stop and exit program here >else: > print "Argument provided!!" > # Looking good so go do some stuff > >print "Done some stuff" > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From johan at accesstel.co.za Fri Nov 4 09:09:26 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 04 Nov 2005 10:09:26 +0200 Subject: [Tutor] Sorting a dictionary Message-ID: <436B1736.4060705@accesstel.co.za> Hi all, In my new project I needed a dictionary with TCP/UDP port numbers as keys and the service for that key as the value. I got the info from the services file in Linux and compiled a dictionary as I needed. The only thing that I want to do is to sort the dictionary from the smallest key number to the largest key number. Example: I have: ser_port = {'4401': 'ds-srvr', \ '5427': 'sco-peer-tta', \ '4446': 'n1-fwp', \ '3734': 'synel-data', \ '4447': 'n1-rmgmt', \ '5745': 'fcopy-server', \ '5990': 'wbem-exp-https', \ '4026': 'as-debug', \ '3724': 'battlenet'} I want: ser_port = { '3724': 'battlenet', \ '3734': 'synel-data', \ '4026': 'as-debug', \ '4401': 'ds-srvr', \ '4446': 'n1-fwp', \ '4447': 'n1-rmgmt', \ '5427': 'sco-peer-tta', \ '5745': 'fcopy-server', \ '5990': 'wbem-exp-https'} My dictionary comsists of a few thousand entries and it will not be fun to do this manually. How do I sort the dictionary to read better/easier? TIA, BTW: If anybody wants this to use, please ask. Johan From dyoo at hkn.eecs.berkeley.edu Fri Nov 4 09:26:26 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 4 Nov 2005 00:26:26 -0800 (PST) Subject: [Tutor] Sorting a dictionary In-Reply-To: <436B1736.4060705@accesstel.co.za> Message-ID: On Fri, 4 Nov 2005, Johan Geldenhuys wrote: > In my new project I needed a dictionary with TCP/UDP port numbers as > keys and the service for that key as the value. I got the info from the > services file in Linux and compiled a dictionary as I needed. > > The only thing that I want to do is to sort the dictionary from the > smallest key number to the largest key number. Hi Johan, Is this so you can more easily read the dictionary better? Be aware that dictionaries in Python are implemented as "hashtables", and these hashtables are deliberately "misordered" to make them work fast. We can take the items() of a dictionary, and sort those. For example: ###### >>> nums = {'one' : 1, 'two' : 2, 'three' : 3 } >>> nums {'three': 3, 'two': 2, 'one': 1} >>> nums.items() [('three', 3), ('two', 2), ('one', 1)] ###### We see that items() is a list of key-value pairs. We can sort lists by using their sort method(). ###### >>> list_of_nums = nums.items() >>> list_of_nums.sort() >>> list_of_nums [('one', 1), ('three', 3), ('two', 2)] ###### Is this what you're looking for? If you have more questions, please feel free to ask. From dyoo at hkn.eecs.berkeley.edu Fri Nov 4 09:31:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 4 Nov 2005 00:31:13 -0800 (PST) Subject: [Tutor] Sorting a dictionary In-Reply-To: <436B1736.4060705@accesstel.co.za> Message-ID: > ser_port = {'4401': 'ds-srvr', \ > '5427': 'sco-peer-tta', \ > '4446': 'n1-fwp', \ > '3734': 'synel-data', \ > '4447': 'n1-rmgmt', \ > '5745': 'fcopy-server', \ > '5990': 'wbem-exp-https', \ > '4026': 'as-debug', \ > '3724': 'battlenet'} Hi Johan, Just as a quick side note: all those continuation characters '\' at the end of those lines are unneccessary --- Python knows that there's more to the line because of it's in the middle of a dictionary definition. So you can clean things up slightly by doing: ########################### ser_port = { '4401': 'ds-srvr', '5427': 'sco-peer-tta', '4446': 'n1-fwp', '3734': 'synel-data', '4447': 'n1-rmgmt', '5745': 'fcopy-server', '5990': 'wbem-exp-https', '4026': 'as-debug', '3724': 'battlenet', } ########################### Everything lines up nicely, and there's a little less line noise. *grin* We can even leave a trailing comma on the last key-value pair, just to make adding more entries into the list easier, as we've done for the '3724' entry. I hope this helps! From ajikoe at gmail.com Fri Nov 4 10:45:24 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Fri, 4 Nov 2005 10:45:24 +0100 Subject: [Tutor] Sorting a dictionary In-Reply-To: References: <436B1736.4060705@accesstel.co.za> Message-ID: Hallo, you can also sort based on the values: >>> list_of_nums = nums.items() >>> list_of_nums.sort(lambda x,y: cmp(x[1],y[1])) Cheers, pujo On 11/4/05, Danny Yoo wrote: > > > > On Fri, 4 Nov 2005, Johan Geldenhuys wrote: > > > In my new project I needed a dictionary with TCP/UDP port numbers as > > keys and the service for that key as the value. I got the info from the > > services file in Linux and compiled a dictionary as I needed. > > > > The only thing that I want to do is to sort the dictionary from the > > smallest key number to the largest key number. > > Hi Johan, > > Is this so you can more easily read the dictionary better? Be aware that > dictionaries in Python are implemented as "hashtables", and these > hashtables are deliberately "misordered" to make them work fast. > > > We can take the items() of a dictionary, and sort those. For example: > > ###### > >>> nums = {'one' : 1, 'two' : 2, 'three' : 3 } > >>> nums > {'three': 3, 'two': 2, 'one': 1} > >>> nums.items() > [('three', 3), ('two', 2), ('one', 1)] > ###### > > We see that items() is a list of key-value pairs. We can sort lists by > using their sort method(). > > ###### > >>> list_of_nums = nums.items() > >>> list_of_nums.sort() > >>> list_of_nums > [('one', 1), ('three', 3), ('two', 2)] > ###### > > > Is this what you're looking for? If you have more questions, please feel > free to ask. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051104/b0853bda/attachment.htm From johan at accesstel.co.za Fri Nov 4 10:45:53 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 04 Nov 2005 11:45:53 +0200 Subject: [Tutor] Sorting a dictionary In-Reply-To: References: Message-ID: <436B2DD1.6020407@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051104/ee8abbea/attachment.html From kent37 at tds.net Fri Nov 4 12:07:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Nov 2005 06:07:26 -0500 Subject: [Tutor] Exit from program early In-Reply-To: <436B0AB3.1010205@accesstel.co.za> References: <5.1.0.14.2.20051104172320.021c0950@localhost> <436B0AB3.1010205@accesstel.co.za> Message-ID: <436B40EE.5090506@tds.net> Johan Geldenhuys wrote: > Try using 'sys.exit()' where you want the script to stop if you haven't > supplied enough arguments. > in you example, it looks like it will go on to the else anyway AND print > the string at the end. > > Roy Bleasdale wrote: >>In the example below I would like the program to stop if I forgot to >>provide an argument . Though I could do all my processing indented under >>the else statement, I was wondering if there was a command that would allow >>me to halt the program execution early. Another way to do this is to structure your program with functions. For example you could write it as def doSomeStuff(): # Looking good so go do some stuff if len(sys.argv) < 2: print "opps missing an argument" # Nice if I could stop and exit program here else: print "Argument provided!!" doSomeStuff() print "Done some stuff" Breaking your program up into small functions will generally make it more readable, testable and maintainable that using long stretches of straight-line code. Kent >> >>Regards, >> >>Roy >> >> >># Example program - Test for valid argument >> >>import sys >> >>if len(sys.argv) < 2: >> print "opps missing an argument" >> # Nice if I could stop and exit program here >>else: >> print "Argument provided!!" >> # Looking good so go do some stuff >> >>print "Done some stuff" >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com From kent37 at tds.net Fri Nov 4 12:18:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Nov 2005 06:18:20 -0500 Subject: [Tutor] Sorting a dictionary In-Reply-To: <436B2DD1.6020407@accesstel.co.za> References: <436B2DD1.6020407@accesstel.co.za> Message-ID: <436B437C.6070505@tds.net> Johan Geldenhuys wrote: > Thanks, Danny. > > You see, I didn't put all the keys and values in the dicionary manually. > It was generated while parsing a file with some Python code, that's why > the dict is not in order. I just want to do it to read easier and look > something up. You want the dict to be sorted in your Python source code, is that it? The simplest thing might be to use an editor with a sort function. If the code was generated from Python then you can use Danny's method to sort and change the output. Something like this: for k, v in sorted(d.items()): print ' %r : %r,' % (k, v) Kent From kent37 at tds.net Fri Nov 4 14:28:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Nov 2005 08:28:22 -0500 Subject: [Tutor] Subclassing data attributes In-Reply-To: References: Message-ID: <436B61F6.1080303@tds.net> Jan Eden wrote: > Not exactly. My current setup bundles all data attributes in a single > module Data containing a single class for each object. So in my main > module (Show), I define:> > class Page(Data.Page): > ... > > and Data contains: > > class Base: > children = 'xyz' > children_query = 'SELECT...' > > class Page: > children = 'something' > own_type = 'somethingelse' > populate_query = "SELECT ..." > index_link = "

..." > ... > > So I can use self.children_query for an object of class Show.Page to > get the data attribute defined in class Data.Base. > > But since there are many data attributes, I'd like to use things like: > > self.templates['index_link'] > self.templates['child_link'] > self.queries['populate'] > > or > > self.Templates.index_link > self.Templates.child_link > self.Queries.populate OK I'll try again. I still don't understand why you don't like using straight class attributes - is it to keep the size of the class namespace smaller? I'm also not sure if you want to be able to access Base.children and Page.children from a subclass of Page. If not, then you can use a hierarchical dictionary to do what you want. How about this? import UserDict class ChainDict(UserDict.DictMixin): ''' A dict that will delegate failed lookups to a parent ''' def __init__(self, parent=None): self._dict = dict() self._parent = parent # __setitem__() and __delitem__() delegate to self._dict self.__setitem__ = self._dict.__setitem__ self.__delitem__ = self._dict.__delitem__ def __getitem__(self, key): try: return self._dict[key] except KeyError: if self._parent is not None: return self._parent[key] def keys(self): keys = self._dict.keys() if self._parent is not None: keys.extend(self._parent.keys()) class Base: templates = dict() templates['children'] = 'xyz' templates['children_query'] = 'SELECT * from Base' class Page(Base): templates = ChainDict(Base.templates) templates['children'] = 'something' templates['own_type'] = 'somethingelse' templates['populate_query'] = "SELECT * from Page" templates['index_link'] = "

..." b = Base() print b.templates['children'] print b.templates['children_query'] print p = Page() print p.templates['children'] print p.templates['children_query'] print p.templates['index_link'] Kent PS Please reply on list. -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Fri Nov 4 14:40:47 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 4 Nov 2005 13:40:47 -0000 Subject: [Tutor] Sorting a dictionary References: <436B2DD1.6020407@accesstel.co.za> Message-ID: <001501c5e145$5d384910$0a01a8c0@xp> Hi JOhan, > You see, I didn't put all the keys and values in the dicionary manually. > It was generated while parsing a file with some Python code, that's why > the dict is not in order. It wouldn't have mattered if you had done it manually. The order of a dictionary is calculated by Python dynamically. In fact the order can even change if you add new items later. Python always organises the dictionary to maximise its search speed regardless of the order the data was inserted. If you need to order the dictionary you need to use the techniques described by the others. > How will I then put my dict together again after sorting the items, Don't take them out of the dictionary, just make a temporary copy for printing, or extract them as you go for printing. But the underlying dictionary should not be changed. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mhansen at cso.atmel.com Fri Nov 4 15:09:30 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 04 Nov 2005 07:09:30 -0700 Subject: [Tutor] RSH? In-Reply-To: References: Message-ID: <436B6B9A.6060909@cso.atmel.com> If we had Python on VMS(which I'm working on), I'd definitely look into Pyro. Thanks, Mike > Subject: > Re: [Tutor] RSH? > From: > Pujo Aji > Date: > Thu, 3 Nov 2005 18:44:11 +0100 > To: > Mike Hansen > > To: > Mike Hansen > CC: > tutor at python.org > > > try pyro. > > Cheers, > pujo > > > On 11/3/05, *Mike Hansen* > wrote: > > Anyone know of a way to have Python run a command on a remote > machine? In my > particular case, I want to run a python program on Windows and run a > command on > VMS. Would the telnetlib module do it, or is there something better? > > Mike From mhansen at cso.atmel.com Fri Nov 4 15:11:29 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri, 04 Nov 2005 07:11:29 -0700 Subject: [Tutor] RSH? In-Reply-To: References: Message-ID: <436B6C11.3030506@cso.atmel.com> That's exactly what I'm looking for! Thanks, Mike > Subject: > Re: [Tutor] RSH? > From: > Bernard Lebel <3dbernard at gmail.com> > Date: > Thu, 3 Nov 2005 14:16:40 -0500 > To: > tutor at python.org > > To: > tutor at python.org > > > I use plink > http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html > > Basically you send a system command (os.system) to the plink > executable. The actuall command will take this form: > > os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, command ) ) > > > Now, if you want to run a python script on the remote machine, you > will have to send two commands (afaik). The first one to cd to the > python script file, the second to send the python execution command: > > os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, > 'cd /blah/blah/' ) ) > os.system( 'plink -pw %s -ssh %s@%s %s' % ( password, user, hostIP, > 'python scriptname.py' ) ) > > [...] >>On 11/3/05, Mike Hansen wrote: >> >>>Anyone know of a way to have Python run a command on a remote machine? In >> >>my >> >>>particular case, I want to run a python program on Windows and run a >> >>command on >> >>>VMS. Would the telnetlib module do it, or is there something better? >>> >>>Mike From lists at janeden.org Fri Nov 4 15:43:33 2005 From: lists at janeden.org (Jan Eden) Date: Fri, 4 Nov 2005 15:43:33 +0100 Subject: [Tutor] Subclassing data attributes In-Reply-To: <436B61F6.1080303@tds.net> Message-ID: Hi Kent, Kent Johnson wrote on 04.11.2005: > >OK I'll try again. I still don't understand why you don't like using >straight class attributes - is it to keep the size of the class >namespace smaller? > Yes, and to distinguish between different kinds of attributes in the main script. In the end, it is mainly a matter of readability in the main script. I am beginning to suspect that I trade in too much simplicity in my Data module. >I'm also not sure if you want to be able to access Base.children and >Page.children from a subclass of Page. If not, then you can use a >hierarchical dictionary to do what you want. How about this? > Your UserDict solution looks good. Thank you! >PS Please reply on list. > I usually do, sorry. - Jan -- Hanlon's Razor: Never attribute to malice that which can be adequately explained by stupidity. From bgailer at alum.rpi.edu Fri Nov 4 16:56:18 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 04 Nov 2005 07:56:18 -0800 Subject: [Tutor] printing statement In-Reply-To: <436AF95B.8040300@accesstel.co.za> References: <436A6584.8020802@accesstel.co.za> <6.1.2.0.0.20051103134622.0357e528@mail.mric.net> <436AAC83.6090604@sympatico.ca> <436AF95B.8040300@accesstel.co.za> Message-ID: <6.1.2.0.0.20051104074909.03616ea0@mail.mric.net> At 10:02 PM 11/3/2005, Johan Geldenhuys wrote: >Found it. This is what I was looking for: >""" > >>> print ('file'+'dir'.center(20))+('\n'+'='*15) >file dir >=============== > >>> >""" I am glad you found what you wanted. I'm sad that you did not tell us more precisely what you wanted, as we could have steered you in that direction. center() puts spaces to the right of dir. It that part of what you wanted, or just a side effect.? I'd find less () easier to read: print 'file'+'dir'.center(20)+'\n'+'='*15 and 2 print statements even better: print 'file'+'dir'.center(20) print '*15 >It's actually a string operator 'center(width)' that I was looking for. > >I saw the '%', but that is what I wanted to use. Do you also appreciate the power of %? I hope you learn to use it also. [snip] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051104/4452bb08/attachment.htm From smiles at worksmail.net Fri Nov 4 10:05:36 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 4 Nov 2005 03:05:36 -0600 Subject: [Tutor] alternation regex--greedy? Message-ID: <002e01c5e159$d17c7260$632c4fca@csmith> Hello, I am writing a script to convert from one font set (used to write in devanagari) to another. This consists of converting certain key sequences to others, e.g. Of --> k. To do the conversion process, I've looked at some of the single-pass multireplacement suggestions posted in the Python Cookbook which build a large regex string with find patterns separated with "|", i.e. a large string of alternations (and then they use a dictionary containing the values of the keys that were put in the regex string). In the process, I found something unexpected about regex patterns that use alternation: the match is not greedy. The result depends on which pattern is listed first. ### >>> import re >>> pat=re.compile('this|th') >>> s='thistle' >>> pat.match(s).group(0) 'this' >>> pat=re.compile('th|this') >>> pat.match(s).group(0) 'th' ### I read the regex docs about the 'match' function and they say that the 'leftmost non-overlapping occurrences of pattern in string' will be returned. I can understand why the pattern 'light|sli' (or 'sli|light') will match 'sli' in text 'slight' (because 'sli' is more to the left than 'light'). But why isn't the greedy result of 'this' obtained for either of the patterns given in the example above (between the ###)? Is this because it is trying to return a pattern that overlaps as little as possible with anything else? Basically what this is meaning for me so far is that a single-pass solution to replacing certain text sequences with others cannot always be done unless the patterns to be found are non-overlapping themselves. In the case of 'light|sli' even though 'light' appears first in the alternation, 'sli' will be found with higher priority in sequences that had 'slight' in them since 'sli' is more to the left. Any comments on the non-greediness of the alternation pattern or on the multi-replacement process in general are appreciated. /c From ewalker at micron.com Fri Nov 4 19:20:39 2005 From: ewalker at micron.com (Eric Walker) Date: Fri, 4 Nov 2005 11:20:39 -0700 Subject: [Tutor] construct Message-ID: <200511041120.39651.ewalker@micron.com> All, Whats the construct that allows to loop through a list and perform an action? you also can add a test at the end. something like myfile = [print name for name in yourlist, if ...] I need to look up how to use the test command and I forgot the name of the construct. Thanks.. From kent37 at tds.net Fri Nov 4 19:38:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Nov 2005 13:38:35 -0500 Subject: [Tutor] alternation regex--greedy? In-Reply-To: <002e01c5e159$d17c7260$632c4fca@csmith> References: <002e01c5e159$d17c7260$632c4fca@csmith> Message-ID: <436BAAAB.6030901@tds.net> Chris or Leslie Smith wrote: > I found something unexpected about regex patterns > that use alternation: the match is not greedy. The result depends on > which pattern is listed first. Yes, this is exactly as described in the docs for "|": As the target string is scanned, REs separated by "|" are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the "|" operator is never greedy. > > ### > >>>> import re pat=re.compile('this|th') s='thistle' >>>> pat.match(s).group(0) > > 'this' > >>>> pat=re.compile('th|this') pat.match(s).group(0) > > 'th' ### > > > I read the regex docs about the 'match' function and they say that > the 'leftmost non-overlapping occurrences of pattern in string' will > be returned. I can understand why the pattern 'light|sli' (or > 'sli|light') will match 'sli' in text 'slight' (because 'sli' is more > to the left than 'light'). But why isn't the greedy result of 'this' > obtained for either of the patterns given in the example above > (between the ###)? Is this because it is trying to return a pattern > that overlaps as little as possible with anything else? The first pattern does return 'this'. > Basically what this is meaning for me so far is that a single-pass > solution to replacing certain text sequences with others cannot > always be done unless the patterns to be found are non-overlapping > themselves. In the case of 'light|sli' even though 'light' appears > first in the alternation, 'sli' will be found with higher priority in > sequences that had 'slight' in them since 'sli' is more to the left. If you want to replace 'light' rather than 'sli' in 'slight' then a multi-pass replace is the simplest solution. You could make a pattern that will do this but it won't scale well to many replacements. You can probably divide your replacements into a few groups such that none of the patterns in group A can overlap, and they all must be done before the replacements in group B, etc. Then apply the replacements in groups rather than each separately. Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Fri Nov 4 19:49:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 4 Nov 2005 10:49:30 -0800 (PST) Subject: [Tutor] construct In-Reply-To: <200511041120.39651.ewalker@micron.com> Message-ID: On Fri, 4 Nov 2005, Eric Walker wrote: > Whats the construct that allows to loop through a list and perform an > action? you also can add a test at the end. something like myfile = > [print name for name in yourlist, if ...] I need to look up how to use > the test command and I forgot the name of the construct. Hi Eric, I think you're looking for list comprehensions. Here you go: http://www.python.org/peps/pep-0202.html If you have more questions, please feel free to ask! From kent37 at tds.net Fri Nov 4 19:53:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Nov 2005 13:53:41 -0500 Subject: [Tutor] construct In-Reply-To: <200511041120.39651.ewalker@micron.com> References: <200511041120.39651.ewalker@micron.com> Message-ID: <436BAE35.5070500@tds.net> Eric Walker wrote: > All, > Whats the construct that allows to loop through a list and perform an action? > you also can add a test at the end. something like myfile = [print name for > name in yourlist, if ...] It's called a list comprehension. You can see some examples here: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 It won't work with your example though - 'print' is a statement, not an expression, and cannot be used in a LC. You could use sys.stdout.write(name + '\n') instead if you like. Personally I think it is bad style to use a LC for its side effects; in those cases I prefer to write the loop out. Kent -- http://www.kentsjohnson.com From hugonz-lists at h-lab.net Fri Nov 4 20:11:08 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 04 Nov 2005 13:11:08 -0600 Subject: [Tutor] Exit from program early In-Reply-To: <436B0AB3.1010205@accesstel.co.za> References: <5.1.0.14.2.20051104172320.021c0950@localhost> <436B0AB3.1010205@accesstel.co.za> Message-ID: <436BB24C.2000001@h-lab.net> or raise SystemExit Hugo Johan Geldenhuys wrote: > Try using 'sys.exit()' where you want the script to stop if you haven't > supplied enough arguments. > in you example, it looks like it will go on to the else anyway AND print > the string at the end. > > HTH, > Johan > > > Roy Bleasdale wrote: > > >>Hi >> >>In the example below I would like the program to stop if I forgot to >>provide an argument . Though I could do all my processing indented under >>the else statement, I was wondering if there was a command that would allow >>me to halt the program execution early. >> >>Regards, >> >>Roy >> >> >># Example program - Test for valid argument >> >>import sys >> >>if len(sys.argv) < 2: >> print "opps missing an argument" >> # Nice if I could stop and exit program here >>else: >> print "Argument provided!!" >> # Looking good so go do some stuff >> >>print "Done some stuff" >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ewalker at micron.com Fri Nov 4 20:26:58 2005 From: ewalker at micron.com (Eric Walker) Date: Fri, 4 Nov 2005 12:26:58 -0700 Subject: [Tutor] construct In-Reply-To: <436BAE35.5070500@tds.net> References: <200511041120.39651.ewalker@micron.com> <436BAE35.5070500@tds.net> Message-ID: <200511041226.58887.ewalker@micron.com> Thanks all On Friday 04 November 2005 11:53 am, Kent Johnson wrote: > Eric Walker wrote: > > All, > > Whats the construct that allows to loop through a list and perform an > > action? you also can add a test at the end. something like myfile = > > [print name for name in yourlist, if ...] > > It's called a list comprehension. You can see some examples here: > http://docs.python.org/tut/node7.html#SECTION007140000000000000000 > > It won't work with your example though - 'print' is a statement, not an > expression, and cannot be used in a LC. You could use sys.stdout.write(name > + '\n') instead if you like. > > Personally I think it is bad style to use a LC for its side effects; in > those cases I prefer to write the loop out. > > Kent From m.haft at abdn.ac.uk Fri Nov 4 21:54:39 2005 From: m.haft at abdn.ac.uk (Mike Haft) Date: Fri, 4 Nov 2005 20:54:39 -0000 (GMT) Subject: [Tutor] File IO and writing lists Message-ID: <1480.87.242.157.194.1131137679.squirrel@www.abdn.ac.uk> "Carroll, Barry" wrote: Second, your current logic is assembling the data from each line into a string. Is that what you want? I'm guessing you want to extract the three fields into a three element list. If so, you need to turn the three strings (fields[1], fields[2] and fields[3]) back into list elements. Do this by placing them in square brackets separated by commas: data = [fields[1], fields[2], fields[7]] Having doen that the code now looks like this: def readSOMNETM(inputName): input = open(inputName, "r") result = [] for line in input: fields = line.split() # add this; it will show you what line(s) have less than 8 fields if len(fields) < 13: print "Line too short", line continue data = [fields[1], fields[2], fields[7]] result.append(data) input.close() return result print "Here goes" print "Enter filename:" filename = raw_input("Name:") print readSOMNETM(filename) print "done" It works fine so thanks for all the help on that, now just one more thing and I can save myself about two months worth of copying and pasting. The output from the above code (for one file) is: Here goes Enter filename: Name:LAU73M.MET Line too short Monthly Weather Data, LAU73M.MET, converted from: Line too short BAD LAUCHSTAEDT; DAILY METEOROLOGICAL DATA FOR 01/01/1973-31/12/1973 Line too short VAP, DEWP CALCULATED FROM MEASURED AVTEMP AND HUMID DATA Line too short ************************************************************************************************************* [['RAIN', 'AVTEMP', 'EVAPW'], ['22.5', '0.3', '11.9'], ['16.1', '1.8', '18.1'], ['16.4', '4.8', '36.8'], ['19.5', '5.9', '45.5'], ['36.1', '13.2', '83.0'], ['36.0', '16.9', '105.7'], ['37.7', '18.2', '98.6'], ['29.3', '18.2', '97.9'], ['27.0', '14.8', '58.7'], ['57.6', '7.6', '31.3'], ['23.4', '3.9', '19.1'], ['14.0', '0.7', '12.5']] done >>> I don't know how to print these values in a new file sperated by new lines and white space between the values (each line needs to be three values corresponding to RAIN AVTEMP and EVAPW). I know how to open a file and use out_file.write() type commands but not how to write a list in the file. I tried the following: print "opening file to write" out_file = open("test.txt","w") out_file.write(readSOMNETM(filename)) out_file.close() But get the following error: Traceback (most recent call last): File "C:\Python24\INProgress.py", line 23, in -toplevel- out_file.write(readSOMNETM(filename)) TypeError: argument 1 must be string or read-only character buffer, not list How do you write a list to a file? (Sorry for the long post) Mike From Barry.Carroll at psc.com Fri Nov 4 22:30:38 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 4 Nov 2005 13:30:38 -0800 Subject: [Tutor] Converting a String to a Tuple Message-ID: Greetings: My UDP client is receiving responses from the server, and now I need to process them. A typical response string looks like this: "(0, ''),some data from the test system" The tuple represents the error code and message. If the command had failed, the response would look like this: "(-1, 'Error message from the test system')" I need to extract the tuple from the rest of the response string. I can do this using eval, like so: errtuple = eval(mytxt[:mytxt.find(')')+1]) Is there another, more specific method for transforming a sting into a tuple? Thanks as always. Barry From singingxduck at gmail.com Fri Nov 4 23:57:35 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Fri, 04 Nov 2005 17:57:35 -0500 Subject: [Tutor] Converting a String to a Tuple In-Reply-To: References: Message-ID: <436BE75F.2010707@gmail.com> Carroll, Barry wrote: >Greetings: > >My UDP client is receiving responses from the server, and now I need to >process them. A typical response string looks like this: > > "(0, ''),some data from the test system" > >The tuple represents the error code and message. If the command had failed, >the response would look like this: > > "(-1, 'Error message from the test system')" > >I need to extract the tuple from the rest of the response string. I can do >this using eval, like so: > > errtuple = eval(mytxt[:mytxt.find(')')+1]) > >Is there another, more specific method for transforming a sting into a >tuple? > >Thanks as always. > >Barry > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Well, if you want to avoid eval and are willing to deal with all the elements being strings, you could use the following, though it could probably be written prettier: >>> tstr = "(-1, 'Error message from the test system')" >>> tstrt = tuple( tstr[ tstr.find("("):tstr.find(")")+1 ].replace( "(","" ).replace( ")","" ).split(", ") ) >>> tstrt ('-1', "'Error message from the test system'") Basically, you first get the part of the string between the first set of parentheses (so even if there are parentheses afterwards like "(0, '') data (specifics of data)", it will still only get the "(0, '')" part), then lose the parentheses, split the string along ", " and make the string a tuple. Note that if you use this, you will either have to guarantee that the string tuple elements will be separated by a comma and a space, or change the above to "....split(","))", in which case they will have to be separated by a comma (or you will have a space in the element). HTH, Orri P.S. - if you know that the first element will always be an integer and that the second will always be a string, you can use the following for better results: >>> tstrt = tuple((int(tstr[tstr.find("("):tstr.find(")")+1].replace("(","").replace(")","").split(", ")[0]),tstr[tstr.find("("):tstr.find(")")+1].replace("(","").replace(")","").split(", ")[1][1:-1])) >>> tstrt (-1, 'Error message from the test system') For a while I tried to come up with some less lengthy lambdas to do the job, but that would probably only serve to make it harder to read. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From kent37 at tds.net Sat Nov 5 00:52:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 04 Nov 2005 18:52:14 -0500 Subject: [Tutor] Converting a String to a Tuple In-Reply-To: References: Message-ID: <436BF42E.7030207@tds.net> Carroll, Barry wrote: > Greetings: > > My UDP client is receiving responses from the server, and now I need to > process them. A typical response string looks like this: > > "(0, ''),some data from the test system" > > The tuple represents the error code and message. If the command had failed, > the response would look like this: > > "(-1, 'Error message from the test system')" > > I need to extract the tuple from the rest of the response string. I can do > this using eval, like so: > > errtuple = eval(mytxt[:mytxt.find(')')+1]) > > Is there another, more specific method for transforming a sting into a > tuple? This is pretty easy to do with a regular expression: >>> import re >>> tupleRe = re.compile(r"\((.*?), '(.*?)'\)") >>> tupleRe.search("(0, ''),some data from the test system").groups() ('0', '') >>> tupleRe.search("(-1, 'Error message from the test system')").groups() ('-1', 'Error message from the test system') If you want the code as an integer instead of a string, you can extract the two values separately and convert the code: >>> code, msg = tupleRe.search("(-1, 'Error message from the test system')").groups() >>> code = int(code) >>> code -1 To pick apart the regular expression: r" # raw strings don't use the normal \ escapes, so the \ chars become part of the string \( # look for a literal ( (.*?) # followed by anything, grouped , ' # up to a literal comma space quote (.*?) # followed by anything, grouped '\) # up to a literal quote ) The result of calling search is a match object; the group() method extracts the grouped sections of the re. Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Sat Nov 5 01:51:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 4 Nov 2005 16:51:41 -0800 (PST) Subject: [Tutor] Converting a String to a Tuple In-Reply-To: Message-ID: On Fri, 4 Nov 2005, Carroll, Barry wrote: > My UDP client is receiving responses from the server, and now I need to > process them. A typical response string looks like this: > > "(0, ''),some data from the test system" > > The tuple represents the error code and message. If the command had > failed, the response would look like this: > > "(-1, 'Error message from the test system')" > > I need to extract the tuple from the rest of the response string. I can do > this using eval, like so: > > errtuple = eval(mytxt[:mytxt.find(')')+1]) > > Is there another, more specific method for transforming a sting into a > tuple? Hi Barry, Since this seems to be such a popular request, here is sample kludgy code that provides a parse() function that does the structure-building. This parser doesn't much adequate error checking yet, and I apologize in advance for that. But I just want to do something to make sure people don't use eval() to extract simple stuff out of network traffic. *grin* (In reality, we'd use a parser-generating tool like pyparsing to make the code below simpler and with good error messages.) ########################################################################## """Simple parsing of expressions. Meant to be a demo of how one could turn strings into structures. If we were to do this for real, though, we'd definitely use parser generator tools instead. Main usage: >>> parse("(0, ''),some data from the test system") (0, '') >>> parse("(-1, 'Error message from the test system')") (-1, 'Error message from the test system') """ import re stringRegex = re.compile(r""" ' # a single quote ( # followed by any number of [^'] # non-quote characters | # or (\') # an escaped quote )* ' """, re.VERBOSE) numberRegex = re.compile(r""" [+-]? ## optional sign \d+ ## one or more digits """, re.VERBOSE) def tokenize(s): """Returns an list of tokens. Each token will be of the form: (tokenType, datum) with the tokenType in ['string', 'number', '(', ')', ','] Tokenizes as much as it can. When it first hits a non-token, will give up and return what it can. """ tokens = [] while True: s = s.lstrip() if not s: break if stringRegex.match(s): m = stringRegex.match(s) tokens.append( ('string', m.group(0)[1:-1]) ) s = s[len(m.group(0)):] elif numberRegex.match(s): m = numberRegex.match(s) tokens.append( ('number', int(m.group(0))) ) s = s[len(m.group(0)):] elif s[0] in ['(', ')', ',']: tokens.append( (s[0], None) ) s = s[1:] else: break return tokens def parse(s): """Given a string s, parses out a single expression from s. The result may be a string, a number, or a tuple.""" tokens = tokenize(s) return parseExpression(tokens) def parseExpression(tokens): """Parses a single expression. An expression can either be a number, a string, or a tuple. """ if not tokens: raise ValueError, "Empty token list" firstToken = tokens[0] if firstToken[0] in ['number', 'string']: tokens.pop(0) return firstToken[1] elif firstToken[0] == '(': return parseTuple(tokens) else: raise ValueError, "Don't know how to handle", tokens[0] def parseTuple(tokens): """Parses a tuple expression. A tuple is a '(', followed by a bunch of comma separated expressions, followed by a ')'. """ elements = [] eat(tokens, '(') while True: if not tokens: raise ValueError, ("Expected either ',', an expression," + " or ')', but exhaused token list") if tokens[0][0] in ['number', 'string', '(']: elements.append(parseExpression(tokens)) if tokens[0][0] == ')': break else: eat(tokens, ',') elif tokens[0][0] == ')': break else: raise ValueError, ("Don't know how to handle %r" % (tokens[0],)) eat(tokens, ')') return tuple(elements) def eat(tokens, typeExpected): """Tries to eat a token of the given type, and returns its datum. If we can't, raises ValueError.""" if not tokens: raise ValueError, ("Expected %4, but exhaused token list" % (typeExpected,)) token = tokens.pop(0) if token != (typeExpected, None): raise ValueError, ("Expected %r, but got %s" % (typeExpected, token,)) return token[1] ########################################################################### Whew. That was a mouthful. *grin* But, again, that's because I'm cooking almost everything from scratch. Parser-generating tools will make this a lot simpler. Anyway, let's see how this parse() function works: ###### >>> parse("(0, ''),some data from the test system") (0, '') >>> parse("(-1, 'Error message from the test system')") (-1, 'Error message from the test system') >>> parse("'question 1) can this handle embedded parens in strings?'") 'question 1) can this handle embedded parens in strings?' >>> parse("('question 2) how about this?:', ((((1), 2), 3), 4), 5)") ('question 2) how about this?:', ((((1,), 2), 3), 4), 5) ###### The worst thing that might happen from parsing an arbitrary string with parse() will be an exception or with a structure that is way too deep or large. But other than that, parse() should be resistant to a code-injection attack since it doesn't do anything too special: it's mostly just list/string manipulation and recursion. I hope this helps! From Barry.Carroll at psc.com Sat Nov 5 02:47:20 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 4 Nov 2005 17:47:20 -0800 Subject: [Tutor] Namespace Problem Message-ID: I have a function that makes use of several global variables: ########## Include struct ABC = 1 DEF = 2 xyz = 0 # Other variables def do_stuff(in_str): hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str)) newstr = hdr+in_str # rest of code snipped ########## When I run the program containing this code I get this error: >>>>>>>>> Traceback (most recent call last): File "sample.py", line 43, in ? ret_data = do_stuff(data) File "sample.py", line 17, in do_stuff hdr = struct.pack('@2BH', ABC|DEF,xyz,len(in_str)) UnboundLocalError: local variable 'xyz' referenced before assignment >>>>>>>>> The error goes away if I include a 'global' statement at the top of the function: ########## def do_stuff(in_str): global xyz hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str)) ########## Why does the interpreter choke on xyz and not on ABC or DEF? Barry From samrobertsmith at gmail.com Sat Nov 5 02:52:22 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 4 Nov 2005 17:52:22 -0800 Subject: [Tutor] pack Message-ID: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> what does pack mean in the following code? # File: hello1.py from Tkinter import * root = Tk() w = Label(root, text="Hello, world!") w.pack() root.mainloop() From hugonz-lists at h-lab.net Sat Nov 5 02:59:41 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 04 Nov 2005 19:59:41 -0600 Subject: [Tutor] pack In-Reply-To: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> References: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> Message-ID: <436C120D.20104@h-lab.net> pack is a method of Tkinter widget that needs to be called in order to have it displayed with the current geometry manager(which per default is the pack method) A geometry manager is just a way for arranging widgets into a window. Another geometry manager is "grid" If you don't specify anything, the widget will simply not be displayed.. see here: http://effbot.org/tkinterbook/pack.htm Hugo Shi Mu wrote: > what does pack mean in the following code? > > # File: hello1.py > > from Tkinter import * > > root = Tk() > > w = Label(root, text="Hello, world!") > w.pack() > > root.mainloop() > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Sat Nov 5 03:05:19 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 4 Nov 2005 18:05:19 -0800 Subject: [Tutor] pack In-Reply-To: <436C120D.20104@h-lab.net> References: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> <436C120D.20104@h-lab.net> Message-ID: <1d987df30511041805x7d64c3a6xde18e021f22d8733@mail.gmail.com> Why the button of the following code does not work? Thanks! from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() On 11/4/05, Hugo Gonz?lez Monteverde wrote: > pack is a method of Tkinter widget that needs to be called in order to > have it displayed with the current geometry manager(which per default is > the pack method) > > A geometry manager is just a way for arranging widgets into a window. > Another geometry manager is "grid" > > If you don't specify anything, the widget will simply not be displayed.. > see here: > > http://effbot.org/tkinterbook/pack.htm > > > Hugo > > Shi Mu wrote: > > what does pack mean in the following code? > > > > # File: hello1.py > > > > from Tkinter import * > > > > root = Tk() > > > > w = Label(root, text="Hello, world!") > > w.pack() > > > > root.mainloop() > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From bgailer at alum.rpi.edu Sat Nov 5 03:31:38 2005 From: bgailer at alum.rpi.edu (bob) Date: Fri, 04 Nov 2005 18:31:38 -0800 Subject: [Tutor] Namespace Problem In-Reply-To: References: Message-ID: <6.1.2.0.0.20051104183038.034f5008@mail.mric.net> At 05:47 PM 11/4/2005, Carroll, Barry wrote: >I have a function that makes use of several global variables: > >########## >Include struct Did you mean "import"? >ABC = 1 >DEF = 2 >xyz = 0 >def do_stuff(in_str): > hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str)) > newstr = hdr+in_str Works find for me. Is there anything else you are not showing us? >When I run the program containing this code I get this error: > > >>>>>>>>> >Traceback (most recent call last): > File "sample.py", line 43, in ? > ret_data = do_stuff(data) > File "sample.py", line 17, in do_stuff > hdr = struct.pack('@2BH', ABC|DEF,xyz,len(in_str)) >UnboundLocalError: local variable 'xyz' referenced before assignment > >>>>>>>>> > >The error goes away if I include a 'global' statement at the top of the >function: > >########## >def do_stuff(in_str): > global xyz > hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str)) >########## > >Why does the interpreter choke on xyz and not on ABC or DEF? > >Barry > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From kaizer at mail.pt Sat Nov 5 04:29:23 2005 From: kaizer at mail.pt (Bruno) Date: Sat, 05 Nov 2005 03:29:23 +0000 Subject: [Tutor] Is Python a good choise for this project? Message-ID: <20051105032924.678111E4002@bag.python.org> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20051105/a9566d25/attachment.pot From ml.cyresse at gmail.com Sat Nov 5 06:14:57 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 5 Nov 2005 18:14:57 +1300 Subject: [Tutor] pack In-Reply-To: <1d987df30511041805x7d64c3a6xde18e021f22d8733@mail.gmail.com> References: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> <436C120D.20104@h-lab.net> <1d987df30511041805x7d64c3a6xde18e021f22d8733@mail.gmail.com> Message-ID: >frame = Frame(master) > self.button Sam - What do you think will happen to frame when __init__ finishes? On 11/5/05, Shi Mu wrote: > Why the button of the following code does not work? Thanks! > > from Tkinter import * > > class App: > > def __init__(self, master): > > frame = Frame(master) > frame.pack() > > self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) > self.button.pack(side=LEFT) > > self.hi_there = Button(frame, text="Hello", command=self.say_hi) > self.hi_there.pack(side=LEFT) > > def say_hi(self): > print "hi there, everyone!" > > root = Tk() > > app = App(root) > > root.mainloop() > > > On 11/4/05, Hugo Gonz?lez Monteverde wrote: > > pack is a method of Tkinter widget that needs to be called in order to > > have it displayed with the current geometry manager(which per default is > > the pack method) > > > > A geometry manager is just a way for arranging widgets into a window. > > Another geometry manager is "grid" > > > > If you don't specify anything, the widget will simply not be displayed.. > > see here: > > > > http://effbot.org/tkinterbook/pack.htm > > > > > > Hugo > > > > Shi Mu wrote: > > > what does pack mean in the following code? > > > > > > # File: hello1.py > > > > > > from Tkinter import * > > > > > > root = Tk() > > > > > > w = Label(root, text="Hello, world!") > > > w.pack() > > > > > > root.mainloop() > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Nov 5 09:53:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 5 Nov 2005 08:53:51 -0000 Subject: [Tutor] Is Python a good choise for this project? References: <20051105032924.678111E4002@bag.python.org> Message-ID: <006001c5e1e6$721a96c0$0a01a8c0@xp> > I'm in the process of chosing a technology for the implementation of a > system that will have a Map builder wich will allow the users to draw a > map > using several construction pieces. This map will then be used in the core > of the program where some pathfinding will be done - and then some > animation showing a character going around the map. The interface will be > simple, a grid and some images that can be chosen to ocuppy spots in the > grid. Input done with the mouse. > > Since I don't know Python (altough I've looked some examples) I am looking > for suggestions... do you think it's a good option to go with Python Python is capable of building such a system if thats what you mean. Proivided high performance (real time rapid animation say) is not required then it should perform adequately. But it will require quite a bit of learning, not just the core language but a GUI toolkit, and maybe the PyGame framework too. > graphics lib, like Pygame)? Other alternatives at this point are Java and > C/SDL/Allegro. If you already know these environments and have built similar applications in them you may be faster sticking with them. But if you have the time and energy to learn a new language then Python offers the promise of more rapid development in the future and easier maintenance. If you know Java you might consider using Jython to write the core objects and Java to do the GUI parts - Jython makes Python objects that are also valid Java objects and vice versa. If you are completely new to programming then you have a big challenge ahead regardless of language but Python is probably easier to learn than the others mentioned. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Nov 5 10:00:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 5 Nov 2005 09:00:02 -0000 Subject: [Tutor] pack References: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com><436C120D.20104@h-lab.net> <1d987df30511041805x7d64c3a6xde18e021f22d8733@mail.gmail.com> Message-ID: <006801c5e1e7$4efe97d0$0a01a8c0@xp> > Why the button of the following code does not work? Thanks! The program works perfectly for me. Which button do you think is not working? If its the Hello one where do you expect to see the output? print always prints to stdout so you need to look in the console window not on the GUI. But otherwise the program worked without modification for me. HTH, Alan G. -------------------------- from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() On 11/4/05, Hugo Gonz?lez Monteverde wrote: > pack is a method of Tkinter widget that needs to be called in order to > have it displayed with the current geometry manager(which per default is > the pack method) > > A geometry manager is just a way for arranging widgets into a window. > Another geometry manager is "grid" > > If you don't specify anything, the widget will simply not be displayed.. > see here: > > http://effbot.org/tkinterbook/pack.htm > > > Hugo > > Shi Mu wrote: > > what does pack mean in the following code? > > > > # File: hello1.py > > > > from Tkinter import * > > > > root = Tk() > > > > w = Label(root, text="Hello, world!") > > w.pack() > > > > root.mainloop() > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From lists at janeden.org Sat Nov 5 22:30:46 2005 From: lists at janeden.org (Jan Eden) Date: Sat, 5 Nov 2005 22:30:46 +0100 Subject: [Tutor] Class attributes not overriding parameters Message-ID: Hi, I use the following construction to make sure the data attribute site_id is set only once for each object: def GetSiteID(self): return self._site_id def SetSiteID(self, value): if not (hasattr(self, '_site_id') and self._site_id): self._site_id = value site_id = property(GetSiteID, SetSiteID) site_id is supposed to be set either through a parameter, derived from the server name (the default case) or via a class attribute: class SiteList(Lists): site_id = 1 The latter case does not work: the site_id is still derived from the server name for objects of class SiteList. Why is that? How can I make Python check the superclasses for a class attribute before applying the SiteMode() method? Thanks, Jan -- How many Microsoft engineers does it take to screw in a lightbulb? None. They just redefine "dark" as the new standard. From samrobertsmith at gmail.com Sat Nov 5 22:57:47 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 5 Nov 2005 13:57:47 -0800 Subject: [Tutor] pack In-Reply-To: <006801c5e1e7$4efe97d0$0a01a8c0@xp> References: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> <436C120D.20104@h-lab.net> <1d987df30511041805x7d64c3a6xde18e021f22d8733@mail.gmail.com> <006801c5e1e7$4efe97d0$0a01a8c0@xp> Message-ID: <1d987df30511051357k425d1be0v96f725d8a49b52d@mail.gmail.com> when I clicked 'quit' button, there is no response. I want to close the interface by clicking 'x', the interface could not be closed. i had to close PYTHONWIN to get out of the program. On 11/5/05, Alan Gauld wrote: > > Why the button of the following code does not work? Thanks! > > The program works perfectly for me. > Which button do you think is not working? > > If its the Hello one where do you expect to see the output? > print always prints to stdout so you need to look in the > console window not on the GUI. > > But otherwise the program worked without modification for me. > > HTH, > > Alan G. > > -------------------------- > from Tkinter import * > > class App: > > def __init__(self, master): > > frame = Frame(master) > frame.pack() > > self.button = Button(frame, text="QUIT", fg="red", > command=frame.quit) > self.button.pack(side=LEFT) > > self.hi_there = Button(frame, text="Hello", command=self.say_hi) > self.hi_there.pack(side=LEFT) > > def say_hi(self): > print "hi there, everyone!" > > root = Tk() > > app = App(root) > > root.mainloop() > > > On 11/4/05, Hugo Gonz?lez Monteverde wrote: > > pack is a method of Tkinter widget that needs to be called in order to > > have it displayed with the current geometry manager(which per default is > > the pack method) > > > > A geometry manager is just a way for arranging widgets into a window. > > Another geometry manager is "grid" > > > > If you don't specify anything, the widget will simply not be displayed.. > > see here: > > > > http://effbot.org/tkinterbook/pack.htm > > > > > > Hugo > > > > Shi Mu wrote: > > > what does pack mean in the following code? > > > > > > # File: hello1.py > > > > > > from Tkinter import * > > > > > > root = Tk() > > > > > > w = Label(root, text="Hello, world!") > > > w.pack() > > > > > > root.mainloop() > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > From bgailer at alum.rpi.edu Sat Nov 5 23:18:05 2005 From: bgailer at alum.rpi.edu (bob) Date: Sat, 05 Nov 2005 14:18:05 -0800 Subject: [Tutor] pack In-Reply-To: <1d987df30511051357k425d1be0v96f725d8a49b52d@mail.gmail.com > References: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> <436C120D.20104@h-lab.net> <1d987df30511041805x7d64c3a6xde18e021f22d8733@mail.gmail.com> <006801c5e1e7$4efe97d0$0a01a8c0@xp> <1d987df30511051357k425d1be0v96f725d8a49b52d@mail.gmail.com> Message-ID: <6.1.2.0.0.20051105141654.034fa6f0@mail.mric.net> At 01:57 PM 11/5/2005, Shi Mu wrote: >when I clicked 'quit' button, >there is no response. I want to close the interface by clicking 'x', >the interface could not be closed. >i had to close PYTHONWIN to get out of the program. That is a known problem running Tkinter stuff under PythonWin. Others may have a solution for you. [snip] From alan.gauld at freenet.co.uk Sat Nov 5 23:24:03 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 5 Nov 2005 22:24:03 -0000 Subject: [Tutor] pack References: <1d987df30511041752s7d7b6a34x15abd68e696510c9@mail.gmail.com> <436C120D.20104@h-lab.net> <1d987df30511041805x7d64c3a6xde18e021f22d8733@mail.gmail.com> <006801c5e1e7$4efe97d0$0a01a8c0@xp> <1d987df30511051357k425d1be0v96f725d8a49b52d@mail.gmail.com> Message-ID: <00b101c5e257$a14987f0$0a01a8c0@xp> Note: CC'ing tutor list to make reply visible to all. > i had to close PYTHONWIN to get out of the program. Aha! There are problems in running Tkinter inside both IDLE and Pythonwin. Basically both programs try to trap abnormal termination - which includes the GUI close messages... IMHO, to test Tkinter programs its better to run the program from a DOS Window - or just double click in explorer although you might not see any error messages that way. Personally I have a DOS window open at the folder with my Tkinter program. I edit in IDLE or vim and sabe I run the program by explicitly calling python: E:\PROJECTS\PYTHON> python myguiprog.py I close the GUI and repeat except I can now use F3 in the DOS window to recall the last command (or up arrow if DOSKEY is defined) So after the first time I simply - edit the code, - save it and then - Alt-tab to DOS and - hit F3 Return. Its quicker to do than to read! HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From samrobertsmith at gmail.com Sun Nov 6 00:39:52 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 5 Nov 2005 15:39:52 -0800 Subject: [Tutor] main Message-ID: <1d987df30511051539s38468d25gce6dae4db69e1c15@mail.gmail.com> It is very hard for me to understand why we need the following line? if __name__ == "__main__": From dyoo at hkn.eecs.berkeley.edu Sun Nov 6 02:42:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 5 Nov 2005 17:42:31 -0800 (PST) Subject: [Tutor] main In-Reply-To: <1d987df30511051539s38468d25gce6dae4db69e1c15@mail.gmail.com> Message-ID: On Sat, 5 Nov 2005, Shi Mu wrote: > It is very hard for me to understand why we need the following line? if > __name__ == "__main__": Hi Shi Mu, It's tied to the concept of modules. Have you learned about modules yet? Python programs can be split into several modular pieces, and these "modules" live in text files. You may have seen some prewritten modules already in the Standard Library: http://www.python.org/doc/lib/ These modules are physically no different than the programs you've already written: they live in text files just like others. The 'if __name__ == "__main__": ..." trick exists in Python so that our Python files can act as either reusable modules, or as standalone programs. As a toy example, let's say that we have two files: ###### mumak:~ dyoo$ cat mymath.py def square(x): return x * x if __name__ == '__main__': print "test: square(42) ==", square(42) mumak:~ dyoo$ cat mygame.py import mymath print "this is mygame." print mymath.square(17) ###### In this example, we've written mymath.py to be both used as a utility module, as well as a standalone program. We can run mymath standalone by doing this: ###### mumak:~ dyoo$ python mymath.py test: square(42) == 1764 ###### But we can also use mymath.py as a module; let's see what happens when we run mygame.py: ###### mumak:~ dyoo$ python mygame.py this is mygame. 289 ###### Notice that here we don't see the 'test' line that mymath.py had near the bottom of its code. That's because, in this context, mymath is not the main program. That's what the 'if __name__ == "__main__": ...' trick is used for. (Another mainstream programming language that does a simliar trick is Java: each Java class can define a "main" function that gets executed if we use that class as our entry point.) Does this make sense? Please feel free to ask more questions about this. From ml.cyresse at gmail.com Sun Nov 6 05:45:17 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sun, 6 Nov 2005 17:45:17 +1300 Subject: [Tutor] Class attributes not overriding parameters In-Reply-To: References: Message-ID: Hi Jan, Won't this site_id = property(GetSiteID, SetSiteID) and this site_id = 1 collide? On 11/6/05, Jan Eden wrote: > Hi, > > I use the following construction to make sure the data attribute site_id is set only once for each object: > > def GetSiteID(self): > return self._site_id > > def SetSiteID(self, value): > if not (hasattr(self, '_site_id') and self._site_id): self._site_id = value > > site_id = property(GetSiteID, SetSiteID) > > site_id is supposed to be set either through a parameter, derived from the server name (the default case) or via a class attribute: > > class SiteList(Lists): > site_id = 1 > > The latter case does not work: the site_id is still derived from the server name for objects of class SiteList. Why is that? How can I make Python check the superclasses for a class attribute before applying the SiteMode() method? > > Thanks, > > Jan > -- > How many Microsoft engineers does it take to screw in a lightbulb? None. They just redefine "dark" as the new standard. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at alum.rpi.edu Sun Nov 6 06:26:08 2005 From: bgailer at alum.rpi.edu (bob) Date: Sat, 05 Nov 2005 21:26:08 -0800 Subject: [Tutor] main In-Reply-To: <1d987df30511051539s38468d25gce6dae4db69e1c15@mail.gmail.co m> References: <1d987df30511051539s38468d25gce6dae4db69e1c15@mail.gmail.com> Message-ID: <6.1.2.0.0.20051105212045.034f7f18@mail.mric.net> At 03:39 PM 11/5/2005, Shi Mu wrote: >It is very hard for me to understand why we need the following line? >if __name__ == "__main__": We don't need it. Often we code a module for importing into another module. But sometimes we also want to run the module independently as a Python program, perhaps just to test it, or for other purposes. if __name__ == "__main__": is one way to test whether the module has been imported or is running standalone. When run standalone __name__ is "__main__". When imported __name__ is the module name. Now is it easier to understand? From lists at janeden.org Sun Nov 6 10:42:03 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 6 Nov 2005 10:42:03 +0100 Subject: [Tutor] Class attributes not overriding parameters In-Reply-To: Message-ID: Hi Liam, Liam Clarke wrote on 06.11.2005: >Hi Jan, > >Won't this > >site_id = property(GetSiteID, SetSiteID) > >and this > >site_id = 1 > >collide? > Yup. After writing my message, I thought about it again: the property function gets never executed when I use the class attribute. So I changed the setup to this: class Base: def GetSiteID(self): return self._site_id def SetSiteID(self, value): if not (hasattr(self, '_site_id') and self._site_id): self._site_id = value site_id = property(GetSiteID, SetSiteID) class Lists(Base): ... class SiteList(Lists, Data.Lists): _site_id = 1 which works just as expected. Thanks for yor help! - Jan -- A core dump is your computer's way of saying "Here's what's on my mind, what's on yours?" From andreas at kostyrka.org Sun Nov 6 10:54:59 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 06 Nov 2005 10:54:59 +0100 Subject: [Tutor] Class attributes not overriding parameters In-Reply-To: References: Message-ID: <1131270899.5670.23.camel@andi-lap> Am Samstag, den 05.11.2005, 22:30 +0100 schrieb Jan Eden: > Hi, > > I use the following construction to make sure the data attribute site_id is set only once for each object: > > def GetSiteID(self): > return self._site_id > > def SetSiteID(self, value): > if not (hasattr(self, '_site_id') and self._site_id): self._site_id = value > > site_id = property(GetSiteID, SetSiteID) > > site_id is supposed to be set either through a parameter, derived from the server name (the default case) or via a class attribute: > > class SiteList(Lists): > site_id = 1 > > The latter case does not work: the site_id is still derived from the server name for objects of class SiteList. Why is that? How can I make Python check the superclasses for a class attribute before applying the SiteMode() method? The basic misunderstanding is how it all works :) class X: dict_definition Basically, Python just collects all that definitions into a dictionary, and it passes it into the type constructor. Using metaclasses one can actually manipulate this dictionary. class X: a = 1 def b(self): print self.a x=X() X.__dict__['b'] # function X.b # unbound method x.b # bound method x.b() # print 1 x.a = 100 # e.g. self.a = self.a + 99 x.b() # print 100 print X.a # print 1 print x.a # print 100 So basically, one of the mechanisms of Python is to look for attributes (like self.a) first in self, and then in all the class dictionaries. Back to your example: class SiteList(Lists): site_id = 1 you can basically do two things: (both solutions untested) Use the internal variable name: class SiteList(Lists): _site_id = 1 This way the hasattr method will find a _site_id attribute. Or use a metaclass, which would then result in something like this class MyMeta(type): def __init__(cls, name, bases, dict): super(MyMeta, cls).__init__(name, bases, dict) if cls.__dict__.has_key("site_id"): cls._site_id = cls.site_id def getSite(self): return self._site_id def setSite(self, val): if not (hasattr(self, '_site_id') and self._site_id): self._site_id = val else: raise TypeError("site_id already set") cls.site_id = property(getSite, setSite) class Base(object): __metaclass__ = MyMeta class Test(Base): site_id = 100 t = Base() t2 = Test() t.site_id = "Baseid" print t.site_id try: t.site_id = "Baseid" assert None == "Something went really wrong." except TypeError: pass print t2.site_id t2.site_id = 101 Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20051106/5a309c84/attachment-0001.pgp From winglion1 at 163.com Sun Nov 6 11:21:55 2005 From: winglion1 at 163.com (=?gb2312?B?zPrKrw==?=) Date: Sun, 6 Nov 2005 18:21:55 +0800 Subject: [Tutor] replacing spaces and tabs before the code Message-ID: <20051106102205.5D0321E4009@bag.python.org> I am try to write a code that turn codes to html file I do it like this,(It is take out from example code form sourceforge): re_lead=re.compile(r"[\f\t]") re_space=re.compile(r"[ ]{2,}") src = re_lead.sub(r"     ",src) src = re_lead.sub(r"     ",src) src is the code string! as you can see, I repeat the search many time to replace two or more \t before the code line. but, if somebody use space, some time may be up to 8 or 9 times before a line,it would be stupid to repeat 8 time of search to replace them! It's there a method that can replace all spaces with " " just at one search action, and pass the single space between words! I am new to re module,please help! thanks! ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡winglion1 at 163.com ¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡2005-11-06 From samrobertsmith at gmail.com Sun Nov 6 11:52:33 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 02:52:33 -0800 Subject: [Tutor] point and polygon Message-ID: <1d987df30511060252m45769e92icb326e1339199e22@mail.gmail.com> why the following code report error? """ Is given point in polygon? """ def pointInPoly(point, pointsList): "Return True if point is contained in polygon (defined by given list of points.)" assert len(pointsList) >= 3, 'Not enough points to define a polygon (I require 3 or more.)' assert len(point) >= 2, 'Not enough dimensions to define a point(I require 2 or more.)' # If given values are ints, code will fail subtly. Force them to floats. x,y = float(point[0]), float(point[1]) xp = [float(p[0]) for p in pointsList] yp = [float(p[1]) for p in pointsList] # Initialize loop c=False i=0 npol = len(pointsList) j=npol-1 while i < npol: if ((((yp[i]<=y) and (y why the following code does not work? # determine if a point is inside a given polygon or not # Polygon is a list of (x,y) pairs. def point_inside_polygon(x,y,poly): n = len(poly) inside =False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): if x <= max(p1x,p2x): if p1y != p2y: xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x if p1x == p2x or x <= xinters: inside = not inside p1x,p1y = p2x,p2y return inside if __name__ == '__main__': print 'Simple pointInPoly() test...' poly = [(-1,-1), (6,-1), (5,6), (0,5)] point_inside_polygon(3,10,poly) From samrobertsmith at gmail.com Sun Nov 6 12:27:12 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 03:27:12 -0800 Subject: [Tutor] color vector Message-ID: <1d987df30511060327t7eedcbf7qa1c30831d78df772@mail.gmail.com> why the following code does not work? """ Tkinter Color Vector Objects Just the bare minimum to create re-sizable and re-usable color icons in tkinter. """ import Tkinter as Tk import math """ Get points for a unit regular-polygon with n sides. """ def getregpoly(sides): points = [] ang = 2*math.pi / sides for i in range(sides): deg = (i+.5)*ang points.append(math.sin(deg)/2.0+.5) points.append(math.cos(deg)/2.0+.5) return points def scale(points, scale): return [x*scale for x in points] def move(points, x, y): xy = [x,y]*(len(points)//2) return [xy+coord for xy, coord in zip(xy,points)] def translate(obj, x, y, zoom): p = scale(obj.points, obj.size) p = move(p, obj.x, obj.y) p = scale(p, zoom) return move(p, x, y) def draw(obj, c, x=0 ,y=0, zoom=1): p = translate(obj, x, y, zoom) if obj.obj=='line': c.create_line( p, fill=obj.fill, width=obj.width, arrow=obj.arrow) elif obj.obj=='rectangle': c.create_line( p, fill=obj.fill, outline=obj.outline,width=obj.width) elif obj.obj=='polygon': c.create_polygon( p, fill=obj.fill, outline=obj.outline,width=obj.width,smooth=obj.smooth) elif obj.obj=='text': size = int(obj.size*zoom) font = (obj.font,size,obj.style) c.create_text(p, text=obj.text, font=font, fill=obj.fill) elif obj.obj=='oval': c.create_oval( p, fill=obj.fill, outline=obj.outline,width=obj.width ) elif obj.obj=='arc': c.create_arc( p, start=obj.start, extent=obj.extent,style=obj.style, fill=obj.fill,outline=obj.outline, width=obj.width) class Shape(object): size = 1 x = y = 0 def __init__(self, **kwds): self.__dict__.update(kwds) def __call__(self, *args, **kwds): for key in self.__dict__: if key not in kwds: kwds[key] = self.__dict__[key] return self.__class__(*args, **kwds) def draw(self, c, x=0, y=0, scale=1.0): draw(self, c, x, y, scale) class Group(list): obj = 'group' def __init__(self, *args, **kwds): self[:] = args self.__dict__.update(kwds) def __call__(self, *args, **kwds): args = self[:]+list(args) for key in self.__dict__: if key not in kwds:# make copies kwds[key] = self.__dict__[key]() return self.__class__(*args, **kwds) def draw(self, c, x=0, y=0, scale=1.0): for item in self: item.draw(c, x, y, scale) for key in self.__dict__: self.__dict__[key].draw(c, x, y, scale) # base shapes. text = Shape( obj='text', text='', fill='black', width=0,font='', style='', points=[0,0] ) line = Shape( obj='line', arrow='none', fill='black',smooth='false', width=1, points=[0,0,1,0]) rectangle = Shape( obj='rectangle', fill='', outline='black',width=1, points=[0,0,1,.5]) polygon = Shape( obj='polygon', fill='grey', outline='',width=0, points=[0,0], smooth='false' ) oval = Shape( obj='oval', fill='grey', outline='',width=0, points=[0,0,1,.75] ) arc = Shape( obj='arc', fill='grey', outline='', width=0,style='arc', start='0', extent='90',points=[0,0,1,1]) # shape variations chord = arc(style='chord') pie = arc(style='pieslice') circle = oval(points=[0,0,1,1]) square = rectangle(points=[0,0,1,1]) triangle = polygon( points=getregpoly(3)) octagon = polygon( points=getregpoly(8)) # CAUTION ICON caution = Group( triangle(x=6, y=5, size=75), triangle(size=75, fill='yellow'), txt = text( text='!', x=38, y=32, size=30, font='times', style='bold') ) # ERROR ICON circlepart = chord( x=15, y=15, size=25, fill='red', start='140', extent='155' ) error = Group( octagon(x=6, y=5, size=56), octagon(size=56, fill='red'), circle(x=9, y=9, size=37, fill='white'), circlepart(), circlepart(start='320') ) # QUESTION & INFO ICONS bubbletip = polygon(points=[34,42,60,56,50,38]) question = Group( bubbletip(x=6, y=5), oval(x=6, y=5, size=60), bubbletip(fill='lightblue'), oval(size=60, fill='lightblue'), txt = text( text='?', x=31, y=22, size=28, font='times', style='bold' ) ) info = question() info.txt.text = 'i' if __name__ == '__main__': root = Tk.Tk() root.title('Resizable Shapes') c = Tk.Canvas(root) caution.draw(c,40,20,.5) error.draw(c,120,20,1) question.draw(c,210,20,2) info.draw(c,50,100) logo = caution() # get a copy logo.txt = text( text='&', fill='#00bb44', x=39, y=34, size=30 ) logo.draw(c,135,110,1.3) message = text( text="What's Your Size?", size=15, fill='white' ) Group( message( x=1, y=1, fill='grey30'), message() ).draw(c,190,235,2) line( width=3, fill='darkgrey', arrow='both').draw(c,20,205,336) c.pack() root.mainloop() From gew75 at hotmail.com Sun Nov 6 12:30:07 2005 From: gew75 at hotmail.com (Glen Wheeler) Date: Sun, 6 Nov 2005 22:30:07 +1100 Subject: [Tutor] inside References: <1d987df30511060305m7e8865dayd99100d64ef5e11d@mail.gmail.com> Message-ID: > why the following code does not work? > [snip script] Give us an error message, please. From samrobertsmith at gmail.com Sun Nov 6 12:41:03 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 03:41:03 -0800 Subject: [Tutor] inside In-Reply-To: References: <1d987df30511060305m7e8865dayd99100d64ef5e11d@mail.gmail.com> Message-ID: <1d987df30511060341t4d0fa106wb24d4f848d91361e@mail.gmail.com> just return the "Simple pointInPoly() test..." no return from point_inside_polygon(3,10,poly) On 11/6/05, Glen Wheeler wrote: > > why the following code does not work? > > [snip script] > > Give us an error message, please. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From lard at tardis.ed.ac.uk Sun Nov 6 12:47:57 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Sun, 06 Nov 2005 11:47:57 +0000 Subject: [Tutor] interfaces and abstract classes in python Message-ID: <436DED6D.3020902@tardis.ed.ac.uk> Interfaces and abstract classes - I know they don't exist per se in Python. But what are the closest analogues? I've found a few examples, e.g. for an abstract class the following page has a fairly common suggestion: http://www.norvig.com/python-iaq.html thanks! alex From ml.cyresse at gmail.com Sun Nov 6 12:42:25 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 7 Nov 2005 00:42:25 +1300 Subject: [Tutor] inside In-Reply-To: <1d987df30511060305m7e8865dayd99100d64ef5e11d@mail.gmail.com> References: <1d987df30511060305m7e8865dayd99100d64ef5e11d@mail.gmail.com> Message-ID: Shi, I've just seen 3 queries from you all along the lines of - why the following code does not work? If English is not your first language, I can understand you're not going to write us a novel. However, you'll get a better response if you copy and paste the error message (the traceback) that you're getting in the console. Do you know how to copy and paste from the console? A lot of us aren't anywhere we can run your code; if we did, it may work, the error may not be an unhandled exception, just unexpected behaviour, and we have no idea what behaviour you're expecting. So please, in future give us this basic information - If there's an error message - copy and paste the error message If there is no error message - tell us what you expected to happen, and what happened instead. Regards, Liam Clarke On 11/7/05, Shi Mu wrote: > why the following code does not work? > > # determine if a point is inside a given polygon or not > # Polygon is a list of (x,y) pairs. > > def point_inside_polygon(x,y,poly): > > n = len(poly) > inside =False > > p1x,p1y = poly[0] > for i in range(n+1): > p2x,p2y = poly[i % n] > if y > min(p1y,p2y): > if y <= max(p1y,p2y): > if x <= max(p1x,p2x): > if p1y != p2y: > xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x > if p1x == p2x or x <= xinters: > inside = not inside > p1x,p1y = p2x,p2y > > return inside > > if __name__ == '__main__': > print 'Simple pointInPoly() test...' > > poly = [(-1,-1), (6,-1), (5,6), (0,5)] > point_inside_polygon(3,10,poly) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Sun Nov 6 13:02:47 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 04:02:47 -0800 Subject: [Tutor] inside In-Reply-To: References: <1d987df30511060305m7e8865dayd99100d64ef5e11d@mail.gmail.com> Message-ID: <1d987df30511060402gcc464ddl3228aee99b3b3f04@mail.gmail.com> there is no error message but in the console I just see Simple pointInPoly() test... On 11/6/05, Liam Clarke wrote: > Shi, > > I've just seen 3 queries from you all along the lines of - > > why the following code does not work? > > > > If English is not your first language, I can understand you're not > going to write us a novel. > However, you'll get a better response if you copy and paste the error > message (the traceback) that you're getting in the console. > > Do you know how to copy and paste from the console? > > A lot of us aren't anywhere we can run your code; if we did, it may > work, the error may not be an unhandled exception, just unexpected > behaviour, and we have no idea what behaviour you're expecting. > > So please, in future give us this basic information - > > If there's an error message - copy and paste the error message > If there is no error message - tell us what you expected to happen, > and what happened instead. > > Regards, > > Liam Clarke > On 11/7/05, Shi Mu wrote: > > why the following code does not work? > > > > # determine if a point is inside a given polygon or not > > # Polygon is a list of (x,y) pairs. > > > > def point_inside_polygon(x,y,poly): > > > > n = len(poly) > > inside =False > > > > p1x,p1y = poly[0] > > for i in range(n+1): > > p2x,p2y = poly[i % n] > > if y > min(p1y,p2y): > > if y <= max(p1y,p2y): > > if x <= max(p1x,p2x): > > if p1y != p2y: > > xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x > > if p1x == p2x or x <= xinters: > > inside = not inside > > p1x,p1y = p2x,p2y > > > > return inside > > > > if __name__ == '__main__': > > print 'Simple pointInPoly() test...' > > > > poly = [(-1,-1), (6,-1), (5,6), (0,5)] > > point_inside_polygon(3,10,poly) > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From ml.cyresse at gmail.com Sun Nov 6 13:08:12 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Mon, 7 Nov 2005 01:08:12 +1300 Subject: [Tutor] inside In-Reply-To: <1d987df30511060402gcc464ddl3228aee99b3b3f04@mail.gmail.com> References: <1d987df30511060305m7e8865dayd99100d64ef5e11d@mail.gmail.com> <1d987df30511060402gcc464ddl3228aee99b3b3f04@mail.gmail.com> Message-ID: This is why - if __name__ == '__main__': print 'Simple pointInPoly() test...' poly = [(-1,-1), (6,-1), (5,6), (0,5)] point_inside_polygon(3,10,poly) And you were expecting to see a True/False as to whether or not the point was inside the polygon right, as point_inside_polygon() returns True/False... Try changing it to - if __name__ == '__main__': print 'Simple pointInPoly() test...' poly = [(-1,-1), (6,-1), (5,6), (0,5)] if point_inside_polygon(3,10,poly): print "Point is inside polygon" else: print "Point is not inside polygon" On 11/7/05, Shi Mu wrote: > there is no error message but in the console > I just see Simple pointInPoly() test... > > > On 11/6/05, Liam Clarke wrote: > > Shi, > > > > I've just seen 3 queries from you all along the lines of - > > > > why the following code does not work? > > > > > > > > If English is not your first language, I can understand you're not > > going to write us a novel. > > However, you'll get a better response if you copy and paste the error > > message (the traceback) that you're getting in the console. > > > > Do you know how to copy and paste from the console? > > > > A lot of us aren't anywhere we can run your code; if we did, it may > > work, the error may not be an unhandled exception, just unexpected > > behaviour, and we have no idea what behaviour you're expecting. > > > > So please, in future give us this basic information - > > > > If there's an error message - copy and paste the error message > > If there is no error message - tell us what you expected to happen, > > and what happened instead. > > > > Regards, > > > > Liam Clarke > > On 11/7/05, Shi Mu wrote: > > > why the following code does not work? > > > > > > # determine if a point is inside a given polygon or not > > > # Polygon is a list of (x,y) pairs. > > > > > > def point_inside_polygon(x,y,poly): > > > > > > n = len(poly) > > > inside =False > > > > > > p1x,p1y = poly[0] > > > for i in range(n+1): > > > p2x,p2y = poly[i % n] > > > if y > min(p1y,p2y): > > > if y <= max(p1y,p2y): > > > if x <= max(p1x,p2x): > > > if p1y != p2y: > > > xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x > > > if p1x == p2x or x <= xinters: > > > inside = not inside > > > p1x,p1y = p2x,p2y > > > > > > return inside > > > > > > if __name__ == '__main__': > > > print 'Simple pointInPoly() test...' > > > > > > poly = [(-1,-1), (6,-1), (5,6), (0,5)] > > > point_inside_polygon(3,10,poly) > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > From gew75 at hotmail.com Sun Nov 6 13:16:42 2005 From: gew75 at hotmail.com (Glen Wheeler) Date: Sun, 6 Nov 2005 23:16:42 +1100 Subject: [Tutor] Fw: point and polygon Message-ID: Missed the rest of the list with this. Still sent to Shi however. From: "Shi Mu" > why the following code report error? > > [..] > assert pointInPoly(pointA, poly) > assert not pointInPoly(pointB, poly) Assuming your function is correct, the asserts are failing, and python is telling you about it. Asserts exist for many reasons but not for output. What you most likely want is: if pointInPoly(pointA, poly): print "pointA in poly" else: print "pointA not in poly" With a similar conditional for pointB. HTH, Glen L:Pyt E+++ T-- R+ P+++ D+ G+ F:*band !RL RLA- W:AF Q+++ AI++ GFX++ SFX-- RN++++ PO--- !Hp Re-- S+ From samrobertsmith at gmail.com Sun Nov 6 13:36:02 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 04:36:02 -0800 Subject: [Tutor] overlay Message-ID: <1d987df30511060436h7d0b0371tbe85d9790c642ce8@mail.gmail.com> Is there any sample code to calculate the overlaid area between two polygons? Thanks! From gew75 at hotmail.com Sun Nov 6 13:50:34 2005 From: gew75 at hotmail.com (Glen Wheeler) Date: Sun, 6 Nov 2005 23:50:34 +1100 Subject: [Tutor] overlay References: <1d987df30511060436h7d0b0371tbe85d9790c642ce8@mail.gmail.com> Message-ID: I would do this by clipping the two polygons together, and then calculating the area of the resultant polygon. You can do that using the Weiler-Atherton polygon clipping algorithm, which is rather common. Glen From: "Shi Mu" > Is there any sample code to calculate the overlaid area between two > polygons? > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Nov 6 14:13:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 08:13:56 -0500 Subject: [Tutor] replacing spaces and tabs before the code In-Reply-To: <20051106102205.5D0321E4009@bag.python.org> References: <20051106102205.5D0321E4009@bag.python.org> Message-ID: <436E0194.7030406@tds.net> Ìúʯ wrote: > I am try to write a code that turn codes to html file You might be interested in existing solutions. Here is an old list, there are probably more now: http://groups.google.com/group/comp.lang.python/browse_thread/thread/904b11321e07460a/fc9a13cf4baf3b05%23fc9a13cf4baf3b05?sa=X&oi=groupsr&start=1&num=3 Pudge is a new one: http://pudge.lesscode.org/ > I do it like this,(It is take out from example code form sourceforge): > > re_lead=re.compile(r"[\f\t]") > re_space=re.compile(r"[ ]{2,}") > src = re_lead.sub(r"     ",src) > src = re_lead.sub(r"     ",src) > > src is the code string! > as you can see, I repeat the search many time to replace two or more \t before the code line. > but, if somebody use space, some time may be up to 8 or 9 times before a line,it > would be stupid to repeat 8 time of search to replace them! > It's there a method that can replace all spaces with " " just at one search > action, and pass the single space between words! re.sub() can take a function (or any callable) as the 'replacement' parameter. The function gets a Match object as its argument and returns the replacement string. This is very handy when you need to do some processing on the match to figure out what the correct replacement string is. Here is an example that looks at the length of the match and returns a corresponding number of   (BTW your example is missing the final semicolon - should be ' ') >>> import re >>> spaceRe = re.compile(r'^( +)') >>> def spaceRepl(m): ... num = len(m.group(1)) ... return ' '*num ... >>> spaceRe.sub(spaceRepl, ' def foo():') '    def foo():' Kent -- http://www.kentsjohnson.com From kent37 at tds.net Sun Nov 6 14:15:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 08:15:43 -0500 Subject: [Tutor] point and polygon In-Reply-To: <1d987df30511060252m45769e92icb326e1339199e22@mail.gmail.com> References: <1d987df30511060252m45769e92icb326e1339199e22@mail.gmail.com> Message-ID: <436E01FF.8050105@tds.net> Shi Mu wrote: > why the following code report error? What error does it report? If you show us the error message and the full stack trace it will be easier to answer your question. Kent From kent37 at tds.net Sun Nov 6 14:16:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 08:16:33 -0500 Subject: [Tutor] color vector In-Reply-To: <1d987df30511060327t7eedcbf7qa1c30831d78df772@mail.gmail.com> References: <1d987df30511060327t7eedcbf7qa1c30831d78df772@mail.gmail.com> Message-ID: <436E0231.80706@tds.net> Shi Mu wrote: > why the following code does not work? In what way does it not work? Kent From alan.gauld at freenet.co.uk Sun Nov 6 16:07:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Nov 2005 15:07:58 -0000 Subject: [Tutor] inside References: <1d987df30511060305m7e8865dayd99100d64ef5e11d@mail.gmail.com> <1d987df30511060341t4d0fa106wb24d4f848d91361e@mail.gmail.com> Message-ID: <010101c5e2e3$dfb7b7a0$0a01a8c0@xp> > just return the "Simple pointInPoly() test..." > no return from point_inside_polygon(3,10,poly) ---------------- if __name__ == '__main__': print 'Simple pointInPoly() test...' poly = [(-1,-1), (6,-1), (5,6), (0,5)] point_inside_polygon(3,10,poly) ----------------- You need to print it to see it.... The function returns a value which you ignore. Alan G. From alan.gauld at freenet.co.uk Sun Nov 6 16:19:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Nov 2005 15:19:48 -0000 Subject: [Tutor] interfaces and abstract classes in python References: <436DED6D.3020902@tardis.ed.ac.uk> Message-ID: <010501c5e2e5$8701afb0$0a01a8c0@xp> > Interfaces and abstract classes - I know they don't exist per se in > Python. First you need to define what you mean by the terms. Every class has an interface - it is the set of messages to which it responds. An Abstract class is one which is not intended to be instantiated. class AbstractClassError(Exception): pass class Abstract: def __init__(self): raise AbstractClassError > But what are the closest analogues? I've found a few examples, Assuming you mean Interface in the Microsoft/Java specific sense of the term rather than the simple OOP sense, then an Interface class is simply an abstract class with empty methods. class InterfaceError(Exception): pass class Interface(Abstract): def myMethod(self): pass def myOther(self): raise InterfaceErrror Does that do what you want? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From sweetdaddysiki at hotmail.com Sun Nov 6 16:56:34 2005 From: sweetdaddysiki at hotmail.com (Trent Rigsbee) Date: Sun, 06 Nov 2005 15:56:34 +0000 Subject: [Tutor] Dictionary Error: 'dict' object has no attribute '_contains_' Message-ID: Hi! I'm on the version 2.4, going through Beginning Python (Wrox), and I'm getting the above error. I'm trying to do this: menu_specials._contains_("test") Any ideas on what I'm doing wrong? Thanks! From piton at kebikec.net Sun Nov 6 17:04:58 2005 From: piton at kebikec.net (sener) Date: Sun, 06 Nov 2005 16:04:58 -0000 Subject: [Tutor] saving project Message-ID: <4384922E.6050405@kebikec.net> hi everyone, Firstly I am a new programmer on python. I am using Python 2.4.1 with IDLE 1.1.1 I can't save my poject in my computer. how can I save my projects and in which format I must save my projects. thanks a lot. From kent37 at tds.net Sun Nov 6 18:42:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 12:42:45 -0500 Subject: [Tutor] interfaces and abstract classes in python In-Reply-To: <436DED6D.3020902@tardis.ed.ac.uk> References: <436DED6D.3020902@tardis.ed.ac.uk> Message-ID: <436E4095.5000405@tds.net> Alex Hunsley wrote: > Interfaces and abstract classes - I know they don't exist per se in > Python. But what are the closest analogues? I've found a few examples, > e.g. for an abstract class the following page has a fairly common > suggestion: > > http://www.norvig.com/python-iaq.html Interfaces are generally implicit in Python. For example the docs will sometimes talk about 'file-like objects' which are just objects that implement the same interface as a file object. 'iterable', 'iterator', 'sequence' and 'mapping' are similarly defined by convention or by explicit documentation but not in the language itself. For example the 'iterator protocol' is defined here: http://docs.python.org/lib/typeiter.html To define an abstract method I just raise NotImplementedError in the body of the method. There are a couple of more formalized ways to add support for explicit type requirments to the language. This is a little different from what you asked - these projects allow a client of an object to specify an interface (or protocol) that must be supported by the object. PyProtocols http://peak.telecommunity.com/PyProtocols.html Zope Interfaces http://www.zope.org/Wikis/Interfaces/FrontPage PEP 246 formalizes this notion. It seems to be slated for inclusion in Python 2.5. http://www.python.org/peps/pep-0246.html Kent -- http://www.kentsjohnson.com From kent37 at tds.net Sun Nov 6 18:47:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 12:47:21 -0500 Subject: [Tutor] Dictionary Error: 'dict' object has no attribute '_contains_' In-Reply-To: References: Message-ID: <436E41A9.7040703@tds.net> Trent Rigsbee wrote: > Hi! I'm on the version 2.4, going through Beginning Python (Wrox), and I'm > getting the above error. I'm trying to do this: > > menu_specials._contains_("test") > > Any ideas on what I'm doing wrong? Thanks! The name of the method is __contains__ (note *double* leading and trailing underscores). But you normally shouldn't call this directly, you should write "test" in menu_specials instead. In general the methods and atttributes whose names start and end with double underscores are special to the language (in fact they are called 'special methods') and they are rarely called by code you write. They are hooks that let the author of a class define its behaviour. In this case, the __contains__() method is created to define how a dict object tests for membership. Kent -- http://www.kentsjohnson.com From smiles at worksmail.net Sun Nov 6 20:20:47 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Sun, 6 Nov 2005 13:20:47 -0600 Subject: [Tutor] overlay Message-ID: <000401c5e307$58a17660$e32c4fca@csmith> | From: Shi Mu | Is there any sample code to calculate the overlaid area between two | polygons? | Thanks! | The polygon module at ( http://www.dezentral.de/warp.html?http://www.dezentral.de/soft/Polygon/ ) was found by googling for "polygon module python". If by "overlay" you mean the area in common between two polygons, it can handle this: ### >>> import Polygon >>> a=Polygon.Polygon(((0.,0.),(1.,0.),(0.,1.))) #it closes automatically back to starting pt >>> b=Polygon.Polygon(((0.,0.),(1.,0.),(1.,1.))) >>> c = a & b >>> Polygon.pointList(c) [(1.0, 0.0), (0.0, 0.0), (0.5, 0.5)] >>> c.area() 0.25 >>> ### Note: the pdf docs did not appear to be included in the download from the page cited above; there is a link on the page cited above that downloads it for you. HTH, /c From alan.gauld at freenet.co.uk Sun Nov 6 20:43:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Nov 2005 19:43:09 -0000 Subject: [Tutor] Dictionary Error: 'dict' object has no attribute '_contains_' References: Message-ID: <014b01c5e30a$511efa90$0a01a8c0@xp> > Hi! I'm on the version 2.4, going through Beginning Python (Wrox), and > I'm getting the above error. I'm trying to do this: > > menu_specials._contains_("test") > > Any ideas on what I'm doing wrong? Thanks! It looks like you may be reading the wrong book! Why they would suggest you ever execute that code I have no idea, using the has_key() method is the normal way to do that. However, if you really want to call contains() it has two underscores on each side. This is a standard Python idiom for naming functions which you are *not* expected to call directly. Occasionally you do need to do so but never as a beginner! Hence why is "Beginning Python" even telling you about them? The purpose of the __contains__ () function is to allow you to modify the behaviour of the has_key() method (which does call __contains__() ) should you define your own dictionary type, you should not have to call it directly. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Nov 6 20:47:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Nov 2005 19:47:20 -0000 Subject: [Tutor] saving project References: <4384922E.6050405@kebikec.net> Message-ID: <014f01c5e30a$e6651710$0a01a8c0@xp> > Firstly I am a new programmer on python. I am using Python 2.4.1 > with IDLE 1.1.1 Welcome to the tutor list! > I can't save my poject in my computer. how can I save my projects and > in which format I must save my projects. Provided you have typed your code into a new editor window - by selecting File->New fromthe menus. Then File->Save As... should save the programme You can save the session from the interactive prompt too by doing the same thing, but it doesn't really help since there is no way to reload it again - I keep meaning to try to write a filter to allow that! Basically treat the >>> prompt as a scratch pad for ideas that will be thrown away. Anything you want to save has to be typed into a python programme file. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Nov 6 20:50:40 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Nov 2005 19:50:40 -0000 Subject: [Tutor] Dictionary Error: 'dict' object has noattribute '_contains_' References: <436E41A9.7040703@tds.net> Message-ID: <015501c5e30b$5df61180$0a01a8c0@xp> > But you normally shouldn't call this directly, you should write > "test" in menu_specials Now howzabout that! Yet another new trick learnt. When did 'in' start working with dictionaries? Alan G. From Liam.Clarke-Hutchinson at business.govt.nz Sun Nov 6 21:05:44 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Mon, 7 Nov 2005 09:05:44 +1300 Subject: [Tutor] Dictionary Error: 'dict' object has noattribute '_con tains_' Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1367@chbnt01.alpha.wd.govt.nz> I believe around Python 2.2... I used to want that syntax when I started, now I stick to for x in y.keys() - The 'explicit > implicit' concept has become important to me; probably because I do most of my coding after midnight and the "should really be in bed" mistakes are bad enough, but adding implicitness in any form tends to increase my time to debug. I'm learning C at the moment, which has a degree of implicitness that could bite me; ditto C#. Regards, Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces+ml.cyresse=gmail.com at python.org [mailto:tutor-bounces+ml.cyresse=gmail.com at python.org] On Behalf Of Alan Gauld Sent: Monday, 7 November 2005 8:51 a.m. To: Kent Johnson Cc: tutor at python.org Subject: Re: [Tutor] Dictionary Error: 'dict' object has noattribute '_contains_' > But you normally shouldn't call this directly, you should write > "test" in menu_specials Now howzabout that! Yet another new trick learnt. When did 'in' start working with dictionaries? Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From kent37 at tds.net Sun Nov 6 21:05:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 15:05:55 -0500 Subject: [Tutor] Dictionary Error: 'dict' object has noattribute '_contains_' In-Reply-To: <015501c5e30b$5df61180$0a01a8c0@xp> References: <436E41A9.7040703@tds.net> <015501c5e30b$5df61180$0a01a8c0@xp> Message-ID: <436E6223.9060901@tds.net> Alan Gauld wrote: >> But you normally shouldn't call this directly, you should write >> "test" in menu_specials > > > Now howzabout that! Yet another new trick learnt. > When did 'in' start working with dictionaries? Oh, about four years ago :-) in Python 2.2 You really should read the "What's New in Python x.x" docs ;) Kent -- http://www.kentsjohnson.com From samrobertsmith at gmail.com Sun Nov 6 22:33:22 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 13:33:22 -0800 Subject: [Tutor] draw lines Message-ID: <1d987df30511061333y74798341w30e67f31968a56d1@mail.gmail.com> I have a list of random points: [[x0,y0],[x1,y1],...,[xn,yn]] how can I use Tkinter to draw lines to connect them one by one based on the order in the list? Thanks a lot! From john at fouhy.net Sun Nov 6 22:41:46 2005 From: john at fouhy.net (John Fouhy) Date: Mon, 7 Nov 2005 10:41:46 +1300 Subject: [Tutor] draw lines In-Reply-To: <1d987df30511061333y74798341w30e67f31968a56d1@mail.gmail.com> References: <1d987df30511061333y74798341w30e67f31968a56d1@mail.gmail.com> Message-ID: <5e58f2e40511061341l4873542cg@mail.gmail.com> On 07/11/05, Shi Mu wrote: > I have a list of random points: > [[x0,y0],[x1,y1],...,[xn,yn]] > how can I use Tkinter to draw lines to connect them one by one based > on the order in the list? You need to use a Tkinter.Canvas. Have a look at Fredrik Lundh's site: http://effbot.org/tkinterbook/canvas.htm -- John. From dyoo at hkn.eecs.berkeley.edu Sun Nov 6 22:52:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Nov 2005 13:52:04 -0800 (PST) Subject: [Tutor] draw lines In-Reply-To: <1d987df30511061333y74798341w30e67f31968a56d1@mail.gmail.com> Message-ID: On Sun, 6 Nov 2005, Shi Mu wrote: > I have a list of random points: [[x0,y0],[x1,y1],...,[xn,yn]] how can I > use Tkinter to draw lines to connect them one by one based on the order > in the list? Do you know how to draw a single line in Tkinter? Have you looked at the Canvas widget documentation? http://www.pythonware.com/library/tkinter/introduction/canvas.htm Next time, you may want to show us what you've done to try to solve the problem you have. For the past few questions, I have not been able to get an intuitive sense of why you're having trouble figuring out things from documentation. All I see right now is that you have some new requirement, and then you ask the Tutor list for help. It's the step in-between that is a mystery to me. Do you just get stuck, or do you try something to figure out what you don't know, or...? Do you know where to look for documentation on subjects like Tkinter? It's not that we don't like answering your questions, but we want to make sure you're learning how to find the answers for yourself too. Otherwise, we end up being a crutch and we do damage to your learning skills. From kent37 at tds.net Sun Nov 6 22:51:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 06 Nov 2005 16:51:59 -0500 Subject: [Tutor] draw lines In-Reply-To: <1d987df30511061333y74798341w30e67f31968a56d1@mail.gmail.com> References: <1d987df30511061333y74798341w30e67f31968a56d1@mail.gmail.com> Message-ID: <436E7AFF.4040200@tds.net> Shi Mu wrote: > I have a list of random points: > [[x0,y0],[x1,y1],...,[xn,yn]] > how can I use Tkinter to draw lines to connect them one by one based > on the order in the list? You can use a Canvas widget to draw lines. You will probably have to scale your coordinates to match the coordinates of the screen. Kent -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Sun Nov 6 23:01:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Nov 2005 22:01:23 -0000 Subject: [Tutor] Dictionary Error: 'dict' object has noattribute '_contains_' References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1367@chbnt01.alpha.wd.govt.nz> Message-ID: <015d01c5e31d$a0cfb210$0a01a8c0@xp> > I used to want that syntax when I started, now I stick to for x in > y.keys() I knew you could do for item in dictionary: instead of for item in dictionary.keys(): But I didn't realise it worked for a single item test too if item in dictionary instead of if dictionary.has_key(item): While the loop is probably as easy to read either way the test is much cleaner using 'in'. Nice. Alan g. From falcon3166 at hotmail.com Sun Nov 6 23:29:06 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 6 Nov 2005 15:29:06 -0700 Subject: [Tutor] How I use images in a GUI? Message-ID: Hey all, I have a question that I can't figure out, despite reading the help and everything else. How do I use an image or images in a Graphic User Interface, and link them to parts of my code i.e. a picture of a game piece to its value? Thanks in advance, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051106/afbde31c/attachment.htm From alan.gauld at freenet.co.uk Sun Nov 6 23:30:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 6 Nov 2005 22:30:56 -0000 Subject: [Tutor] Dictionary Error: 'dict' object hasnoattribute '_contains_' References: <436E41A9.7040703@tds.net> <015501c5e30b$5df61180$0a01a8c0@xp> <436E6223.9060901@tds.net> Message-ID: <017c01c5e321$c17874d0$0a01a8c0@xp> > Oh, about four years ago :-) in Python 2.2 > > You really should read the "What's New in Python x.x" docs ;) :-) Hmm, I usually skim them but pick up most of my info from this list because I rarely upgrade to the latest version right away - I only upgraded my XP box. to 2.4 a few weeks ago... Alan G. From Liam.Clarke-Hutchinson at business.govt.nz Sun Nov 6 23:47:11 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Mon, 7 Nov 2005 11:47:11 +1300 Subject: [Tutor] How I use images in a GUI? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1372@chbnt01.alpha.wd.govt.nz> Depends on your GUI toolkit and widget. For instance, in wxPython's wx.BitmapButton widget, there's a specific method to set the bitmap, and then the underlying C++ code interfaces with the GDI portion of the Win32 API and draws it for you. http://www.wxpython.org/docs/api/wx.BitmapButton-class.html I'm not too sure about Tkinter, but I assume it's the same way. With regards to games, I suggest you check out www.pygame.org , instead of trying to use a GUI framework as it makes basic game development very simple, whereas a GUI framework doesn't. Especially with adding images to shapes on screen. Regards, Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Nathan Pinno Sent: Monday, 7 November 2005 11:29 a.m. To: Tutor Mailing List Subject: [Tutor] How I use images in a GUI? Hey all, I have a question that I can't figure out, despite reading the help and everything else. How do I use an image or images in a Graphic User Interface, and link them to parts of my code i.e. a picture of a game piece to its value? Thanks in advance, Nathan Pinno A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/183f9bcf/attachment.html From ds-python-tutor at sidorof.com Mon Nov 7 01:20:16 2005 From: ds-python-tutor at sidorof.com (DS) Date: Sun, 06 Nov 2005 16:20:16 -0800 Subject: [Tutor] Object instances Message-ID: <436E9DC0.4050801@sidorof.com> I had thought I was developing a clue regarding objects in Python, but I ran across an oddity today that I didn't expect. It had seemed to me that once an instance was created, it would have a separate data pool from any other instance of the same object. It would share methods, of course, but the data assigned to it would be totally separate. After running into peculiar errors I now see how this is not totally true, but I would like to understand why not. I think I'm missing something kind of fundamental here. The following is my toy example: In [1]: class test(object): ...: testlist = [] ...: In [2]: c1 = test() In [3]: c1.testlist.append(0) In [4]: c2 = test() In [5]: c2.testlist Out[5]: [0] In this example, I create two instances of the object test, assigned data to c1.testlist and it shows up in the other instance, c2. Typically, I have been assigning values within an object from being passed in via __init__, but it seemed like it wasn't really necessary for this particular kind of object. In my next example, I show the creation of testlist via an __init__ and all goes as I expected. In [10]: class test(object): ....: def __init__(self): ....: self.testlist = [] ....: In [11]: c1 = test() In [12]: c2 = test() In [13]: c1.testlist.append(0) In [14]: c2.testlist Out[14]: [] So, I can see the error of my ways. I can also see that this behavior gives me an opportunity to globally change a value in all of the object instances, if I ever had to do something like that. I just don't have a clue as to why objects were designed this way. Can anyone point me in the right direction? Thanks ds From Liam.Clarke-Hutchinson at business.govt.nz Mon Nov 7 01:29:19 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Mon, 7 Nov 2005 13:29:19 +1300 Subject: [Tutor] Object instances Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1374@chbnt01.alpha.wd.govt.nz> Hi DS, I'm not sure what language you've dealt with before, but if it was Java or C++, then you've run into Python's variant of static members. class X(object): classMember = True def __init__(self): self.instanceMember = True Does that make it any clearer? As to the why, I'd ask Guido Van Rossum. ;) -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of DS Sent: Monday, 7 November 2005 1:20 p.m. To: tutor at python.org Subject: [Tutor] Object instances I had thought I was developing a clue regarding objects in Python, but I ran across an oddity today that I didn't expect. It had seemed to me that once an instance was created, it would have a separate data pool from any other instance of the same object. It would share methods, of course, but the data assigned to it would be totally separate. After running into peculiar errors I now see how this is not totally true, but I would like to understand why not. I think I'm missing something kind of fundamental here. The following is my toy example: In [1]: class test(object): ...: testlist = [] ...: In [2]: c1 = test() In [3]: c1.testlist.append(0) In [4]: c2 = test() In [5]: c2.testlist Out[5]: [0] In this example, I create two instances of the object test, assigned data to c1.testlist and it shows up in the other instance, c2. Typically, I have been assigning values within an object from being passed in via __init__, but it seemed like it wasn't really necessary for this particular kind of object. In my next example, I show the creation of testlist via an __init__ and all goes as I expected. In [10]: class test(object): ....: def __init__(self): ....: self.testlist = [] ....: In [11]: c1 = test() In [12]: c2 = test() In [13]: c1.testlist.append(0) In [14]: c2.testlist Out[14]: [] So, I can see the error of my ways. I can also see that this behavior gives me an opportunity to globally change a value in all of the object instances, if I ever had to do something like that. I just don't have a clue as to why objects were designed this way. Can anyone point me in the right direction? Thanks ds _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From john at fouhy.net Mon Nov 7 01:43:41 2005 From: john at fouhy.net (John Fouhy) Date: Mon, 7 Nov 2005 13:43:41 +1300 Subject: [Tutor] Object instances In-Reply-To: <436E9DC0.4050801@sidorof.com> References: <436E9DC0.4050801@sidorof.com> Message-ID: <5e58f2e40511061643s409b114ej@mail.gmail.com> On 07/11/05, DS wrote: > So, I can see the error of my ways. I can also see that this behavior > gives me an opportunity to globally change a value in all of the object > instances, if I ever had to do something like that. I just don't have a > clue as to why objects were designed this way. > > Can anyone point me in the right direction? The difference is between class objects and class instances. When you say "class Foo: ...", you are creating a class object. When you call a class object, you create an instance of that class. Let's have a look: >>> class Foo(object): ... testList = [] ... print 'Foo class object being created now!' ... def __init__(self): ... self.testList2 = [] ... print 'Foo instance being initialised now!' ... Foo class object being created now! >>> Foo When I hit , the python interpreted executed the class definition. This is why it printed out "Foo class object being created now!". This is also when it executed "testList = []". testList is an attribute of Foo: >>> Foo.testList [] >>> Foo.testList.append(5) >>> Foo.testList [5] On the other hand, the code in Foo.__init__ did not execute. That code will only execute when we create an instance of Foo. So, Foo has no testList2 attribute, because "self.testList2 = []" only happens in __init__. >>> Foo.testList2 Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'Foo' has no attribute 'testList2' We can create an instance in the usual way, by calling the class object: >>> f = Foo() Foo instance being initialised now! Now, we can get at testList2. >>> f.testList2 [] We can also get at testList in the same way --- but testList belongs to the class, not the instance. >>> f.testList [5] >>> f.testList is f.__class__.testList is Foo.testList True I guess the same thing happens with methods --- that there is only one copy of each method --- but you don't notice, becuase when you call a method on an instance, it gets passed the instance as the first parameter. Hope this helps! -- John. From falcon3166 at hotmail.com Mon Nov 7 02:22:27 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 6 Nov 2005 18:22:27 -0700 Subject: [Tutor] How I use images in a GUI? References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1372@chbnt01.alpha.wd.govt.nz> Message-ID: MessageLiam, I am using Pygame, but I am still don't know how to use it. I read it, and it confused me. ----- Original Message ----- From: Liam Clarke-Hutchinson To: 'Nathan Pinno' Cc: 'tutor at python.org' Sent: November 6, 2005 3:47 PM Subject: RE: [Tutor] How I use images in a GUI? Depends on your GUI toolkit and widget. For instance, in wxPython's wx.BitmapButton widget, there's a specific method to set the bitmap, and then the underlying C++ code interfaces with the GDI portion of the Win32 API and draws it for you. http://www.wxpython.org/docs/api/wx.BitmapButton-class.html I'm not too sure about Tkinter, but I assume it's the same way. With regards to games, I suggest you check out www.pygame.org, instead of trying to use a GUI framework as it makes basic game development very simple, whereas a GUI framework doesn't. Especially with adding images to shapes on screen. Regards, Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Nathan Pinno Sent: Monday, 7 November 2005 11:29 a.m. To: Tutor Mailing List Subject: [Tutor] How I use images in a GUI? Hey all, I have a question that I can't figure out, despite reading the help and everything else. How do I use an image or images in a Graphic User Interface, and link them to parts of my code i.e. a picture of a game piece to its value? Thanks in advance, Nathan Pinno A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services ------------------------------------------------------------------------------ Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ------------------------------------------------------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051106/45e9a0cb/attachment-0001.html From samrobertsmith at gmail.com Mon Nov 7 02:53:50 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 17:53:50 -0800 Subject: [Tutor] click and line Message-ID: <1d987df30511061753h1b3a2212h2a45c887c2c2bf23@mail.gmail.com> I tried to write the follwoing code to draw lines on the anvas based on the clicked points but retur the message: >>> 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 "C:\Python23\test\Q_line.py", line 13, in ? l5=c.create_line(m1,n1,event.x,event.y,fill='blue',width='50') NameError: name 'm1' is not defined The ocde migth be naive,... from Tkinter import * root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) def click(event): print event.x, event.y m1=event.x n1=event.y frame = c c.bind('',click) l5=c.create_line(m1,n1,event.x,event.y,fill='blue',width='50') c.pack() root.mainloop() From dyoo at hkn.eecs.berkeley.edu Mon Nov 7 04:21:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 6 Nov 2005 19:21:22 -0800 (PST) Subject: [Tutor] click and line In-Reply-To: <1d987df30511061753h1b3a2212h2a45c887c2c2bf23@mail.gmail.com> Message-ID: Hi Shi Mu, Let's look at click(): ########################## def click(event): print event.x, event.y m1=event.x n1=event.y ########################## By default, variable names in functions are local. Do you know about local vs global variables? The assignments to m1 and n1 won't be remembered once we come out of the click() function. It sounds like you want a function-like thing that remembers the very last event we passed to it before. One way to do this is to use globals, because globals last beyond function calls. For example: ###### >>> n = None >>> def lastNumber(x): ... global n ... print "I last saw", n ... n = x ... >>> lastNumber(42) I last saw None >>> lastNumber(17) I last saw 42 >>> lastNumber(3) I last saw 17 ###### So for something very simple, using a global will probably be easiest. However, there are other approaches that don't use globals. One that fits Python's model well is to use a class instance, since instances can store state: ###### >>> class LastNumber: ... def __init__(self): ... self.n = None ... def getAndSet(self, x): ... value = self.n ... self.n = x ... return value ... >>> last = LastNumber() >>> last.getAndSet(42) >>> last.getAndSet(3) 42 >>> last.getAndSet(7) 3 >>> last.getAndSet(9) 7 ###### Does this make sense? Please feel free to ask questions here. From samrobertsmith at gmail.com Mon Nov 7 04:44:53 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 19:44:53 -0800 Subject: [Tutor] click and line In-Reply-To: References: <1d987df30511061753h1b3a2212h2a45c887c2c2bf23@mail.gmail.com> Message-ID: <1d987df30511061944j7fda28e9l5864150988459fd8@mail.gmail.com> based on the following rewritten code, why the lines still can not be drawn? (there is no error report and the canvas appears). from Tkinter import * root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) lastX="" lastY="" def click(event): global lastX, lastY if lastX != "": c.create_line(lastX,lastY,event.x,event.y,fill="white") lastX = event.x lastY = event.y frame = c c.bind('',click) c.pack() root.mainloop() On 11/6/05, Danny Yoo wrote: > > Hi Shi Mu, > > Let's look at click(): > > ########################## > def click(event): > print event.x, event.y > m1=event.x > n1=event.y > ########################## > > By default, variable names in functions are local. Do you know about > local vs global variables? The assignments to m1 and n1 won't be > remembered once we come out of the click() function. > > > It sounds like you want a function-like thing that remembers the very last > event we passed to it before. One way to do this is to use globals, > because globals last beyond function calls. > > For example: > > ###### > >>> n = None > >>> def lastNumber(x): > ... global n > ... print "I last saw", n > ... n = x > ... > >>> lastNumber(42) > I last saw None > >>> lastNumber(17) > I last saw 42 > >>> lastNumber(3) > I last saw 17 > ###### > > So for something very simple, using a global will probably be easiest. > > > However, there are other approaches that don't use globals. One that fits > Python's model well is to use a class instance, since instances can store > state: > > ###### > >>> class LastNumber: > ... def __init__(self): > ... self.n = None > ... def getAndSet(self, x): > ... value = self.n > ... self.n = x > ... return value > ... > >>> last = LastNumber() > >>> last.getAndSet(42) > >>> last.getAndSet(3) > 42 > >>> last.getAndSet(7) > 3 > >>> last.getAndSet(9) > 7 > ###### > > > Does this make sense? Please feel free to ask questions here. > > From samrobertsmith at gmail.com Mon Nov 7 04:52:06 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 19:52:06 -0800 Subject: [Tutor] click and line In-Reply-To: <1d987df30511061944j7fda28e9l5864150988459fd8@mail.gmail.com> References: <1d987df30511061753h1b3a2212h2a45c887c2c2bf23@mail.gmail.com> <1d987df30511061944j7fda28e9l5864150988459fd8@mail.gmail.com> Message-ID: <1d987df30511061952r12d2f08eyc0b1c1d4a3472669@mail.gmail.com> it works now. from Tkinter import * root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) frame = c lastX="" lastY="" def click(event): global lastX, lastY if lastX != "": c.create_line(lastX,lastY,event.x,event.y,fill="white") lastX = event.x lastY = event.y c.bind('',click) c.pack() root.mainloop() On 11/6/05, Shi Mu wrote: > based on the following rewritten code, why the lines still can not be > drawn? (there is no error report and the canvas appears). > > from Tkinter import * > > root = Tk() > > c = Canvas(root, bg='#0e2e0e', height=500, width=1000) > > lastX="" > lastY="" > def click(event): > global lastX, lastY > if lastX != "": > c.create_line(lastX,lastY,event.x,event.y,fill="white") > lastX = event.x > lastY = event.y > > frame = c > c.bind('',click) > > c.pack() > > root.mainloop() > > On 11/6/05, Danny Yoo wrote: > > > > Hi Shi Mu, > > > > Let's look at click(): > > > > ########################## > > def click(event): > > print event.x, event.y > > m1=event.x > > n1=event.y > > ########################## > > > > By default, variable names in functions are local. Do you know about > > local vs global variables? The assignments to m1 and n1 won't be > > remembered once we come out of the click() function. > > > > > > It sounds like you want a function-like thing that remembers the very last > > event we passed to it before. One way to do this is to use globals, > > because globals last beyond function calls. > > > > For example: > > > > ###### > > >>> n = None > > >>> def lastNumber(x): > > ... global n > > ... print "I last saw", n > > ... n = x > > ... > > >>> lastNumber(42) > > I last saw None > > >>> lastNumber(17) > > I last saw 42 > > >>> lastNumber(3) > > I last saw 17 > > ###### > > > > So for something very simple, using a global will probably be easiest. > > > > > > However, there are other approaches that don't use globals. One that fits > > Python's model well is to use a class instance, since instances can store > > state: > > > > ###### > > >>> class LastNumber: > > ... def __init__(self): > > ... self.n = None > > ... def getAndSet(self, x): > > ... value = self.n > > ... self.n = x > > ... return value > > ... > > >>> last = LastNumber() > > >>> last.getAndSet(42) > > >>> last.getAndSet(3) > > 42 > > >>> last.getAndSet(7) > > 3 > > >>> last.getAndSet(9) > > 7 > > ###### > > > > > > Does this make sense? Please feel free to ask questions here. > > > > > From Liam.Clarke-Hutchinson at business.govt.nz Mon Nov 7 05:07:26 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Mon, 7 Nov 2005 17:07:26 +1300 Subject: [Tutor] Pygame - was How I use images in a GUI? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B137C@chbnt01.alpha.wd.govt.nz> Hi Nathan, Pygame is a little confusing at first, but it makes sense one you can get the hang of the basics. http://www.pygame.org/docs/tut/intro/intro.html is a good example. import sys, pygame pygame.init() size = width, height = (320, 240) speed = [2, 2] black = (0, 0, 0) screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.bmp") ballrect = ball.get_rect() That's the basic ingredients of a Pygame app right there. screen is the base window that all your drawing will occur on. !A caveat here is that (0,0) on computer screens tends to be the top left corner, with y increasing downwards.! ball is a Surface which is painted with the image at http://www.pygame.org/docs/tut/intro/ball.gif . ballrect is a Rect object which is rectangular and matches the size of the ball (as much as a rectangle can.) Rects and Surfaces are the key to Pygame. If you had a pygame app where two cars crashed into each other, all movement and collision detection is being done with two rects, which have a car drawn on top of them via a Surface. You can of course, use many smaller rects, to give more accurate collision detection. i.e. for a stick figure, you could have one rectangle which was matched the height and width of the whole stick figure. Or, you could have one for each arm, one for each leg, one for the body and one for the head, which would allow for more accurate collision checking. If you've ever played a fps and shot someone in the head and blood came out of their body, then you've met rects in action, and not quite working properly too. I tried having 786,432 rects at one point, each one was one pixel in size. Didn't work overly well. Surfaces are images/colours/textures etc. I consider it like this, the rect is an invisible wireframe, the surface is the nice shiny textures and colours all over it. OK, to continue with the Pygame tutorial - ---- while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip() --------------------------------- for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() So once the set up is done, Pygame goes into an infinite loop. Once per loop, it checks for a Pygame event of type QUIT. Pygame handles events a bit like a GUI, in that it has a queue, but programmes need to specifically check for events as opposed to using event handlers - it's a game, so you can focus on events that are important to you. ;) ballrect = ballrect.move(speed) Ok, so now it's moving ballrect. If you have a look at http://www.pygame.org/docs/ref/rect.html there's a lot of methods which basically equate to moving/resizing/colliding the Rect. The command Rect.move() has the following syntax - Rect.move(x, y): return Rect Game programming involves a fair bit of physics. At the most basic, you'll get to deal with vectors. So, ballrect = ballrect.move((2,2)) returns a new Rect two pixels to the right, and two pixels downward. OK, so, ballrect has moved 2 down and 2 across. if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] ballrect.left, ballrect.right, top, bottom etc. are the edges of ballrect. So, this is checking to see if it has exceeded the limits of the screen. Now, this is very simple collision checking. A fun exercise is to add a second ball, and check once per loop using Rect.colliderect(otherRect) to see if they just hit. OK, so if ballrect.left is less than 0, or ballrect.right is greater than the 320, then the horizontal vector is inverted. So a movement of 5 becomes -5, which would start moving left. Likewise, if it was -5 then it would become -(-5) which is 5. Ditto also with top and bottom, except that -y is moving upwards towards 0, and y is moving downwards 240. Remember, 0,0 is top left. I had to stick a note to my screen with that on it. OK now to the last bit of code - screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip() Ok, so, ballrect has been moved to the new position, so we need to remove the old drawing of ballrect, and redraw the ball at the new position, to simulate movement; like a cartoon. screen.fill(black) fills the main screen with a solid colour, which over-writes the old drawing of the ball. screen.blit(ball, ballrect) then draws the image of the ball onto the frame of the ballrect. Lastly, pygame.display.flip() 'flips' the display. When you're looking at one frame, pygame is busy drawing the screen in memory. When you call flip() it swaps the screen your viewing into memory, and replaces it with the freshly drawn one. This makes sures that your user doesn't see the actual redrawing occur. This is a very basic intro, but have a play with it. Copying and pasting the above linked tutorial and modifying it is how I learnt. Add another ball, and add collision detection between it and the first ball. Make them double their speed when they hit one wall and halve it when they hit another... Good luck, Liam Clarke-Hutchinson -----Original Message----- From: Nathan Pinno [mailto:falcon3166 at hotmail.com] Sent: Monday, 7 November 2005 2:22 p.m. To: Liam Clarke-Hutchinson Cc: tutor at python.org Subject: Re: [Tutor] How I use images in a GUI? Liam, I am using Pygame, but I am still don't know how to use it. I read it, and it confused me. ----- Original Message ----- From: Liam Clarke-Hutchinson To: 'Nathan Pinno' Cc: 'tutor at python.org' Sent: November 6, 2005 3:47 PM Subject: RE: [Tutor] How I use images in a GUI? Depends on your GUI toolkit and widget. For instance, in wxPython's wx.BitmapButton widget, there's a specific method to set the bitmap, and then the underlying C++ code interfaces with the GDI portion of the Win32 API and draws it for you. http://www.wxpython.org/docs/api/wx.BitmapButton-class.html I'm not too sure about Tkinter, but I assume it's the same way. With regards to games, I suggest you check out www.pygame.org , instead of trying to use a GUI framework as it makes basic game development very simple, whereas a GUI framework doesn't. Especially with adding images to shapes on screen. Regards, Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Nathan Pinno Sent: Monday, 7 November 2005 11:29 a.m. To: Tutor Mailing List Subject: [Tutor] How I use images in a GUI? Hey all, I have a question that I can't figure out, despite reading the help and everything else. How do I use an image or images in a Graphic User Interface, and link them to parts of my code i.e. a picture of a game piece to its value? Thanks in advance, Nathan Pinno A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services _____ Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. _____ A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/80074d3c/attachment-0001.htm From alan.gauld at freenet.co.uk Mon Nov 7 05:33:35 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Nov 2005 04:33:35 -0000 Subject: [Tutor] Object instances References: <436E9DC0.4050801@sidorof.com> Message-ID: <019b01c5e354$6ae44530$0a01a8c0@xp> >I had thought I was developing a clue regarding objects in Python, but I > ran across an oddity today that I didn't expect. It had seemed to me > that once an instance was created, it would have a separate data pool > from any other instance of the same object. And this is true... > It would share methods, of course, but the data assigned to it would > be totally separate. The data assigned top the instance is separate but you can also assign data to classes. Such data is stored in "class variables". Class variables are shared by all instances and indeed can be accessed even when no instances exist. Methods are a special type of class variable. This all comes under the black art known as "Meta Programming". > I would like to understand why not. I think I'm missing something kind > of fundamental here. Its very useful to know things about the class as an entirety. For example a class variable can be used to keep track of the total number of instances alive at any one time, or of standard lists of values that are valid for a variable type (subsets of colors or max/min range values etc) > The following is my toy example: > In [1]: class test(object): > ...: testlist = [] This is a class variable because its not distinguished by self (self is unique to each instance). > In [2]: c1 = test() > > In [3]: c1.testlist.append(0) > > In [4]: c2 = test() > > In [5]: c2.testlist > Out[5]: [0] > In this example, I create two instances of the object test, assigned > data to c1.testlist and it shows up in the other instance, c2. But you can also override that with c2.testlist = [1,2,3] c1.testlist [0] c2.testlist [1,2,3] c3 = test() c3.testlist [0] So now c2 has its own copy of testlist... > Typically, I have been assigning values within an object from being > passed in via __init__, but it seemed like it wasn't really necessary > for this particular kind of object. It is if you want the values to be instance specific. > In [10]: class test(object): > ....: def __init__(self): > ....: self.testlist = [] Now you are creating instance variables by assigning them with self. > instances, if I ever had to do something like that. I just don't have a > clue as to why objects were designed this way. Look up class variables (and static varoiables - their name in C++ and some other languages) on Google or http://www.cetus-links.org HTH< Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Nov 7 05:35:40 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 7 Nov 2005 04:35:40 -0000 Subject: [Tutor] Object instances References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1374@chbnt01.alpha.wd.govt.nz> Message-ID: <019f01c5e354$b52eac20$0a01a8c0@xp> > I'm not sure what language you've dealt with before, but if it was Java or > C++, then you've run into Python's variant of static members. > > class X(object): > classMember = True > > def __init__(self): > self.instanceMember = True > > > Does that make it any clearer? As to the why, I'd ask Guido Van Rossum. ;) Its a standard feature of the Object Model of programming. Virtally all OOP systems provide a mechanism for setting class level attributes. Alan G. From cfaj at freeshell.org Mon Nov 7 05:43:08 2005 From: cfaj at freeshell.org (Chris F.A. Johnson) Date: Sun, 6 Nov 2005 23:43:08 -0500 (EST) Subject: [Tutor] click and line In-Reply-To: <1d987df30511061944j7fda28e9l5864150988459fd8@mail.gmail.com> References: <1d987df30511061753h1b3a2212h2a45c887c2c2bf23@mail.gmail.com> <1d987df30511061944j7fda28e9l5864150988459fd8@mail.gmail.com> Message-ID: On Sun, 6 Nov 2005, Shi Mu wrote: > based on the following rewritten code, why the lines still can not be > drawn? (there is no error report and the canvas appears). It works for me. > from Tkinter import * > > root = Tk() > > c = Canvas(root, bg='#0e2e0e', height=500, width=1000) > > lastX="" > lastY="" > def click(event): > global lastX, lastY > if lastX != "": > c.create_line(lastX,lastY,event.x,event.y,fill="white") > lastX = event.x > lastY = event.y > > frame = c > c.bind('',click) > > c.pack() > > root.mainloop() -- Chris F.A. Johnson ================================================================== Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress From samrobertsmith at gmail.com Mon Nov 7 05:47:38 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 20:47:38 -0800 Subject: [Tutor] click and line In-Reply-To: References: <1d987df30511061753h1b3a2212h2a45c887c2c2bf23@mail.gmail.com> <1d987df30511061944j7fda28e9l5864150988459fd8@mail.gmail.com> Message-ID: <1d987df30511062047n5f17d66ft42331ae9486e7992@mail.gmail.com> frame = c needs to be put before the click function or the lines can not be drawn. On 11/6/05, Chris F.A. Johnson wrote: > On Sun, 6 Nov 2005, Shi Mu wrote: > > > based on the following rewritten code, why the lines still can not be > > drawn? (there is no error report and the canvas appears). > > It works for me. > > > > from Tkinter import * > > > > root = Tk() > > > > c = Canvas(root, bg='#0e2e0e', height=500, width=1000) > > > > lastX="" > > lastY="" > > def click(event): > > global lastX, lastY > > if lastX != "": > > c.create_line(lastX,lastY,event.x,event.y,fill="white") > > lastX = event.x > > lastY = event.y > > > > frame = c > > c.bind('',click) > > > > c.pack() > > > > root.mainloop() > > -- > Chris F.A. Johnson > ================================================================== > Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress > > From cfaj at freeshell.org Mon Nov 7 06:27:23 2005 From: cfaj at freeshell.org (Chris F.A. Johnson) Date: Mon, 7 Nov 2005 00:27:23 -0500 (EST) Subject: [Tutor] click and line In-Reply-To: <1d987df30511062047n5f17d66ft42331ae9486e7992@mail.gmail.com> References: <1d987df30511061753h1b3a2212h2a45c887c2c2bf23@mail.gmail.com> <1d987df30511061944j7fda28e9l5864150988459fd8@mail.gmail.com> <1d987df30511062047n5f17d66ft42331ae9486e7992@mail.gmail.com> Message-ID: On Sun, 6 Nov 2005, Shi Mu wrote: > frame = c needs to be put before the click function or the lines can > not be drawn. Not at all. I have everything after the click function and it works. This is my version (includes a small addition): def click(event): global lastX, lastY if lastX != "": c.create_line(lastX,lastY,event.x,event.y,fill="white") lastX = event.x lastY = event.y def newline(event): global lastX, lastY lastX="" lastY="" from Tkinter import * lastX="" lastY="" root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) frame = c c.bind('',click) c.bind('',newline) c.pack() root.mainloop() > On 11/6/05, Chris F.A. Johnson wrote: >> On Sun, 6 Nov 2005, Shi Mu wrote: >> >>> based on the following rewritten code, why the lines still can not be >>> drawn? (there is no error report and the canvas appears). >> >> It works for me. >> >> >>> from Tkinter import * >>> >>> root = Tk() >>> >>> c = Canvas(root, bg='#0e2e0e', height=500, width=1000) >>> >>> lastX="" >>> lastY="" >>> def click(event): >>> global lastX, lastY >>> if lastX != "": >>> c.create_line(lastX,lastY,event.x,event.y,fill="white") >>> lastX = event.x >>> lastY = event.y >>> >>> frame = c >>> c.bind('',click) >>> >>> c.pack() >>> >>> root.mainloop() -- Chris F.A. Johnson ================================================================== Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress From samrobertsmith at gmail.com Mon Nov 7 07:03:25 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sun, 6 Nov 2005 22:03:25 -0800 Subject: [Tutor] no error no result Message-ID: <1d987df30511062203j7128b094q946aad92887b0398@mail.gmail.com> when I read some python sample codes. I found that several of them need "python -i" to run them or you will not get any result though the program does not report any error. I really can not understand it. Thanks! From samrobertsmith at gmail.com Mon Nov 7 09:02:51 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 7 Nov 2005 00:02:51 -0800 Subject: [Tutor] image Message-ID: <1d987df30511070002u231fc44dk4e90d7dd8c628777@mail.gmail.com> why the follwoing code report the error: 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 "C:\Python23\Examples\AppB\text.py", line 24, in ? text.image_create(END, image=photo) File "C:\Python23\lib\lib-tk\Tkinter.py", line 2882, in image_create return self.tk.call( TclError: image "pyimage4" doesn't exist from Tkinter import * root = Tk() root.option_readfile('optionDB') root.title('Text') text = Text(root, height=26, width=50) scroll = Scrollbar(root, command=text.yview) text.configure(yscrollcommand=scroll.set) text.tag_configure('bold_italics', font=('Verdana', 12, 'bold', 'italic')) text.tag_configure('big', font=('Verdana', 24, 'bold')) text.tag_configure('color', foreground='blue', font=('Tempus Sans ITC', 14)) text.tag_configure('groove', relief=GROOVE, borderwidth=2) text.tag_bind('bite', '<1>', lambda e, t=text: t.insert(END, "I'll bite your legs off!")) text.insert(END, 'Something up with my banter, chaps?\n') text.insert(END, 'Four hours to bury a cat?\n', 'bold_italics') text.insert(END, 'Can I call you "Frank"?\n', 'big') text.insert(END, "What's happening Thursday then?\n", 'color') text.insert(END, 'Did you write this symphony in the shed?\n', 'groove') button = Button(text, text='I do live at 46 Horton terrace') text.window_create(END, window=button) photo=PhotoImage(file='img52.gif') text.image_create(END, image=photo) text.insert(END, 'I dare you to click on this\n', 'bite') text.pack(side=LEFT) scroll.pack(side=RIGHT, fill=Y) root.mainloop() From dyoo at hkn.eecs.berkeley.edu Mon Nov 7 09:40:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Nov 2005 00:40:18 -0800 (PST) Subject: [Tutor] click and line In-Reply-To: <1d987df30511061952r12d2f08eyc0b1c1d4a3472669@mail.gmail.com> Message-ID: > it works now. Hi Shi Mu, Can you describe how you fixed it? The only diff between the two programs that I see is that you repositioned the setting of the frame variable. ################################# mumak:~ dyoo$ diff t1.txt t2.txt 6c6 < --- > frame = c 16c16 < frame = c --- > ################################# What makes the "fixed" code suspicious is that the 'frame' variable is useless in the sense that it doesn't do anything. And even if it did do something, the fix --- moving a variable definition around --- doesn't make sense to me. *grin* Try changing it back and see if the problem recurs. (I suspect that your first version also worked, but that you may have forgotten to save your file before testing it.) Best of wishes! From dyoo at hkn.eecs.berkeley.edu Mon Nov 7 09:45:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Nov 2005 00:45:02 -0800 (PST) Subject: [Tutor] no error no result In-Reply-To: <1d987df30511062203j7128b094q946aad92887b0398@mail.gmail.com> Message-ID: On Sun, 6 Nov 2005, Shi Mu wrote: > when I read some python sample codes. > I found that several of them need "python -i" to run them or you will > not get any result though the program does not report any error. > I really can not understand it. Hi Shi Mu, Ok, let's compare-and-constrast. Can you show us an example of a program that doesn't get a result? Can you show us a different example of a program that does get a result? From samrobertsmith at gmail.com Mon Nov 7 10:16:38 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 7 Nov 2005 01:16:38 -0800 Subject: [Tutor] click and line In-Reply-To: References: <1d987df30511061952r12d2f08eyc0b1c1d4a3472669@mail.gmail.com> Message-ID: <1d987df30511070116y2e92de85uc7fb0596f82593ff@mail.gmail.com> Danny, You are right. Thanks for your great patience and kindness. Shi On 11/7/05, Danny Yoo wrote: > > > > it works now. > > Hi Shi Mu, > > Can you describe how you fixed it? The only diff between the two programs > that I see is that you repositioned the setting of the frame variable. > > > ################################# > mumak:~ dyoo$ diff t1.txt t2.txt > 6c6 > < > --- > > frame = c > 16c16 > < frame = c > --- > > > ################################# > > What makes the "fixed" code suspicious is that the 'frame' variable is > useless in the sense that it doesn't do anything. And even if it did do > something, the fix --- moving a variable definition around --- doesn't > make sense to me. *grin* > > Try changing it back and see if the problem recurs. (I suspect that your > first version also worked, but that you may have forgotten to save your > file before testing it.) > > > Best of wishes! > > From samrobertsmith at gmail.com Mon Nov 7 10:29:56 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 7 Nov 2005 01:29:56 -0800 Subject: [Tutor] geometry Message-ID: <1d987df30511070129y7ab6bdb6oa11884b0a1a92ea5@mail.gmail.com> any python code for middle school geometry teaching use? for instance, calculate the polygon area size, overlaid area size? Thanks. From johan at accesstel.co.za Mon Nov 7 14:40:04 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 07 Nov 2005 15:40:04 +0200 Subject: [Tutor] Percentage Message-ID: <436F5934.20905@accesstel.co.za> Hi all, What is the syntax if I want to work out what percentage 42 is out of 250? TIA, From tubaranger at gmail.com Mon Nov 7 14:43:15 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Mon, 7 Nov 2005 07:43:15 -0600 Subject: [Tutor] Re; Geometry Message-ID: <57aa55060511070543i5e3e4ea2mddaf4d2b64edda5@mail.gmail.com> If there's not code for geometry, let's write some!! What, precisely, are you looking for? Or, better yet, do you have the resources to have you students write the code after teaching them "just enough" python? I did that with a physics class a few years ago and the students loved it! --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/2f240929/attachment.htm From godoy at ieee.org Mon Nov 7 14:50:05 2005 From: godoy at ieee.org (Jorge Godoy) Date: 07 Nov 2005 11:50:05 -0200 Subject: [Tutor] Percentage References: <436F5934.20905@accesstel.co.za> Message-ID: <87zmoga7oy.fsf@jupiter.g2ctech> Johan Geldenhuys writes: > What is the syntax if I want to work out what percentage 42 is out of 250? If you want it as a factor to multiply / divide by something: perc = 42/250 If you want it to "read" as percentage: perc_100 = (42/250)*100 Sds, -- Jorge Godoy From francis.moore at rawflow.com Mon Nov 7 14:58:14 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Mon, 07 Nov 2005 13:58:14 +0000 Subject: [Tutor] Percentage In-Reply-To: <436F5934.20905@accesstel.co.za> References: <436F5934.20905@accesstel.co.za> Message-ID: <436F5D76.2010309@rawflow.com> Johan Geldenhuys wrote: >Hi all, > >What is the syntax if I want to work out what percentage 42 is out of 250? > > Johan, You could try: percentage = (42 * 250)/100 This gives the answer 105. Cheers, F. From kent37 at tds.net Mon Nov 7 14:58:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 08:58:16 -0500 Subject: [Tutor] geometry In-Reply-To: <1d987df30511070129y7ab6bdb6oa11884b0a1a92ea5@mail.gmail.com> References: <1d987df30511070129y7ab6bdb6oa11884b0a1a92ea5@mail.gmail.com> Message-ID: <436F5D78.3030504@tds.net> Shi Mu wrote: > any python code for middle school geometry teaching use? > for instance, calculate the polygon area size, overlaid area size? You might be interested in PyGeo. I think it is more oriented toward visualization than calculation but it is definitely intended to aid in teaching geometry. http://pw1.netcom.com/~ajs/ Kent -- http://www.kentsjohnson.com From ajikoe at gmail.com Mon Nov 7 14:59:14 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 7 Nov 2005 14:59:14 +0100 Subject: [Tutor] Percentage In-Reply-To: <87zmoga7oy.fsf@jupiter.g2ctech> References: <436F5934.20905@accesstel.co.za> <87zmoga7oy.fsf@jupiter.g2ctech> Message-ID: don't forget to use dot or converge into float. perc = 42./250 or perc = float(42)/250 otherwise: it is treated as integer. pujo On 07 Nov 2005 11:50:05 -0200, Jorge Godoy wrote: > > Johan Geldenhuys writes: > > > What is the syntax if I want to work out what percentage 42 is out of > 250? > > If you want it as a factor to multiply / divide by something: > > perc = 42/250 > > If you want it to "read" as percentage: > > perc_100 = (42/250)*100 > > > Sds, > -- > Jorge Godoy > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/c12374fd/attachment.html From johan at accesstel.co.za Mon Nov 7 15:00:37 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 07 Nov 2005 16:00:37 +0200 Subject: [Tutor] Percentage In-Reply-To: <87zmoga7oy.fsf@jupiter.g2ctech> References: <436F5934.20905@accesstel.co.za> <87zmoga7oy.fsf@jupiter.g2ctech> Message-ID: <436F5E05.2010001@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/612612af/attachment.htm From johan at accesstel.co.za Mon Nov 7 15:02:43 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 07 Nov 2005 16:02:43 +0200 Subject: [Tutor] Percentage In-Reply-To: <436F5D76.2010309@rawflow.com> References: <436F5934.20905@accesstel.co.za> <436F5D76.2010309@rawflow.com> Message-ID: <436F5E83.4030502@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/38a2c46d/attachment.html From sanelson at gmail.com Mon Nov 7 15:04:06 2005 From: sanelson at gmail.com (Steve Nelson) Date: Mon, 7 Nov 2005 14:04:06 +0000 Subject: [Tutor] Percentage In-Reply-To: <87zmoga7oy.fsf@jupiter.g2ctech> References: <436F5934.20905@accesstel.co.za> <87zmoga7oy.fsf@jupiter.g2ctech> Message-ID: On 07 Nov 2005 11:50:05 -0200, Jorge Godoy wrote: > Johan Geldenhuys writes: > > > What is the syntax if I want to work out what percentage 42 is out of 250? > > If you want it as a factor to multiply / divide by something: > > perc = 42/250 Don't you need to specify one of these numbers as a float? >>> print 42/250 0 >>> print 42/250.0 0.168 I recall reading somewhere that all division would be 'true division' from >3.0 but this isn't the case in 2.x is it? > Jorge Godoy S. From godoy at ieee.org Mon Nov 7 15:14:03 2005 From: godoy at ieee.org (Jorge Godoy) Date: 07 Nov 2005 12:14:03 -0200 Subject: [Tutor] Percentage References: <436F5934.20905@accesstel.co.za> <436F5D76.2010309@rawflow.com> Message-ID: <87irv4a6l0.fsf@jupiter.g2ctech> Frank Moore writes: > Johan, > > You could try: > > percentage = (42 * 250)/100 > > This gives the answer 105. And that sounds weird, doesn't it? 42 is smaller than 250, so I'd expect it to be less than 100% of the value... In fact, it is >>> 42.0/250 0.16800000000000001 >>> (42.0/250)*100 16.800000000000001 >>> I suspect the problem is due to the fact that Python does integer division by default: >>> 42/250 0 >>> So, how to make it generic? >>> a = 42 >>> b = 250 >>> a / b 0 >>> float(a)/b 0.16800000000000001 >>> One of the members has to be a floating point so that floating point division is performed instead of integer division. Be seeing you, -- Jorge Godoy From godoy at ieee.org Mon Nov 7 15:18:10 2005 From: godoy at ieee.org (Jorge Godoy) Date: 07 Nov 2005 12:18:10 -0200 Subject: [Tutor] Percentage References: <436F5934.20905@accesstel.co.za> <87zmoga7oy.fsf@jupiter.g2ctech> Message-ID: <87d5lca6e5.fsf@jupiter.g2ctech> Steve Nelson writes: > Don't you need to specify one of these numbers as a float? You do. My mistake and I haven't seen both corrections before sending my last message. :-) > I recall reading somewhere that all division would be 'true division' > from >3.0 but this isn't the case in 2.x is it? There was also some kind of "from future import true division method" but I don't remember where I found it. Oh! Found it! http://mail.python.org/pipermail/python-dev/2001-July/016174.html >>> from __future__ import division >>> 42 / 250 0.16800000000000001 >>> Be seeing you, -- Jorge Godoy From ds-python-tutor at sidorof.com Mon Nov 7 15:28:58 2005 From: ds-python-tutor at sidorof.com (DS) Date: Mon, 07 Nov 2005 06:28:58 -0800 Subject: [Tutor] Object instances Message-ID: <436F64AA.7000700@sidorof.com> All right! That's penetrated. Thanks very much. ds From godoy at ieee.org Mon Nov 7 15:18:44 2005 From: godoy at ieee.org (Jorge Godoy) Date: 07 Nov 2005 12:18:44 -0200 Subject: [Tutor] Percentage References: <436F5934.20905@accesstel.co.za> <87zmoga7oy.fsf@jupiter.g2ctech> Message-ID: <877jbka6d7.fsf@jupiter.g2ctech> Pujo Aji writes: > don't forget to use dot or converge into float. Or import division from __future__. >>> from __future__ import division >>> 42 / 250 0.16800000000000001 >>> -- Jorge Godoy From ajikoe at gmail.com Mon Nov 7 16:05:14 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 7 Nov 2005 16:05:14 +0100 Subject: [Tutor] Percentage In-Reply-To: <877jbka6d7.fsf@jupiter.g2ctech> References: <436F5934.20905@accesstel.co.za> <87zmoga7oy.fsf@jupiter.g2ctech> <877jbka6d7.fsf@jupiter.g2ctech> Message-ID: nice syntax..... Cheers, pujo On 07 Nov 2005 12:18:44 -0200, Jorge Godoy wrote: > > Pujo Aji writes: > > > don't forget to use dot or converge into float. > > Or import division from __future__. > > >>> from __future__ import division > >>> 42 / 250 > 0.16800000000000001 > >>> > > -- > Jorge Godoy > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/c033c9be/attachment.html From francis.moore at rawflow.com Mon Nov 7 16:08:16 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Mon, 07 Nov 2005 15:08:16 +0000 Subject: [Tutor] Percentage In-Reply-To: <436F5E83.4030502@accesstel.co.za> References: <436F5934.20905@accesstel.co.za> <436F5D76.2010309@rawflow.com> <436F5E83.4030502@accesstel.co.za> Message-ID: <436F6DE0.20805@rawflow.com> Johan Geldenhuys wrote: > Wow, you gave 105% on this one. ;-) > You're right. I misread the question and thought that you wanted 42% of 250. My mistake. Cheers, F. From sowden at gmail.com Mon Nov 7 18:05:44 2005 From: sowden at gmail.com (Eddie S) Date: Mon, 7 Nov 2005 17:05:44 +0000 Subject: [Tutor] base64MIME module import error Message-ID: <3082bc030511070905t1844fc72t@mail.gmail.com> I was just trying to make a simple cgi email form when I encountered this error. Traceback (most recent call last): File "/Users/eddie/Sites/python/email.py", line 4, in ? import smtplib File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/smtplib.py", line 49, in ? from email.base64MIME import encode as encode_base64 ImportError: No module named base64MIME It says it can not find the module base64MIME. I also tried importing the module from the command line and that worked fine. Any help is appreciated Eddie Sowden From kent37 at tds.net Mon Nov 7 18:27:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 12:27:05 -0500 Subject: [Tutor] base64MIME module import error In-Reply-To: <3082bc030511070905t1844fc72t@mail.gmail.com> References: <3082bc030511070905t1844fc72t@mail.gmail.com> Message-ID: <436F8E69.6030405@tds.net> Eddie S wrote: > I was just trying to make a simple cgi email form when I encountered > this error. > > Traceback (most recent call last): > File "/Users/eddie/Sites/python/email.py", line 4, in ? > import smtplib > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/smtplib.py", > line 49, in ? > from email.base64MIME import encode as encode_base64 > ImportError: No module named base64MIME > > It says it can not find the module base64MIME. I also tried importing > the module from the command line and that worked fine. The problem is that your email.py module is shadowing the library email module. Python is looking for base64MIME in your module. Rename your email.py to something else and it should work. Kent -- http://www.kentsjohnson.com From smiles at worksmail.net Mon Nov 7 14:19:13 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Mon, 7 Nov 2005 07:19:13 -0600 Subject: [Tutor] geometry References: Message-ID: <001a01c5e3c3$10ad5510$b32c4fca@csmith> | any python code for middle school geometry teaching use? | for instance, calculate the polygon area size, overlaid area size? | Thanks. | Yes, the module I refered to in response to the email with subject "Overlay" will handle these calculations. Again, see ( http://www.dezentral.de/warp.html?http://www.dezentral.de/soft/Polygon/ ). /c From sowden at gmail.com Mon Nov 7 19:07:26 2005 From: sowden at gmail.com (Eddie S) Date: Mon, 7 Nov 2005 18:07:26 +0000 Subject: [Tutor] base64MIME module import error In-Reply-To: <436F8E69.6030405@tds.net> References: <3082bc030511070905t1844fc72t@mail.gmail.com> <436F8E69.6030405@tds.net> Message-ID: <3082bc030511071007r55b8836fr@mail.gmail.com> > The problem is that your email.py module is shadowing the library email module. Python is looking for base64MIME in your module. Rename your email.py to something else and it should work. > > Kent > > -- > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Cheers that works better. That is the second time that has happened to me. (you would have thought I would have learned. Eddie From ronin_cpim at hotmail.com Mon Nov 7 19:57:11 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Mon, 07 Nov 2005 13:57:11 -0500 Subject: [Tutor] simple report writing? Message-ID: Can someone suggest a specific tutorial strictly on report writing? I'm able to write reports fairly easily in Python. I know the stuff like str(round(x,2)) where x = 3.145678 will yield 3.14. What I'm looking for is to be able to control left and right justification, column by column while using string and numeric data of variable lengths so that my reports look much neater. Possibly a generalized def print_line(*x)? Thanks. RC _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From matthew.williams at cancer.org.uk Mon Nov 7 19:57:20 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Mon, 07 Nov 2005 18:57:20 +0000 Subject: [Tutor] Easier way to access wxPython Message-ID: <1131389840.2742.38.camel@localhost.localdomain> Dear All, Just a note: When the next question about "which GUI for Python" comes around (and I should plead guilty to having asked a few times) I thought that the Dabo framework, which wraps wxPython in a nicer API would be worth pointing to. And even if the question didn't get asked, I thought people might like to know... http://daboenv.com/ HTH, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com From ronin_cpim at hotmail.com Mon Nov 7 20:10:57 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Mon, 07 Nov 2005 14:10:57 -0500 Subject: [Tutor] simple report writing? Message-ID: I have a list (x_list) of class data. How do I sort that list by a selected variable common to all members of the list? x_list.sort(key=x_list.v_name) # doesn't work becuase x_list can't see the individual items. RC _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From matthew.williams at cancer.org.uk Mon Nov 7 18:25:16 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Mon, 07 Nov 2005 17:25:16 +0000 Subject: [Tutor] Mono Message-ID: <1131384316.2742.34.camel@localhost.localdomain> Dear List, Slightly off topic, but could someone explain/ point me to a URL that explains how one might use Python with Mono (I guess it would be IronPython, rather than CPython), and what advantages it might give you (apart from a possible speed up of IronPython vs. CPython). I'm especially interested in the idea of being able to write different bits in different languages, and then run them all on Mono. Thanks, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com From kent37 at tds.net Mon Nov 7 20:20:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 14:20:08 -0500 Subject: [Tutor] simple report writing? In-Reply-To: References: Message-ID: <436FA8E8.4020104@tds.net> CPIM Ronin wrote: > Can someone suggest a specific tutorial strictly on report writing? > > I'm able to write reports fairly easily in Python. I know the stuff like > str(round(x,2)) where x = 3.145678 will yield 3.14. What I'm looking for is > to be able to control left and right justification, column by column while > using string and numeric data of variable lengths so that my reports look > much neater. Do you know about the string formatting operator %? http://docs.python.org/lib/typesseq-strings.html You might also be interested in this recipe which formats a table for output: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Kent From kent37 at tds.net Mon Nov 7 20:30:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 14:30:02 -0500 Subject: [Tutor] simple report writing? In-Reply-To: References: Message-ID: <436FAB3A.6080702@tds.net> CPIM Ronin wrote: > I have a list (x_list) of class data. How do I sort that list by a > selected variable common to all members of the list? > > x_list.sort(key=x_list.v_name) # doesn't work becuase x_list can't see > the individual items. Use import operator x_list.sort(key=operator.attrgetter('v_name')) Kent -- http://www.kentsjohnson.com From kent37 at tds.net Mon Nov 7 20:31:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 14:31:14 -0500 Subject: [Tutor] Easier way to access wxPython In-Reply-To: <1131389840.2742.38.camel@localhost.localdomain> References: <1131389840.2742.38.camel@localhost.localdomain> Message-ID: <436FAB82.2080205@tds.net> Matt Williams wrote: > Dear All, > > Just a note: When the next question about "which GUI for Python" comes > around (and I should plead guilty to having asked a few times) I thought > that the Dabo framework, which wraps wxPython in a nicer API would be > worth pointing to. > > http://daboenv.com/ Are there any examples or docs of using Dabo this way? I haven't downloaded Dabo but the info on the web site is pretty thin. Kent From ronin_cpim at hotmail.com Mon Nov 7 20:34:59 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Mon, 07 Nov 2005 14:34:59 -0500 Subject: [Tutor] simple report writing? Message-ID: I neglected to mention that the list x_list was created by x_list = [] and then a series of x_list.append(y), where y are class instances with a variety of variables, one of which I want to use as a sort key. >I have a list (x_list) of class data. How do I sort that list by a selected >variable common to all members >of the list? > >x_list.sort(key=x_list.v_name) # doesn't work becuase x_list can't see the >individual items. > >RC _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kaizer at mail.pt Mon Nov 7 20:38:04 2005 From: kaizer at mail.pt (bruno) Date: Mon, 07 Nov 2005 19:38:04 +0000 Subject: [Tutor] Is Python a good choise for this project? Message-ID: <436FAD1C.8080304@mail.pt> Hey, > > Python is capable of building such a system if thats what you mean. > Proivided high performance (real time rapid animation say) is not required > then it should perform adequately. Yes, performance is not a great concern. > But it will require quite a bit of > learning, > not just the core language but a GUI toolkit, and maybe the PyGame > framework too. > > graphics lib, like Pygame)? Other alternatives at this point are Java and > > C/SDL/Allegro. > > If you already know these environments and have built similar applications > in them you may be faster sticking with them. But if you have the time and > energy to learn a new language then Python offers the promise of more rapid > development in the future and easier maintenance. If you know Java you > might consider using Jython to write the core objects and Java to do the > GUI parts - Jython makes Python objects that are also valid Java objects > and vice versa. > I have experience with both Java and C. However using them will also involve some learning since I don't have much graphical animation experience (Java 2D if Java, SDL or Allegro if C). Since I got somewhat interested in Python's simplicity I added it to the possibility list because this would be an "excuse" to learn Python and Python's simplicity could help concentrate on the techniques and algorithms and less on the syntax. Java will probably be the choisen since I'm confortable with it and it can lead to less problems than C - the downsite is Java's heavy sintax. Jython seams interesting. Will check it. Thanks for your message. From dyoo at hkn.eecs.berkeley.edu Mon Nov 7 20:44:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Nov 2005 11:44:58 -0800 (PST) Subject: [Tutor] Mono In-Reply-To: <1131384316.2742.34.camel@localhost.localdomain> Message-ID: > Slightly off topic, but could someone explain/ point me to a URL that > explains how one might use Python with Mono (I guess it would be > IronPython, rather than CPython), and what advantages it might give you > (apart from a possible speed up of IronPython vs. CPython). I'm > especially interested in the idea of being able to write different bits > in different languages, and then run them all on Mono. Hi Matt, This is really specialized; I'd recommend checking with the IronPython folks on this one. http://lists.ironpython.com/listinfo.cgi/users-ironpython.com They're pretty active; I see some familiar faces like Liam in the archives there. *grin* I'd ask them, since they'd be most familiar with Python on Mono. From Liam.Clarke-Hutchinson at business.govt.nz Mon Nov 7 20:45:53 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Tue, 8 Nov 2005 08:45:53 +1300 Subject: [Tutor] simple report writing? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B137D@chbnt01.alpha.wd.govt.nz> Hi RC, >I have a list (x_list) of class data. So, a list of instances/classes then. You'll have to pass a custom function. def tSort(objA,objB): #assuming that objA.x & objB.x are the items to sort by, and are integers if objA < objB: result = -1 elif objA = objB: result = 0 elif objA > objB: #Would normally just do as an else #But being ultra explicit result = 1 return result x_list.sort(cmp=tSort) Regards, Liam Clarke -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of CPIM Ronin Sent: Tuesday, 8 November 2005 8:11 a.m. To: tutor at python.org Subject: [Tutor] simple report writing? I have a list (x_list) of class data. How do I sort that list by a selected variable common to all members of the list? x_list.sort(key=x_list.v_name) # doesn't work becuase x_list can't see the individual items. RC _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From alan.gauld at freenet.co.uk Mon Nov 7 21:01:10 2005 From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk) Date: Mon, 7 Nov 2005 20:01:10 -0000 Subject: [Tutor] simple report writing? Message-ID: <380-22005111720110959@freenet.co.uk> > >>Can someone suggest a specific tutorial strictly >>on report writing? >> >>to be able to control left and right justification, ... It doesn't sound like you need a tutorial per se, simply to spend some time with Pythons format strings - like C printf() Otherwise the only other advice I'd give is to read some general books on data transformations - something like Michael Jacksons classic JSP book maybe? (Try your local university library! or Amazons second hand service...) Alan G. From Barry.Carroll at psc.com Mon Nov 7 22:01:47 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 7 Nov 2005 13:01:47 -0800 Subject: [Tutor] Namespace Problem Message-ID: Bob: Yes I did mean 'import' and yes there is more to the function. Here is the entire program. ######################## import socket import struct # data packet flags ABC = 1 DEF = 2 GHI = 4 JKL = 8 seq = 0 buf = 8192 # This is the max_packet_size defined in the SocketServer module addr = ('localhost', 12345) # Host and port used by the server def do_stuff(in_str): hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str)) newstr = hdr+in_str if(sock.sendto(newstr,addr)): response = sock.recv(buf) flags, retseq, dlen = struct.unpack('@2BH', response[:4]) print "flags: 0x%X, retseq: %u, dlen: %u" % (flags, retseq, dlen) response = response[4:] rsphdr=eval(response[:response.find(')')+1]) response = response[response.find(')')+2:] resptupl = (rsphdr, response) seq += 1 return resptupl sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg # Send messages while (1): data = raw_input('>> ') if not data: break else: print "Sending message '",data,"'" ret_data = do_stuff(data) print "Got back: ", ret_data sock.close( ) ######################## Here is a trace of program execution. >>>>>>>>>>>>>>>>>>>>>>>> ===Enter message to send to server=== >> send some data Sending message ' send some data ' Traceback (most recent call last): File "./bgctest.py", line 40, in ? ret_data = do_stuff(data) File "./bgctest.py", line 15, in do_stuff hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str)) UnboundLocalError: local variable 'seq' referenced before assignment>>>>>>>>>>>>>>>>>>>>>>>> I can't figure it out. Barry > -----Original Message----- > From: bob [mailto:bgailer at alum.rpi.edu] > Sent: Friday, November 04, 2005 6:32 PM > To: Carroll, Barry; 'tutor at python.org' > Cc: Carroll, Barry > Subject: Re: [Tutor] Namespace Problem > > At 05:47 PM 11/4/2005, Carroll, Barry wrote: > >I have a function that makes use of several global variables: > > > >########## > >Include struct > > Did you mean "import"? > > >ABC = 1 > >DEF = 2 > >xyz = 0 > >def do_stuff(in_str): > > hdr = struct.pack('@2BH',ABC|DEF,xyz,len(in_str)) > > newstr = hdr+in_str > > Works find for me. Is there anything else you are not showing us? > <> From doublesix at ureach.com Mon Nov 7 22:11:16 2005 From: doublesix at ureach.com (Double Six) Date: Mon, 7 Nov 2005 16:11:16 -0500 Subject: [Tutor] Error message with testing Tkinter Message-ID: <200511072111.QAA29316@www20.ureach.com> Hi, I'm learning Tkinter with the following code on Mac OS X 10.4: from Tkinter import * from sys import stdout, exit widget = Button(None, text = 'Hello?', command=(lambda: stdout.write('Hello?\n') or exit())) widget.pack() widget.mainloop() I do successfully get a GUI with a button, but the problem is if I click the button, the GUI window hangs there with the following message message in the console: Hello? Traceback (most recent call last): File "/Users/gangc/Python_Scripting/test.py", line 7, in -toplevel- widget.mainloop() File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/Tkinter.py", line 965, in mainloop self.tk.mainloop(n) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/lib-tk/Tkinter.py", line 1347, in __call__ raise SystemExit, msg SystemExit What am I missing? Any help will be highly appreciated, Joe ________________________________________________ Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag From Liam.Clarke-Hutchinson at business.govt.nz Mon Nov 7 22:19:09 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Tue, 8 Nov 2005 10:19:09 +1300 Subject: [Tutor] Easier way to access wxPython Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1381@chbnt01.alpha.wd.govt.nz> For wxPython - Wax is alright, Pythoncard is great. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Tuesday, 8 November 2005 8:31 a.m. Cc: Python Tutor Subject: Re: [Tutor] Easier way to access wxPython Matt Williams wrote: > Dear All, > > Just a note: When the next question about "which GUI for Python" comes > around (and I should plead guilty to having asked a few times) I > thought that the Dabo framework, which wraps wxPython in a nicer API > would be worth pointing to. > > http://daboenv.com/ Are there any examples or docs of using Dabo this way? I haven't downloaded Dabo but the info on the web site is pretty thin. Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From kent37 at tds.net Mon Nov 7 22:26:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 07 Nov 2005 16:26:39 -0500 Subject: [Tutor] Namespace Problem In-Reply-To: References: Message-ID: <436FC68F.9020806@tds.net> Carroll, Barry wrote: > Bob: > > Yes I did mean 'import' and yes there is more to the function. Here is the > entire program. > > ######################## > import socket > import struct > > # data packet flags > ABC = 1 > DEF = 2 > GHI = 4 > JKL = 8 > seq = 0 > > buf = 8192 # This is the max_packet_size defined in the SocketServer module > addr = ('localhost', 12345) # Host and port used by the server > > def do_stuff(in_str): > hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str)) > newstr = hdr+in_str > if(sock.sendto(newstr,addr)): > response = sock.recv(buf) > flags, retseq, dlen = struct.unpack('@2BH', response[:4]) > print "flags: 0x%X, retseq: %u, dlen: %u" % (flags, retseq, dlen) > response = response[4:] > rsphdr=eval(response[:response.find(')')+1]) > response = response[response.find(')')+2:] > resptupl = (rsphdr, response) > seq += 1 The above statement binds a value to the name 'seq'. If a name is bound anywhere within a block, the compiler treats it as a local name and it will not be looked up in the global namespace. When the struct.pack() line is executed, seq is not bound in the local namespace and you get an error. The solution is to include 'global seq' in do_stuff(); this tells the compiler that seq should always be treated as a global name even though it is bound in the current block. This a little bit subtle because you are using seq += 1. Still this is binding a new value to seq and you need to declare it global. Kent > return resptupl > > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > > def_msg = "===Enter message to send to server==="; > print "\n",def_msg > > # Send messages > while (1): > data = raw_input('>> ') > if not data: > break > else: > print "Sending message '",data,"'" > ret_data = do_stuff(data) > print "Got back: ", ret_data > > sock.close( ) > ######################## > > Here is a trace of program execution. > > > ===Enter message to send to server=== > >>>send some data > > Sending message ' send some data ' > Traceback (most recent call last): > File "./bgctest.py", line 40, in ? > ret_data = do_stuff(data) > File "./bgctest.py", line 15, in do_stuff > hdr = struct.pack('@2BH',ABC|DEF,seq,len(in_str)) > UnboundLocalError: local variable 'seq' referenced before > assignment>>>>>>>>>>>>>>>>>>>>>>>> > From dyoo at hkn.eecs.berkeley.edu Mon Nov 7 22:35:38 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 7 Nov 2005 13:35:38 -0800 (PST) Subject: [Tutor] Error message with testing Tkinter In-Reply-To: <200511072111.QAA29316@www20.ureach.com> Message-ID: On Mon, 7 Nov 2005, Double Six wrote: > I'm learning Tkinter with the following code on Mac OS X 10.4: > > from Tkinter import * > from sys import stdout, exit > widget = Button(None, text = 'Hello?', command=(lambda: > stdout.write('Hello?\n') or exit())) > widget.pack() > widget.mainloop() > > I do successfully get a GUI with a button, but the problem is if I click > the button, the GUI window hangs there with the following message > message in the console: Hello, sys.exit() will raise a SystemExit exception when it's called, so the program is doing what you think it's doing. However, it looks like the mainloop() code from Tkinter doesn't expect to see that SystemExit. You probably want to call the quit() method of the graphical widgets instead: that'll get us out of the mainloop(). http://www.pythonware.com/library/tkinter/introduction/x9374-event-processing.htm Best of wishes! From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 8 00:09:08 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Tue, 8 Nov 2005 12:09:08 +1300 Subject: [Tutor] [OT] Mono Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1385@chbnt01.alpha.wd.govt.nz> Hi Matt, The main advantage of IronPython is access to the .NET framework in Python. For most Python scripts I run, there is no speed advantage due to the overhead of loading the framework (but then, I have an old computer.) But, I like being able to poke .NET within a Python environment, as I didn't want to have to learn C# to just have a play. Because everything in .NET, whether from C# or VB.Net or C++ or IronPython, compiles down to Intermediate Language, you've got a wide community to draw 3rd party modules from. Downside is that IL isn't that nice to try and read, so if you didn't get the source, then it can be a bit of a black box scenario. But yeah. I'm very impressed with what little of the .NET framework I've seen. Avalon/WFP is the sane GUI library that Windows always needed. It's probably a bit simpler to use than Tkinter, but seems more powerful than wxWidgets. Of course, it's OS specific... (I also think that once IronPython is released properly, there'll be few reasons that pointy haired bosses could stop you using it. It's made by Microsoft, it's .NET (is that still an 'in' buzzword?), and it all turns into IL at the end.) That said, the main disadvantage is that it doesn't play well with CPython at all. The standard library is being ported across, bit by bit, but the chances of any 3rd party module working are slim. Anything that relies on C won't work, so it exists in great isolation from the rest of Python. i.e. I can import the os and popen2 modules, but i can't use any variant of popen(), as popen is built on a C function called pipe(). Also, .NET is a bit more... verbose. Here's a comparison of CPython and IronPython creating a subprocess and creating pipes to it. The .NET variant allows a little more flexibility in how the process is started (although I believe the CPython subprocess module would be a more accurate comparison, but I can't be bothered trying to understand it's docs), yet oddly enough has no way whereby stderr and stdout can be combined as per popen4(). Both the below code samples perform the exact same function. CPython - import os (procStdin, procStdOut, procStdErr ) = os.popen3("c:/window/system23/cmd.exe") #I think I got those around the right way. This is all from memory. IronPython - import System.Diagnostics #.NET library process = System.Diagnostics.Process() stInfObj = System.Diagnostics.StartInfo("c:/window/system23/cmd.exe") stInfObj.CreateNoWindow = True stInfObj.UseShellExecute = False stInfObj.RedirectStandardInput = True stInfObj.RedirectStandardOutput = True stInfObj.RedirectStandardError = True process.StartInfo = stInfObj process.Start() (procStdin, procStdOut, procStdErr) = (process.StandardInput, process.StandardOutput, process.StandardError) Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Danny Yoo Sent: Tuesday, 8 November 2005 8:45 a.m. To: Matt Williams Cc: Python Tutor Subject: Re: [Tutor] Mono > Slightly off topic, but could someone explain/ point me to a URL that > explains how one might use Python with Mono (I guess it would be > IronPython, rather than CPython), and what advantages it might give > you (apart from a possible speed up of IronPython vs. CPython). I'm > especially interested in the idea of being able to write different > bits in different languages, and then run them all on Mono. Hi Matt, This is really specialized; I'd recommend checking with the IronPython folks on this one. http://lists.ironpython.com/listinfo.cgi/users-ironpython.com They're pretty active; I see some familiar faces like Liam in the archives there. *grin* I'd ask them, since they'd be most familiar with Python on Mono. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From falcon3166 at hotmail.com Tue Nov 8 01:23:31 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 7 Nov 2005 17:23:31 -0700 Subject: [Tutor] Does Pygame allow background images? Message-ID: Hey all, Does Pygame allow background images (i.e. a hockey rink for a hockey game)? Thanks, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051107/7b6364fa/attachment.html From amonroe at columbus.rr.com Tue Nov 8 01:59:45 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 7 Nov 2005 19:59:45 -0500 Subject: [Tutor] Does Pygame allow background images? In-Reply-To: References: Message-ID: <15882378363.20051107195945@columbus.rr.com> > Does Pygame allow background images (i.e. a hockey rink for a hockey game)? Sure... just check out the supplied chimp.py example, which has a message in the background, and two sprites on top of it. Alan From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 8 03:06:25 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Tue, 8 Nov 2005 15:06:25 +1300 Subject: [Tutor] Does Pygame allow background images? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1388@chbnt01.alpha.wd.govt.nz> Hi Nathan, Just create a surface the same size as your screen, and have a loop like so while True: Here's some rough code to add a background for that ball one I posted yesterday. Bear in mind that I can't check this at work. Lines with !! are new- import sys, pygame pygame.init() !!background = pygame.image.load("bckgrnd.bmp")#Pygame can handle other formats. !!backgrountRect = background.get_rect() !!size = (width, height) = background.get_size() #Returns size of image as (x, y) so game screen will be as big as background screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.bmp") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] !!screen.blit(background, backgroundRect) #instead of screen.fill() screen.blit(ball, ballrect) pygame.display.flip() That's very basic, but it should work. www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Nathan Pinno Sent: Tuesday, 8 November 2005 1:24 p.m. To: Tutor Mailing List Subject: [Tutor] Does Pygame allow background images? Hey all, Does Pygame allow background images (i.e. a hockey rink for a hockey game)? Thanks, Nathan Pinno A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 8 03:17:36 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Tue, 8 Nov 2005 15:17:36 +1300 Subject: [Tutor] Does Pygame allow background images? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1389@chbnt01.alpha.wd.govt.nz> Oh dear, The full code would be (hopefully correct this time) import sys, pygame pygame.init() ball = pygame.image.load("ball.bmp") background = pygame.image.load("bckgrnd.bmp") ballrect = ball.get_rect() backgroundRect = background.get_rect() size = (width, height) = background.get_size() screen = pygame.display.set_mode(size) while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.blit(background, backgroundRect) screen.blit(ball, ballrect) pygame.display.flip() Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces+ml.cyresse=gmail.com at python.org [mailto:tutor-bounces+ml.cyresse=gmail.com at python.org] On Behalf Of Liam Clarke-Hutchinson Sent: Tuesday, 8 November 2005 3:06 p.m. To: 'Nathan Pinno'; Tutor Mailing List Subject: Re: [Tutor] Does Pygame allow background images? Hi Nathan, Just create a surface the same size as your screen, and have a loop like so while True: Here's some rough code to add a background for that ball one I posted yesterday. Bear in mind that I can't check this at work. Lines with !! are new- import sys, pygame pygame.init() !!background = pygame.image.load("bckgrnd.bmp")#Pygame can handle other formats. !!backgrountRect = background.get_rect() !!size = (width, height) = background.get_size() #Returns size of image as (x, y) so game screen will be as big as background screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.bmp") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] !!screen.blit(background, backgroundRect) #instead of screen.fill() screen.blit(ball, ballrect) pygame.display.flip() That's very basic, but it should work. www.med.govt.nz -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Nathan Pinno Sent: Tuesday, 8 November 2005 1:24 p.m. To: Tutor Mailing List Subject: [Tutor] Does Pygame allow background images? Hey all, Does Pygame allow background images (i.e. a hockey rink for a hockey game)? Thanks, Nathan Pinno A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Barry.Carroll at psc.com Tue Nov 8 03:28:19 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Mon, 7 Nov 2005 18:28:19 -0800 Subject: [Tutor] Namespace Problem Message-ID: Kent: Thank you for the explanation. This is a subtlety of Python that has tripped me up before. Barry > Date: Mon, 07 Nov 2005 16:26:39 -0500 > From: Kent Johnson > Subject: Re: [Tutor] Namespace Problem > Cc: "'tutor at python.org'" > Message-ID: <436FC68F.9020806 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > <> > > seq += 1 > > The above statement binds a value to the name 'seq'. If a name is bound > anywhere within a block, the compiler treats it as a local name and it > will not be looked up in the global namespace. When the struct.pack() line > is executed, seq is not bound in the local namespace and you get an error. > The solution is to include 'global seq' in do_stuff(); this tells the > compiler that seq should always be treated as a global name even though it > is bound in the current block. > > This a little bit subtle because you are using seq += 1. Still this is > binding a new value to seq and you need to declare it global. > > Kent > <> From rob at customdatasoft.com Tue Nov 8 07:10:16 2005 From: rob at customdatasoft.com (Rob Dowell) Date: Tue, 08 Nov 2005 00:10:16 -0600 Subject: [Tutor] TKinter Question Message-ID: <43704148.1000804@customdatasoft.com> Just a quick TKinter question. Is it possible to have custom frames/widgets? In other words can I customize the way that the GUI looks (i.e. rounded corners on the frames, beveled/raised edges, etc.) I was just wondering if it was possible and if it is possible then where I might get some information on how to do it. Thank you very much, Rob. From samrobertsmith at gmail.com Tue Nov 8 08:51:05 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 7 Nov 2005 23:51:05 -0800 Subject: [Tutor] geometry In-Reply-To: <001a01c5e3c3$10ad5510$b32c4fca@csmith> References: <001a01c5e3c3$10ad5510$b32c4fca@csmith> Message-ID: <1d987df30511072351p4397dc68mbabf5975aeabe762@mail.gmail.com> Because i am also teaching some introduction courses of programming in middle school, I prefer some 2D geometry codes. On 11/7/05, Chris or Leslie Smith wrote: > > | any python code for middle school geometry teaching use? > | for instance, calculate the polygon area size, overlaid area size? > | Thanks. > | > > Yes, the module I refered to in response to the email with subject "Overlay" will handle these calculations. > > Again, see ( http://www.dezentral.de/warp.html?http://www.dezentral.de/soft/Polygon/ ). > > /c > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From fatearthling at gmail.com Tue Nov 8 10:32:12 2005 From: fatearthling at gmail.com (Howard Kao) Date: Tue, 8 Nov 2005 17:32:12 +0800 Subject: [Tutor] Python persistent webserver? Message-ID: Hi all, I know the subject is confusing but I don't know how to describe what I would like to ask concisely. Basically I would like to have a program (or server or whatever) take an HTTP POST method (which contains some information, maybe even an XML file) from a client, process these XML/information, and then generate an XML to send back to the client. Currently the environment it has to be done under is Apache on Linux. I am thinking that it may have to be a persistent running program... However it seems a daunting task for a Python noob like me. Preferably it doesn't need threading and need not to be sophiscated at all, as long as it can take the request, process info and send stuff back to a client. I have no idea how to do this at all and couldn't find much information. The Base, Simple, CGI HTTPServer modules all seem a little lacking , but that's probably due to my lack of py-fu to start with... Any suggestions would be appreciated. Many thanks! From klappnase at freenet.de Tue Nov 8 11:23:26 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 8 Nov 2005 11:23:26 +0100 Subject: [Tutor] TKinter Question In-Reply-To: <43704148.1000804@customdatasoft.com> References: <43704148.1000804@customdatasoft.com> Message-ID: <20051108112326.747e8cb4.klappnase@freenet.de> On Tue, 08 Nov 2005 00:10:16 -0600 Rob Dowell wrote: > Just a quick TKinter question. Is it possible to have custom > frames/widgets? In other words can I customize the way that the GUI > looks (i.e. rounded corners on the frames, beveled/raised edges, etc.) I > was just wondering if it was possible and if it is possible then where I > might get some information on how to do it. Thank you very much, Rob. > Hi Rob, I'm not sure what you mean with "beveled/raised edges" , maybe setting the widget's relief to GROOVE or RIDGE does what you want? Rounded corners are much more complicated; you will probably need the shape extension for Tk which adds non-rectangular window support to Tk. A version of shape that works with unix systems is included in the tkdnd drag and drop extension (http://sourceforge.net/projects/tkdnd); I wrote a Tkinter wrapper for tkdnd (http://www.8ung.at/klappnase/TkinterDnD/TkinterDnD.html) that makes it possible to use tkdnd from python. If you need windows support, you can try a newer version of shape (http://www.cs.man.ac.uk/~fellowsd/tcl/shapeidx.html) that seems to support windows platforms, too. Regards Michael From samrobertsmith at gmail.com Tue Nov 8 11:37:55 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Tue, 8 Nov 2005 02:37:55 -0800 Subject: [Tutor] image In-Reply-To: <1d987df30511070002u231fc44dk4e90d7dd8c628777@mail.gmail.com> References: <1d987df30511070002u231fc44dk4e90d7dd8c628777@mail.gmail.com> Message-ID: <1d987df30511080237h84ce2b2u9a088f6b31bd2752@mail.gmail.com> any python module to calculate sin, cos, arctan? From kent37 at tds.net Tue Nov 8 12:03:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 06:03:13 -0500 Subject: [Tutor] Python persistent webserver? In-Reply-To: References: Message-ID: <437085F1.2010807@tds.net> Howard Kao wrote: > Basically I would like to have a program (or server or whatever) take > an HTTP POST method (which contains some information, maybe even an > XML file) from a client, process these XML/information, and then > generate an XML to send back to the client. > > Currently the environment it has to be done under is Apache on Linux. > I am thinking that it may have to be a persistent running program... > However it seems a daunting task for a Python noob like me. You can do this with a Python CGI program that runs behind Apache. Apachee will be the 'persistent running program'. Your CGI will be invoked with each POST request. Look at the CGI module docs and google for 'python cgi' for more information. > > Preferably it doesn't need threading and need not to be sophiscated at > all, as long as it can take the request, process info and send stuff > back to a client. With a CGI all the sophisticated stuff is handled by Apache. Kent -- http://www.kentsjohnson.com From kent37 at tds.net Tue Nov 8 12:05:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 06:05:03 -0500 Subject: [Tutor] image In-Reply-To: <1d987df30511080237h84ce2b2u9a088f6b31bd2752@mail.gmail.com> References: <1d987df30511070002u231fc44dk4e90d7dd8c628777@mail.gmail.com> <1d987df30511080237h84ce2b2u9a088f6b31bd2752@mail.gmail.com> Message-ID: <4370865F.7000200@tds.net> Shi Mu wrote: > any python module to calculate sin, cos, arctan? The index to the Library Reference has the answer to this question... Kent -- http://www.kentsjohnson.com From lard at tardis.ed.ac.uk Tue Nov 8 12:12:50 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 03:12:50 -0800 Subject: [Tutor] interfaces and abstract classes in python In-Reply-To: <010501c5e2e5$8701afb0$0a01a8c0@xp> References: <436DED6D.3020902@tardis.ed.ac.uk> <010501c5e2e5$8701afb0$0a01a8c0@xp> Message-ID: <43708832.3040608@tardis.ed.ac.uk> Alan Gauld wrote: >> Interfaces and abstract classes - I know they don't exist per se in >> Python. > > > First you need to define what you mean by the terms. > Every class has an interface - it is the set of messages to which it > responds. Yup, I was thinking more in terms of the Java idea, whereby an interface is declared specifically and then a class claiming to implement it causes compilation problems if it doesn't properly implement it. > > An Abstract class is one which is not intended to be instantiated. > > class AbstractClassError(Exception): pass > > class Abstract: > def __init__(self): raise AbstractClassError Yes, this and the code below with it are very similar to the common idiom for abstract classes (in Python) that I see quite often. > >> But what are the closest analogues? I've found a few examples, > > > Assuming you mean Interface in the Microsoft/Java specific sense of > the term rather than the simple OOP sense, then an Interface class is > simply an abstract class with empty methods. > > class InterfaceError(Exception): pass > > class Interface(Abstract): > def myMethod(self): pass > def myOther(self): raise InterfaceErrror > > Does that do what you want? I presume the "def myMethod(self): pass" is just for an 'optional' part of the interface? The above code does serve the purpose of making an interface more explicit, which is helpful. I have seen this use before and I was just wondering if there was any other common ways to make interfaces more explicit. Thanks! Btw, I notice this email list sends the emails with the originator as the sender, and CC'd to the tutor at python.org address. Is it standard here to reply to the email address of the sender of the message you're replying to, as well as the list itself, or should I be trimming out the sender email and just replying to the list only? thanks, alex From lard at tardis.ed.ac.uk Tue Nov 8 12:16:14 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 03:16:14 -0800 Subject: [Tutor] interfaces and abstract classes in python In-Reply-To: <436E4095.5000405@tds.net> References: <436DED6D.3020902@tardis.ed.ac.uk> <436E4095.5000405@tds.net> Message-ID: <437088FE.8050603@tardis.ed.ac.uk> Kent Johnson wrote: >Alex Hunsley wrote: > > >>Interfaces and abstract classes - I know they don't exist per se in >>Python. But what are the closest analogues? I've found a few examples, >>e.g. for an abstract class the following page has a fairly common >>suggestion: >> >>http://www.norvig.com/python-iaq.html >> >> > >Interfaces are generally implicit in Python. For example the docs will sometimes talk about 'file-like objects' which are just objects that implement the same interface as a file object. 'iterable', 'iterator', 'sequence' and 'mapping' are similarly defined by convention or by explicit documentation but not in the language itself. For example the 'iterator protocol' is defined here: >http://docs.python.org/lib/typeiter.html > > Yup, I've run into the __getitem__ etc. methods that you can overload which is pretty handy stuff. >To define an abstract method I just raise NotImplementedError in the body of the method. > > Ah, ok. This appears to be the pythonic way. >There are a couple of more formalized ways to add support for explicit type requirments to the language. This is a little different from what you asked - these projects allow a client of an object to specify an interface (or protocol) that must be supported by the object. >PyProtocols http://peak.telecommunity.com/PyProtocols.html >Zope Interfaces http://www.zope.org/Wikis/Interfaces/FrontPage > > I've had a look at these before and although they look relevant, I'm more interested in the core python language at the moment, and what that can do itself. >PEP 246 formalizes this notion. It seems to be slated for inclusion in Python 2.5. >http://www.python.org/peps/pep-0246.html > > This PEP looks like a good idea! thanks alex >Kent > > > From johan at accesstel.co.za Tue Nov 8 12:18:20 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 08 Nov 2005 13:18:20 +0200 Subject: [Tutor] Percentage In-Reply-To: <87irv4a6l0.fsf@jupiter.g2ctech> References: <436F5934.20905@accesstel.co.za> <436F5D76.2010309@rawflow.com> <87irv4a6l0.fsf@jupiter.g2ctech> Message-ID: <4370897C.7060500@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051108/b823c1a4/attachment.html From samrobertsmith at gmail.com Tue Nov 8 12:21:24 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Tue, 8 Nov 2005 03:21:24 -0800 Subject: [Tutor] any code to draw parabola or curve? Message-ID: <1d987df30511080321m7c4847fawc5d262f6e3619a79@mail.gmail.com> any code to draw parabola or curve? From lard at tardis.ed.ac.uk Tue Nov 8 12:45:59 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 03:45:59 -0800 Subject: [Tutor] overloading binary operator for mixed types: a no-no? Message-ID: <43708FF7.2040704@tardis.ed.ac.uk> I'm writing a Vector class (think Vector as in the mathematical vector)... A critical snippet is as follows: class Vector(lister.Lister): def __init__(self, *elems): # ensure that we create a list, not a tuple self.elems = list(elems) def __add__(self, other): return map(lambda x,y: x + y , self.elems, other.elems) def __mult__(self, other): return map(lambda x,y: x * y , self.elems, [other]) The overloading of + (add) works fine: >>> a=Vector(1,2,3) >>> a+a [2, 4, 6] But of course, I have problems with mult. When using vectors, it would seem to make sense to overload the * (multiply) operator to mean multiply a vector by a scalar as this would be the common usage in maths/physics. (I've made a seperate method call dotProduct for dot products for sake of clarity.) Anyway, my multiply doesn't work of course: >>> a=Vector(1,2,3) >>> a * 2 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for *: 'instance' and 'int' ... presumably because overloading binary operators like * requires that both operands be instances of the class in question! My question is: is there any way to overload * for my Vector class so that notation like (a * 2) would work, and call __mult__ or similar? Or should I just bite the bullet and write a normal method called 'multiply'? ('scale' would be better actually.) thanks alex From lard at tardis.ed.ac.uk Tue Nov 8 12:55:34 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 03:55:34 -0800 Subject: [Tutor] any code to draw parabola or curve? In-Reply-To: <1d987df30511080321m7c4847fawc5d262f6e3619a79@mail.gmail.com> References: <1d987df30511080321m7c4847fawc5d262f6e3619a79@mail.gmail.com> Message-ID: <43709236.1080903@tardis.ed.ac.uk> Shi Mu wrote: >any code to draw parabola or curve? > > That question is so general and vague it's either unanswerable, or very easy to answer. I'll try the 'very easy' answer: yes, there is probably code somewhere to draw a parabola or curve. Have you tried making a start on this yourself? Did you run into a problem? Or perhaps: did you try googling for 'draw parabola' or 'parabola equation'? If you've not made a start on attempting this problem, and need help, try breaking down your help request into sub-requests. Like, you might be wondering what the algorithm or maths is for drawing a parabola/curve. Or you might be wondering about how to display a curve on screen. (Ascii output? Generating an image file like a gif? Output to a window using a GUI toolkit like wxPython?) Or are you just expecting someone to post fully functional code from a vague request? The following is highly recommended reading. It's called "How to ask questions the smart way": http://www.catb.org/~esr/faqs/smart-questions.html best of luck! alex From godoy at ieee.org Tue Nov 8 12:59:31 2005 From: godoy at ieee.org (Jorge Godoy) Date: 08 Nov 2005 09:59:31 -0200 Subject: [Tutor] Percentage References: <436F5934.20905@accesstel.co.za> <436F5D76.2010309@rawflow.com> <87irv4a6l0.fsf@jupiter.g2ctech> <4370897C.7060500@accesstel.co.za> Message-ID: <87vez3gxjw.fsf@jupiter.g2ctech> Johan Geldenhuys writes: > Now that I have the answer (16.800000000000001), How do I round it of to 16.80 > ? I only need it to be to the closest 1/100. >>> print "%.2f" % 16.800000000000001 16.80 >>> a = 16.8000000000001 >>> b = "%.2f" % a >>> b '16.80' >>> float(b) 16.800000000000001 >>> str(float(b)) '16.8' >>> (The reason for the '000000000001' is because of the numeric base used to represent data -- binary -- and the numeric base I'm requesting the answer to be in -- decimal.) Be seeing you, -- Jorge Godoy From johan at accesstel.co.za Tue Nov 8 13:42:30 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 08 Nov 2005 14:42:30 +0200 Subject: [Tutor] Percentage In-Reply-To: <87vez3gxjw.fsf@jupiter.g2ctech> References: <436F5934.20905@accesstel.co.za> <436F5D76.2010309@rawflow.com> <87irv4a6l0.fsf@jupiter.g2ctech> <4370897C.7060500@accesstel.co.za> <87vez3gxjw.fsf@jupiter.g2ctech> Message-ID: <43709D36.40505@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051108/edb60838/attachment.htm From kent37 at tds.net Tue Nov 8 13:49:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 07:49:59 -0500 Subject: [Tutor] interfaces and abstract classes in python In-Reply-To: <43708832.3040608@tardis.ed.ac.uk> References: <436DED6D.3020902@tardis.ed.ac.uk> <010501c5e2e5$8701afb0$0a01a8c0@xp> <43708832.3040608@tardis.ed.ac.uk> Message-ID: <43709EF7.1060808@tds.net> Alex Hunsley wrote: > Alan Gauld wrote: > > >>>Interfaces and abstract classes - I know they don't exist per se in >>>Python. >> >> >>First you need to define what you mean by the terms. >>Every class has an interface - it is the set of messages to which it >>responds. > > > Yup, I was thinking more in terms of the Java idea, whereby an interface > is declared specifically and then a class claiming to implement it > causes compilation problems if it doesn't properly implement it. No, there is nothing like this in Python. This is a form of static type checking which is not part of Python. In general type errors are detected at runtime in Python. > Btw, I notice this email list sends the emails with the originator as > the sender, and CC'd to the tutor at python.org address. Is it standard > here to reply to the email address of the sender of the message you're > replying to, as well as the list itself, or should I be trimming out the > sender email and just replying to the list only? I don't know if it's standard, but I reply just to the list. I see this list as a kind of commons that benefits many, and I want all interactions to be on list. I see my replies as a contribution to the list as much as to the original questioner. Kent -- http://www.kentsjohnson.com From kent37 at tds.net Tue Nov 8 14:02:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 08:02:02 -0500 Subject: [Tutor] overloading binary operator for mixed types: a no-no? In-Reply-To: <43708FF7.2040704@tardis.ed.ac.uk> References: <43708FF7.2040704@tardis.ed.ac.uk> Message-ID: <4370A1CA.4010105@tds.net> Alex Hunsley wrote: > I'm writing a Vector class (think Vector as in the mathematical vector)... > A critical snippet is as follows: > > class Vector(lister.Lister): > def __init__(self, *elems): > # ensure that we create a list, not a tuple > self.elems = list(elems) > > def __add__(self, other): > return map(lambda x,y: x + y , self.elems, other.elems) Don't you want this to return a new Vector, rather than a list? So for example you can add three vectors a + b + c? Instead of defining your own function, you can use operator.add(). So I would write this as return Vector(map(operator.add, self.elems, other.elems)) > def __mult__(self, other): > return map(lambda x,y: x * y , self.elems, [other]) This could be map(lambda x: x * other, self.elems) or [ x * other for x in self.elems ] > The overloading of + (add) works fine: > > >>> a=Vector(1,2,3) > >>> a+a > [2, 4, 6] > > But of course, I have problems with mult. When using vectors, it would > seem to make sense to overload the * (multiply) operator to mean > multiply a vector by a scalar as this would be the common usage in > maths/physics. (I've made a seperate method call dotProduct for dot > products for sake of clarity.) > > Anyway, my multiply doesn't work of course: > > >>> a=Vector(1,2,3) > >>> a * 2 > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unsupported operand type(s) for *: 'instance' and 'int' > > ... presumably because overloading binary operators like * requires that > both operands be instances of the class in question! No, actually it is because you have misspelled __mul__! You might also want to implement __rmul__() so you can write 2 * a. See this page for a list of all special methods for numeric types: http://docs.python.org/ref/numeric-types.html Do you know about Numeric and numpy? They are high-performance implementations of arrays that support operations like these. You should probably look into them. Kent -- http://www.kentsjohnson.com From lard at tardis.ed.ac.uk Tue Nov 8 14:05:51 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 05:05:51 -0800 Subject: [Tutor] interfaces and abstract classes in python In-Reply-To: <43709EF7.1060808@tds.net> References: <436DED6D.3020902@tardis.ed.ac.uk> <010501c5e2e5$8701afb0$0a01a8c0@xp> <43708832.3040608@tardis.ed.ac.uk> <43709EF7.1060808@tds.net> Message-ID: <4370A2AF.50203@tardis.ed.ac.uk> Kent Johnson wrote: >Alex Hunsley wrote: > > >>Alan Gauld wrote: >> >> >> >> >>>>Interfaces and abstract classes - I know they don't exist per se in >>>>Python. >>>> >>>> >>>First you need to define what you mean by the terms. >>>Every class has an interface - it is the set of messages to which it >>>responds. >>> >>> >>Yup, I was thinking more in terms of the Java idea, whereby an interface >>is declared specifically and then a class claiming to implement it >>causes compilation problems if it doesn't properly implement it. >> >> > >No, there is nothing like this in Python. This is a form of static type checking which is not part of Python. In general type errors are detected at runtime in Python. > > Yes, I've come to realise this isn't the python way. Just getting my head around pythonland. > > > >>Btw, I notice this email list sends the emails with the originator as >>the sender, and CC'd to the tutor at python.org address. Is it standard >>here to reply to the email address of the sender of the message you're >>replying to, as well as the list itself, or should I be trimming out the >>sender email and just replying to the list only? >> >> > >I don't know if it's standard, but I reply just to the list. I see this list as a kind of commons that benefits many, and I want all interactions to be on list. I see my replies as a contribution to the list as much as to the original questioner. > > Oh yes, I'd always reply to the list in the very least; I was really just wondering what the etiquette was concerning emails also going back to the person you're reply to directly (as well as to the list). I ask because the list is set up so that it appears replies are also meant to go to the person you're replying to. It would seem to be more sensible if the emails sent out to the list had the 'from:' being the list address, rather than the actual sender; then hitting plain old reply would work (currently I have to hit 'reply all', otherwise it just emails the person I'm replying to). cheers alex >Kent > > > From lard at tardis.ed.ac.uk Tue Nov 8 14:09:57 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 05:09:57 -0800 Subject: [Tutor] testing: doctest and unittest Message-ID: <4370A3A5.6080701@tardis.ed.ac.uk> Regards testing, I've been playing with both the unittest (http://pyunit.sourceforge.net/pyunit.html) and doctest (http://docs.python.org/lib/module-doctest.html). I was wondering what peoples thoughts were on the effectiveness and convenience of one versus the other. It seems to me that doctest is good for quicky and straightforwards input/output tests for small units, whereas unittest would be good for dynamic or complicated testing. Where do you seasoned pythonites see unittest and doctest in relation to each other? Do you only use one or the other? ta, alex From kent37 at tds.net Tue Nov 8 14:17:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 08:17:59 -0500 Subject: [Tutor] interfaces and abstract classes in python In-Reply-To: <4370A2AF.50203@tardis.ed.ac.uk> References: <436DED6D.3020902@tardis.ed.ac.uk> <010501c5e2e5$8701afb0$0a01a8c0@xp> <43708832.3040608@tardis.ed.ac.uk> <43709EF7.1060808@tds.net> <4370A2AF.50203@tardis.ed.ac.uk> Message-ID: <4370A587.5040702@tds.net> Alex Hunsley wrote: > Oh yes, I'd always reply to the list in the very least; I was really > just wondering what the etiquette was concerning emails also going back > to the person you're reply to directly (as well as to the list). I ask > because the list is set up so that it appears replies are also meant to > go to the person you're replying to. It would seem to be more sensible > if the emails sent out to the list had the 'from:' being the list > address, rather than the actual sender; then hitting plain old reply > would work (currently I have to hit 'reply all', otherwise it just > emails the person I'm replying to). This is a frequent request, the reason is here: http://www.unicom.com/pw/reply-to-harmful.html -- http://www.kentsjohnson.com From lard at tardis.ed.ac.uk Tue Nov 8 14:34:55 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 05:34:55 -0800 Subject: [Tutor] interfaces and abstract classes in python In-Reply-To: <4370A587.5040702@tds.net> References: <436DED6D.3020902@tardis.ed.ac.uk> <010501c5e2e5$8701afb0$0a01a8c0@xp> <43708832.3040608@tardis.ed.ac.uk> <43709EF7.1060808@tds.net> <4370A2AF.50203@tardis.ed.ac.uk> <4370A587.5040702@tds.net> Message-ID: <4370A97F.9040102@tardis.ed.ac.uk> Kent Johnson wrote: >Alex Hunsley wrote: > > >>Oh yes, I'd always reply to the list in the very least; I was really >>just wondering what the etiquette was concerning emails also going back >>to the person you're reply to directly (as well as to the list). I ask >>because the list is set up so that it appears replies are also meant to >>go to the person you're replying to. It would seem to be more sensible >>if the emails sent out to the list had the 'from:' being the list >>address, rather than the actual sender; then hitting plain old reply >>would work (currently I have to hit 'reply all', otherwise it just >>emails the person I'm replying to). >> >> > >This is a frequent request, the reason is here: >http://www.unicom.com/pw/reply-to-harmful.html > > thanks for that. alex From frankbloeink at nerdshack.com Tue Nov 8 15:47:30 2005 From: frankbloeink at nerdshack.com (Frank Bloeink) Date: Tue, 08 Nov 2005 15:47:30 +0100 Subject: [Tutor] Python persistent webserver? In-Reply-To: References: Message-ID: <1131461250.8973.7.camel@speedking.dyndns.org> Hi, maybe you can have a look at twisted http://twistedmatrix.com , which is an "event-driven network framework". I think you could easily build your own server to handle your requests, you don't even need an apache webserver for that. Just have a look, there's some documentation/tutorials out there and there's even a book on the framework called "Twisted Network Programming Essentials" which I'm working through atm. On Tue, 2005-11-08 at 17:32 +0800, Howard Kao wrote: > Hi all, > > I know the subject is confusing but I don't know how to describe what > I would like to ask concisely. > > Basically I would like to have a program (or server or whatever) take > an HTTP POST method (which contains some information, maybe even an > XML file) from a client, process these XML/information, and then > generate an XML to send back to the client. > > Currently the environment it has to be done under is Apache on Linux. > I am thinking that it may have to be a persistent running program... > However it seems a daunting task for a Python noob like me. > > Preferably it doesn't need threading and need not to be sophiscated at > all, as long as it can take the request, process info and send stuff > back to a client. > > I have no idea how to do this at all and couldn't find much > information. The Base, Simple, CGI HTTPServer modules all seem a > little lacking , but that's probably due to my lack of py-fu to start > with... Any suggestions would be appreciated. Many thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From marcink at ieee.org Tue Nov 8 16:09:26 2005 From: marcink at ieee.org (Marcin Komorowski) Date: Tue, 8 Nov 2005 10:09:26 -0500 Subject: [Tutor] Raw image display in a GUI window Message-ID: <005201c5e476$68d8f510$66f6a8c0@zobook> Hello, I want to use Python to do some experimentation with graphic processing/manipulation, and I am looking for a way to be able to manipulate individual pixels of the image, as well as display it in a GUI. Ideal image representation would be something of the form of a two-dimensional array of tuples, each tuple containing the Red, Green and Blue components. I have looked at Tk and Tkinter, and there is a PhotoImage class that can define an image which can than be displayed in a Canvas widget, but the PhotoImage class seams to be doing a lot of extra work on the image, including gamma correction, etc. I am interested in being able to display exactly the pixel values I set. Thank You all in advance, Marcin From cjw at sympatico.ca Tue Nov 8 16:16:17 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 08 Nov 2005 10:16:17 -0500 Subject: [Tutor] testing: doctest and unittest In-Reply-To: <4370A3A5.6080701@tardis.ed.ac.uk> References: <4370A3A5.6080701@tardis.ed.ac.uk> Message-ID: <4370C141.7070003@sympatico.ca> Alex Hunsley wrote: >Regards testing, I've been playing with both the unittest >(http://pyunit.sourceforge.net/pyunit.html) and doctest >(http://docs.python.org/lib/module-doctest.html). I was wondering what >peoples thoughts were on the effectiveness and convenience of one versus >the other. It seems to me that doctest is good for quicky and >straightforwards input/output tests for small units, whereas unittest >would be good for dynamic or complicated testing. > >Where do you seasoned pythonites see unittest and doctest in relation to >each other? Do you only use one or the other? > >ta, >alex > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > I looked at doctest and feel that it clutters the module text and so would prefer unittest but I haven't yet got to formalizing my tests in that way. See some of the numarray source as an example of clutter. Some argue that having the examples in the source is beneficial. I agree but feel that the clutter outweighs the benefit. Colin W. Colin W. From lard at tardis.ed.ac.uk Tue Nov 8 16:32:20 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 07:32:20 -0800 Subject: [Tutor] Raw image display in a GUI window In-Reply-To: <005201c5e476$68d8f510$66f6a8c0@zobook> References: <005201c5e476$68d8f510$66f6a8c0@zobook> Message-ID: <4370C504.8020201@tardis.ed.ac.uk> Marcin Komorowski wrote: >Hello, > >I want to use Python to do some experimentation with graphic >processing/manipulation, and I am looking for a way to be able to manipulate >individual pixels of the image, as well as display it in a GUI. Ideal image >representation would be something of the form of a two-dimensional array of >tuples, each tuple containing the Red, Green and Blue components. > >I have looked at Tk and Tkinter, and there is a PhotoImage class that can >define an image which can than be displayed in a Canvas widget, but the >PhotoImage class seams to be doing a lot of extra work on the image, >including gamma correction, etc. I am interested in being able to display >exactly the pixel values I set. > >Thank You all in advance, >Marcin > > How about PyUI? http://pyui.sourceforge.net/ It may do what you're looking for... alex > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From matthew.williams at cancer.org.uk Tue Nov 8 17:19:39 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Tue, 08 Nov 2005 16:19:39 +0000 Subject: [Tutor] Python and Semantic Web Message-ID: <1131466779.2747.13.camel@localhost.localdomain> Dear List, Does anyone know of any python semweb tools? I'm especially interested in tools to build and handle ontologies. I've come across CWM (built by Tim BL) but not that much else. I'd be really interested in anything that can interface with a DIG reasoner. Really, I'm looking for a pythonic version of something like Protege or SWOOP Thanks, Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com From bgailer at alum.rpi.edu Tue Nov 8 17:33:49 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 08 Nov 2005 08:33:49 -0800 Subject: [Tutor] Python and Semantic Web In-Reply-To: <1131466779.2747.13.camel@localhost.localdomain> References: <1131466779.2747.13.camel@localhost.localdomain> Message-ID: <6.1.2.0.0.20051108083134.03528388@mail.mric.net> At 08:19 AM 11/8/2005, Matt Williams wrote: >Dear List, > >Does anyone know of any python semweb tools? I'm especially interested >in tools to build and handle ontologies. I've come across CWM (built by >Tim BL) but not that much else. I'd be really interested in anything >that can interface with a DIG reasoner. > >Really, I'm looking for a pythonic version of something like Protege or >SWOOP Acronym Limit Error! That takes the record for Unknown Acronym/Term Density. So I can't be of any help. I hope there are some on this list who recognize and can help. Otherwise please expand some of the concepts for the rest of us. >Thanks, >Matt >-- >Dr. M. Williams MRCP(UK) >Clinical Research Fellow >Cancer Research UK >+44 (0)207 269 2953 >+44 (0)7834 899570 >http://acl.icnet.uk/~mw >http://adhominem.blogspot.com > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Nov 8 17:49:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 11:49:47 -0500 Subject: [Tutor] Raw image display in a GUI window In-Reply-To: <005201c5e476$68d8f510$66f6a8c0@zobook> References: <005201c5e476$68d8f510$66f6a8c0@zobook> Message-ID: <4370D72B.2040501@tds.net> Marcin Komorowski wrote: > Hello, > > I want to use Python to do some experimentation with graphic > processing/manipulation, and I am looking for a way to be able to manipulate > individual pixels of the image, as well as display it in a GUI. Ideal image > representation would be something of the form of a two-dimensional array of > tuples, each tuple containing the Red, Green and Blue components. Take a look at Python Imaging Library http://www.pythonware.com/products/pil/ It has functions for manipulating images and it interfaces to Tkinter. Kent -- http://www.kentsjohnson.com From maillist at roomity.com Tue Nov 8 17:56:37 2005 From: maillist at roomity.com (shenanigans) Date: Tue, 8 Nov 2005 08:56:37 -0800 (PST) Subject: [Tutor] [OTAnn] Feedback Message-ID: <31478357.1921131468997279.JavaMail.tomcat5@slave1.roomity.com> I was interested in getting feedback from current mail group users. We have mirrored your mail list in a new application that provides a more aggregated and safe environment which utilizes the power of broadband. Roomity.com v 1.5 is a web 2.01 community webapp. Our newest version adds broadcast video and social networking such as favorite authors and an html editor. It?s free to join and any feedback would be appreciated. S. ------------------------------------------------------------------------------------------------------------------------------ Broadband interface (RIA) + mail box saftey = Python_Tutor_List.roomity.com *Your* clubs, no sign up to read, ad supported; try broadband internet. ~~1131468997277~~ ------------------------------------------------------------------------------------------------------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051108/e01e35e1/attachment.html From bill at celestial.net Tue Nov 8 18:59:39 2005 From: bill at celestial.net (Bill Campbell) Date: Tue, 8 Nov 2005 09:59:39 -0800 Subject: [Tutor] Who called me? Message-ID: <20051108175939.GA36985@alexis.mi.celestial.com> Is there a way in python for a method to determine its parent? In particular, I'm working with SimpleXMLRPCServer, and would like to be able to find the client_address in the routine that has been dispatched. I know that client_address is an attribute of the handler class instance, but don't know how to get to that. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ My brother sent me a postcard the other day with this big satellite photo of the entire earth on it. On the back it said: ``Wish you were here''. -- Steven Wright From m.haft at abdn.ac.uk Tue Nov 8 19:13:11 2005 From: m.haft at abdn.ac.uk (Mike Haft) Date: Tue, 8 Nov 2005 18:13:11 -0000 (GMT) Subject: [Tutor] lists and strings Message-ID: <4061.134.34.34.75.1131473591.squirrel@www.abdn.ac.uk> Hello, I've been working on a problem and have now sorted most of it (thanks to some help from the list). All the ways of writing data to a file I know keep telling me that lists can't be written to the file. I'm trying to convert data from one set of files into files of a different format. But the easiest way to get the data from the first set of files is in a list(s). So, is there any way to convert lists to strings? Or a way to write lists to a file? Thanks Mike From matthew.williams at cancer.org.uk Tue Nov 8 20:03:18 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Tue, 08 Nov 2005 19:03:18 +0000 Subject: [Tutor] Python and Semantic Web In-Reply-To: <6.1.2.0.0.20051108083134.03528388@mail.mric.net> References: <1131466779.2747.13.camel@localhost.localdomain> <6.1.2.0.0.20051108083134.03528388@mail.mric.net> Message-ID: <1131476598.2747.35.camel@localhost.localdomain> Mea Culpa, Mea Culpa, Mea Maxima Culpa (or, MCMCMMC to repeat my sin of poly-acronymony. Semantic Web - (loosely) the idea of incorporating semantic information in the WWW, so it becomes machine understandable (rather than just parsable). CWM is Tim Berners-Lee's (and others) tool to handle ontologies. I think it has some rules in-built, but for reasons of efficiency, most ontology tools communicte with external Description Logic Reasoners via the DIG (Desc. Logic Implementation Group) interface, which is http/XML based. Much of the semweb stuff is OWL (Web Ontology Language - need to be a Winnie The Pooh fan to get the acronym) based. OWL is a layer that lies on top of RDF (which in turn, lies on top of XML). In general, yu build an ontology in OWL, and then interface with a reasoner to infer more info. about the model. The two big ontology building tools are Protege (with the Protege OWL plugin) and SWOOP, but both are Java based. HTH. Matt -- Dr. M. Williams MRCP(UK) Clinical Research Fellow Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 http://acl.icnet.uk/~mw http://adhominem.blogspot.com From hugonz-lists at h-lab.net Tue Nov 8 20:13:49 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 08 Nov 2005 13:13:49 -0600 Subject: [Tutor] lists and strings In-Reply-To: <4061.134.34.34.75.1131473591.squirrel@www.abdn.ac.uk> References: <4061.134.34.34.75.1131473591.squirrel@www.abdn.ac.uk> Message-ID: <4370F8ED.40502@h-lab.net> Hi Mike, Converting an (almost)arbitrary object into a string is what the Pickle module does. CPickle is faster. Take a look into into it in the docs. Here's an example: >>> import cPickle >>> lala = [1, 2, 3, 'four', 'V'] >>> lala [1, 2, 3, 'four', 'V'] >>> fileo = open('lala.pkl', 'w') >>> cPickle.dump(lala, fileo) >>> fileo.close() >>> fileo = open('lala.pkl', 'r') >>> serialized_data = fileo.read() >>> serialized_data "(lp1\nI1\naI2\naI3\naS'four'\np2\naS'V'\na." >>> fileo.seek(0) >>> recovered = cPickle.load(fileo) >>> recovered [1, 2, 3, 'four', 'V'] >>> See the docs and feel free to ask if there is some part oyu do not understand. Hope it helps! Hugo Mike Haft wrote: > Hello, > I've been working on a problem and have now sorted most of it (thanks > to some help from the list). > > All the ways of writing data to a file I know keep telling me that lists > can't be written to the file. I'm trying to convert data from one set of > files into files of a different format. But the easiest way to get the > data from the first set of files is in a list(s). > > So, is there any way to convert lists to strings? Or a way to write lists > to a file? > > Thanks > > Mike > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ajikoe at gmail.com Tue Nov 8 20:17:52 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 8 Nov 2005 20:17:52 +0100 Subject: [Tutor] lists and strings In-Reply-To: <4061.134.34.34.75.1131473591.squirrel@www.abdn.ac.uk> References: <4061.134.34.34.75.1131473591.squirrel@www.abdn.ac.uk> Message-ID: yes it is... convert list to string: L = [1,2,3] L = [str(x) for x in L] s = string.join(L,' ') print len(s) convert list to a file myF = open(namaFile,"w") for s in myList[:-1]: myF.write(str(s)+"\n") myF.write(str(myList[len(myList)-1])) myF.close() Cheers, pujo On 11/8/05, Mike Haft wrote: > > Hello, > I've been working on a problem and have now sorted most of it (thanks > to some help from the list). > > All the ways of writing data to a file I know keep telling me that lists > can't be written to the file. I'm trying to convert data from one set of > files into files of a different format. But the easiest way to get the > data from the first set of files is in a list(s). > > So, is there any way to convert lists to strings? Or a way to write lists > to a file? > > Thanks > > Mike > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051108/b9de233a/attachment.htm From marcink at ieee.org Tue Nov 8 20:24:12 2005 From: marcink at ieee.org (Marcin Komorowski) Date: Tue, 8 Nov 2005 14:24:12 -0500 Subject: [Tutor] Raw image display in a GUI window References: <005201c5e476$68d8f510$66f6a8c0@zobook> <4370C504.8020201@tardis.ed.ac.uk> Message-ID: <002801c5e49a$000ce9f0$66f6a8c0@zobook> Thanks Alex, Do you know if I can find somewhere sample code that would, lets say, create a 100x100 image and display it? Thanks, Marcin ----- Original Message ----- From: "Alex Hunsley" To: "Marcin Komorowski" Cc: "python-tutor" Sent: Tuesday, November 08, 2005 10:32 AM Subject: Re: [Tutor] Raw image display in a GUI window > Marcin Komorowski wrote: > >>Hello, >> >>I want to use Python to do some experimentation with graphic >>processing/manipulation, and I am looking for a way to be able to >>manipulate individual pixels of the image, as well as display it in a GUI. >>Ideal image representation would be something of the form of a >>two-dimensional array of tuples, each tuple containing the Red, Green and >>Blue components. >> >>I have looked at Tk and Tkinter, and there is a PhotoImage class that can >>define an image which can than be displayed in a Canvas widget, but the >>PhotoImage class seams to be doing a lot of extra work on the image, >>including gamma correction, etc. I am interested in being able to display >>exactly the pixel values I set. >> >>Thank You all in advance, >>Marcin > How about PyUI? > http://pyui.sourceforge.net/ > It may do what you're looking for... > alex > >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > From alan.gauld at freenet.co.uk Tue Nov 8 20:23:07 2005 From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 8 Nov 2005 19:23:07 -0000 Subject: [Tutor] interfaces and abstract classes in python Message-ID: <380-22005112819237221@freenet.co.uk> >>Yup, I was thinking more in terms of the Java idea, whereby an >>interface is declared specifically and then a class claiming >>to implement it causes compilation problems if it doesn't >>properly implement it. I guessed as much but that is an idea dreamt up by Microsoft for COM and picked up by Java to compensate for its lack of multiple inheritance. Since Python supports MI interfaces are neither useful nor desirable IMHO! Howeber they are being introduced in a future version I believe, mainly to appease the legions of Java programmers who think they are using OOP... >>> class InterfaceError(Exception): pass >>> >>> class Interface(Abstract): >>> def myMethod(self): pass >>> def myOther(self): raise InterfaceErrror >>> >>> Does that do what you want? >> >>I presume the "def myMethod(self): pass" is >> just for an 'optional' part of the interface? Its an optional way of doing interfaces. If you take the ObjectiveC or lisp approach defining a null method is a valid implementation, the second case shows what to do if you want a failure for unimplemented methods. The 'pass' approach is most akin to mixin style programming used in Lisp to implement interfaces (as originally defined in the Flavors dialect of Lisp) and used in most Multiple Inheriting languages(including C++) where as the exception style is typically used in statically typed single inheritance languages. Python can use the somple method of throwing an exception when a method is not found - this allows partial implementation of interfaces as is commonly found with "file-like2 interfaces where only open() and read() are actually coded not the whole gamut of file object methods. This is a much more powerful mechanism since it reduces the code to be produced while still ensuring errors are thrown when actually necessary. >>wondering if there was any other common ways >> to make interfaces more Not that I know of, after all one of the strengths of Python (and other dynamic OOPLs) is that they on rely on static checking of types. >>here to reply to the email address of the sender of the message In general yes, use Reply-All. It seems to prevent problems. Alan G. From alan.gauld at freenet.co.uk Tue Nov 8 20:30:38 2005 From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 8 Nov 2005 19:30:38 -0000 Subject: [Tutor] overloading binary operator for mixed types: a no-no? Message-ID: <380-220051128193038671@freenet.co.uk> Alex, I assume you've looked at NumPy? It has a bunch of math stuff written as a Python module in C. So its fast and proven correct. (Lawrence Livermore Labs wrote it I believe) It should do all the heavy lifting you need, and might even provide a full solution. Just a thought, Alan G. From kent37 at tds.net Tue Nov 8 20:37:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 14:37:56 -0500 Subject: [Tutor] Raw image display in a GUI window In-Reply-To: <003701c5e49a$358bad50$66f6a8c0@zobook> References: <005201c5e476$68d8f510$66f6a8c0@zobook> <4370D72B.2040501@tds.net> <003701c5e49a$358bad50$66f6a8c0@zobook> Message-ID: <4370FE94.2040000@tds.net> Marcin Komorowski wrote: > Thanks Kent, this looks promising. > Are you very familiar with the Python Imaging Library? No, I have just used it for a few small things. I know it mostly by reputation. > Can I pick your > brains if I have questions? Best to ask questions to the list, I will answer the ones I can. Fredrik Lundh is the author of PIL, he answers questions on comp.lang.python, so if you can't get the help you need here then try there. Kent From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 8 20:40:09 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 9 Nov 2005 08:40:09 +1300 Subject: [Tutor] Who called me? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B138C@chbnt01.alpha.wd.govt.nz> I believe only by explicitly passing a reference to the parent? Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Bill Campbell Sent: Wednesday, 9 November 2005 7:00 a.m. To: Tutor Subject: [Tutor] Who called me? Is there a way in python for a method to determine its parent? In particular, I'm working with SimpleXMLRPCServer, and would like to be able to find the client_address in the routine that has been dispatched. I know that client_address is an attribute of the handler class instance, but don't know how to get to that. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ My brother sent me a postcard the other day with this big satellite photo of the entire earth on it. On the back it said: ``Wish you were here''. -- Steven Wright _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From alan.gauld at freenet.co.uk Tue Nov 8 20:43:02 2005 From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 8 Nov 2005 19:43:02 -0000 Subject: [Tutor] Raw image display in a GUI window Message-ID: <380-22005112819432846@freenet.co.uk> > >>>I want to use Python to do some experimentation with graphic >>>processing/manipulation, and I am looking for a way to be able to >manipulate >>>individual pixels of the image, as well as display it in a GUI. Sounds like a job for the Python Image Library - PIL. Alan G From kent37 at tds.net Tue Nov 8 20:46:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 14:46:07 -0500 Subject: [Tutor] Who called me? In-Reply-To: <20051108175939.GA36985@alexis.mi.celestial.com> References: <20051108175939.GA36985@alexis.mi.celestial.com> Message-ID: <4371007F.7070008@tds.net> Bill Campbell wrote: > Is there a way in python for a method to determine its parent? > > In particular, I'm working with SimpleXMLRPCServer, and would > like to be able to find the client_address in the routine that > has been dispatched. I know that client_address is an attribute > of the handler class instance, but don't know how to get to that. You can inspect the stack frame to find this out. Search the online cookbook for _getframe - I don't see one recipe that does exactly what you want but the pieces are there. http://aspn.activestate.com/ASPN/Cookbook/Python Kent -- http://www.kentsjohnson.com From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 8 20:38:43 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 9 Nov 2005 08:38:43 +1300 Subject: [Tutor] [OTAnn] Feedback Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B138B@chbnt01.alpha.wd.govt.nz> Oh dear. Is Web 2.01 like that whole Web 2 I've heard so much about, but better? Is it the semantic web, but not so pedantic? Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of shenanigans Sent: Wednesday, 9 November 2005 5:57 a.m. To: tutor at python.org Subject: [Tutor] [OTAnn] Feedback I was interested in getting feedback from current mail group users. We have mirrored your mail list in a new application that provides a more aggregated and safe environment which utilizes the power of broadband. Roomity.com v 1.5 is a web 2.01 community webapp. Our newest version adds broadcast video and social networking such as favorite authors and an html editor. It?s free to join and any feedback would be appreciated. S. ---------------------------------------------------------------------------- -------------------------------------------------- Broadband interface (RIA) + mail box saftey = Python_Tutor_List.roomity.com *Your* clubs, no sign up to read, ad supported; try broadband internet. ~~1131468997277~~ ---------------------------------------------------------------------------- -------------------------------------------------- A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From project5 at redrival.net Tue Nov 8 20:57:34 2005 From: project5 at redrival.net (Andrei) Date: Tue, 08 Nov 2005 20:57:34 +0100 Subject: [Tutor] Who called me? In-Reply-To: <20051108175939.GA36985@alexis.mi.celestial.com> References: <20051108175939.GA36985@alexis.mi.celestial.com> Message-ID: Bill Campbell wrote: > Is there a way in python for a method to determine its parent? > In particular, I'm working with SimpleXMLRPCServer, and would > like to be able to find the client_address in the routine that > has been dispatched. I know that client_address is an attribute > of the handler class instance, but don't know how to get to that. I'm not sure what you mean by its parent (also never worked with SimpleXMLRPCServer). Something like this? >>> class A(object): ... pass >>> class B(object): ... pass >>> def func(self): ... print self.__class__ >>> A.f = func >>> B.f = func >>> a, b = A(), B() >>> a.f(), b.f() -- Yours, Andrei ===== Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) From cjw at sympatico.ca Tue Nov 8 21:10:34 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 08 Nov 2005 15:10:34 -0500 Subject: [Tutor] Who called me? In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B138C@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B138C@chbnt01.alpha.wd.govt.nz> Message-ID: <4371063A.9040508@sympatico.ca> Liam Clarke-Hutchinson wrote: >I believe only by explicitly passing a reference to the parent? > >Liam Clarke-Hutchinson > >-----Original Message----- >From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf >Of Bill Campbell >Sent: Wednesday, 9 November 2005 7:00 a.m. >To: Tutor >Subject: [Tutor] Who called me? > > >Is there a way in python for a method to determine its parent? > >In particular, I'm working with SimpleXMLRPCServer, and would like to be >able to find the client_address in the routine that has been dispatched. I >know that client_address is an attribute of the handler class instance, but >don't know how to get to that. > >Bill >-- >INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC >UUCP: camco!bill PO Box 820; 6641 E. Mercer Way >FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 >URL: http://www.celestial.com/ > >My brother sent me a postcard the other day with this big satellite photo of >the entire earth on it. On the back it said: ``Wish you were here''. > -- Steven Wright >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > >A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. > > > > >http://www.govt.nz - connecting you to New Zealand central & local government services > >Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > You might consider the inspect module. See 3.11.4 in the Library Reference. I think that the interpreter stack contains this information but have not used te module myself. Colin W. From chris.irish at libertydistribution.com Tue Nov 8 21:32:16 2005 From: chris.irish at libertydistribution.com (Chris Irish) Date: Tue, 08 Nov 2005 13:32:16 -0700 Subject: [Tutor] How to launch executable from a Python script?? Message-ID: <43710B50.1070909@libertydistribution.com> Hello all :) I made a GUI app with pyGTK that I want to be able to launch a game I've downloaded from the pygame website when a button is clicked. I was able to do this on a linux box since the file was a .py file, but I'm not sure how to do it on a windows box since the file is an executeable. On linux I did this: import os olddir = os.getcwd() #to keep a reference to the old directory to switch games later os.chdir('spacinVaders-0.1') #switch to the game's directory os.spawnlp(os.P_NOWAIT, 'pythonw', 'pythonw', 'play.py') and it would launch fine.... can someone help me with this?? Thanks in advance..... Chris :P From dyoo at hkn.eecs.berkeley.edu Tue Nov 8 21:37:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 8 Nov 2005 12:37:57 -0800 (PST) Subject: [Tutor] [OTAnn] Feedback In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B138B@chbnt01.alpha.wd.govt.nz> Message-ID: On Wed, 9 Nov 2005, Liam Clarke-Hutchinson wrote: > Is Web 2.01 like that whole Web 2 I've heard so much about, but better? Is > it the semantic web, but not so pedantic? That was bad, and the first spam I've seen on the list in a while. I'm blocking this joker off the mailing list now. From kent37 at tds.net Tue Nov 8 21:46:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 15:46:48 -0500 Subject: [Tutor] Who called me? In-Reply-To: <4371007F.7070008@tds.net> References: <20051108175939.GA36985@alexis.mi.celestial.com> <4371007F.7070008@tds.net> Message-ID: <43710EB8.9090705@tds.net> Kent Johnson wrote: > Bill Campbell wrote: > >>Is there a way in python for a method to determine its parent? >> >>In particular, I'm working with SimpleXMLRPCServer, and would >>like to be able to find the client_address in the routine that >>has been dispatched. I know that client_address is an attribute >>of the handler class instance, but don't know how to get to that. > > > You can inspect the stack frame to find this out. Search the online cookbook for _getframe - I don't see one recipe that does exactly what you want but the pieces are there. > http://aspn.activestate.com/ASPN/Cookbook/Python OK here is a simple module that shows callers on the stack. import sys def showFrame(f): print 'Name =', f.f_code.co_name for k, v in f.f_locals.iteritems(): print ' ', k, '=', v print def whereAmI(): i=1 while True: try: f = sys._getframe(i) showFrame(f) i += 1 except ValueError: break if __name__ == '__main__': def foo(a): bar = 'baz' zap = 3 whereAmI() def bar(): foo(3) bar() When I run this it prints Name = foo a = 3 bar = baz zap = 3 Name = bar Name = ? bar = showFrame = __builtins__ = __file__ = F:\Tutor\ShowStack.py sys = whereAmI = __name__ = __main__ foo = __doc__ = Show stuff from the stack frame HOWEVER, I don't think this is a good solution to your problem - it's quite a fragile hack. Better would be to find a way to pass the information you need to your function. For example, from a quick look at the code for SimpleXMLRPCServer, it looks like you could subclass SimpleXMLRPCServer and make your own _dispatch() method that adds client_address to the parameter list, then all your functions would be passed the client_address. Or even specialize it so that just one special function gets this treatment. Kent From shantanoo at gmail.com Tue Nov 8 22:02:41 2005 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Wed, 9 Nov 2005 02:32:41 +0530 Subject: [Tutor] lists and strings In-Reply-To: <4370F8ED.40502@h-lab.net> References: <4370F8ED.40502@h-lab.net> Message-ID: <20051108210241.GA3562@ghar.dhoomketu.net.in> +++ Hugo Gonz?lez Monteverde [08-11-05 13:13 -0600]: | Hi Mike, | | Converting an (almost)arbitrary object into a string is what the Pickle module does. CPickle is faster. Take | a look into into it in the docs. | Is there a way to dump the varialble in XML format and retrive it? e.g. a="this is string" b=1234567890 c={} c['a'] = a c['b'] = b and then dump c. Regards, Shantanoo -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 187 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051109/93c11d60/attachment.pgp From chris.arndt at web.de Tue Nov 8 22:45:45 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Tue, 08 Nov 2005 21:45:45 +0000 Subject: [Tutor] lists and strings In-Reply-To: <20051108210241.GA3562@ghar.dhoomketu.net.in> References: <4370F8ED.40502@h-lab.net> <20051108210241.GA3562@ghar.dhoomketu.net.in> Message-ID: <43711C89.7010102@web.de> Shantanoo Mahajan schrieb: > +++ Hugo Gonz?lez Monteverde [08-11-05 13:13 -0600]: > | Hi Mike, > | > | Converting an (almost)arbitrary object into a string is what the Pickle module does. CPickle is faster. Take > | a look into into it in the docs. > | > > Is there a way to dump the varialble in XML format and retrive it? Look for xml_pickle.py in http://gnosis.cx/download/Gnosis_Utils-current.tar.gz and see the article on it here: http://gnosis.cx/publish/programming/xml_matters_1.txt Also, xmlrpclib.py from the Standard library contains functions to serialize basic Python data types to XML according to the XML-RPC specification. Chris From kent37 at tds.net Tue Nov 8 23:05:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 17:05:28 -0500 Subject: [Tutor] lists and strings In-Reply-To: <4061.134.34.34.75.1131473591.squirrel@www.abdn.ac.uk> References: <4061.134.34.34.75.1131473591.squirrel@www.abdn.ac.uk> Message-ID: <43712128.7000303@tds.net> Mike Haft wrote: > All the ways of writing data to a file I know keep telling me that lists > can't be written to the file. I'm trying to convert data from one set of > files into files of a different format. But the easiest way to get the > data from the first set of files is in a list(s). > > So, is there any way to convert lists to strings? Or a way to write lists > to a file? What do you want the data to look like in the file? You can create a string from your list and write the string to the file. For example if the list contains strings and you just want to separate the values with spaces use join(): >>> data = ['22.5', '0.3', '11.9'] >>> ' '.join(data) '22.5 0.3 11.9' Or you could separate the values with comma and space: >>> ', '.join(data) '22.5, 0.3, 11.9' I think from your previous post that your actual data is a list of lists, so you have to iterate the outside list, formatting each line and writing it to the file, something like this (borrowing from your previous unanswered post): out_file = open("test.txt","w") data = readSOMNETM(filename) for line in data: line = ' '.join(line) out_file.write(line) out_file.write('\n') # need a newline after each line out_file.close() Kent -- http://www.kentsjohnson.com From john at fouhy.net Tue Nov 8 23:17:07 2005 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Nov 2005 11:17:07 +1300 Subject: [Tutor] TKinter Question In-Reply-To: <5e58f2e40511081416n77e7adc8r@mail.gmail.com> References: <43704148.1000804@customdatasoft.com> <5e58f2e40511081416n77e7adc8r@mail.gmail.com> Message-ID: <5e58f2e40511081417l476f522as@mail.gmail.com> On 08/11/05, Rob Dowell wrote: > Just a quick TKinter question. Is it possible to have custom > frames/widgets? In other words can I customize the way that the GUI > looks (i.e. rounded corners on the frames, beveled/raised edges, etc.) I > was just wondering if it was possible and if it is possible then where I > might get some information on how to do it. Thank you very much, Rob. Have you looked at the options for the frame class? Eg, Frame(parent, borderwidth=2, relief=RIDGE) If you want more, you could build custom widgets using a Canvas. Finally, you could try the Widget Construction Kit: http://effbot.org/zone/wck.htm This is quite new, however, so you might not get any help here (unless there's some WCK experts hiding here somewhere :-) ). -- John. From dyoo at hkn.eecs.berkeley.edu Tue Nov 8 23:34:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 8 Nov 2005 14:34:42 -0800 (PST) Subject: [Tutor] TKinter Question In-Reply-To: <5e58f2e40511081417l476f522as@mail.gmail.com> Message-ID: > On 08/11/05, Rob Dowell wrote: > > Just a quick TKinter question. Is it possible to have custom > > frames/widgets? In other words can I customize the way that the GUI > > looks (i.e. rounded corners on the frames, beveled/raised edges, etc.) I > > was just wondering if it was possible and if it is possible then where I > > might get some information on how to do it. Thank you very much, Rob. > > Have you looked at the options for the frame class? Eg, Frame(parent, > borderwidth=2, relief=RIDGE) Hi Rob, Also, some people have written some custom widget classes as part of the Python Megawidgets project: http://pmw.sourceforge.net/ But it sounds more like you might be interested in things like skinning; unfortunately, I don't know too much about that. Best of wishes to you! From ajikoe at gmail.com Wed Nov 9 00:08:15 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 9 Nov 2005 00:08:15 +0100 Subject: [Tutor] How to launch executable from a Python script?? In-Reply-To: <43710B50.1070909@libertydistribution.com> References: <43710B50.1070909@libertydistribution.com> Message-ID: Try to add .py in PATHEXT environment windows XP After that, you can call your python program just like you call exe file. Hope this help. pujo On 11/8/05, Chris Irish wrote: > > Hello all :) > I made a GUI app with pyGTK that I want to be able to launch a game I've > downloaded from the pygame website when a button is clicked. I was able > to do this on a linux box since the file was a .py file, but I'm not > sure how to do it on a windows box since the file is an executeable. On > linux I did this: > > import os > olddir = os.getcwd() #to keep a reference to the old > directory to switch games later > os.chdir('spacinVaders-0.1') #switch to the game's directory > os.spawnlp(os.P_NOWAIT, 'pythonw', 'pythonw', 'play.py') > > and it would launch fine.... can someone help me with this?? > > Thanks in advance..... Chris :P > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051109/d5f1bf1d/attachment.htm From lard at tardis.ed.ac.uk Wed Nov 9 00:41:18 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 23:41:18 +0000 Subject: [Tutor] Raw image display in a GUI window In-Reply-To: <4370FE94.2040000@tds.net> References: <005201c5e476$68d8f510$66f6a8c0@zobook> <4370D72B.2040501@tds.net> <003701c5e49a$358bad50$66f6a8c0@zobook> <4370FE94.2040000@tds.net> Message-ID: <4371379E.1010807@tardis.ed.ac.uk> Kent Johnson wrote: >Marcin Komorowski wrote: > > >>Thanks Kent, this looks promising. >>Are you very familiar with the Python Imaging Library? >> >> > >No, I have just used it for a few small things. I know it mostly by reputation. > > > >>Can I pick your >>brains if I have questions? >> >> > >Best to ask questions to the list, I will answer the ones I can. > >Fredrik Lundh is the author of PIL, he answers questions on comp.lang.python, so if you can't get the help you need here then try there. > > I've used PIL a little before and found it to be very useful! Make loading, saving and manipulating images programatticaly quite easy. >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From lard at tardis.ed.ac.uk Wed Nov 9 00:43:21 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 23:43:21 +0000 Subject: [Tutor] Raw image display in a GUI window In-Reply-To: <4370C504.8020201@tardis.ed.ac.uk> References: <005201c5e476$68d8f510$66f6a8c0@zobook> <4370C504.8020201@tardis.ed.ac.uk> Message-ID: <43713819.3030603@tardis.ed.ac.uk> Alex Hunsley wrote: > Marcin Komorowski wrote: > >> Hello, >> >> I want to use Python to do some experimentation with graphic >> processing/manipulation, and I am looking for a way to be able to >> manipulate individual pixels of the image, as well as display it in a >> GUI. Ideal image representation would be something of the form of a >> two-dimensional array of tuples, each tuple containing the Red, Green >> and Blue components. >> >> I have looked at Tk and Tkinter, and there is a PhotoImage class that >> can define an image which can than be displayed in a Canvas widget, >> but the PhotoImage class seams to be doing a lot of extra work on the >> image, including gamma correction, etc. I am interested in being >> able to display exactly the pixel values I set. >> >> Thank You all in advance, >> Marcin >> > How about PyUI? > http://pyui.sourceforge.net/ > It may do what you're looking for... > alex To add to my previous comment.... have a look at PyGame too: http://www.pygame.org/news.html It's designed for games programming, and makes it a snap to load and display an image in a window! (and lots of other things, e.g. sprites and animation) From lard at tardis.ed.ac.uk Wed Nov 9 00:45:48 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 23:45:48 +0000 Subject: [Tutor] overloading binary operator for mixed types: a no-no? In-Reply-To: <380-220051128193038671@freenet.co.uk> References: <380-220051128193038671@freenet.co.uk> Message-ID: <437138AC.4050302@tardis.ed.ac.uk> alan.gauld at freenet.co.uk wrote: >Alex, > >I assume you've looked at NumPy? > > Yup, I'm aware of it and it would do the job just fine (and faster too, probably). However, I'm happy writing my own code (+tests) for the moment - I'm getting more experience of writing stuff in Python. I may switch to NumPy or similar later! thanks alex From lard at tardis.ed.ac.uk Wed Nov 9 00:50:06 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 08 Nov 2005 23:50:06 +0000 Subject: [Tutor] testing: doctest and unittest In-Reply-To: <4370C141.7070003@sympatico.ca> References: <4370A3A5.6080701@tardis.ed.ac.uk> <4370C141.7070003@sympatico.ca> Message-ID: <437139AE.10000@tardis.ed.ac.uk> Colin J. Williams wrote: > Alex Hunsley wrote: > >> Regards testing, I've been playing with both the unittest >> (http://pyunit.sourceforge.net/pyunit.html) and doctest >> (http://docs.python.org/lib/module-doctest.html). I was wondering >> what peoples thoughts were on the effectiveness and convenience of >> one versus the other. It seems to me that doctest is good for quicky >> and straightforwards input/output tests for small units, whereas >> unittest would be good for dynamic or complicated testing. >> >> Where do you seasoned pythonites see unittest and doctest in relation >> to each other? Do you only use one or the other? >> >> ta, >> alex >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > I looked at doctest and feel that it clutters the module text and so > would prefer unittest but I haven't yet got to formalizing my tests in > that way. > > See some of the numarray source as an example of clutter. Some argue > that having the examples in the source is beneficial. I agree but > feel that the clutter outweighs the benefit. I also feel that the clutter aspect of doctest can be a little bit of a put off. I like the idea of the having the target code nicely seperate from the tests, and really thorough doctests could swamp the target code a little too much! Plus, of course, if you write unittests, there are more options apparently available, like using the graphical test runner, etc. doctest is simpler (not always necessarily a bad thing). ta alex From ewalker at micron.com Wed Nov 9 00:47:07 2005 From: ewalker at micron.com (Eric Walker) Date: Tue, 8 Nov 2005 16:47:07 -0700 Subject: [Tutor] Video Message-ID: <200511081647.07211.ewalker@micron.com> I would like to do some testing of video streams from say a vcr tape. Possibly using the PVR type capture card. Maybe modules to control it.. or some info on how I can control it through C/C++ and link those functions into python. Are there any python user groups or modules that could help me in this regard? Thanks Eric ... From kens7601 at gmail.com Wed Nov 9 01:11:49 2005 From: kens7601 at gmail.com (Ken Stevens) Date: Tue, 8 Nov 2005 19:11:49 -0500 Subject: [Tutor] Testing for gui Message-ID: <20051109001149.GA7261@mercury.squeezel.com> How does one test for a running gui in python? Thanks, Ken -- A journey of a thousand miles starts under one's feet. -- Lao Tsu From Liam.Clarke-Hutchinson at business.govt.nz Wed Nov 9 01:16:03 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 9 Nov 2005 13:16:03 +1300 Subject: [Tutor] Testing for gui Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1392@chbnt01.alpha.wd.govt.nz> Hi Ken, How do you mean? I assume you're referring to a non-Windows environment? In Linux, I'd imagine that using os.popen("ps") would do it. Cheers, Liam -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Ken Stevens Sent: Wednesday, 9 November 2005 1:12 p.m. To: tutor at python.org Subject: [Tutor] Testing for gui How does one test for a running gui in python? Thanks, Ken -- A journey of a thousand miles starts under one's feet. -- Lao Tsu _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Liam.Clarke-Hutchinson at business.govt.nz Wed Nov 9 01:28:47 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 9 Nov 2005 13:28:47 +1300 Subject: [Tutor] Testing for gui Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1395@chbnt01.alpha.wd.govt.nz> Hmm, no x-server. If you're looking to detect running Python GUI packages, you could check the namespaces for 'em, but beyond that, I'm stumped. -----Original Message----- From: Ken Stevens [mailto:kens7601 at gmail.com] Sent: Wednesday, 9 November 2005 1:23 p.m. To: Liam Clarke-Hutchinson Subject: Re: [Tutor] Testing for gui On Wed, Nov 09, 2005 at 01:16:03PM +1300, Liam Clarke-Hutchinson wrote: > > Hi Ken, > > How do you mean? I assume you're referring to a non-Windows > environment? In Linux, I'd imagine that using os.popen("ps") would do > it. > > Cheers, > > Liam > Yes. Under Linux no x-server running? I guess it really wouldn't be applicable under a windows enviroment, although I would like my code to be transportable. Just under a MS windows enviroment it would always be a "gui" environment. Thanks, Ken -- Go 'way! You're bothering me! A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From john at fouhy.net Wed Nov 9 01:45:07 2005 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Nov 2005 13:45:07 +1300 Subject: [Tutor] Testing for gui In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1395@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1395@chbnt01.alpha.wd.govt.nz> Message-ID: <5e58f2e40511081645u2e2e7e8q@mail.gmail.com> From: Ken Stevens [mailto:kens7601 at gmail.com] > Yes. Under Linux no x-server running? I guess it really wouldn't be > applicable under a windows enviroment, although I would like my code > to be transportable. Just under a MS windows enviroment it would > always be a "gui" environment. What happens if you try to create a GUI and X is not running? Maybe you could just try to create a Tkinter.Tk() --- if it throws a python exception (probably TclError), you could just catch that. -- John. From carroll at tjc.com Wed Nov 9 01:49:55 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 8 Nov 2005 16:49:55 -0800 (PST) Subject: [Tutor] Using debuglevel with urllib2? Message-ID: With urllib, you can set httplib.HTTPConnection.debuglevel to see the HTTP conversation. But it doesn't work with urllib2. Can someone explain how to use it in conjunction with urllib2? Longer story: debuuglevel is a nice debug tool that lets you see the client-server HTTP conversation: >>> import httplib >>> httplib.HTTPConnection.debuglevel = 1 >>> import urllib >>> testurl = "http://www.yahoo.com" >>> f = urllib.urlopen(testurl) connect: (www.yahoo.com, 80) send: 'GET / HTTP/1.0\r\nHost: www.yahoo.com\r\nUser-agent: Python-urllib/1.16\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Date: Wed, 09 Nov 2005 00:37:50 GMT header: P3P: policyref="http://p3p.yahoo.com/w3c/p3p.xml", CP="CAO DSP COR CUR ADM DEV TAI PSA PSD IVAi IVDi CONi TELo OTPi OUR DELi SAMi OTRi UNRi PUBi IND PHY ONL UNI PUR FIN COM NAV INT DEM CNT STA POL HEA PRE GOV" header: Cache-Control: private header: Vary: User-Agent header: Set-Cookie: FPB=pkvre11vo11n2h6u; expires=Thu, 01 Jun 2006 19:00:00 GMT; path=/; domain=www.yahoo.com header: Connection: close header: Content-Type: text/html >>> Alas, it doesn't work with urllib2: >>> import urllib2 >>> f = urllib2.urlopen(testurl) >>> [silence] I need to use urllib2, because I need to include some headers, and as far as I can tell, urllib doesn't let you do that. The debuglevel issue was reported as a bug, 1152723,[1] but one of the comments is that the h.set_debuglevel(self._debuglevel) can be used to address this, on a per-connection basis. Leaving aside the issue of whether this actually is a bug or an imporvement, I don't follow the explanation. Can someone explain to me how to set the debuglevel using urllib2? Thanks! [1] Link to bug report: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1152723&group_id=5470 or http://makeashorterlink.com/?F23C2102C From amonroe at columbus.rr.com Wed Nov 9 02:48:25 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 8 Nov 2005 20:48:25 -0500 Subject: [Tutor] Raw image display in a GUI window In-Reply-To: <4370FE94.2040000@tds.net> References: <005201c5e476$68d8f510$66f6a8c0@zobook> <4370D72B.2040501@tds.net> <003701c5e49a$358bad50$66f6a8c0@zobook> <4370FE94.2040000@tds.net> Message-ID: <58171697948.20051108204825@columbus.rr.com> > Marcin Komorowski wrote: >> Thanks Kent, this looks promising. >> Are you very familiar with the Python Imaging Library? > No, I have just used it for a few small things. I know it mostly by reputation. Somewhat related question: Why isn't PIL in the standard library? Alan From kent37 at tds.net Wed Nov 9 04:16:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 22:16:26 -0500 Subject: [Tutor] testing: doctest and unittest In-Reply-To: <4370A3A5.6080701@tardis.ed.ac.uk> References: <4370A3A5.6080701@tardis.ed.ac.uk> Message-ID: <43716A0A.9070409@tds.net> Alex Hunsley wrote: > Regards testing, I've been playing with both the unittest > (http://pyunit.sourceforge.net/pyunit.html) and doctest > (http://docs.python.org/lib/module-doctest.html). I was wondering what > peoples thoughts were on the effectiveness and convenience of one versus > the other. It seems to me that doctest is good for quicky and > straightforwards input/output tests for small units, whereas unittest > would be good for dynamic or complicated testing. > > Where do you seasoned pythonites see unittest and doctest in relation to > each other? Do you only use one or the other? I think it is mostly personal preference. Doctest is nice where you create examples for others, maybe not so nice where you are creating exhaustive unit tests trying to exercise every corner case. unittest is perhaps easier to aggregate tests from multiple modules. Doctests integrate with unittest in Python 2.4. Personally I use unittest but I come from a Java background and learned TDD with JUnit which is related to unittest. Another option is py.test which is part of the PyPy project, not part of the standard library. Some people think it is simpler and more Pythonic than unittest. This page has good articles about doctest, unittest and py.test: http://agiletesting.blogspot.com/2005/11/articles-and-tutorials-page-updated.html -- http://www.kentsjohnson.com From ismaelgf at adinet.com.uy Wed Nov 9 04:20:17 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 09 Nov 2005 01:20:17 -0200 Subject: [Tutor] Spanish text in BS problem Message-ID: <43716AF1.8030101@adinet.com.uy> Hello I'm using Beautiful Soup to scrape a site (that's in Spanish) I sometimes come across strings like: 'Ner\\xf3n como cantor' Which gets printed: Ner\xf3n como cantor When they should be: Ner?n como cantor I don't know if it is my fault (due to me misusing BS) or is it a BS fault. Anyway, is there a way to print the string correctly? This is the code I'm using in BS a = open("zona.htm") text = a.readlines() a.close() BS = BeautifulSoup.BeautifulSoup(str(text)) for ed in BS('span', {'class':'ed_ant_fecha'}): urlynombre = ed.findNextSibling().findNextSibling().findNextSibling() nombre = urlynombre.next.next And "nombre" is that string I mentioned. Any help is appreciated, thanks Ismael From kent37 at tds.net Wed Nov 9 04:32:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 08 Nov 2005 22:32:41 -0500 Subject: [Tutor] Using debuglevel with urllib2? In-Reply-To: References: Message-ID: <43716DD9.8030804@tds.net> Terry Carroll wrote: > With urllib, you can set httplib.HTTPConnection.debuglevel to see the HTTP > conversation. But it doesn't work with urllib2. Can someone explain how > to use it in conjunction with urllib2? You have to create your own HTTPHandler, set it to debug and install it in urllib2. Like this: >>> import urllib2 >>> h=urllib2.HTTPHandler(debuglevel=1) >>> opener = urllib2.build_opener(h) >>> urllib2.install_opener(opener) >>> urllib2.urlopen('http://www.google.com').read() connect: (www.google.com, 80) send: 'GET / HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.com\r\nConnection: close\r\nUser-agent: Python-urllib/2. reply: 'HTTP/1.1 200 OK\r\n' header: Cache-Control: private ...etc. > Leaving aside the issue of whether this actually is a bug or an > imporvement, I don't follow the explanation. It's pretty obscure. I had to poke around in the source for a while before I could understand it. Kent -- http://www.kentsjohnson.com From royb at ubiquity.com.au Wed Nov 9 04:54:52 2005 From: royb at ubiquity.com.au (Roy Bleasdale) Date: Wed, 09 Nov 2005 14:54:52 +1100 Subject: [Tutor] Problem appending to a list using a property within a class Message-ID: <5.1.0.14.2.20051109143340.02b8d090@localhost> I have created a List within a class. If I try and append to the list using the set function using the property value my variable stops being a list. Can anyone explain why the set function called by the class property does not append to the list? Here is some sample code: class ShoppingBag: def __init__(self): self.fruit = [] self.veg = [] self.spam = 0 self.beer = [] def getspam(self): return self.spam def setspam(self,value): self.spam = value spam = property(getspam,setspam,None,None) def getveg(self): return self.veg def setveg(self,value): self.veg.append(value) veg = property(getveg,setveg,None,None) def getfruit(self): return self.fruit def setfruit(self,value): self.fruit.append(value) fruit = property(getfruit,setfruit,None,None) def Addfruit(self,value): self.fruit.append(value) def getbeer(self): return self.beer def setbeer(self,value): self.beer.append(value) beer = property(getbeer,setbeer,None,None) bag = ShoppingBag() bag.spam = 3 bag.veg = "carrots" bag.veg = "broccoli" bag.veg = "cauliflower" bag.Addfruit("apple") bag.Addfruit("banana") bag.Addfruit("orange") bag.setbeer ("coopers") bag.setbeer("mountain goat") bag.setbeer("cascade") print "contents of bag" print bag.spam print bag.veg print bag.fruit print bag.beer basket = ShoppingBag() basket.setveg ( "carrots") basket.setveg ( "broccoli") basket.setveg ( "cauliflower") print "contents of basket" print basket.veg when I run it I get: contents of bag 3 cauliflower ['apple', 'banana', 'orange'] ['coopers', 'mountain goat', 'cascade'] contents of basket ['carrots', 'broccoli', 'cauliflower'] Thanks From billburns at pennswoods.net Wed Nov 9 05:07:44 2005 From: billburns at pennswoods.net (Bill Burns) Date: Tue, 08 Nov 2005 23:07:44 -0500 Subject: [Tutor] Find multiple lines in a file Message-ID: <43717610.8090704@pennswoods.net> I have a PostScript file which contains the following lines (the numbers are for reference only and are *not* in the file): 1 << 2 /Policies << 3 /PageSize 3 4 >> 5 >> setpagedevice These lines never change and are always formatted like this (at least in the PostScript files that I'm generating with tiff2ps). I want to open the the file and read it, find these five lines and then replace the lines with something different. I understand how to open and read the file. I have no problems finding and changing a *single* line, but I can not figure out how to find the *multiple* lines (and put them into one variable). Here's some code I'm using to replace just a *single* line in the PostScript file (Note - I'm changing the BoundingBox which is in the same file, but is *not* one of the five lines above). import fileinput class ChangeBBox: pass def getBBox(self, filename): f = open(filename, "rb") buffer = 1000 tmp = f.readlines(buffer) f.close() for line in tmp: if line.startswith('%%BoundingBox:'): return line.strip() def modifyBBox(self, filename): old = self.getBBox(filename) new = '%%BoundingBox: 0 0 1296 1728' for line in fileinput.input(filename, inplace=1): print line.replace(old, new), The above code uses the fileinput module which makes it really nice for modifying a file 'inplace'. I use the code like this c = ChangeBBox() c.modifyBBox(somePostScriptFile.ps) and it works great, but it's really simple because it only has to modify *one* line. Can anyone offer suggestions on how to find all five lines? I don't think I'll have a problem replacing the lines, it's just getting them all into one variable that stumping me :-) Thanks, Bill From john at fouhy.net Wed Nov 9 05:09:05 2005 From: john at fouhy.net (John Fouhy) Date: Wed, 9 Nov 2005 17:09:05 +1300 Subject: [Tutor] Problem appending to a list using a property within a class In-Reply-To: <5.1.0.14.2.20051109143340.02b8d090@localhost> References: <5.1.0.14.2.20051109143340.02b8d090@localhost> Message-ID: <5e58f2e40511082009k6a1d3e4cp@mail.gmail.com> On 09/11/05, Roy Bleasdale wrote: > I have created a List within a class. If I try and append to the list using > the set function using the property value my variable stops being a list. > > Can anyone explain why the set function called by the class property does > not append to the list? > > > Here is some sample code: > > class ShoppingBag: Properties only work properly with new style classes. You get a new style class by inheriting from another new style class, or by inheriting from object. Try changing the first line to "class ShoppingBag(object):". This is a somewhat annoying distinction that will hopefully go away in a future version of python (when all classes become new style). -- John. From carroll at tjc.com Wed Nov 9 05:30:37 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue, 8 Nov 2005 20:30:37 -0800 (PST) Subject: [Tutor] Using debuglevel with urllib2? In-Reply-To: <43716DD9.8030804@tds.net> Message-ID: On Tue, 8 Nov 2005, Kent Johnson wrote: > You have to create your own HTTPHandler, set it to debug and install it > in urllib2. Like this: Thanks, Kent! From sli1que at yahoo.com Wed Nov 9 05:56:32 2005 From: sli1que at yahoo.com (Eric Walker) Date: Tue, 8 Nov 2005 20:56:32 -0800 (PST) Subject: [Tutor] Video In-Reply-To: <200511081647.07211.ewalker@micron.com> Message-ID: <20051109045632.19588.qmail@web60118.mail.yahoo.com> no takrs on this one? --- Eric Walker wrote: > I would like to do some testing of video streams > from say a vcr tape. Possibly > using the PVR type capture card. Maybe modules to > control it.. or some info > on how I can control it through C/C++ and link those > functions into python. > Are there any python user groups or modules that > could help me in this > regard? > > Thanks > > Eric ... > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Pre-Paid Legal can help protect your legal rights. Be able to say, "I'm going to talk to my lawyer about that." -- AND MEAN IT! Phone Consultations on Unlimited Matters Legally written Letters to show you mean Business Contract and Document Review. Need Webhosting? __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Wed Nov 9 07:29:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 8 Nov 2005 22:29:06 -0800 (PST) Subject: [Tutor] Video In-Reply-To: <200511081647.07211.ewalker@micron.com> Message-ID: On Tue, 8 Nov 2005, Eric Walker wrote: > I would like to do some testing of video streams from say a vcr tape. > Possibly using the PVR type capture card. Maybe modules to control it.. > or some info on how I can control it through C/C++ and link those > functions into python. Are there any python user groups or modules that > could help me in this regard? Hi Eric, You probably want to ask this on a newsgroup like comp.lang.python; I don't think many of us here are familiar with PVR stuff. There are such systems written in Python. For example, Freevo: http://freevo.sourceforge.net/ but the subject is so specialized that Python-tutor probably won't be too effective. A larger audience like comp.lang.python might be able to give you better guidance. Good luck! From fatearthling at gmail.com Wed Nov 9 10:54:54 2005 From: fatearthling at gmail.com (Howard Kao) Date: Wed, 9 Nov 2005 17:54:54 +0800 Subject: [Tutor] Python persistent webserver? Message-ID: Thanks everyone for the help. I'll look into them. From kent37 at tds.net Wed Nov 9 11:55:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Nov 2005 05:55:54 -0500 Subject: [Tutor] Problem appending to a list using a property within a class In-Reply-To: <5e58f2e40511082009k6a1d3e4cp@mail.gmail.com> References: <5.1.0.14.2.20051109143340.02b8d090@localhost> <5e58f2e40511082009k6a1d3e4cp@mail.gmail.com> Message-ID: <4371D5BA.70405@tds.net> John Fouhy wrote: > On 09/11/05, Roy Bleasdale wrote: > >>I have created a List within a class. If I try and append to the list using >>the set function using the property value my variable stops being a list. > > Properties only work properly with new style classes. You get a new > style class by inheriting from another new style class, or by > inheriting from object. > > Try changing the first line to "class ShoppingBag(object):". Also you should use different names for the instance attributes (e.g. self.fruit) and the class properties (ShoppingBag.fruit). The usual convention is to prefix the attribute names with an underscore (self._fruit). If you use the same name the instance attribute will not be accessible - the property has priority (unlike most attribute lookups where an instance attribute will be found first). Kent -- http://www.kentsjohnson.com From kent37 at tds.net Wed Nov 9 12:08:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Nov 2005 06:08:48 -0500 Subject: [Tutor] Find multiple lines in a file In-Reply-To: <43717610.8090704@pennswoods.net> References: <43717610.8090704@pennswoods.net> Message-ID: <4371D8C0.3000106@tds.net> Bill Burns wrote: > I have a PostScript file which contains the following lines (the numbers > are for reference only and are *not* in the file): > > 1 << > 2 /Policies << > 3 /PageSize 3 > 4 >> > 5 >> setpagedevice > > I want to open the the file and read it, find these five lines and then > replace the lines with something different. > > Here's some code I'm using to replace just a *single* line in the > PostScript file (Note - I'm changing the BoundingBox which is in the > same file, but is *not* one of the five lines above). > > > import fileinput > > class ChangeBBox: > pass > > def getBBox(self, filename): > f = open(filename, "rb") > buffer = 1000 > tmp = f.readlines(buffer) > f.close() > for line in tmp: > if line.startswith('%%BoundingBox:'): > return line.strip() > > def modifyBBox(self, filename): > old = self.getBBox(filename) > new = '%%BoundingBox: 0 0 1296 1728' > for line in fileinput.input(filename, inplace=1): > print line.replace(old, new), > A few comments on the above.. - You don't need to put these functions in a class, the class isn't adding any value. (OK, it puts the two functions in a single namespace but a module would be more appropriate for that.) - The 'pass' statement is not needed. - You are adding blank lines to the file - the lines returned by fileinput.input() contain newlines, and print adds another. Avoid this using sys.stdout.write() instead of print. - A simpler way to iterate the lines in a file is for line in f: In fact the whole pre-search is really not needed, you could write this as (untested!): import fileinput, sys def modifyBBox(filename): for line in fileinput.input(filename, inplace=1): if line.startswith('%%BoundingBox:'): line = '%%BoundingBox: 0 0 1296 1728\n' sys.stdout.write(line) > Can anyone offer suggestions on how to find all five lines? I don't > think I'll have a problem replacing the lines, it's just getting them > all into one variable that stumping me :-) OK, none of my suggestions gets you closer to this...the simplest way is if you can read the whole file into memory. Then you can just replace the strings in place and write it out again. For example: oldPolicies = '''<< /Policies << /PageSize 3 >> >> setpagedevice''' newPolicies = 'something completely different' f = open(filename) data = f.read() f.close() data.replace(oldPolicies, newPolicies) f = open(filename, 'w') f.write(data) f.close() Replacing the bounding box is a little trickier because you have to search for the end of line. You can do this with a regular expression or a couple of find() calls on the string. I'm out of time now so maybe someone else will fill that in. Kent -- http://www.kentsjohnson.com From samrobertsmith at gmail.com Wed Nov 9 13:16:13 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Wed, 9 Nov 2005 04:16:13 -0800 Subject: [Tutor] triangulation Message-ID: <1d987df30511090416n69d86d84rf394a38d814d8ea3@mail.gmail.com> is there any sample code of triangulation? many thanks! From billburns at pennswoods.net Wed Nov 9 13:44:23 2005 From: billburns at pennswoods.net (Bill Burns) Date: Wed, 09 Nov 2005 07:44:23 -0500 Subject: [Tutor] Find multiple lines in a file In-Reply-To: <4371D8C0.3000106@tds.net> References: <43717610.8090704@pennswoods.net> <4371D8C0.3000106@tds.net> Message-ID: <4371EF27.8030902@pennswoods.net> >> I have a PostScript file which contains the following lines (the numbers >> are for reference only and are *not* in the file): >> >> 1 << >> 2 /Policies << >> 3 /PageSize 3 >> 4 >> >> 5 >> setpagedevice >> >> I want to open the the file and read it, find these five lines and then >> replace the lines with something different. >> >> Here's some code I'm using to replace just a *single* line in the >> PostScript file (Note - I'm changing the BoundingBox which is in the >> same file, but is *not* one of the five lines above). >> >> >> import fileinput >> >> class ChangeBBox: >> pass >> >> def getBBox(self, filename): >> f = open(filename, "rb") >> buffer = 1000 >> tmp = f.readlines(buffer) >> f.close() >> for line in tmp: >> if line.startswith('%%BoundingBox:'): >> return line.strip() >> >> def modifyBBox(self, filename): >> old = self.getBBox(filename) >> new = '%%BoundingBox: 0 0 1296 1728' >> for line in fileinput.input(filename, inplace=1): >> print line.replace(old, new), >> > > > A few comments on the above.. > - You don't need to put these functions in a class, the class isn't > adding any value. (OK, it puts the two functions in a single namespace > but a module would be more appropriate for that.) > - The 'pass' statement is not needed. Yeah, I have the above code in its own module. I've been trying to 'clean-up' my main module (which has way too much 'stuff' going on in it) and put logical parts & pieces together in separate modules. Not sure how that pass statement got in there.. must have been from testing at some point, oops :-) > - You are adding blank lines to the file - the lines returned by > fileinput.input() contain newlines, and print adds another. Avoid this > using sys.stdout.write() instead of print. Much nicer than print! I'll change it. > - A simpler way to iterate the lines in a file is > for line in f: > > In fact the whole pre-search is really not needed, you could write this > as (untested!): > import fileinput, sys > def modifyBBox(filename): > for line in fileinput.input(filename, inplace=1): > if line.startswith('%%BoundingBox:'): > line = '%%BoundingBox: 0 0 1296 1728\n' > sys.stdout.write(line) Much simpler, will take a look at this. > >> Can anyone offer suggestions on how to find all five lines? I don't >> think I'll have a problem replacing the lines, it's just getting them >> all into one variable that stumping me :-) > > > OK, none of my suggestions gets you closer to this...the simplest way is > if you can read the whole file into memory. Then you can just replace > the strings in place and write it out again. For example: > > oldPolicies = '''<< > /Policies << > /PageSize 3 > >> > >>> setpagedevice''' > > > newPolicies = 'something completely different' > > f = open(filename) > data = f.read() > f.close() > data.replace(oldPolicies, newPolicies) > f = open(filename, 'w') > f.write(data) > f.close() > > Replacing the bounding box is a little trickier because you have to > search for the end of line. You can do this with a regular expression or > a couple of find() calls on the string. I'm out of time now so maybe > someone else will fill that in. I'll test out this suggestion later, unfortunately, I've gotta get to work :-( Thanks for the reply, Kent!! I really appreciate it! Bill From kent37 at tds.net Wed Nov 9 13:53:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Nov 2005 07:53:56 -0500 Subject: [Tutor] Spanish text in BS problem In-Reply-To: <43716AF1.8030101@adinet.com.uy> References: <43716AF1.8030101@adinet.com.uy> Message-ID: <4371F164.3090906@tds.net> Ismael Garrido wrote: > Hello > > I'm using Beautiful Soup to scrape a site (that's in Spanish) I > sometimes come across strings like: > 'Ner\\xf3n como cantor' > > Which gets printed: > Ner\xf3n como cantor > > When they should be: > Ner?n como cantor > > I don't know if it is my fault (due to me misusing BS) or is it a BS > fault. Anyway, is there a way to print the string correctly? > > This is the code I'm using in BS > > a = open("zona.htm") > text = a.readlines() > a.close() > > BS = BeautifulSoup.BeautifulSoup(str(text)) > > for ed in BS('span', {'class':'ed_ant_fecha'}): > urlynombre = ed.findNextSibling().findNextSibling().findNextSibling() > nombre = urlynombre.next.next > > And "nombre" is that string I mentioned. Can you show a complete example including the URL you are fetching and the code that prints nombre? It's hard to tell from what you have shown where the problem is. We have seen some strangeness in BS when dealing with non-ASCII so that could be the problem, or you could be misinterpreting what is being printed. Kent -- http://www.kentsjohnson.com From lard at tardis.ed.ac.uk Wed Nov 9 14:07:45 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Wed, 09 Nov 2005 05:07:45 -0800 Subject: [Tutor] triangulation In-Reply-To: <1d987df30511090416n69d86d84rf394a38d814d8ea3@mail.gmail.com> References: <1d987df30511090416n69d86d84rf394a38d814d8ea3@mail.gmail.com> Message-ID: <4371F4A1.8020208@tardis.ed.ac.uk> Shi Mu wrote: >is there any sample code of triangulation? many thanks! > > Yes, probably. From lard at tardis.ed.ac.uk Wed Nov 9 15:44:08 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Wed, 09 Nov 2005 06:44:08 -0800 Subject: [Tutor] draw lines In-Reply-To: References: Message-ID: <43720B38.1090409@tardis.ed.ac.uk> Danny Yoo wrote: >On Sun, 6 Nov 2005, Shi Mu wrote: > > > >>I have a list of random points: [[x0,y0],[x1,y1],...,[xn,yn]] how can I >>use Tkinter to draw lines to connect them one by one based on the order >>in the list? >> >> > >Do you know how to draw a single line in Tkinter? Have you looked at the >Canvas widget documentation? > > http://www.pythonware.com/library/tkinter/introduction/canvas.htm > >Next time, you may want to show us what you've done to try to solve the >problem you have. > >For the past few questions, I have not been able to get an intuitive sense >of why you're having trouble figuring out things from documentation. All >I see right now is that you have some new requirement, and then you ask >the Tutor list for help. It's the step in-between that is a mystery to >me. > > I get the impression the OP isn't even trying to look anything up. They just seem to be firing random requirements at the tutor mailing list. (And calling them 'requirements' is being charitable.. :) From m.haft at abdn.ac.uk Wed Nov 9 18:08:22 2005 From: m.haft at abdn.ac.uk (Michael Haft) Date: Wed, 9 Nov 2005 17:08:22 -0000 (GMT) Subject: [Tutor] lists strings and files Message-ID: <3866.134.34.34.23.1131556102.squirrel@www.abdn.ac.uk> Hello, thanks for all the help with lists and strings, the list I have has nested sublists in it though. How do I remove these or is there a way to convert from lists to strings without removing them? The code looks something like: result = [] data = [fields[1] fields[3] fields[7]] result.append(data) which gives a list containing 12 sublists Appologies if the code isn't quite right I'm stuck on a library computer in a strange German university and can't use my memory stick to check the exact code. Mike From ismaelgf at adinet.com.uy Wed Nov 9 18:22:29 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 09 Nov 2005 15:22:29 -0200 Subject: [Tutor] [Fwd: Re: Spanish text in BS problem] Message-ID: <43723055.1020300@adinet.com.uy> Forwarding... Forgot the list. -------------- next part -------------- An embedded message was scrubbed... From: Ismael Garrido Subject: Re: [Tutor] Spanish text in BS problem Date: Wed, 09 Nov 2005 13:58:41 -0200 Size: 2420 Url: http://mail.python.org/pipermail/tutor/attachments/20051109/bc80a758/TutorSpanishtextinBSproblem.mht From billburns at pennswoods.net Wed Nov 9 18:34:55 2005 From: billburns at pennswoods.net (billburns@pennswoods.net) Date: Wed, 09 Nov 2005 12:34:55 -0500 Subject: [Tutor] Find multiple lines in a file In-Reply-To: <4371EF27.8030902@pennswoods.net> References: <43717610.8090704@pennswoods.net> <4371D8C0.3000106@tds.net> <4371EF27.8030902@pennswoods.net> Message-ID: <1131557695.4372333fcee13@webmail.pennswoods.net> [Kent wrote] > > OK, none of my suggestions gets you closer to this...the simplest way is > > if you can read the whole file into memory. Then you can just replace > > the strings in place and write it out again. For example: > > > > oldPolicies = '''<< > > /Policies << > > /PageSize 3 > > >> > > > >>> setpagedevice''' > > > > > > newPolicies = 'something completely different' > > > > f = open(filename) > > data = f.read() > > f.close() > > data.replace(oldPolicies, newPolicies) > > f = open(filename, 'w') > > f.write(data) > > f.close() Hi Kent, I just tested the following code and it works like a champ :-) filename = r'C:\TEST.ps' old = '''<< /Policies << /PageSize 3 >> >> setpagedevice''' new = '''<< /EndPage { exch pop 0 eq { gsave initmatrix save 850 1250 moveto 45 rotate 0 setgray /Helvetica 25 selectfont (CAUTION - DO NOT SCALE!) true charpath .2 setlinewidth stroke restore true } { false } ifelse } bind >> setpagedevice''' f = open(filename) data = f.read() f.close() newData = data.replace(old, new) f = open(filename, 'w') f.write(newData) f.close() Thanks again for your help!! Bill From hugonz-lists at h-lab.net Wed Nov 9 18:42:31 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 09 Nov 2005 11:42:31 -0600 Subject: [Tutor] lists strings and files In-Reply-To: <3866.134.34.34.23.1131556102.squirrel@www.abdn.ac.uk> References: <3866.134.34.34.23.1131556102.squirrel@www.abdn.ac.uk> Message-ID: <43723506.3010206@h-lab.net> Have you tried pickling them? If you want it to be flattened, so that result is: [fields[1], fields[2], fields[3]] instead of [[fields[1], fields[2], fields[3]]] you should use the extend method instead of the append method. Hugo Michael Haft wrote: > Hello, > thanks for all the help with lists and strings, the list I have has > nested sublists in it though. How do I remove these or is there a way > to convert from lists to strings without removing them? > > The code looks something like: > > result = [] > data = [fields[1] fields[3] fields[7]] > result.append(data) > which gives a list containing 12 sublists > > Appologies if the code isn't quite right I'm stuck on a library computer > in a strange German university and can't use my memory stick to check the > exact code. > > Mike > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz-lists at h-lab.net Wed Nov 9 18:45:18 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed, 09 Nov 2005 11:45:18 -0600 Subject: [Tutor] Python persistent webserver? In-Reply-To: References: Message-ID: <437235AE.5030305@h-lab.net> Looks like CherryPy is a good candidate. Take a look at: www.cherrypy.org` it can be plugged into Apache, and if persistency is what you need, you'll get it. There are nice examples for getting started. Hugo Howard Kao wrote: > Hi all, > > I know the subject is confusing but I don't know how to describe what > I would like to ask concisely. > > Basically I would like to have a program (or server or whatever) take > an HTTP POST method (which contains some information, maybe even an > XML file) from a client, process these XML/information, and then > generate an XML to send back to the client. > > Currently the environment it has to be done under is Apache on Linux. > I am thinking that it may have to be a persistent running program... > However it seems a daunting task for a Python noob like me. > > Preferably it doesn't need threading and need not to be sophiscated at > all, as long as it can take the request, process info and send stuff > back to a client. > > I have no idea how to do this at all and couldn't find much > information. The Base, Simple, CGI HTTPServer modules all seem a > little lacking , but that's probably due to my lack of py-fu to start > with... Any suggestions would be appreciated. Many thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Nov 9 19:09:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Nov 2005 13:09:57 -0500 Subject: [Tutor] lists strings and files In-Reply-To: <3866.134.34.34.23.1131556102.squirrel@www.abdn.ac.uk> References: <3866.134.34.34.23.1131556102.squirrel@www.abdn.ac.uk> Message-ID: <43723B75.1030204@tds.net> Michael Haft wrote: > Hello, > thanks for all the help with lists and strings, the list I have has > nested sublists in it though. How do I remove these or is there a way > to convert from lists to strings without removing them? > > The code looks something like: > > result = [] > data = [fields[1] fields[3] fields[7]] > result.append(data) > which gives a list containing 12 sublists Did you miss my reply to your last thread? I said, > I think from your previous post that your actual data is a list of lists, so you have to iterate the outside list, formatting each line and writing it to the file, something like this (borrowing from your previous unanswered post): > > out_file = open("test.txt","w") > data = readSOMNETM(filename) > for line in data: > line = ' '.join(line) > out_file.write(line) > out_file.write('\n') # need a newline after each line > out_file.close() > Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Wed Nov 9 19:24:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Nov 2005 10:24:34 -0800 (PST) Subject: [Tutor] triangulation In-Reply-To: <1d987df30511090416n69d86d84rf394a38d814d8ea3@mail.gmail.com> Message-ID: On Wed, 9 Nov 2005, Shi Mu wrote: > is there any sample code of triangulation? many thanks! Hi Shi Mu, I know people have already asked you to read "How to Ask Questions the Smart Way". http://www.catb.org/~esr/faqs/smart-questions.html Please really look at it. Frankly, you're asking questions in a bad way, and I'm annoyed that you appear to ignore people if they don't give you The Correct Answer. If you have done previous research for your question, show that work to us; we want to avoid repeating something that you already know. Have you tried a Google search yet on the terms "triangulation" and "python"? What have you done to look for answers? From smiles at worksmail.net Wed Nov 9 18:52:08 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Wed, 9 Nov 2005 11:52:08 -0600 Subject: [Tutor] unicode characters from integers? Message-ID: <001001c5e567$3d3b3610$772c4fca@csmith> I know that chr() can be used to convert an integer into an ASCII character, but I am having a hard time trying to generate unicode characters from numbers. e.g. say I want to generate u'\u0950' from the integer 950, does anyone know if/how this can be done? Here are some failures: ### >>> unicode(950) u'950' >>> >>> u'\u%04i' % 950 Traceback (UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-2: truncated \uXXXX escape >>> >>> unicode('\u%04i' % 950) u'\\u0950' >>> >>> unicode('\\u%04i' % 950) #double \\ u'\\u0950' ### Here is a successful method, but is there a better way? (Please don't clobber me if there is a very simple way to do this ;-).) import StringIO def uni(x): #convert hexadecimal x into string representation and return as unicode escape char s=StringIO.StringIO() s.write('0000') x=hex(x).split('x')[1] s.seek(4-len(x)) s.write(x) s.seek(0) return eval(unicode("u'\u%s'" % s.read())) ### >>> uni(0x095a) u'\u095a' >>> type(_) #check if it's right >>> ### /c From kent37 at tds.net Wed Nov 9 21:04:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 09 Nov 2005 15:04:25 -0500 Subject: [Tutor] unicode characters from integers? In-Reply-To: <001001c5e567$3d3b3610$772c4fca@csmith> References: <001001c5e567$3d3b3610$772c4fca@csmith> Message-ID: <43725649.4050704@tds.net> Chris or Leslie Smith wrote: > I know that chr() can be used to convert an integer into an ASCII > character, but I am having a hard time trying to generate unicode > characters from numbers. e.g. say I want to generate u'\u0950' from > the integer 950, does anyone know if/how this can be done? unichr(950) Kent From Liam.Clarke-Hutchinson at business.govt.nz Wed Nov 9 21:30:31 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Thu, 10 Nov 2005 09:30:31 +1300 Subject: [Tutor] triangulation Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13A0@chbnt01.alpha.wd.govt.nz> As in Pythagoras? from math import * c = sqrt(a^2 + b^2) Or as in triangulation on a 2D surface, navigation etc.? from math import * o = tan(theta) * a o = sin(theta) * h h = o/sin(theta) Noting of course that theta defaults to radians. Or, do you mean radio triangulation by directional signal propagation strength? The equations for that are a bit beyond me currently, but I'm studying. Or, do you mean drawing a triangle in Tkinter? from Tkinter import * #Do some stuff to create a Tkinter canvas in a window, call it... myCanvas. pointA = [100,100] pointB = [200,100] pointC = [150, 0] triangle = myCanvas.create_polygon(pointA[0],pointA[1],pointB[0],pointA[1],pointC[0],po intA[1]) ...Not that I know if that will work or not. I'm just going on some outdated Tkinter tutorials; I daresay the syntax of passing co-ordinates has changed (I'd hope so.) Can you be more specific? -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Shi Mu Sent: Thursday, 10 November 2005 1:16 a.m. To: Chris or Leslie Smith Cc: tutor at python.org Subject: [Tutor] triangulation is there any sample code of triangulation? many thanks! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From alan.gauld at freenet.co.uk Wed Nov 9 22:56:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Nov 2005 21:56:39 -0000 Subject: [Tutor] How to launch executable from a Python script?? References: <43710B50.1070909@libertydistribution.com> Message-ID: <005501c5e578$76e9fed0$0a01a8c0@xp> > sure how to do it on a windows box since the file is an executeable. > os.chdir('spacinVaders-0.1') #switch to the game's directory > os.spawnlp(os.P_NOWAIT, 'pythonw', 'pythonw', 'play.py') > > and it would launch fine.... can someone help me with this?? You should be able to use os.system. possibly utilisoing the Windows START command if you dont want it to block until the program finishes - at least I think thats what START does! Alan G. From alan.gauld at freenet.co.uk Wed Nov 9 23:00:49 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Nov 2005 22:00:49 -0000 Subject: [Tutor] Testing for gui References: <20051109001149.GA7261@mercury.squeezel.com> Message-ID: <009101c5e579$0bc39de0$0a01a8c0@xp> > How does one test for a running gui in python? > Can you be more specific? A GUI is a feature of a program. The GUI is part of the program - although a few programs can run in either GUI or Text mode, but they are the exception. Can you give an example of what you want to test for? Alan G From dyoo at hkn.eecs.berkeley.edu Wed Nov 9 23:09:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Nov 2005 14:09:57 -0800 (PST) Subject: [Tutor] triangulation In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13A0@chbnt01.alpha.wd.govt.nz> Message-ID: > ...Not that I know if that will work or not. I'm just going on some > outdated Tkinter tutorials; I daresay the syntax of passing co-ordinates > has changed (I'd hope so.) > > Can you be more specific? Hi Liam, Many of the questions that Shi Mu has been asking: http://mail.python.org/pipermail/tutor/2005-October/042052.html http://mail.python.org/pipermail/tutor/2005-October/042087.html http://mail.python.org/pipermail/tutor/2005-November/042906.html http://mail.python.org/pipermail/tutor/2005-November/042916.html have had an introductory CS graphics or computational geometry flavor to them. So Shi Mu could even be asking about Delauney triangulation. It's very hard to tell, and the problem is even fuzzier because "triangulation", like most words, has multiple meanings: http://en.wikipedia.org/wiki/Triangulation_%28disambiguation%29 That's why we need context. From alan.gauld at freenet.co.uk Wed Nov 9 23:07:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Nov 2005 22:07:19 -0000 Subject: [Tutor] Testing for gui References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1395@chbnt01.alpha.wd.govt.nz> <5e58f2e40511081645u2e2e7e8q@mail.gmail.com> Message-ID: <009f01c5e579$f429c9b0$0a01a8c0@xp> From: Ken Stevens [mailto:kens7601 at gmail.com] > Yes. Under Linux no x-server running? I guess it really wouldn't be > applicable under a windows enviroment, OK, I see what you wanted now, ignore my previous message . Note that X windows is a protocol and not a GUI. There are several GUI environments that can run under X, not all of them requre an X server on the local machine. Secondly note that not all GUIs on Unix run under X - the Mac Aqua interface is one example, NeXT/OpenStep another, Squeak another and the original Sun SunView and OpenLook(*) were all non X based GUIs that are still occasionally found today. (*)Later versions of openLook were ported to X, the original used display postscript as did NeXTstep. HTH, (in a nit picking kind of way! :-) Alan G. From blamb at mercury.com Wed Nov 9 23:25:35 2005 From: blamb at mercury.com (Brian Lamb) Date: Wed, 9 Nov 2005 14:25:35 -0800 Subject: [Tutor] Python persistent webserver? Message-ID: <24AF0A45B9F25247AEF3A172AE9312C105E98ACC@svexmb06> Hi Howard, It sounds like you want to integrate Python to handle CGI requests from Apache. So, don't look down the road of building your own web server with the HTTPServer stuff in Python but rather investigate how to hook Python up to *process Apache CGI requests*. I imagine on linux this is pretty simple and somewhat documented (I have only set this up quickly for IIS which worked easily...) I hope I understood what you wanted correctly. Regards, Brian ---- Original Message ---- From: Hugo Gonz?lez Monteverde Subject: Re: [Tutor] Python persistent webserver? To: Howard Kao Cc: tutor at python.org - Looks like CherryPy is a good candidate. Take a look at: www.cherrypy.org` it can be plugged into Apache, and if persistency is what you need, you'll get it. There are nice examples for getting started. Hugo Howard Kao wrote: > Hi all, > > I know the subject is confusing but I don't know how to describe what > I would like to ask concisely. > > Basically I would like to have a program (or server or whatever) take > an HTTP POST method (which contains some information, maybe even an > XML file) from a client, process these XML/information, and then > generate an XML to send back to the client. > > Currently the environment it has to be done under is Apache on Linux. > I am thinking that it may have to be a persistent running program... > However it seems a daunting task for a Python noob like me. > > Preferably it doesn't need threading and need not to be sophiscated at > all, as long as it can take the request, process info and send stuff > back to a client. > > I have no idea how to do this at all and couldn't find much > information. The Base, Simple, CGI HTTPServer modules all seem a > little lacking , but that's probably due to my lack of py-fu to start > with... Any suggestions would be appreciated. Many thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051109/fee7a4ff/attachment.html From adam.jtm30 at gmail.com Wed Nov 9 23:25:27 2005 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 9 Nov 2005 22:25:27 +0000 Subject: [Tutor] Comments, bug report and/or feature requests for my program please. Message-ID: ACS is a program to verify checksums of files (sha1 and md5) from the command line. It allows you to check for the sum in local and remote files via ftp or http. Any comments on the code would be good along with anything in the subject. Cheers. Adam -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051109/f448502a/attachment.htm From adam.jtm30 at gmail.com Wed Nov 9 23:27:02 2005 From: adam.jtm30 at gmail.com (Adam) Date: Wed, 9 Nov 2005 22:27:02 +0000 Subject: [Tutor] Fwd: Comments, bug report and/or feature requests for my program please. In-Reply-To: References: Message-ID: ACS is a program to verify checksums of files (sha1 and md5) from the command line. It allows you to check for the sum in local and remote files via ftp or http. Any comments on the code would be good along with anything in the subject. Cheers. Adam err woops this might be useful link -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051109/d8015ddc/attachment.html From lard at tardis.ed.ac.uk Thu Nov 10 00:07:38 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Wed, 09 Nov 2005 23:07:38 +0000 Subject: [Tutor] image In-Reply-To: <1d987df30511080237h84ce2b2u9a088f6b31bd2752@mail.gmail.com> References: <1d987df30511070002u231fc44dk4e90d7dd8c628777@mail.gmail.com> <1d987df30511080237h84ce2b2u9a088f6b31bd2752@mail.gmail.com> Message-ID: <4372813A.9010803@tardis.ed.ac.uk> Shi Mu wrote: >any python module to calculate sin, cos, arctan? > > STFW. Have you heard of this site called "Google"? From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 10 00:07:03 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Thu, 10 Nov 2005 12:07:03 +1300 Subject: [Tutor] image Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AA@chbnt01.alpha.wd.govt.nz> Oh dear, I missed that query. Nevermind google, try docs.python.org... -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Alex Hunsley Sent: Thursday, 10 November 2005 12:08 p.m. To: Shi Mu Cc: tutor at python.org Subject: Re: [Tutor] image Shi Mu wrote: >any python module to calculate sin, cos, arctan? > > STFW. Have you heard of this site called "Google"? _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From alan.gauld at freenet.co.uk Thu Nov 10 00:06:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 9 Nov 2005 23:06:53 -0000 Subject: [Tutor] triangulation References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13A0@chbnt01.alpha.wd.govt.nz> Message-ID: <00e701c5e582$46aa6b10$0a01a8c0@xp> > As in Pythagoras? > Or as in triangulation on a 2D surface, navigation etc.? > Or, do you mean radio triangulation by directional signal propagation > Or, do you mean drawing a triangle in Tkinter? Or even triangulation of currency from EU currency to EU currency via the euro? See: http://www.sysmod.com/eurofaq.htm#Triangulation Alan G. From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 10 00:14:30 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Thu, 10 Nov 2005 12:14:30 +1300 Subject: [Tutor] triangulation Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AB@chbnt01.alpha.wd.govt.nz> Eek. -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: Thursday, 10 November 2005 12:07 p.m. To: Liam Clarke-Hutchinson; 'Shi Mu' Cc: tutor at python.org Subject: Re: [Tutor] triangulation > As in Pythagoras? > Or as in triangulation on a 2D surface, navigation etc.? > Or, do you mean radio triangulation by directional signal propagation > Or, do you mean drawing a triangle in Tkinter? Or even triangulation of currency from EU currency to EU currency via the euro? See: http://www.sysmod.com/eurofaq.htm#Triangulation Alan G. A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From kens7601 at gmail.com Thu Nov 10 00:27:24 2005 From: kens7601 at gmail.com (Ken Stevens) Date: Wed, 9 Nov 2005 18:27:24 -0500 Subject: [Tutor] Testing for gui In-Reply-To: <009101c5e579$0bc39de0$0a01a8c0@xp> References: <20051109001149.GA7261@mercury.squeezel.com> <009101c5e579$0bc39de0$0a01a8c0@xp> Message-ID: <20051109232724.GF4113@mercury.squeezel.com> On Wed, Nov 09, 2005 at 10:00:49PM -0000, Alan Gauld wrote: > >How does one test for a running gui in python? > > > > Can you be more specific? A GUI is a feature of a program. > The GUI is part of the program - although a few programs > can run in either GUI or Text mode, but they are the exception. > > Can you give an example of what you want to test for? > > Alan G I haven't written any code yet, but I was thinking I would like to test for either a windows environment (Is an X-Server running) or is this a strictly console (no X-server) environment and then do the appropriate thing for each environment. I am not sure that is any clearer, but I hope it is. Ken -- Money is its own reward. From dyoo at hkn.eecs.berkeley.edu Thu Nov 10 00:51:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Nov 2005 15:51:34 -0800 (PST) Subject: [Tutor] Testing for gui In-Reply-To: <20051109232724.GF4113@mercury.squeezel.com> Message-ID: > I haven't written any code yet, but I was thinking I would like to test > for either a windows environment (Is an X-Server running) or is this a > strictly console (no X-server) environment and then do the appropriate > thing for each environment. I am not sure that is any clearer, but I > hope it is. Hi Ken, That makes sense. Can you check to see if the DISPLAY environmental variable is set? That appears to be a fairly standard kludgy way to determine if the user is in a graphical vs. non-graphical environment. emacs, for example, appears to check for DISPLAY before switching a terminal or X-Windows based UI. Best of wishes! From glingl at aon.at Thu Nov 10 01:44:04 2005 From: glingl at aon.at (Gregor Lingl) Date: Thu, 10 Nov 2005 01:44:04 +0100 Subject: [Tutor] triangulation In-Reply-To: <4371F4A1.8020208@tardis.ed.ac.uk> References: <1d987df30511090416n69d86d84rf394a38d814d8ea3@mail.gmail.com> <4371F4A1.8020208@tardis.ed.ac.uk> Message-ID: <437297D4.9070608@aon.at> Alex Hunsley schrieb: > Shi Mu wrote: > > >>is there any sample code of triangulation? many thanks! >> >> > > Yes, probably. > Indeed, there is. See attachment regards Gregor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: triangulation.py Url: http://mail.python.org/pipermail/tutor/attachments/20051110/17804a21/triangulation.asc From glingl at aon.at Thu Nov 10 01:52:40 2005 From: glingl at aon.at (Gregor Lingl) Date: Thu, 10 Nov 2005 01:52:40 +0100 Subject: [Tutor] any code to draw parabola or curve? In-Reply-To: <1d987df30511080321m7c4847fawc5d262f6e3619a79@mail.gmail.com> References: <1d987df30511080321m7c4847fawc5d262f6e3619a79@mail.gmail.com> Message-ID: <437299D8.5000603@aon.at> Both! See attachment Regards, Gregor Shi Mu schrieb: > any code to draw parabola or curve? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: plotter.py Url: http://mail.python.org/pipermail/tutor/attachments/20051110/ec11fdc5/plotter.pot From glingl at aon.at Thu Nov 10 01:55:37 2005 From: glingl at aon.at (Gregor Lingl) Date: Thu, 10 Nov 2005 01:55:37 +0100 Subject: [Tutor] [OT] triangulation In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> Message-ID: <43729A89.90408@aon.at> Liam Clarke-Hutchinson schrieb: > German is an awesome language, I love the compound words (if that's what > they are). What does 'Gegenuhrzeigersinn' mean in English? > counterclockwise but Shi Mu didn't ask for a program in English ;-) Gregor > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of Gregor Lingl > Sent: Thursday, 10 November 2005 1:44 p.m. > To: tutor at python.org > Subject: Re: [Tutor] triangulation > > > > > Alex Hunsley schrieb: > >>Shi Mu wrote: >> >> >> >>>is there any sample code of triangulation? many thanks! >>> >>> >> >>Yes, probably. >> > > > > Indeed, there is. > See attachment > > regards > Gregor > > >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From john at fouhy.net Thu Nov 10 02:04:20 2005 From: john at fouhy.net (John Fouhy) Date: Thu, 10 Nov 2005 14:04:20 +1300 Subject: [Tutor] [OT] triangulation In-Reply-To: <43729A89.90408@aon.at> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> <43729A89.90408@aon.at> Message-ID: <5e58f2e40511091704q49de18dfv@mail.gmail.com> On 10/11/05, Gregor Lingl wrote: > but Shi Mu didn't ask for a program in English ;-) This is pretty off-topic, but --- Is it possible to be a programmer and not speak English? Are there any languages out there where the reserved words, library functions, etc. are in (say) German? -- John. From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 10 02:14:33 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Thu, 10 Nov 2005 14:14:33 +1300 Subject: [Tutor] [OT] triangulation Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13B0@chbnt01.alpha.wd.govt.nz> Perl seems to be written in a foreign language. ;) -----Original Message----- From: tutor-bounces+ml.cyresse=gmail.com at python.org [mailto:tutor-bounces+ml.cyresse=gmail.com at python.org] On Behalf Of John Fouhy Sent: Thursday, 10 November 2005 2:04 p.m. To: Tutor Subject: Re: [Tutor] [OT] triangulation On 10/11/05, Gregor Lingl wrote: > but Shi Mu didn't ask for a program in English ;-) This is pretty off-topic, but --- Is it possible to be a programmer and not speak English? Are there any languages out there where the reserved words, library functions, etc. are in (say) German? -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From ismaelgf at adinet.com.uy Thu Nov 10 02:35:54 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 09 Nov 2005 23:35:54 -0200 Subject: [Tutor] [Fwd: Re: Spanish text in BS problem] In-Reply-To: <43723055.1020300@adinet.com.uy> References: <43723055.1020300@adinet.com.uy> Message-ID: <4372A3FA.4030704@adinet.com.uy> Found the problem myself. (look down) Ismael Garrido wrote: > This is the script: > > import BeautifulSoup > import os > > a = open("zona.htm") > text = a.readlines() > a.close() > > BS = BeautifulSoup.BeautifulSoup(str(text)) Apparently, str(text) is the cause of the problem. If instead I do: "".join(text) it all works allright. I guess this is because str converts '?' to '\xf3' while "".join() does not change the strings in any way. Now the output from BS makes sense. Bye, Ismael > for ed in BS('span', {'class':'ed_ant_fecha'}): > fecha = ed.next.split(" ")[1].replace(".","-") > urlynombre = ed.findNextSibling().findNextSibling().findNextSibling() > url = 'http://espectador.com/' + urlynombre.get('href') > nombre = urlynombre.next.next > > print url > print "D:/dolina/"+fecha, nombre > print > ###end From dyoo at hkn.eecs.berkeley.edu Thu Nov 10 02:39:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 9 Nov 2005 17:39:02 -0800 (PST) Subject: [Tutor] [OT] triangulation In-Reply-To: <5e58f2e40511091704q49de18dfv@mail.gmail.com> Message-ID: > Is it possible to be a programmer and not speak English? Are there any > languages out there where the reserved words, library functions, etc. > are in (say) German? Hi John, If you're asking about if it's possible, as in technically feasible, then yes. As an example of this, see Damian Conway's Perligata, which is an embedding of Latin in Perl: http://www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html I suspect, though, that the advantages of writing programs using keywords in a different language is offset against the network effect of using other people's code. We have a hard enough time convincing people to look into languages like Python or Scheme or Ocaml, where the differences are more than just syntax. If we toss regional keywords into the mix, where the variation is merely superficial, I don't know what will happen, but I don't think it will be pretty. *grin* Best of wishes! From ismaelgf at adinet.com.uy Thu Nov 10 02:45:55 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 09 Nov 2005 23:45:55 -0200 Subject: [Tutor] [OT] triangulation In-Reply-To: <5e58f2e40511091704q49de18dfv@mail.gmail.com> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> <43729A89.90408@aon.at> <5e58f2e40511091704q49de18dfv@mail.gmail.com> Message-ID: <4372A653.8090206@adinet.com.uy> John Fouhy wrote: >On 10/11/05, Gregor Lingl wrote: > > >>but Shi Mu didn't ask for a program in English ;-) >> >> > >This is pretty off-topic, but --- > >Is it possible to be a programmer and not speak English? Are there any >languages out there where the reserved words, library functions, etc. >are in (say) German? > > I believe there was a version of Qbasic translated to French or Spanish. By "translated" I mean that the keywords (reserved words) were, for instance, "para" instead of "for", that is, their French/Spanish counterpart. Ismael From glingl at aon.at Thu Nov 10 07:08:06 2005 From: glingl at aon.at (Gregor Lingl) Date: Thu, 10 Nov 2005 07:08:06 +0100 Subject: [Tutor] [OT] triangulation In-Reply-To: <4372A653.8090206@adinet.com.uy> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> <43729A89.90408@aon.at> <5e58f2e40511091704q49de18dfv@mail.gmail.com> <4372A653.8090206@adinet.com.uy> Message-ID: <4372E3C6.6060409@aon.at> Ismael Garrido schrieb: > John Fouhy wrote: ... > > I believe there was a version of Qbasic translated to French or Spanish. > By "translated" I mean that the keywords (reserved words) were, for > instance, "para" instead of "for", that is, their French/Spanish > counterpart. > I know that this definitely (still) exists for Logo in German Gregor > Ismael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 From alan.gauld at freenet.co.uk Thu Nov 10 09:16:12 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 10 Nov 2005 08:16:12 -0000 Subject: [Tutor] [OT] triangulation References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz><43729A89.90408@aon.at> <5e58f2e40511091704q49de18dfv@mail.gmail.com> Message-ID: <012401c5e5cf$038c1430$0a01a8c0@xp> > Is it possible to be a programmer and not speak English? Are there any > languages out there where the reserved words, library functions, etc. > are in (say) German? This is second-hand news so treat with caution but a colleague of mine used to work for Norsk Data in Norway writing financial programs in their proprietary language (it began with an E...) which had Norwegian keywords. Given he spoke no Norwegian he found it a "challenging assignment"... Alan G From matthew.williams at cancer.org.uk Thu Nov 10 09:36:02 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Thu, 10 Nov 2005 08:36:02 +0000 Subject: [Tutor] Latin Perl In-Reply-To: References: Message-ID: <1131611762.2745.4.camel@localhost.localdomain> The suprising thing about Latin Perl is that it's more readable than normal Perl.... Matt From lumbricus at gmx.net Thu Nov 10 10:46:41 2005 From: lumbricus at gmx.net (Joerg Woelke) Date: Thu, 10 Nov 2005 10:46:41 +0100 Subject: [Tutor] [OT] triangulation In-Reply-To: <43729A89.90408@aon.at> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> <43729A89.90408@aon.at> Message-ID: <20051110094641.GA3802@localhost.localdomain> On Thu, Nov 10, 2005 at 01:55:37AM +0100, Gregor Lingl wrote: > > > Liam Clarke-Hutchinson schrieb: > > German is an awesome language, I love the compound words (if that's what > > they are). What does 'Gegenuhrzeigersinn' mean in English? > > > > counterclockwise Try "Donaudampfschifffahrtskapit?nsm?tzen". More Oddities in Mark Twains wonderful "The Awful German Language". -- Q: Do you know what the death rate around here is? A: One per person. From lumbricus at gmx.net Thu Nov 10 11:00:55 2005 From: lumbricus at gmx.net (Joerg Woelke) Date: Thu, 10 Nov 2005 11:00:55 +0100 Subject: [Tutor] [OT] triangulation In-Reply-To: <5e58f2e40511091704q49de18dfv@mail.gmail.com> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> <43729A89.90408@aon.at> <5e58f2e40511091704q49de18dfv@mail.gmail.com> Message-ID: <20051110100055.GB3802@localhost.localdomain> On Thu, Nov 10, 2005 at 02:04:20PM +1300, John Fouhy wrote: > On 10/11/05, Gregor Lingl wrote: > > but Shi Mu didn't ask for a program in English ;-) > > This is pretty off-topic, but --- > > Is it possible to be a programmer and not speak English? Are there any > languages out there where the reserved words, library functions, etc. > are in (say) German? Dont know for sure, but perhaps Plankalk?l by Konrad Zuse? > -- > John. -- In the stairway of life, you'd best take the elevator. From dklose at nimr.mrc.ac.uk Thu Nov 10 11:20:51 2005 From: dklose at nimr.mrc.ac.uk (Dan Klose) Date: Thu, 10 Nov 2005 10:20:51 +0000 Subject: [Tutor] [OT] triangulation In-Reply-To: <20051110100055.GB3802@localhost.localdomain> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13AD@chbnt01.alpha.wd.govt.nz> <43729A89.90408@aon.at> <5e58f2e40511091704q49de18dfv@mail.gmail.com> <20051110100055.GB3802@localhost.localdomain> Message-ID: <1131618052.25212.21.camel@yangon.mathbio.nimr> Hello, On Thu, 2005-11-10 at 11:00 +0100, Joerg Woelke wrote: > On Thu, Nov 10, 2005 at 02:04:20PM +1300, John Fouhy wrote: > > On 10/11/05, Gregor Lingl wrote: > > > but Shi Mu didn't ask for a program in English ;-) > > > > This is pretty off-topic, but --- > > > > Is it possible to be a programmer and not speak English? Are there any > > languages out there where the reserved words, library functions, etc. > > are in (say) German? I was bored: http://en.wikipedia.org/wiki/Category:Non-English- based_programming_languages Enjoy. Dan. > > Dont know for sure, but perhaps Plankalk?l by Konrad Zuse? > > > -- > > John. > -- Daniel Klose PhD Student - Taylor Group Mathematical Biology National Institute for Medical Research The Ridgeway Mill Hill London NW7 1AA From hugonz-lists at h-lab.net Thu Nov 10 14:38:40 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 10 Nov 2005 07:38:40 -0600 Subject: [Tutor] [Fwd: Re: Spanish text in BS problem] In-Reply-To: <4372A3FA.4030704@adinet.com.uy> References: <43723055.1020300@adinet.com.uy> <4372A3FA.4030704@adinet.com.uy> Message-ID: <43734D60.5030001@h-lab.net> Hi Ismael, I'm glad you found the answer. It is very enlightening as I thought I had to do with locale and did some tests without getting the problem (I do not have BS installed now) As I speak Spanish this had got me worried. :/ Hugo Ismael Garrido wrote: > Found the problem myself. > (look down) > > Ismael Garrido wrote: > > >>This is the script: >> >>import BeautifulSoup >>import os >> >>a = open("zona.htm") >>text = a.readlines() >>a.close() >> >>BS = BeautifulSoup.BeautifulSoup(str(text)) > > > Apparently, str(text) is the cause of the problem. If instead I do: > "".join(text) it all works allright. I guess this is because str > converts '?' to '\xf3' while "".join() does not change the strings in > any way. Now the output from BS makes sense. > > Bye, > Ismael > > >>for ed in BS('span', {'class':'ed_ant_fecha'}): >> fecha = ed.next.split(" ")[1].replace(".","-") >> urlynombre = ed.findNextSibling().findNextSibling().findNextSibling() >> url = 'http://espectador.com/' + urlynombre.get('href') >> nombre = urlynombre.next.next >> >> print url >> print "D:/dolina/"+fecha, nombre >> print >>###end > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From captnswing at gmx.net Thu Nov 10 15:50:07 2005 From: captnswing at gmx.net (=?ISO-8859-1?Q?=22Frank_Hoffs=FCmmer=22?=) Date: Thu, 10 Nov 2005 15:50:07 +0100 (MET) Subject: [Tutor] python watchfolder as daemon Message-ID: <2262.1131634207@www74.gmx.net> Hello all, I found this gem of a python recipe that allows me to monitor a hierarchy of folders on my filesystem for additions / changes / removals of files: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215418 I would like to monitor a folder hierarchy using this script but now I wonder what would be the best way to have this watchfolder script running at all times in the background? nohup python watchfolder.py myfolder & ? would that be suitable?? or is there a way to launch a process like that from python that detaches itself from the shell? what would be the best way, any insight or recommendation is very much appreciated thanks, -frank -- Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! Satte Provisionen für GMX Partner: http://www.gmx.net/de/go/partner From captnswing at gmx.net Thu Nov 10 15:49:22 2005 From: captnswing at gmx.net (=?ISO-8859-1?Q?=22Frank_Hoffs=FCmmer=22?=) Date: Thu, 10 Nov 2005 15:49:22 +0100 (MET) Subject: [Tutor] ftp transfer - queue & retry pattern Message-ID: <32727.1131634162@www74.gmx.net> Hello, I want to write a module that transfers a given file to a given destination with a given protocol (ftp, sftp, scp) to start out, just ftp would be sufficient the destination machines are sometimes unavailable, or the transfer fails sometimes due to connection problems I have several questions (sorry....): 1) python ftplib or curl via commands.getoutput(...)? what are the benefits / drawbacks (portability is not an issue for me, and I like curl a lot) 2) Is there a simple way to create a subprocess(?) that I can dispatch my transfer jobs to from my main script. The goal is that my main script can proceed without beeing hung by the transfer process 3) that subprocess would need a queue, that collects all transfer jobs. can you give me some hints on how that could be done in python 4) the subprocess (?) would try to transfer all jobs one after another if one transfer fails, retry after a certain time period (say 2, 5, 10, 20, 40 min) and stop after maxnum retries how could I code this nicely in python without resorting to if then else etc? or is there a module that does 1)-4) out there somewhere already? thanks for any insight you might have -frank -- 10 GB Mailbox, 100 FreeSMS/Monat http://www.gmx.net/de/go/topmail +++ GMX - die erste Adresse für Mail, Message, More +++ From lard at tardis.ed.ac.uk Thu Nov 10 18:02:23 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Thu, 10 Nov 2005 09:02:23 -0800 Subject: [Tutor] python watchfolder as daemon In-Reply-To: <2262.1131634207@www74.gmx.net> References: <2262.1131634207@www74.gmx.net> Message-ID: <43737D1F.3080106@tardis.ed.ac.uk> Frank Hoffs?mmer wrote: >Hello all, >I found this gem of a python recipe that allows me to monitor a hierarchy of >folders on my filesystem for additions / changes / removals of files: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215418 > >I would like to monitor a folder hierarchy using this script but now I >wonder what would be the best way to have this watchfolder script running at >all times in the background? > >nohup python watchfolder.py myfolder & > >? would that be suitable?? or is there a way to launch a process like that >from python that detaches itself from the shell? > > Using nohup should certainly work fine. Make sure you understand what happens to any standard (etc.) output from your script when you use it with nohup - i.e. read the nohup man page! alex From lard at tardis.ed.ac.uk Thu Nov 10 18:04:22 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Thu, 10 Nov 2005 09:04:22 -0800 Subject: [Tutor] triangulation In-Reply-To: <00e701c5e582$46aa6b10$0a01a8c0@xp> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13A0@chbnt01.alpha.wd.govt.nz> <00e701c5e582$46aa6b10$0a01a8c0@xp> Message-ID: <43737D96.4050802@tardis.ed.ac.uk> Alan Gauld wrote: >>As in Pythagoras? >> >> > > > >>Or as in triangulation on a 2D surface, navigation etc.? >> >> > > > >>Or, do you mean radio triangulation by directional signal propagation >> >> > > > >>Or, do you mean drawing a triangle in Tkinter? >> >> > >Or even triangulation of currency from EU currency to EU currency >via the euro? > >See: >http://www.sysmod.com/eurofaq.htm#Triangulation > >Alan G. > > This Shi Mu character is a little frustrating. They won't even respond to peoples polite responses for clarification.... Hit'n'run help requests. From captnswing at gmx.net Thu Nov 10 19:35:17 2005 From: captnswing at gmx.net (captnswing) Date: Thu, 10 Nov 2005 19:35:17 +0100 Subject: [Tutor] logging to a database Message-ID: Hello all, I would like to log messages to a database (mysql) I found the example log_test14.py that comes with python logging module http://www.red-dove.com/python_logging.html but that example is a bit greek for me ... :) and it doesnt work with mysql is there some kind of tutorial how to get going if you want to log to a database? thanks, -frank From 3dbernard at gmail.com Thu Nov 10 19:36:12 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 10 Nov 2005 13:36:12 -0500 Subject: [Tutor] Finding wich word matched in a OR re Message-ID: <61d0e2b40511101036o14647680uf41147c169838b5d@mail.gmail.com> Hello, I have compiled this regular expression, with 3 strings. Basically it looks like this. r'word1|word2|word3' The point is to try to match one of these words in a string. Now let say I indeed got a match in a string. How can I find out wich one, between word1-word2-word3 has the string been matched to? Thanks Bernard From 3dbernard at gmail.com Thu Nov 10 19:46:06 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 10 Nov 2005 13:46:06 -0500 Subject: [Tutor] Finding wich word matched in a OR re In-Reply-To: <61d0e2b40511101036o14647680uf41147c169838b5d@mail.gmail.com> References: <61d0e2b40511101036o14647680uf41147c169838b5d@mail.gmail.com> Message-ID: <61d0e2b40511101046y46696d02s22c2cbe0b9ef471c@mail.gmail.com> Never mind, just came accross "groups" of the match object. Can't believe there is such a nice feature! Cheers Bernard On 11/10/05, Bernard Lebel <3dbernard at gmail.com> wrote: > Hello, > > I have compiled this regular expression, with 3 strings. Basically it > looks like this. > > r'word1|word2|word3' > > The point is to try to match one of these words in a string. > > > Now let say I indeed got a match in a string. How can I find out wich > one, between word1-word2-word3 has the string been matched to? > > > Thanks > Bernard > From kent37 at tds.net Thu Nov 10 19:46:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Nov 2005 13:46:59 -0500 Subject: [Tutor] Finding wich word matched in a OR re In-Reply-To: <61d0e2b40511101036o14647680uf41147c169838b5d@mail.gmail.com> References: <61d0e2b40511101036o14647680uf41147c169838b5d@mail.gmail.com> Message-ID: <437395A3.9030202@tds.net> Bernard Lebel wrote: > Hello, > > I have compiled this regular expression, with 3 strings. Basically it > looks like this. > > r'word1|word2|word3' > > The point is to try to match one of these words in a string. > > Now let say I indeed got a match in a string. How can I find out wich > one, between word1-word2-word3 has the string been matched to? A successful search returns a match object. You can query the match to find out what it matched; match.group() will give the whole matched string. See http://docs.python.org/lib/match-objects.html for details. Kent -- http://www.kentsjohnson.com From hugonz-lists at h-lab.net Thu Nov 10 21:48:18 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 10 Nov 2005 14:48:18 -0600 Subject: [Tutor] python watchfolder as daemon In-Reply-To: <2262.1131634207@www74.gmx.net> References: <2262.1131634207@www74.gmx.net> Message-ID: <4373B212.4020408@h-lab.net> Hi, I do this all the time. I use a recipe, and import a daemon module. The module is here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 in your script, just do import daemon and daemon.createDaemon() Works like a charm. Hugo Frank Hoffs?mmer wrote: > Hello all, > I found this gem of a python recipe that allows me to monitor a hierarchy of > folders on my filesystem for additions / changes / removals of files: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/215418 > > I would like to monitor a folder hierarchy using this script but now I > wonder what would be the best way to have this watchfolder script running at > all times in the background? > > nohup python watchfolder.py myfolder & > > ? would that be suitable?? or is there a way to launch a process like that > from python that detaches itself from the shell? > what would be the best way, any insight or recommendation is very much > appreciated > thanks, > -frank > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jeffpeery at yahoo.com Thu Nov 10 22:13:02 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 10 Nov 2005 13:13:02 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <20051110211302.60014.qmail@web30503.mail.mud.yahoo.com> --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051110/3e22b92f/attachment-0001.html From jeffpeery at yahoo.com Thu Nov 10 22:13:02 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 10 Nov 2005 13:13:02 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <20051110211303.56610.qmail@web30505.mail.mud.yahoo.com> --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051110/bcea0fee/attachment-0001.htm From jeffpeery at yahoo.com Thu Nov 10 22:18:16 2005 From: jeffpeery at yahoo.com (Jeff Peery) Date: Thu, 10 Nov 2005 13:18:16 -0800 (PST) Subject: [Tutor] numeric typeError Message-ID: <20051110211817.5645.qmail@web30502.mail.mud.yahoo.com> hello, I'm getting this strange error: myArray1[1:2] = myArray2[3:4] TypeError: Array can not be safely cast to required type everytime I try to copy a slice from one array to the next this error occurs. the slices are the same size and I initialized the arrays using Numeric.zeros(10, 'Float'). anyone have an idea why this happens? thanks. Jeff --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051110/ce0ef1af/attachment.html From samrobertsmith at gmail.com Thu Nov 10 22:47:05 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Thu, 10 Nov 2005 13:47:05 -0800 Subject: [Tutor] triangulation In-Reply-To: <437297D4.9070608@aon.at> References: <1d987df30511090416n69d86d84rf394a38d814d8ea3@mail.gmail.com> <4371F4A1.8020208@tardis.ed.ac.uk> <437297D4.9070608@aon.at> Message-ID: <1d987df30511101347m1f2913cfkba9600954d1f61e9@mail.gmail.com> the Internet is down for one day and so wonderful to have so many responses. i have checked all the links you guys mentioned. what i want is delaunay triangulation and the available ones online are written in C, Java and FORTRAN. I want to see some in Python because it is hard for me to figure out using python to do Fortune's sweeping line algorithm. Is python is not good in doing that kind of computation or some other reason? Thanks a lot for all of your responses!!! On 11/9/05, Gregor Lingl wrote: > > > Alex Hunsley schrieb: > > Shi Mu wrote: > > > > > >>is there any sample code of triangulation? many thanks! > >> > >> > > > > Yes, probably. > > > > > Indeed, there is. > See attachment > > regards > Gregor > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Gregor Lingl > Reisnerstrasse 3/19 > A-1030 Wien > > Telefon: +43 1 713 33 98 > Mobil: +43 664 140 35 27 > > Website: python4kids.net > > > ## Run this program and create a polygon without > ## intersecting edges by clicking the vertices with the mouse > > from Tkinter import * > > def area2(A,B,C): > """2 * Flaeche des 2D-Dreiecks ABC""" > return (A[0]-C[0])*(B[1]-C[1]) - (A[1]-C[1])*(B[0]-C[0]) > > def insideTriangle(A, B, C, P): > """Liegt P im Dreieck ABC?, > ABC sind im Gegenuhrzeigersinn angenommen!""" > return area2(A,B,P)>=0 and area2(B,C,P)>=0 and area2(C,A,P)>=0 > > def triangulate(poly): > tri = [] > while len(poly) > 2: > triaFound = False > count = 0 > while not triaFound and count < len(poly): #n: > count += 1 > A, B, C = poly[:3] > if area2(A, B, C) >= 0: > for P in poly[3:]: > if insideTriangle(A,B,C,P): > break > else: > tri.append( (A,B,C) ) > poly.remove(B) > triaFound = True > poly.append(poly.pop(0)) > if count == len(poly): # n: > print "Not a simple polygon" > return None > return tri > > > class CvDefPoly(Canvas): > def __init__(self, root): > Canvas.__init__(self, root, bg="white", cursor="crosshair") > self.v = () > self.rWidth, self.rHeight = 10.0, 7.5 > > self.bind("", self.repaint) > self.bind("", self.mousePressed) > > self.done = False > > def mousePressed(self, event): > if self.done: > self.done = False > self.v = () > x ,y = self.fx(event.x), self.fy(event.y) > if self.v: > x0, y0 = self.v[:2] > if abs(x-x0) self.done = True > if not self.done: > self.v += (x,y) > self.repaint(None) > > def iX(self,x): > return self.centerX + x/self.pixelSize > def iY(self,y): > return self.centerY - y/self.pixelSize > def fx(self,x): > return (x-self.centerX)*self.pixelSize > def fy(self,y): > return (self.centerY - y)*self.pixelSize > > def repaint(self, event): > items = self.find_all() > for item in items: > self.delete(item) > if event: > self.w, self.h = event.width, event.height > w,h = self.w, self.h > self.minX = self.minY = 2.0 > self.maxX, self.maxY = w-3.0, h-3.0 > dx, dy = self.maxX-self.minX, self.maxY-self.minY > self.centerX = 2.0 + dx/2.0 > self.centerY = 2.0 + dy/2.0 > self.pixelSize = max(self.rWidth/dx, self.rHeight/dy) > > left = self.iX(-self.rWidth/2.0) > right = self.iX(self.rWidth/2.0) > bottom = self.iY(-self.rHeight/2.0) > top = self.iY(self.rHeight/2.0) > > self.create_rectangle(left,top,right,bottom, outline="red") > if len(self.v) > 1: > x,y = self.v[:2] > self.create_rectangle(self.iX(x)-2, self.iY(y)-2, > self.iX(x)+2, self.iY(y)+2, outline="green") > if len(self.v) > 3: > if self.done: > v = [] > sv = self.v[:] > while sv: > a,b=sv[:2] > v.extend([self.iX(a), self.iY(b)]) > sv = sv[2:] > self.create_polygon( v, fill="", outline="blue") > else: > coo = list(self.v[2:]) > while coo: > x1,y1 = coo[:2] > self.create_line(self.iX(x),self.iY(y), > self.iX(x1),self.iY(y1),fill="blue") > x,y=x1,y1 > coo = coo[2:] > > def ccw(poly): > n = len(poly) > k = poly.index(min(poly)) > return area2(poly[k-1], poly[k], poly[(k+1)%n]) > 0 > > def color(n): > return "#%02x%02x%02x" % (255-n,0,n) > > class PolyTria(Tk): > def __init__(self): > Tk.__init__(self) > self.geometry("500x300-10+50") > self.title("Define polygon vertices by clicking") > CvPolyTria(self).pack(expand=1, fill="both") > > class CvPolyTria(CvDefPoly): > def repaint(self, event): > doit = False > if len(self.v)>3 and self.done: > poly = [] > v = self.v[:] > while v: > p = tuple(v[:2]) > poly.append(p) > v = v[2:] > if not ccw(poly): > poly.reverse() > tri = triangulate(poly) > doit = True > CvDefPoly.repaint(self, event) > if doit: > anz = len(tri) > diff = 255//anz > for i,t in enumerate(tri): > (x1,y1),(x2,y2),(x3,y3) = t > t = (self.iX(x1),self.iY(y1),self.iX(x2),self.iY(y2),self.iX(x3),self.iY(y3)) > self.create_polygon(t, fill=color(i*diff), outline="black") > > if __name__ == "__main__": > PolyTria().mainloop() > > > From jason.massey at gmail.com Thu Nov 10 22:57:49 2005 From: jason.massey at gmail.com (Jason Massey) Date: Thu, 10 Nov 2005 15:57:49 -0600 Subject: [Tutor] triangulation In-Reply-To: <1d987df30511101347m1f2913cfkba9600954d1f61e9@mail.gmail.com> References: <1d987df30511090416n69d86d84rf394a38d814d8ea3@mail.gmail.com> <4371F4A1.8020208@tardis.ed.ac.uk> <437297D4.9070608@aon.at> <1d987df30511101347m1f2913cfkba9600954d1f61e9@mail.gmail.com> Message-ID: <7e3eab2c0511101357h747159ecvc8b1665ffafcac5d@mail.gmail.com> lol, that's just funny. On 11/10/05, Shi Mu wrote: > the Internet is down for one day and so wonderful to have so many > responses. i have checked all the links you guys mentioned. what i > want is delaunay triangulation and the available ones online are > written in C, Java and FORTRAN. I want to see some in Python because > it is hard for me to figure out using python to do Fortune's sweeping > line algorithm. Is python is not good in doing that kind of > computation or some other reason? > Thanks a lot for all of your responses!!! > > On 11/9/05, Gregor Lingl wrote: > > > > > > Alex Hunsley schrieb: > > > Shi Mu wrote: > > > > > > > > >>is there any sample code of triangulation? many thanks! > > >> > > >> > > > > > > Yes, probably. > > > > > > > > > Indeed, there is. > > See attachment > > > > regards > > Gregor > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > -- > > Gregor Lingl > > Reisnerstrasse 3/19 > > A-1030 Wien > > > > Telefon: +43 1 713 33 98 > > Mobil: +43 664 140 35 27 > > > > Website: python4kids.net > > > > > > ## Run this program and create a polygon without > > ## intersecting edges by clicking the vertices with the mouse > > > > from Tkinter import * > > > > def area2(A,B,C): > > """2 * Flaeche des 2D-Dreiecks ABC""" > > return (A[0]-C[0])*(B[1]-C[1]) - (A[1]-C[1])*(B[0]-C[0]) > > > > def insideTriangle(A, B, C, P): > > """Liegt P im Dreieck ABC?, > > ABC sind im Gegenuhrzeigersinn angenommen!""" > > return area2(A,B,P)>=0 and area2(B,C,P)>=0 and area2(C,A,P)>=0 > > > > def triangulate(poly): > > tri = [] > > while len(poly) > 2: > > triaFound = False > > count = 0 > > while not triaFound and count < len(poly): #n: > > count += 1 > > A, B, C = poly[:3] > > if area2(A, B, C) >= 0: > > for P in poly[3:]: > > if insideTriangle(A,B,C,P): > > break > > else: > > tri.append( (A,B,C) ) > > poly.remove(B) > > triaFound = True > > poly.append(poly.pop(0)) > > if count == len(poly): # n: > > print "Not a simple polygon" > > return None > > return tri > > > > > > class CvDefPoly(Canvas): > > def __init__(self, root): > > Canvas.__init__(self, root, bg="white", cursor="crosshair") > > self.v = () > > self.rWidth, self.rHeight = 10.0, 7.5 > > > > self.bind("", self.repaint) > > self.bind("", self.mousePressed) > > > > self.done = False > > > > def mousePressed(self, event): > > if self.done: > > self.done = False > > self.v = () > > x ,y = self.fx(event.x), self.fy(event.y) > > if self.v: > > x0, y0 = self.v[:2] > > if abs(x-x0) abs(y-y0) > self.done = True > > if not self.done: > > self.v += (x,y) > > self.repaint(None) > > > > def iX(self,x): > > return self.centerX + x/self.pixelSize > > def iY(self,y): > > return self.centerY - y/self.pixelSize > > def fx(self,x): > > return (x-self.centerX)*self.pixelSize > > def fy(self,y): > > return (self.centerY - y)*self.pixelSize > > > > def repaint(self, event): > > items = self.find_all() > > for item in items: > > self.delete(item) > > if event: > > self.w, self.h = event.width, event.height > > w,h = self.w, self.h > > self.minX = self.minY = 2.0 > > self.maxX, self.maxY = w-3.0, h-3.0 > > dx, dy = self.maxX-self.minX, self.maxY-self.minY > > self.centerX = 2.0 + dx/2.0 > > self.centerY = 2.0 + dy/2.0 > > self.pixelSize = max(self.rWidth/dx, self.rHeight/dy) > > > > left = self.iX(-self.rWidth/2.0) > > right = self.iX(self.rWidth/2.0) > > bottom = self.iY(-self.rHeight/2.0) > > top = self.iY(self.rHeight/2.0) > > > > self.create_rectangle(left,top,right,bottom, outline="red") > > if len(self.v) > 1: > > x,y = self.v[:2] > > self.create_rectangle(self.iX(x)-2, self.iY(y)-2, > > self.iX(x)+2, self.iY(y)+2, > outline="green") > > if len(self.v) > 3: > > if self.done: > > v = [] > > sv = self.v[:] > > while sv: > > a,b=sv[:2] > > v.extend([self.iX(a), self.iY(b)]) > > sv = sv[2:] > > self.create_polygon( v, fill="", outline="blue") > > else: > > coo = list(self.v[2:]) > > while coo: > > x1,y1 = coo[:2] > > self.create_line(self.iX(x),self.iY(y), > > self.iX(x1),self.iY(y1),fill="blue") > > x,y=x1,y1 > > coo = coo[2:] > > > > def ccw(poly): > > n = len(poly) > > k = poly.index(min(poly)) > > return area2(poly[k-1], poly[k], poly[(k+1)%n]) > 0 > > > > def color(n): > > return "#%02x%02x%02x" % (255-n,0,n) > > > > class PolyTria(Tk): > > def __init__(self): > > Tk.__init__(self) > > self.geometry("500x300-10+50") > > self.title("Define polygon vertices by clicking") > > CvPolyTria(self).pack(expand=1, fill="both") > > > > class CvPolyTria(CvDefPoly): > > def repaint(self, event): > > doit = False > > if len(self.v)>3 and self.done: > > poly = [] > > v = self.v[:] > > while v: > > p = tuple(v[:2]) > > poly.append(p) > > v = v[2:] > > if not ccw(poly): > > poly.reverse() > > tri = triangulate(poly) > > doit = True > > CvDefPoly.repaint(self, event) > > if doit: > > anz = len(tri) > > diff = 255//anz > > for i,t in enumerate(tri): > > (x1,y1),(x2,y2),(x3,y3) = t > > t = > (self.iX(x1),self.iY(y1),self.iX(x2),self.iY(y2),self.iX(x3),self.iY(y3)) > > self.create_polygon(t, fill=color(i*diff), > outline="black") > > > > if __name__ == "__main__": > > PolyTria().mainloop() > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From wildcard2005 at comcast.net Thu Nov 10 23:29:59 2005 From: wildcard2005 at comcast.net (Terry Kemmerer) Date: Thu, 10 Nov 2005 14:29:59 -0800 Subject: [Tutor] Newbie Anxiety Message-ID: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A Computer Scientist" and I still can't count. (Don't laugh! I can't play the violin either...) In Basic, I would have said: 10 x = x + 1 : print x : goto 10 run 1 2 3 etc.... I don't know why, but this great UNKNOWN bothers me a lot. Maybe it is because it was the first thing I learned in Basic, back 20 years ago when I was actually a programmer.... But I think it goes toward visualizing how things are going flow and be constructed without line numbers and the venerable GOTO statement. How is this done in Python? (So I can stop holding my breath as I study this great language....and relax.) Thanks, Terry -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051110/aaf71e2a/attachment.htm From john at fouhy.net Thu Nov 10 23:49:37 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 11 Nov 2005 11:49:37 +1300 Subject: [Tutor] Newbie Anxiety In-Reply-To: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> References: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> Message-ID: <5e58f2e40511101449h36274f5ap@mail.gmail.com> On 11/11/05, Terry Kemmerer wrote: > I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A > Computer Scientist" and I still can't count. > (Don't laugh! I can't play the violin either...) > > In Basic, I would have said: > > 10 x = x + 1 : print x : goto 10 > > run > 1 > 2 > 3 > etc.... > > How is this done in Python? (So I can stop holding my breath as I study > this great language....and relax.) Hi Terry, There's a couple of options. First, we could do it with a while loop. This is not the best or the most idiomatic way, but it's probably most similar to what you've seen before. #### count forever i = 0 while True: print i i = i + 1 #### Of course, we generally don't want to keep counting forever. Maybe we'll count up to 9. #### count to 9 i = 0 while i < 10:: print i i = i + 1 #### A while loop contains an implicit "GOTO start" at the end. At the start, it checks the condition, and breaks out of the loop if the condition is false. Like i said, though, this is not idiomatic Python. Python has for loops which are based around the idea of iterating over a sequence. So, we could count to 9 like this: #### count to 9 for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: print i #### The loop will go through the list, assigning each item to i in turn, until the list is exhausted. The range() function is useful for building lists like that, so we don't have to type it out manually. #### count to 9 for i in range(10): print i #### And, of course, once we've got range(), we can give it a variable limit (eg, n = 10; range(n)). Iteration is the key to doing all kinds of funky stuff in python (including new ideas like geneartor functions), so it's good to get the hang of :-) -- John. From kent37 at tds.net Thu Nov 10 23:49:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Nov 2005 17:49:54 -0500 Subject: [Tutor] Newbie Anxiety In-Reply-To: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> References: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> Message-ID: <4373CE92.1000309@tds.net> Terry Kemmerer wrote: > In Basic, I would have said: > > 10 x = x + 1 : print x : goto 10 > > run > 1 > 2 > 3 > etc.... > > How is this done in Python? (So I can stop holding my breath as I study > this great language....and relax.) In Python there is no goto, as you have discovered. Loops are constructed using the 'for' and 'while' statements. A while loop will loop as long as its condition is true. If you give it a condition that is always true, it will create an infinite loop like yours above. So the equivalent Python code would be x=0 while True: x = x + 1 print x You can read a little more about while loops here and in the next chapter of your book: http://docs.python.org/tut/node5.html#SECTION005200000000000000000 Now relax and forget all the bad habits from you BASIC days ;-) Kent -- http://www.kentsjohnson.com From rschroev_nospam_ml at fastmail.fm Thu Nov 10 23:50:16 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 10 Nov 2005 23:50:16 +0100 Subject: [Tutor] Newbie Anxiety In-Reply-To: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> References: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> Message-ID: Terry Kemmerer wrote: > I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A > Computer Scientist" and I still can't count. > (Don't laugh! I can't play the violin either...) > > In Basic, I would have said: > > 10 x = x + 1 : print x : goto 10 > > run > 1 > 2 > 3 > etc.... > > How is this done in Python? (So I can stop holding my breath as I study > this great language....and relax.) You need to choose the appropriate control structure. In this case you need an infinite loop, which in Python is written as: while True: # do stuff... Also, in Python you need to explicitly give x its initial value: x = 0 In Python 'x = x + 1' can be written shorter as 'x += 1' (though 'x = x + 1') works too. All together: x = 0 while True: x += 1 print x HTH -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From cfaj at freeshell.org Fri Nov 11 00:07:22 2005 From: cfaj at freeshell.org (Chris F.A. Johnson) Date: Thu, 10 Nov 2005 18:07:22 -0500 (EST) Subject: [Tutor] Newbie Anxiety In-Reply-To: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> References: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> Message-ID: On Thu, 10 Nov 2005, Terry Kemmerer wrote: > I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A > Computer Scientist" and I still can't count. > (Don't laugh! I can't play the violin either...) > > In Basic, I would have said: > > 10 x = x + 1 : print x : goto 10 Good heavens! I never used GOTO, even on the C-64: 10 for n = 1 to 10 20 print n 25 rem n = 1 rem remove first rem for infinite loop 30 next > run > 1 > 2 > 3 > etc.... > > I don't know why, but this great UNKNOWN bothers me a lot. Maybe it is > because it was the first thing I learned in Basic, > back 20 years ago when I was actually a programmer.... But I think it > goes toward visualizing how things are > going flow and be constructed without line numbers and the venerable > GOTO statement. > > How is this done in Python? (So I can stop holding my breath as I study > this great language....and relax.) n = 1 while n <= 10: print n n = n + 1 Or: for n in [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]: print n Or: for n in range(10): print n + 1 Etc...... -- Chris F.A. Johnson ================================================================== Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress From dyoo at hkn.eecs.berkeley.edu Fri Nov 11 00:16:27 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 10 Nov 2005 15:16:27 -0800 (PST) Subject: [Tutor] triangulation In-Reply-To: <1d987df30511101347m1f2913cfkba9600954d1f61e9@mail.gmail.com> Message-ID: Hi Shi Mu, There are some direct ways you can find a delaunay triangulation implementation in Python. In fact, the first Google hit to "triangulation python" should come up with something relevant. Also, try the search "triangulation" in: http://www.python.org/pypi?%3Aaction=search_form Are you having trouble accessing Google or the Web? I mean this in all seriousness; do you have little experience with web search engines, or does your ISP restrict you from accessing them? I'm just trying to construct some reasonable explanation why you're having difficulty finding these utilities and tools. I'm trying to treat it the same way I treat a software bug, by probing for causes and reasons. Good luck to you. From alan.gauld at freenet.co.uk Fri Nov 11 00:18:26 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 10 Nov 2005 23:18:26 -0000 Subject: [Tutor] Newbie Anxiety Message-ID: <018a01c5e64d$0db2f770$0a01a8c0@xp> > compared Python to old style BASIC. You might find it helpful if you > were weaned on BASIC. You can still find the old site here: > > http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/ > > Check out the Loops topic for the GOTO discussion. Oops, so long since I looked at that version... Its actually the Branching topic that discusses GOTO. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Nov 11 00:16:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 10 Nov 2005 23:16:22 -0000 Subject: [Tutor] Newbie Anxiety References: <1131661800.12136.30.camel@c-24-16-68-31.hsd1.wa.comcast.net> Message-ID: <017a01c5e64c$c3ca5f90$0a01a8c0@xp> > In Basic, I would have said: > > 10 x = x + 1 : print x : goto 10 Tsk, tsk, even in BASIC that's considered bad form :-) 10 FOR X =1 to 10 20 PRINT X 30 NEXT Would be the better BASIC form. And as you've seen Python provides a close analog to that in its for loop. for X in [1,2,3,4,5,6,7,8,9,10]: print X OR for X in range(1,11): print X > goes toward visualizing how things are > going flow and be constructed without line numbers and the venerable > GOTO statement. I discuss why this is a bad idea in the old version of my tutor, which compared Python to old style BASIC. You might find it helpful if you were weaned on BASIC. You can still find the old site here: http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/ Check out the Loops topic for the GOTO discussion. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From wildcard2005 at comcast.net Fri Nov 11 00:25:10 2005 From: wildcard2005 at comcast.net (Terry Kemmerer) Date: Thu, 10 Nov 2005 15:25:10 -0800 Subject: [Tutor] Newbie Anxiety Message-ID: <1131665111.12136.51.camel@c-24-16-68-31.hsd1.wa.comcast.net> (I accidentally sent this to the originator. Sorry.) Sweet! Almost everything is sooo familiar, yet, merged in many interesting ways. I never had a DO WHILE statement, but in many ways, your further examples are like a combination of my old FOR NEXT loop and IF logical evaluation statement put together for reading in/out lists. JUST TOO COOL! And it looks so CLEAN! --compared to my old BASIC of having to name the variable belonging to each NEXT incrementation executed while keeping the code nested properly relative to each FOR NEXT loop!!! Thanks! THIS LOOKS GREAT! Terry On Fri, 2005-11-11 at 11:49 +1300, John Fouhy wrote: > On 11/11/05, Terry Kemmerer wrote: > > I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A > > Computer Scientist" and I still can't count. > > (Don't laugh! I can't play the violin either...) > > > > In Basic, I would have said: > > > > 10 x = x + 1 : print x : goto 10 > > > > run > > 1 > > 2 > > 3 > > etc.... > > > > How is this done in Python? (So I can stop holding my breath as I study > > this great language....and relax.) > > Hi Terry, > > There's a couple of options. > > First, we could do it with a while loop. This is not the best or the > most idiomatic way, but it's probably most similar to what you've seen > before. > > #### count forever > i = 0 > while True: > print i > i = i + 1 > #### > > Of course, we generally don't want to keep counting forever. Maybe > we'll count up to 9. > > #### count to 9 > i = 0 > while i < 10:: > print i > i = i + 1 > #### > > A while loop contains an implicit "GOTO start" at the end. At the > start, it checks the condition, and breaks out of the loop if the > condition is false. > > Like i said, though, this is not idiomatic Python. Python has for > loops which are based around the idea of iterating over a sequence. > So, we could count to 9 like this: > > #### count to 9 > for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: > print i > #### > > The loop will go through the list, assigning each item to i in turn, > until the list is exhausted. The range() function is useful for > building lists like that, so we don't have to type it out manually. > > #### count to 9 > for i in range(10): > print i > #### > > And, of course, once we've got range(), we can give it a variable > limit (eg, n = 10; range(n)). Iteration is the key to doing all kinds > of funky stuff in python (including new ideas like geneartor > functions), so it's good to get the hang of :-) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051110/f81f5c71/attachment.html From wildcard2005 at comcast.net Fri Nov 11 00:57:19 2005 From: wildcard2005 at comcast.net (Terry Kemmerer) Date: Thu, 10 Nov 2005 15:57:19 -0800 Subject: [Tutor] Newbie Anxiety Message-ID: <1131667039.12136.60.camel@c-24-16-68-31.hsd1.wa.comcast.net> I want to thank everyone for their responses. This has help tremendously to ease my mind. Thanks! Branching in the program, is actually my real anxiety, as I have been feeling the void, (maybe that should be WITHDRAWALS!) as I am working my way through How To Think Like a Computer Scientists..... By the way, I REALLY LIKE THE BOOK! --However, your recommended discussion comparing against basic is going to be very helpful in orientating me! Basic was my only language (although we went through several versions) and I haven't written a line for almost 20 years, so, I am very rusty as it is. Terry > compared Python to old style BASIC. You might find it helpful if you > were weaned on BASIC. You can still find the old site here: > > http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/ > > Check out the Loops topic for the GOTO discussion. Oops, so long since I looked at that version... Its actually the Branching topic that discusses GOTO. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051110/4916a88f/attachment.htm From Liam.Clarke-Hutchinson at business.govt.nz Fri Nov 11 00:59:14 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 11 Nov 2005 12:59:14 +1300 Subject: [Tutor] Newbie Anxiety Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13CE@chbnt01.alpha.wd.govt.nz> Hi Terry, Python is great, very much so if the last you used was Basic. I highly recommend Alan Gauld's tutorial, but I look forward to your queries here. :-) Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Terry Kemmerer Sent: Friday, 11 November 2005 12:25 p.m. To: Python_TUTOR Subject: [Tutor] Newbie Anxiety (I accidentally sent this to the originator. Sorry.) Sweet! Almost everything is sooo familiar, yet, merged in many interesting ways. I never had a DO WHILE statement, but in many ways, your further examples are like a combination of my old FOR NEXT loop and IF logical evaluation statement put together for reading in/out lists. JUST TOO COOL! And it looks so CLEAN! --compared to my old BASIC of having to name the variable belonging to each NEXT incrementation executed while keeping the code nested properly relative to each FOR NEXT loop!!! Thanks! THIS LOOKS GREAT! Terry On Fri, 2005-11-11 at 11:49 +1300, John Fouhy wrote: On 11/11/05, Terry Kemmerer > wrote: > I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A > Computer Scientist" and I still can't count. > (Don't laugh! I can't play the violin either...) > > In Basic, I would have said: > > 10 x = x + 1 : print x : goto 10 > > run > 1 > 2 > 3 > etc.... > > How is this done in Python? (So I can stop holding my breath as I study > this great language....and relax.) Hi Terry, There's a couple of options. First, we could do it with a while loop. This is not the best or the most idiomatic way, but it's probably most similar to what you've seen before. #### count forever i = 0 while True: print i i = i + 1 #### Of course, we generally don't want to keep counting forever. Maybe we'll count up to 9. #### count to 9 i = 0 while i < 10:: print i i = i + 1 #### A while loop contains an implicit "GOTO start" at the end. At the start, it checks the condition, and breaks out of the loop if the condition is false. Like i said, though, this is not idiomatic Python. Python has for loops which are based around the idea of iterating over a sequence. So, we could count to 9 like this: #### count to 9 for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: print i #### The loop will go through the list, assigning each item to i in turn, until the list is exhausted. The range() function is useful for building lists like that, so we don't have to type it out manually. #### count to 9 for i in range(10): print i #### And, of course, once we've got range(), we can give it a variable limit (eg, n = 10; range(n)). Iteration is the key to doing all kinds of funky stuff in python (including new ideas like geneartor functions), so it's good to get the hang of :-) -- John. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051111/09ddc15e/attachment-0001.html From bill at celestial.net Fri Nov 11 00:59:55 2005 From: bill at celestial.net (Bill Campbell) Date: Thu, 10 Nov 2005 15:59:55 -0800 Subject: [Tutor] Who called me? In-Reply-To: <43710EB8.9090705@tds.net> References: <20051108175939.GA36985@alexis.mi.celestial.com> <4371007F.7070008@tds.net> <43710EB8.9090705@tds.net> Message-ID: <20051110235955.GA4147@alexis.mi.celestial.com> On Tue, Nov 08, 2005, Kent Johnson wrote: >Kent Johnson wrote: >> Bill Campbell wrote: >> >>>Is there a way in python for a method to determine its parent? >>> >>>In particular, I'm working with SimpleXMLRPCServer, and would >>>like to be able to find the client_address in the routine that >>>has been dispatched. I know that client_address is an attribute >>>of the handler class instance, but don't know how to get to that. > ... good stuff deleted... >HOWEVER, I don't think this is a good solution to your problem - it's quite >a fragile hack. Better would be to find a way to pass the information you >need to your function. For example, from a quick look at the code for >SimpleXMLRPCServer, it looks like you could subclass SimpleXMLRPCServer and >make your own _dispatch() method that adds client_address to the parameter >list, then all your functions would be passed the client_address. Or even >specialize it so that just one special function gets this treatment. That's one solution that I had considered, but in this particular case, I will probably use the CGI version of the XMLRPCServer since I can get the information from the REMOTE_ADDR environment variable that apache will set for me. The problem I'm working on now is to have our client's machines connect to our XML-RPC server in cron jobs which will do at least two things, check to see if their dynamic IP address has changed so we can update DNS for them, and/or let our system know they're still alive and functioning. This part of the job is probably best handled behind apache using the CGIXMLRPCRequestHandler as it makes some things simpler and can be done via https. Being fairly new to python, I wanted to know if there was a clean way to get parent information if the author of a package hadn't provided this. I generally have attributes in children that point back to the parent making it easy to get back to the parent from the child. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``The children who know how to think for themselves spoil the harmony of the collective society that is coming, where everyone would be interdependent.'' 1899 John Dewey, educational philosopher, proponent of modern public schools. From kent37 at tds.net Fri Nov 11 01:49:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 10 Nov 2005 19:49:45 -0500 Subject: [Tutor] Who called me? In-Reply-To: <20051110235955.GA4147@alexis.mi.celestial.com> References: <20051108175939.GA36985@alexis.mi.celestial.com> <4371007F.7070008@tds.net> <43710EB8.9090705@tds.net> <20051110235955.GA4147@alexis.mi.celestial.com> Message-ID: <4373EAA9.6080302@tds.net> Bill Campbell wrote: > The problem I'm working on now is to have our client's machines connect to > our XML-RPC server in cron jobs which will do at least two things, check to > see if their dynamic IP address has changed so we can update DNS for them, > and/or let our system know they're still alive and functioning. If you have control of the code on the client machines you could just have them add their IP address to the parameters they send the server... Kent -- http://www.kentsjohnson.com From bill at celestial.net Fri Nov 11 01:55:05 2005 From: bill at celestial.net (Bill Campbell) Date: Thu, 10 Nov 2005 16:55:05 -0800 Subject: [Tutor] Who called me? In-Reply-To: <4373EAA9.6080302@tds.net> References: <20051108175939.GA36985@alexis.mi.celestial.com> <4371007F.7070008@tds.net> <43710EB8.9090705@tds.net> <20051110235955.GA4147@alexis.mi.celestial.com> <4373EAA9.6080302@tds.net> Message-ID: <20051111005505.GA9421@alexis.mi.celestial.com> On Thu, Nov 10, 2005, Kent Johnson wrote: >Bill Campbell wrote: > >>The problem I'm working on now is to have our client's machines connect to >>our XML-RPC server in cron jobs which will do at least two things, check to >>see if their dynamic IP address has changed so we can update DNS for them, >>and/or let our system know they're still alive and functioning. > >If you have control of the code on the client machines you could just have >them add their IP address to the parameters they send the server... The problem is that the clients are often on dynamic IP addresses behind a router/firewall that's doing NAT (Network Address Translation) so they don't know their IP address. One of the primary reasons for doing this is to be able to easily and automatically detect when a dynamic IP address has changed so we can update the DNS, postfix rules, etc. so we know where the client is. Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ The Constitution is a written instrument. As such, its meaning does not alter. That which it meant when it was adopted, it means now. -- SOUTH CAROLINA v. US, 199 U.S. 437, 448 (1905) From wildcard2005 at comcast.net Fri Nov 11 02:03:40 2005 From: wildcard2005 at comcast.net (Terry Kemmerer) Date: Thu, 10 Nov 2005 17:03:40 -0800 Subject: [Tutor] Newbie Anxiety Message-ID: <1131671021.12136.125.camel@c-24-16-68-31.hsd1.wa.comcast.net> A good natured word of explanation for Chris and others: Rest assured I am not criticizing the FORM and USE of white space that Python so eloquently uses, and subsequently makes it so beautiful and easy to read to the eye, by my example of a single line of BASIC. Actually, back in the day, I would never have written it the way I did for my question. I would have written it this way: 10 X=X+1:?X:GOTO10 (The Computer would have automatically translated that to 10 X=X +1:PRINTX:GOTO10) And I would have written Chris's for next loop as follows: 10 FORN=1TO10:?N:NEXTN: REM It is bad form not to name N after NEXT to label which FOR NEXT loop is being incremented. And I would not have been ashamed of the crunched out spaces, nor the multiple statements per line, because in the real world when you are building a business, you do what you need to do to get the job done. Let me explain. My company was writing full blown computerizations of every aspect of various kinds of companies on micro computers in the micro revolution, and replacing big IBM systems with tiny multi-user systems, and we had only 48,000 bytes of RAM CORE, of which 20,500 bytes was used for the entire operating system, which included either OS-65D or OS-65U Basic programming languages of OSI (Ohio Scientific Inc.), which left only 27,500 bytes to construct your entire program in. We were selling against the BIG machines, (WE WERE BEATING THEM OUT!) and we needed SPEED, which meant a lightning fast BASIC (which we hired Steve Jobs to create when he was a starving software engineer) and then we implemented coding in ways that sped that up further. Spaces and wasted lines that a teacher would have given me an A+ for in school (if there had been a class on it), in the real world, both cut down on the speed of execution of the program and drastically cut back on the amount of what could be accomplished in a single program, thus forcing a jump to a new program, all of which again cut down on speed of getting things done because we had to write our variables to disk before making the jump, and then reloaded them in the "chained" program next to be executed making a big PAUSE in the process of processing. (Of course, don't forget we also had to leave room for all of the data we were going to hold in memory also......IT ALL SHARED THE SAME 27,500 bytes. To give you an idea of how successful we were at invading BIG BLUE's turf with our tiny machines, we ended up specializing in Telephone Companies, after having written complete "turn-key" systems for many many different kinds of companies. And in all of those lines of code my company generated, which surely must be in the seven figures, GOTO, and its other versions was unabashedly and freely used because BASIC is a line-number-orientated language, and GOTO naturally follows as the size of the program increases. And I can only say to you, from a personal point of view, that the real grade for excellence that counts, is the real world reward of what happens and continues to happen with your business's bank account. Customers buy solutions that work out well for them, both in the sale and after the sale....they just want it to work. And while I am sure someone is thinking Spaghetti Code, our style was highly conventionalized, something that we enforced rather strictly. What can I say? It worked out great! Maintaining the programs and adding new abilities was never a problem. When I sold the company, we were still writing 99% of our code in Basic. (IT WAS A VERY VERY VERY FAST BASIC.) So, you see, Basic was my ONLY language. But that was the PAST. This is FINALLY the FUTURE. And while I am a bit disappointed those flying cars that were promised aren't here yet, we of the future now have the luxury of white space with no downside. It makes sense to use it as part of the programming logic. And while I am used to reading condensed code more than I am the great open spaces of programming freedom today, I will surely get used to it, and love it. My only real concern has been in how the flow of python works for the WHOLE PROGRAM FLOW, and you all have help me a lot here.......and I really appreciate it. And I assure you, intend to CONFORM to how Python sees itself being written. This is, after all, the future. I am really looking forward to the adventure of Python. And rest assured, I read up on all the other languages first, as it is my habit to trace the path to the goal in advance of launching the ship, and nowhere do I find as much potential in the view I gained, than python affords. Which is why I am braving the waters of SOMETHING DIFFERENT, that is MUCH BETTER! And n =+ 1 is an abbreviation that warms my heart to see! Thanks, Terry On Thu, 10 Nov 2005, Terry Kemmerer wrote: > I'm working on Ch. 5, "Fruitful Functions", or "How To Think Like A > Computer Scientist" and I still can't count. > (Don't laugh! I can't play the violin either...) > > In Basic, I would have said: > > 10 x = x + 1 : print x : goto 10 Good heavens! I never used GOTO, even on the C-64: 10 for n = 1 to 10 20 print n 25 rem n = 1 rem remove first rem for infinite loop 30 next > run > 1 > 2 > 3 > etc.... > > I don't know why, but this great UNKNOWN bothers me a lot. Maybe it is > because it was the first thing I learned in Basic, > back 20 years ago when I was actually a programmer.... But I think it > goes toward visualizing how things are > going flow and be constructed without line numbers and the venerable > GOTO statement. > > How is this done in Python? (So I can stop holding my breath as I study > this great language....and relax.) n = 1 while n <= 10: print n n = n + 1 Or: for n in [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]: print n Or: for n in range(10): print n + 1 Etc...... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051110/965346c0/attachment.htm From nequeo at gmail.com Fri Nov 11 03:32:33 2005 From: nequeo at gmail.com (Simon Gerber) Date: Fri, 11 Nov 2005 13:32:33 +1100 Subject: [Tutor] OT - Newbie Anxiety Message-ID: <667ca7b60511101832t1c1e35c4n@mail.gmail.com> > But that was the PAST. This is FINALLY the FUTURE. And while I am a bit > disappointed those flying cars that were promised aren't here yet, we of the > future now have the luxury of white space with no downside. Whaddaya mean, no flying cars? http://www.moller.com/skycar/ Aside from that, thanks for the interested read. Cheers! -- Simon Gerber - Prodigi Solutions http://www.prodigi.com.au From samrobertsmith at gmail.com Fri Nov 11 04:36:08 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Thu, 10 Nov 2005 19:36:08 -0800 Subject: [Tutor] triangulation In-Reply-To: References: <1d987df30511101347m1f2913cfkba9600954d1f61e9@mail.gmail.com> Message-ID: <1d987df30511101936j45a6a6adi68340e197c7b0748@mail.gmail.com> I see. maybe some websites are blocked to me. On 11/10/05, Danny Yoo wrote: > > Hi Shi Mu, > > There are some direct ways you can find a delaunay triangulation > implementation in Python. In fact, the first Google hit to "triangulation > python" should come up with something relevant. > > Also, try the search "triangulation" in: > > http://www.python.org/pypi?%3Aaction=search_form > > Are you having trouble accessing Google or the Web? I mean this in all > seriousness; do you have little experience with web search engines, or > does your ISP restrict you from accessing them? > > I'm just trying to construct some reasonable explanation why you're having > difficulty finding these utilities and tools. I'm trying to treat it the > same way I treat a software bug, by probing for causes and reasons. > > Good luck to you. > > From johan at accesstel.co.za Fri Nov 11 06:57:00 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 11 Nov 2005 07:57:00 +0200 Subject: [Tutor] logging to a database In-Reply-To: References: Message-ID: <437432AC.1040504@accesstel.co.za> Try looking here; http://sourceforge.net/projects/mysql-python Johan captnswing wrote: >Hello all, >I would like to log messages to a database (mysql) >I found the example log_test14.py that comes with python logging >module http://www.red-dove.com/python_logging.html >but that example is a bit greek for me ... :) and it doesnt work with >mysql >is there some kind of tutorial how to get going if you want to log to >a database? >thanks, >-frank > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From johan at accesstel.co.za Fri Nov 11 07:31:53 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 11 Nov 2005 08:31:53 +0200 Subject: [Tutor] simple report writing? In-Reply-To: References: Message-ID: <43743AD9.8050908@accesstel.co.za> Did you manage to get something that worked for you? Johan CPIM Ronin wrote: >Can someone suggest a specific tutorial strictly on report writing? > >I'm able to write reports fairly easily in Python. I know the stuff like >str(round(x,2)) where x = 3.145678 will yield 3.14. What I'm looking for is >to be able to control left and right justification, column by column while >using string and numeric data of variable lengths so that my reports look >much neater. > >Possibly a generalized def print_line(*x)? > >Thanks. > >RC > >_________________________________________________________________ >Express yourself instantly with MSN Messenger! Download today - it's FREE! >http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From samrobertsmith at gmail.com Fri Nov 11 08:38:15 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Thu, 10 Nov 2005 23:38:15 -0800 Subject: [Tutor] two ways Message-ID: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> what is the difference between the two ways of assigning the list? p=a vs. p=a[:] >>> a=range(5) >>> a [0, 1, 2, 3, 4] >>> p=a >>> p [0, 1, 2, 3, 4] >>> p=a[:] >>> p [0, 1, 2, 3, 4] From ml.cyresse at gmail.com Fri Nov 11 08:50:30 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 11 Nov 2005 20:50:30 +1300 Subject: [Tutor] two ways In-Reply-To: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> References: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> Message-ID: Hi Shi, For what you're doing, nothing at all. When you use a colon, slice syntax, it defaults to [start:end] so p = a[:] is the same as p = a[0:len(a)] Regards, Liam Clarke On 11/11/05, Shi Mu wrote: > what is the difference between the two ways of assigning the list? > p=a vs. p=a[:] > >>> a=range(5) > >>> a > [0, 1, 2, 3, 4] > >>> p=a > >>> p > [0, 1, 2, 3, 4] > >>> p=a[:] > >>> p > [0, 1, 2, 3, 4] > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Fri Nov 11 08:56:03 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Thu, 10 Nov 2005 23:56:03 -0800 Subject: [Tutor] two ways In-Reply-To: References: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> Message-ID: <1d987df30511102356i3b5aaf97ia76415f2a3966386@mail.gmail.com> thanks! On 11/10/05, Liam Clarke wrote: > Hi Shi, > > For what you're doing, nothing at all. > > When you use a colon, slice syntax, it defaults to [start:end] so p = > a[:] is the same as > p = a[0:len(a)] > > Regards, > > Liam Clarke > > On 11/11/05, Shi Mu wrote: > > what is the difference between the two ways of assigning the list? > > p=a vs. p=a[:] > > >>> a=range(5) > > >>> a > > [0, 1, 2, 3, 4] > > >>> p=a > > >>> p > > [0, 1, 2, 3, 4] > > >>> p=a[:] > > >>> p > > [0, 1, 2, 3, 4] > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From shaleh at speakeasy.net Fri Nov 11 09:37:43 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri, 11 Nov 2005 00:37:43 -0800 Subject: [Tutor] Percentage In-Reply-To: <436F5934.20905@accesstel.co.za> References: <436F5934.20905@accesstel.co.za> Message-ID: <43745857.3090205@speakeasy.net> Johan Geldenhuys wrote: > Hi all, > > What is the syntax if I want to work out what percentage 42 is out of 250? > 42 is x percent of 250. (is / of) = (x / 100) one of those formulas from school I will always remember. (42 / 250) = (x / 100.0) 250x = 4200.0 x = 4200.0 / 250 x = 16.8% From glingl at aon.at Fri Nov 11 11:24:19 2005 From: glingl at aon.at (Gregor Lingl) Date: Fri, 11 Nov 2005 11:24:19 +0100 Subject: [Tutor] two ways In-Reply-To: References: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> Message-ID: <43747153.6090201@aon.at> Liam Clarke schrieb: >Hi Shi, > >For what you're doing, nothing at all. > >When you use a colon, slice syntax, it defaults to [start:end] so p = >a[:] is the same as >p = a[0:len(a)] > > > But in fact there is a difference. I'll show you: >>> a=range(5) ### creates a list-object >>> id(a) ### which has an identity 14716520 >>> p=a ### creates the new name p for the same object >>> id(p) ### let's see 14716520 ### o.k. really the same >>> q=a[:] ### this names a *copy* of a q >>> id(q) ### identity? 14714840 ### different! >>> a is p ### check if objects named a and p are identical True ### yes >>> a is q ### check if objects named a and q are identical False ### no! >>> a == q True ### but have the same "content", i. e. two different list-objects with the same elements >>> >>> ### Beware, lists are mutable: >>> >>> a [0, 1, 2, 3, 4] >>> a[1]=1001 >>> a [0, 1001, 2, 3, 4] >>> p [0, 1001, 2, 3, 4] ### object named a *and* p is changed >>> q ### copy q of a is not changed!? [0, 1, 2, 3, 4] >>> regards Gregor From ml.cyresse at gmail.com Fri Nov 11 11:30:30 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 11 Nov 2005 23:30:30 +1300 Subject: [Tutor] two ways In-Reply-To: <43747153.6090201@aon.at> References: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> <43747153.6090201@aon.at> Message-ID: Oooh... that's a gotcha. Shi Mu - did you understand that? There is a crucial difference as Gregor pointed out, that I missed, and I do apologise. On 11/11/05, Gregor Lingl wrote: > Liam Clarke schrieb: > > >Hi Shi, > > > >For what you're doing, nothing at all. > > > >When you use a colon, slice syntax, it defaults to [start:end] so p = > >a[:] is the same as > >p = a[0:len(a)] > > > > > > > But in fact there is a difference. I'll show you: > > >>> a=range(5) ### creates a list-object > >>> id(a) ### which has an identity > 14716520 > >>> p=a ### creates the new name p for the same object > >>> id(p) ### let's see > 14716520 ### o.k. really the same > >>> q=a[:] ### this names a *copy* of a q > >>> id(q) ### identity? > 14714840 ### different! > >>> a is p ### check if objects named a and p are identical > True ### yes > >>> a is q ### check if objects named a and q are identical > False ### no! > >>> a == q > True ### but have the same "content", i. e. two > different list-objects with the same elements > >>> > >>> ### Beware, lists are mutable: > >>> > >>> a > [0, 1, 2, 3, 4] > >>> a[1]=1001 > >>> a > [0, 1001, 2, 3, 4] > >>> p > [0, 1001, 2, 3, 4] ### object named a *and* p is changed > >>> q ### copy q of a is not changed!? > [0, 1, 2, 3, 4] > >>> > regards > Gregor > From alan.gauld at freenet.co.uk Fri Nov 11 12:18:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 11 Nov 2005 11:18:57 -0000 Subject: [Tutor] Newbie Anxiety References: <1131671021.12136.125.camel@c-24-16-68-31.hsd1.wa.comcast.net> Message-ID: <01c401c5e6b1$b5e76d90$0a01a8c0@xp> Ah, memory lane time again :-) >A good natured word of explanation for Chris and others: > 10 FORN=1TO10:?N:NEXTN: REM It is bad form not to name N after NEXT to > label which FOR NEXT loop is being incremented. Oh, you had advanced BASIC - it allowed nested for loops! :-) My first BASIC only allowed for loops that could be written in a single line...Anything more complex you had to call a subroutine with GOSUB. > and replacing big IBM systems with tiny multi-user systems, and we had > only 48,000 bytes of RAM CORE, of which 20,500 bytes was used for the > entire operating system, Yes, I remember those days, in fact 48K was quite generous! My original box only had 16K RAM and 16K ROM for the OS and interpreter. > SPEED, which meant a lightning fast BASIC (which we hired Steve Jobs to Ah yes, now there's another difference. Our BASIC was SLOOOOOW! The machine was slow too, it had a 500KHz clock - yes, half a megahertz! > accomplished in a single program, thus forcing a jump to a new program, > all of which again cut down on speed of getting things done because we > had to write our variables to disk before making the jump, You had Disks?!! We were using loops of punched tape... > reloaded them in the "chained" program next to be executed making a big > PAUSE in the process of processing. Yes, the forerunner of Overlay programming, I used to have such fun debugging Overlays! :-( > line-number-orientated language, and GOTO naturally follows as the size > of the program increases. And here we have another advanced feature. Our BASIC didn't renumber GOTO or GOSUB statements, you had to do that manually. Thats why we used a lot of GOSUB but very few GOTO. And SUBs were all given 1000 lines each to minimise risk of renumbering... > point of view, that the real grade for excellence that counts, is the > real world reward of what happens and continues to happen with your > business's bank account. Depends on how you measure excellence. A lot of excellent software has been written by companies that went bust. The software was sufficiently excellent to survive and be bought out or just made publicly available as open source. So excellence can also be measured on how long lived the software is regardless of how long lived be the commercial body that created it. > And while I am sure someone is thinking Spaghetti Code, our style was > highly conventionalized, something that we enforced rather strictly. Yep you can write structured assembly and spaghetti Python. Its ultimately about behaviours not language. > writing 99% of our code in Basic. (IT WAS A VERY > VERY VERY FAST BASIC.) So, you see, Basic was my ONLY language. But I've fortunately never been limited to one language, even on my most primitive machines I've had recourse to assembler, and usually some kind of scripting environment. Only on very early PCs, where BASIC was the OS was I so restricted - and PEEK/POKE were my friends :-). > only real concern has been in how the flow of python works for the WHOLE > PROGRAM FLOW, and you all have help me a lot here.......and I really One of the things that some folks find hard is divorcing themselves from that old line by line way of thinking. Modern languages can seem a little like black magic at times(*) - especially when you start programming with objects. The trick is to trust the language and just believe it will work! :-) (*)I'm having the same problem right now with the JSP Tomcat/Struts framework where all sorts of magical things just seem to happen. I keep fighting my desire to go trawl through the source code to see what's going on. Then I tell myself ' just trust in the force Luke...' Enjoy your voyage of discovery and question us freely here on tutor. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Nov 11 12:26:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Nov 2005 06:26:05 -0500 Subject: [Tutor] logging to a database In-Reply-To: References: Message-ID: <43747FCD.3030900@tds.net> captnswing wrote: > Hello all, > I would like to log messages to a database (mysql) > I found the example log_test14.py that comes with python logging > module http://www.red-dove.com/python_logging.html > but that example is a bit greek for me ... :) and it doesnt work with > mysql Have you used mysql from Python before? I looked at that example and it is not that complex if you understand how to program a database. I think what you have to do is - install MySQL and create the database table that you want to log to. The SQL statement in the example shows the fields you might want, or you can use a subset of those fields if you don't need so much information. - modify the example program a little: change import mx.ODBC.Windows to the correct import for the MySQL driver change self.conn = mx.ODBC.Windows.connect(self.dsn, self.uid, self.pwd) to the correct statement to connect to MySQL change the SQL statement to correspond to your database schema If you *haven't* used MySQL from Python before, you should probably learn a little about the basics first. BTW the example is vulnerable to SQL injection attacks - if any of the log messages contain text from user input you should fix that. But get it working first, then come back and ask for help again. Kent -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Fri Nov 11 12:45:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 11 Nov 2005 11:45:31 -0000 Subject: [Tutor] two ways References: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> Message-ID: <01dc01c5e6b5$6b991230$0a01a8c0@xp> > what is the difference between the two ways of assigning the list? > p=a vs. p=a[:] The first makes p point at the same list as a. The second makes p point at a *copy* of the list pointed to by a. You will see the difference if you try to modify the lists after assignment. In the first case modifying either variable will affect both variables values. In the second changing p will not affect a. This is one of the common 'gotchas' of Python programjming. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From samrobertsmith at gmail.com Fri Nov 11 13:47:30 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 11 Nov 2005 04:47:30 -0800 Subject: [Tutor] two ways In-Reply-To: <43747153.6090201@aon.at> References: <1d987df30511102338u69d3ca84i2e7f8e7bd26ff761@mail.gmail.com> <43747153.6090201@aon.at> Message-ID: <1d987df30511110447s65cc378bwb8463a54577ddba8@mail.gmail.com> thanks! On 11/11/05, Gregor Lingl wrote: > Liam Clarke schrieb: > > >Hi Shi, > > > >For what you're doing, nothing at all. > > > >When you use a colon, slice syntax, it defaults to [start:end] so p = > >a[:] is the same as > >p = a[0:len(a)] > > > > > > > But in fact there is a difference. I'll show you: > > >>> a=range(5) ### creates a list-object > >>> id(a) ### which has an identity > 14716520 > >>> p=a ### creates the new name p for the same object > >>> id(p) ### let's see > 14716520 ### o.k. really the same > >>> q=a[:] ### this names a *copy* of a q > >>> id(q) ### identity? > 14714840 ### different! > >>> a is p ### check if objects named a and p are identical > True ### yes > >>> a is q ### check if objects named a and q are identical > False ### no! > >>> a == q > True ### but have the same "content", i. e. two > different list-objects with the same elements > >>> > >>> ### Beware, lists are mutable: > >>> > >>> a > [0, 1, 2, 3, 4] > >>> a[1]=1001 > >>> a > [0, 1001, 2, 3, 4] > >>> p > [0, 1001, 2, 3, 4] ### object named a *and* p is changed > >>> q ### copy q of a is not changed!? > [0, 1, 2, 3, 4] > >>> > regards > Gregor > From kent37 at tds.net Fri Nov 11 14:50:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 11 Nov 2005 08:50:29 -0500 Subject: [Tutor] testing: doctest and unittest In-Reply-To: <43716A0A.9070409@tds.net> References: <4370A3A5.6080701@tardis.ed.ac.uk> <43716A0A.9070409@tds.net> Message-ID: <4374A1A5.9070504@tds.net> Kent Johnson wrote: > Alex Hunsley wrote: >>Where do you seasoned pythonites see unittest and doctest in relation to >>each other? Do you only use one or the other? > > > I think it is mostly personal preference. Doctest is nice where you > create examples for others, maybe not so nice where you are creating > exhaustive unit tests trying to exercise every corner case. unittest > is perhaps easier to aggregate tests from multiple modules. Doctests > integrate with unittest in Python 2.4. Personally I use unittest but > I come from a Java background and learned TDD with JUnit which is > related to unittest. I have recently begun a project where I am using extreme test-driven development with unittest - writing very small tests, then writing the code to make the test pass [1]. In this case much of the code is testing access to data that I read from a text file. I think these tests would make very poor doctests because - they are just exercising the accessors (attributes, actually) of a data class; they don't contribute much to understanding the class under test - they rely on test files for the data, they won't run in isolation [2] Most of my unit tests are crushingly boring reading, so for me I think unittest is a better fit. [1] I like this style in general. In this case the programming is fairly exploratory - I have to figure out what data I need from the file, then figure out how to get it - which is an excellent fit for this style of programming. I figure out one bit of data, write a test for it, write the code to access the data, repeat. [2] I know, some unit testing purists say unit tests shouldn't rely on external resources such as files and databases. I disagree :-) as long as the tests are fast I don't care what resources they use. Kent -- http://www.kentsjohnson.com From ewalker at micron.com Fri Nov 11 22:39:32 2005 From: ewalker at micron.com (Eric Walker) Date: Fri, 11 Nov 2005 14:39:32 -0700 Subject: [Tutor] dictionary question Message-ID: <200511111439.32456.ewalker@micron.com> All, I have a dictionary say: d = {'first':[]} I am going through another list and depending on whats going on, I want to add to the empty list. I have tried the following to noavail. d['first'] = d['first'].append("string") I would think this would result in the dictionary key first's empty list to become ["string"]. can anyone help clear my head? Thanks... From samrobertsmith at gmail.com Fri Nov 11 22:52:18 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Fri, 11 Nov 2005 13:52:18 -0800 Subject: [Tutor] dictionary question In-Reply-To: <200511111439.32456.ewalker@micron.com> References: <200511111439.32456.ewalker@micron.com> Message-ID: <1d987df30511111352l70e9bfa0i22b4d1e645b6d7dc@mail.gmail.com> On 11/11/05, Eric Walker wrote: > All, > I have a dictionary say: > d = {'first':[]} > I am going through another list and depending on whats going on, > I want to add to the empty list. I have tried the following to noavail. > > d['first'] = d['first'].append("string") > > I would think this would result in the dictionary key first's empty list to > become ["string"]. can anyone help clear my head? > > Thanks... I guess d['first'].append("string"), instead of, d['first'] = d['first'].append("string") or you will make d['first'] NoneType From ds-python-tutor at sidorof.com Fri Nov 11 22:59:29 2005 From: ds-python-tutor at sidorof.com (DS) Date: Fri, 11 Nov 2005 13:59:29 -0800 Subject: [Tutor] dictionary question In-Reply-To: <200511111439.32456.ewalker@micron.com> References: <200511111439.32456.ewalker@micron.com> Message-ID: <43751441.1050905@sidorof.com> You almost have it. Do this instead. d = {'first':[]} d['first'].append("string") Append acts on the list, so assignment is unnecessary. ds Eric Walker wrote: >All, >I have a dictionary say: >d = {'first':[]} >I am going through another list and depending on whats going on, >I want to add to the empty list. I have tried the following to noavail. > >d['first'] = d['first'].append("string") > >I would think this would result in the dictionary key first's empty list to >become ["string"]. can anyone help clear my head? > >Thanks... > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > From ewalker at micron.com Fri Nov 11 23:02:34 2005 From: ewalker at micron.com (Eric Walker) Date: Fri, 11 Nov 2005 15:02:34 -0700 Subject: [Tutor] dictionary question In-Reply-To: <43751441.1050905@sidorof.com> References: <200511111439.32456.ewalker@micron.com> <43751441.1050905@sidorof.com> Message-ID: <200511111502.34931.ewalker@micron.com> ahh man, I should have known. sheesh python is so kewl. I keep forgetting most times, it will do stuff directly and you don't have to assign.. Thanks Python Newbie.... On Friday 11 November 2005 02:59 pm, DS wrote: > You almost have it. Do this instead. > > d = {'first':[]} > d['first'].append("string") > > Append acts on the list, so assignment is unnecessary. > > ds > > Eric Walker wrote: > >All, > >I have a dictionary say: > >d = {'first':[]} > >I am going through another list and depending on whats going on, > >I want to add to the empty list. I have tried the following to noavail. > > > >d['first'] = d['first'].append("string") > > > >I would think this would result in the dictionary key first's empty list > > to become ["string"]. can anyone help clear my head? > > > >Thanks... > > > >_______________________________________________ > >Tutor maillist - Tutor at python.org > >http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From zmerch at 30below.com Fri Nov 11 23:36:29 2005 From: zmerch at 30below.com (Roger Merchberger) Date: Fri, 11 Nov 2005 17:36:29 -0500 Subject: [Tutor] Does a module for DirectFB exist? In-Reply-To: <5.1.0.14.2.20051101144204.047d34e0@mail.30below.com> Message-ID: <5.1.0.14.2.20051111170627.03a934f0@mail.30below.com> Rumor has it that Roger Merchberger may have mentioned these words: >DirectFB is short for Direct Frame Buffer, and allows access to a graphical >frame buffer system in *nix (and I think maybe MacOSX) from a text prompt >without going through X. > >Anyone know of a module to access this through Python? I've googled for it, >but didn't know if anyone here knew about something along these lines. Yea, I like talking to myself... This is just fer the archives anywho... The DirectFB can make use of the SDL which does access the hardware directly, and I did find a python module for libSDL, but it looked like it hadn't been supported for 3-4 years... according to the webpage, all of the functionality of that module was built into a module called PyGame. PyGame makes direct access to the hardware possible through SDL or DirectFB (altho for some reason the DirectFB component couldn't compile on my system. :-/ ) and with other SDL modules supports blitting graphics and TTF fonts directly to the framebuffer. It took a little work getting it working, but now I can print text & graphics of any size to the framebuffer without needing X to do it (and X is kinda limited when you're talking 200-pixel text rendering in an xterm... PyGame does it easily as it doesn't have xterm's restraints.). Anyway, I hope this helps someone else out there... Laterz, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | "Profile, don't speculate." SysAdmin, Iceberg Computers | Daniel J. Bernstein zmerch at 30below.com | From wildcard2005 at comcast.net Fri Nov 11 23:22:34 2005 From: wildcard2005 at comcast.net (Terry Kemmerer) Date: Fri, 11 Nov 2005 14:22:34 -0800 Subject: [Tutor] Newbie Anxiety In-Reply-To: <01c401c5e6b1$b5e76d90$0a01a8c0@xp> References: <1131671021.12136.125.camel@c-24-16-68-31.hsd1.wa.comcast.net> <01c401c5e6b1$b5e76d90$0a01a8c0@xp> Message-ID: <1131747757.12136.407.camel@c-24-16-68-31.hsd1.wa.comcast.net> > Ah, memory lane time again :-) > Oh, you had advanced BASIC - it allowed nested for loops! :-) > My first BASIC only allowed for loops that could be written in a single > line...Anything more complex you had to call a subroutine with GOSUB. > Ha! Yes! As Monte Python would say, "Well......It got better!" > Yes, I remember those days, in fact 48K was quite generous! > My original box only had 16K RAM and 16K ROM for the OS and interpreter. > The OSI "machine" I learned BASIC on, had 8K of usable RAM (I could have bought it with 4K RAM instead, but I splurged) and I used a radio shack cassette tape to store my programs and play them back into the CORE. Speaking of ROM, I remember setting there in front of the TV screen, thinking this means if they upgrade the OS, I am going to have to throw away the second most populated board in the machine! (The biggest board was the nearly empty BUS back plane board. > You had Disks?!! We were using loops of punched tape... > OSI led the micro computer revolution in technical innovation. We were years ahead of the other microcomputer manufacturers. Of course, at the onset, WE CHEATED. (Cheating is natural...sometimes...) We didn't wait for the little hard drives or small floppies that were priced right. Instead, we immediately adapted, and used the more expensive Industrial components available for the REAL COMPUTERS of our day, which were all around us already. This move immediately PUSHED US FORWARD in OS development. So, early on, we had the option of 8 inch industry standard dual floppies, a 40 MB and 80 MB Winchester hard drives (they were very big and very heavy), and OSI quickly added time sharing capability to the OS, which opened up a whole new level of capability and opportunity, then distributed processing, then Multiprocessing, etc. while the rest of the micro computer world lagged behind us. We were the first in the microcomputer world to do all these things. In fact, OSI created and marketed the first SINGLE BOARD COMPUTER which they called the PC. (That's right. IBM stole the name from OSI. It is very true, the victor writes the history.) So, with these innovations our OS and BASIC were pushed for increased capability. This, of course, was all done on the 8 bit 6502 chip which had the advantage of pipe line processing. So, while the 6502 was seen as a gaming chip by the world, running video arcades in the mall, we were running full blown timeshare computer systems on it. It was only natural that later OSI jumped to the Motorola 68,000 series chip which had pipe line capability also. Each step from time sharing forward, gave us orders of magnitude of capability over our peers and bigger and bigger teeth to bite IBM with. It was a magical time......full of wonderful risks. Ha Ha Ha > And here we have another advanced feature. Our BASIC didn't renumber > GOTO or GOSUB statements, you had to do that manually. Thats why we > used a lot of GOSUB but very few GOTO. And SUBs were all given 1000 > lines each to minimise risk of renumbering... > Yes. Our Basic was very advanced for its time. When Steve Jobs began doing his Apple thing with real money, he came back to OSI, and wanted to purchase "rights" for the stuff he had written for us. The factory made it's second biggest mistake by not SHARING the OS and the BASIC with Apple. That would have put both Apple and OSI on the same team against IBM, and made all the software being developed on their 6502 platform run on ours also and viceversa. Oh? What was the first biggest mistake? The factory turned down the wall street guys who wanted to take them public, and those same brokers went to Apple next, and took them public instead. Ooops! > Depends on how you measure excellence. A lot of excellent software has > been written by companies that went bust. The software was sufficiently > excellent to survive and be bought out or just made publicly available as > open source. So excellence can also be measured on how long lived the > software is regardless of how long lived be the commercial body that created > it. > Essentially, I agree with you completely from the lifetime viewpoint of software. From the productivity business point of view, I would have said it differently, but we both would have ended up with the same goal. No one floats far on thin ice. > But I've fortunately never been limited to one language, even on my most > primitive machines I've had recourse to assembler, and usually some kind > of scripting environment. Only on very early PCs, where BASIC was the OS > was I so restricted - and PEEK/POKE were my friends :-). > Ha! Yes. We used PEEK/POKE also in our BASIC STATEMENTS, but soon left that behind. Before we went into business, however, as we surveyed the lay of the land, and we saw people laboriously toggling programs in binary into Emsai and Altair machines by flipping switches, and we saw people programming in assembler, and we looked into that, but the bottom line for my thinking was, THIS IS ALL TOO SLOW. And slow meant that RESPONSE SOLUTIONS to changing customer needs would come far too late, and probably much later than hitting the iceberg. This was a major reason we latched onto BASIC and stay there. Later, we hired people from time to time to create utilities that we could employ via BASIC, that were written in Assembler or C later yet, but that represented a very minute part of our stuff. Things like faster GARBAGE COLLECTION routines, etc. Which brings us back to why I have picked PYTHON. It is fast to do development work in, and excellent enough to leave working code as PYTHON, rather than writing it into something else later. Further, I don't like to repeat myself, and do things more than once. When I finish something, I want it to be done, and get on with life, and the next step. The fact is, at my age, I am looking for a way NOT TO EXPAND past Python into any other language. I want one excellent language to concentrate my investment time into which will then magnify my skills learned, and let me apply them and my language in any situation I run into on my way to the bank. I am looking for ONE LANGUAGE to get me from scratch to a finished business in play......a ZERO DOLLAR BUDGETING PHILOSOPHY OF PROGRAMMING SPECIALIZATION, if you get my drift. That means that language must be versatile and excel in the majority of areas I will encounter, whatever they may be, and at least adequate for those "other" areas where few have tread with the language before. Python sure looks like it fits in that class of animal from where I am standing....of course, I am looking from a long distance in time, from where I left the industry.......but still.....I also trust my instincts. And I have a very strong feeling about Python. I would put money on it. In fact, I am going to do just that. I intend to completely automate this business as close to 100% as possible, letting it do the accounting, banking, etc. (either hand writing those packages or integrating them from what is available using PYTHON like glue), and put the applicable portions of it on the web. (And no, I have been out of the computer world inventing strange devices for quite some time, so, I have no idea which software parts go where yet. Like, is it possible to safely put EVERYTHING on the web site, like automated accounting of the books, etc? ) --And I have decided to let the LANGUAGE take me there, much the way you recommend a bit later in this letter, where you say to trust the language. I do. From my prior experience I understand that THE WAY OF THE LANGUAGE is everything. Right now, my goal is to actually grasp that about Python. Ha. My assessment is, PYTHON is the most probable SINGLE path language that has the potential to carry me to my goal from where it is located on the advancing time line of events, and if this is so, I want to ride it, as a single language ride, it greatly minimizes my learning curve and investment time. And since I am business orientated, it isn't about the intellectual, although that is always great to have, it is about getting from here to there efficiently, and being able to respond quickly to what I didn't think of when it bites me in the ass out of the blue, and getting the action going in the market, and then being able to quickly fine tune or even change directions in my code in real time (business real time), or as near that as possible. And that all appears to be in the nature of PYTHON. This is the same way I picked my computer and programming horse in the beginning of the microcomputer revolution. Somethings are still inherent in the situation. In the end, the language and the subsequent code created, are just tools to an end.........although I will probably burn incense at night in front of the Python Bible..........just in case. So, my goal will be, regardless of what lanugage any packages are written in that I might use, to do all my own work, whatever that turns out that I need to do, from scratch to final website business, in PYTHON. Does it sound like it can be done? > > only real concern has been in how the flow of python works for the WHOLE > > PROGRAM FLOW, and you all have help me a lot here.......and I really > > One of the things that some folks find hard is divorcing themselves from > that > old line by line way of thinking. Modern languages can seem a little like > black magic at times(*) - especially when you start programming with > objects. > The trick is to trust the language and just believe it will work! :-) > > (*)I'm having the same problem right now with the JSP Tomcat/Struts > framework where all sorts of magical things just seem to happen. I keep > fighting my desire to go trawl through the source code to see what's going > on. Ha! I know that instinct well.... > Then I tell myself ' just trust in the force Luke...' I will take your advice! Thanks. Another good one is, "STAY ON TARGET!" Anyway, I am generally not this chatty. And I will try to keep my future questions brief. But now that I am working my way back into the computer world, it is good to have found Python, as I feel I recognize it, even from a distance. I know I have a long ways to go.... Thanks, Terry -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051111/409e630f/attachment.html From ronin_cpim at hotmail.com Sat Nov 12 00:06:25 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Fri, 11 Nov 2005 18:06:25 -0500 Subject: [Tutor] simple report writing? -- Thanks! In-Reply-To: <43743AD9.8050908@accesstel.co.za> Message-ID: Yes Johan, I did! Both the report and sort suggestions worked! Thanks to everyone who replied! FP >From: Johan Geldenhuys >Reply-To: johan at accesstel.co.za >To: CPIM Ronin >CC: tutor at python.org >Subject: Re: [Tutor] simple report writing? >Date: Fri, 11 Nov 2005 08:31:53 +0200 > >Did you manage to get something that worked for you? >Johan > >CPIM Ronin wrote: > >>Can someone suggest a specific tutorial strictly on report writing? >> >>I'm able to write reports fairly easily in Python. I know the stuff like >>str(round(x,2)) where x = 3.145678 will yield 3.14. What I'm looking for >>is to be able to control left and right justification, column by column >>while using string and numeric data of variable lengths so that my reports >>look much neater. >> >>Possibly a generalized def print_line(*x)? >> >>Thanks. >> >>RC >> >>_________________________________________________________________ >>Express yourself instantly with MSN Messenger! Download today - it's FREE! >>http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From alan.gauld at freenet.co.uk Sat Nov 12 00:50:16 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 11 Nov 2005 23:50:16 -0000 Subject: [Tutor] dictionary question References: <200511111439.32456.ewalker@micron.com><43751441.1050905@sidorof.com> <200511111502.34931.ewalker@micron.com> Message-ID: <021001c5e71a$ab25e300$0a01a8c0@xp> > I should have known. sheesh python is so kewl. I keep forgetting most > times, > it will do stuff directly and you don't have to assign.. Whether thats 'kewl' depends on your viewpoint. >From a pure computing point of view returning a value is more consistent and correct in a functional programming sense, however its usually much less efficient since temporary variables and copying are slow and resource hungry, so direct action is preferred. Alan G. From Barry.Carroll at psc.com Sat Nov 12 02:09:53 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Fri, 11 Nov 2005 17:09:53 -0800 Subject: [Tutor] File extension for CGI scripts written in Python Message-ID: Greetings: I am writing the first of the handler routines for my test system web interface. They will be Common Gateway Interface (CGI) scripts written in Python. In the literature I have studied, I have seen the extensions .cgi and .py applied to such files. Is one preferred over the other, or is it a matter of personal preference? As always, thanks for taking the time to respond. Barry From python at venix.com Sat Nov 12 02:40:46 2005 From: python at venix.com (Python) Date: Fri, 11 Nov 2005 20:40:46 -0500 Subject: [Tutor] Using CGIHTTPServer on Windows to run Perl & Python scripts - POST to Perl fails Message-ID: <1131759646.6232.103.camel@www.venix.com> The perl scripts use cgi.pm. The Python scripts use the cgi module. Everything runs OK on Linux, where fork is available. On Windows the run_cgi method uses os.popen3 to run the script and writes the post data to the script's input file. The Python scripts are OK. The Perl scripts do not receive the POST parameters so they execute as though no parameters were supplied. I've added logic to display the environment and that appears (to my Python oriented eye) to be correct. In particular, the CONTENT_LENGTH and CONTENT_TYPE are correct. GET requests work correctly. In googling around, I found references to old POST problems under Windows. Those have clearly been fixed. The Python scripts work and the comments in the source code explain what was done (reading extra characters beyond the specified content-length that IE pushes up to the server). My guesses are that the Perl CGI module in Windows needs some other environment cue to get it to read the input file or it expects a different mechanism for receiving POST data than reading it from a file. Any suggestions would be greatly appreciated. (My fall back will be to change the run_cgi method for the Perl scripts to mimic a GET and put the parameters into the environment QUERY_STRING and hope that I do not exceed any limits on the string size.) -- Lloyd Kvam Venix Corp From hugonz-lists at h-lab.net Sat Nov 12 06:49:14 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Fri, 11 Nov 2005 23:49:14 -0600 Subject: [Tutor] Question about resetting values In-Reply-To: References: <066201c597a3$1c0266b0$8eaa8651@xp> Message-ID: <4375825A.8030209@h-lab.net> There may be more than one way to have it get a zero value. But in languages like Python readability and clarity are valued, and clearly var = 0 is the clearest way to do it, although var = var^var comes to mind, *grin* Hugo Nathan Pinno wrote: > Never mind all. I was just being stupid as usual. I thought that there might > be a Python command for resetting and wanted to find out if that was the > case. > ----- Original Message ----- > From: "Alan G" > To: "Nathan Pinno" ; "Tutor mailing list" > > Sent: Tuesday, August 02, 2005 2:45 PM > Subject: Re: [Tutor] Question about resetting values > > > >>>I am writing a Blackjack program, and was wondering how to reset the >>>values to zero, e.g. cash = 0? >> >>Yes, that's how you do it. Now what is the bit you don't understand? >> >>Alan G >>Author of the Learn to Program web tutor >>http://www.freenetpages.co.uk/hp/alan.gauld >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Sat Nov 12 09:41:28 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 00:41:28 -0800 Subject: [Tutor] output question Message-ID: <1d987df30511120041j22fd3aa0lb1401bc136ee01f6@mail.gmail.com> I got the output as: >>> Yes!!! This line will always print from the code: try: fsock = open("c:/TEMP/hello.txt") except IOError: print "The file does not exist, exiting gracefully" print "Yes!!! This line will always print" it means the code found there is hello.txt, why it does not show on the output. From ml.cyresse at gmail.com Sat Nov 12 11:54:14 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Sat, 12 Nov 2005 23:54:14 +1300 Subject: [Tutor] output question In-Reply-To: <1d987df30511120041j22fd3aa0lb1401bc136ee01f6@mail.gmail.com> References: <1d987df30511120041j22fd3aa0lb1401bc136ee01f6@mail.gmail.com> Message-ID: Sorry Shi Mu, don't understand the question. So, you're successfull opening a file. Now, you need to read it for line in fsock: print line or fsockData = fsock.read() or nextLine = fsock.readline() Have a play with those. On 11/12/05, Shi Mu wrote: > I got the output as: > >>> > Yes!!! This line will always print > from the code: > try: > fsock = open("c:/TEMP/hello.txt") > except IOError: > print "The file does not exist, exiting gracefully" > print "Yes!!! This line will always print" > > it means the code found there is hello.txt, > why it does not show on the output. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From samrobertsmith at gmail.com Sat Nov 12 12:02:50 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 03:02:50 -0800 Subject: [Tutor] output question In-Reply-To: References: <1d987df30511120041j22fd3aa0lb1401bc136ee01f6@mail.gmail.com> Message-ID: <1d987df30511120302tfe0941ev64282b9a1858ded2@mail.gmail.com> On 11/12/05, Liam Clarke wrote: > Sorry Shi Mu, don't understand the question. > > So, you're successfull opening a file. Now, you need to read it > > for line in fsock: > print line > > or > > fsockData = fsock.read() > > or > > nextLine = fsock.readline() > > Have a play with those. it works! thanks! From alan.gauld at freenet.co.uk Sat Nov 12 13:50:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 12 Nov 2005 12:50:25 -0000 Subject: [Tutor] File extension for CGI scripts written in Python References: Message-ID: <023101c5e787$a75c1c40$0a01a8c0@xp> > Python. In the literature I have studied, I have seen the extensions .cgi > and .py applied to such files. Is one preferred over the other, or is it > a > matter of personal preference? It depends on how your web server hsa been set up, there are two basic options: 1) All CGUI scripts go in a common dirdectory (usually cgi-bin) in which case you would name them as .py 2) You can store the CGI files with the corresponding html files in which case they are named .cgi to tell the web server to execute them as such. Which method you use is determined by your web servers settings which could have either or both enabled. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Nov 12 13:53:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 12 Nov 2005 12:53:23 -0000 Subject: [Tutor] output question References: <1d987df30511120041j22fd3aa0lb1401bc136ee01f6@mail.gmail.com> Message-ID: <023701c5e788$11729e60$0a01a8c0@xp> > fsock = open("c:/TEMP/hello.txt") This opens the file ready for you to read it. Thats all. You need to tell Python what you want to do with the file now that you've opened it. > why it does not show on the output. To display the contents you need print fsock.read() Have a look at the Handling Files topic in my tutorial for more options, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From chris.arndt at web.de Sat Nov 12 14:39:19 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Sat, 12 Nov 2005 13:39:19 +0000 Subject: [Tutor] Using CGIHTTPServer on Windows to run Perl & Python scripts - POST to Perl fails In-Reply-To: <1131759646.6232.103.camel@www.venix.com> References: <1131759646.6232.103.camel@www.venix.com> Message-ID: Python schrieb: > The Python scripts are OK. The Perl scripts do not receive the POST > parameters so they execute as though no parameters were supplied. I've > added logic to display the environment and that appears (to my Python > oriented eye) to be correct. In particular, the CONTENT_LENGTH and > CONTENT_TYPE are correct. GET requests work correctly. Could you post some code examples, i.e. the HTML form which does the POST request and the Perl code to handle it? Have you checked, that the REQUEST_METHOD is really POST? Chris From ronin_cpim at hotmail.com Sat Nov 12 14:44:58 2005 From: ronin_cpim at hotmail.com (CPIM Ronin) Date: Sat, 12 Nov 2005 08:44:58 -0500 Subject: [Tutor] Windows IDLE error msgs? Message-ID: I can get the standard Python error messages IF I execute a Python script via the command line OR the script I'm running from IDLE passes the initial syntax check and generates an execution error. However, if I have a syntax error that's caught in the initial syntax checking phase, IDLE merely goes to the particular line and highlights the line where the error was detected. How do I get IDLE to say specifically what's wrong? I'm running the latest version: Python 2.4.2 (#67, Sep 28 2005, 12:41:11) under XP. Thanks. RC _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From m.moghimi at gmail.com Sat Nov 12 17:00:34 2005 From: m.moghimi at gmail.com (Mohammad Moghimi) Date: Sat, 12 Nov 2005 19:30:34 +0330 Subject: [Tutor] calculus in python Message-ID: Hi do you know any module can calculate numeric integral and analytic derivative of n-dimension function? -- -- Mohammad do you Python?!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051112/6165d166/attachment.html From falcon3166 at hotmail.com Sat Nov 12 17:50:04 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 12 Nov 2005 09:50:04 -0700 Subject: [Tutor] How do I make a text box pop up in a GUI before the main part of the program loads? Message-ID: Hey all, How do I make a text box pop up in a GUI before the main part of the program loads? Thanks, Nathan Pinno, Owner/operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051112/398e8742/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051112/398e8742/attachment.gif -------------- next part -------------- A non-text attachment was scrubbed... Name: Pinno, Nathan Paul.vcf Type: text/x-vcard Size: 592 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051112/398e8742/PinnoNathanPaul.vcf From captnswing at gmx.net Sat Nov 12 18:11:18 2005 From: captnswing at gmx.net (captnswing) Date: Sat, 12 Nov 2005 18:11:18 +0100 Subject: [Tutor] ftp transfer - queue & retry pattern Message-ID: <067B098B-9245-4823-B5FE-A30C58A23D0C@gmx.net> Hello, I want to write a module that transfers a given file to a given destination with a given protocol (ftp, sftp, scp) to start out, just ftp would be sufficient the destination machines are sometimes unavailable, or the transfer fails sometimes due to connection problems I have several questions (sorry....): 1) python ftplib or curl via commands.getoutput(...)? what are the benefits / drawbacks (portability is not an issue for me, and I like curl a lot) 2) Is there a simple way to create a subprocess(?) that I can dispatch my transfer jobs to from my main script. The goal is that my main script can proceed without beeing hung by the transfer process 3) that subprocess would need a queue, that collects all transfer jobs. can you give me some hints on how that could be done in python 4) the subprocess (?) would try to transfer all jobs one after another if one transfer fails, retry after a certain time period (say 2, 5, 10, 20, 40 min) and stop after maxnum retries how could I code this nicely in python without resorting to if then else etc? or is there a module that does 1)-4) out there somewhere already? thanks for any insight you might have -frank From captnswing at gmx.net Sat Nov 12 18:14:39 2005 From: captnswing at gmx.net (captnswing) Date: Sat, 12 Nov 2005 18:14:39 +0100 Subject: [Tutor] logging to a database In-Reply-To: <43747FCD.3030900@tds.net> References: <43747FCD.3030900@tds.net> Message-ID: <93496EDD-56C2-4791-B119-51D332FBBF52@gmx.net> thanks kent, I actually got it working! -frank On 11 nov 2005, at 12.26, Kent Johnson wrote: > captnswing wrote: >> Hello all, >> I would like to log messages to a database (mysql) >> I found the example log_test14.py that comes with python logging >> module http://www.red-dove.com/python_logging.html >> but that example is a bit greek for me ... :) and it doesnt work with >> mysql > > Have you used mysql from Python before? I looked at that example > and it is not that complex if you understand how to program a > database. I think what you have to do is > > - install MySQL and create the database table that you want to log > to. The SQL statement in the example shows the fields you might > want, or you can use a subset of those fields if you don't need so > much information. > > - modify the example program a little: > change > import mx.ODBC.Windows > to the correct import for the MySQL driver > > change > self.conn = mx.ODBC.Windows.connect(self.dsn, self.uid, self.pwd) > to the correct statement to connect to MySQL > > change the SQL statement to correspond to your database schema > > > If you *haven't* used MySQL from Python before, you should probably > learn a little about the basics first. > > BTW the example is vulnerable to SQL injection attacks - if any of > the log messages contain text from user input you should fix that. > But get it working first, then come back and ask for help again. > > Kent > > -- > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Sat Nov 12 18:48:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 12 Nov 2005 17:48:48 -0000 Subject: [Tutor] Windows IDLE error msgs? References: Message-ID: <025e01c5e7b1$56693410$0a01a8c0@xp> > syntax check and generates an execution error. However, if I have a syntax > error that's caught in the initial syntax checking phase, IDLE merely goes > to the particular line and highlights the line where the error was > detected. Can you be more specific? Maybe include some short code that demonstrates the symptom. I'm not sure I've seen that - but then I rarely use IDLE nowadays. Alan G. From alan.gauld at freenet.co.uk Sat Nov 12 18:47:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 12 Nov 2005 17:47:01 -0000 Subject: [Tutor] How do I make a text box pop up in a GUI before the mainpart of the program loads? References: Message-ID: <025601c5e7b1$16ac5eb0$0a01a8c0@xp> > How do I make a text box pop up in a GUI before the main part of the > program > loads? Do you mean like a splash screen? If you are using Tkinter you can use a TopLevel widget to create and display the splash screen before you pack the main application window. If its only a simple message box type display then use the standard dialogs that Tkinter provides. Those work regardless of whether the Tkinter environment is initialised. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Sat Nov 12 18:59:41 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 12 Nov 2005 10:59:41 -0700 Subject: [Tutor] How do I make a text box pop up in a GUI before the mainpart of the program loads? References: <025601c5e7b1$16ac5eb0$0a01a8c0@xp> Message-ID: Actually, I'm going to be using Pygame. I need to know, because I want to pop up a polite explanation of how to play the game and a reminder. Nathan Pinno ----- Original Message ----- From: Alan Gauld To: Nathan Pinno ; tutor at python.org Sent: November 12, 2005 10:47 AM Subject: Re: [Tutor] How do I make a text box pop up in a GUI before the mainpart of the program loads? > How do I make a text box pop up in a GUI before the main part of the > program > loads? Do you mean like a splash screen? If you are using Tkinter you can use a TopLevel widget to create and display the splash screen before you pack the main application window. If its only a simple message box type display then use the standard dialogs that Tkinter provides. Those work regardless of whether the Tkinter environment is initialised. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051112/1a07d7ea/attachment.htm From dyoo at hkn.eecs.berkeley.edu Sat Nov 12 19:11:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 12 Nov 2005 10:11:47 -0800 (PST) Subject: [Tutor] output question In-Reply-To: <1d987df30511120302tfe0941ev64282b9a1858ded2@mail.gmail.com> Message-ID: > > So, you're successfull opening a file. Now, you need to read it > > > > for line in fsock: > > print line > > > > Have a play with those. > it works! thanks! Hi Shi Mu, Ok, but let's go back to your original question now, just to make sure we've learned something. You asked earlier: > from the code: > try: > fsock = open("c:/TEMP/hello.txt") > except IOError: > print "The file does not exist, exiting gracefully" > print "Yes!!! This line will always print" > > it means the code found there is hello.txt, why it does not show on the > output. Do you know now why the original code didn't do what you want? Can you explain why? I know it's seems like a silly question, but we are trying to avoid a cargo-cult attitude here. What knowledge did you learn? Again, I'm really not getting any sense whatsoever of knowing why you had difficulty here. Personally, if I run into difficulty with a problem, even if I hack out something that "works", I'm not satisified until I understand the reasons why I got stuck. I've been bitten too many times by being satisifed by the "right" answer for the wrong reasons. *grin* From falcon3166 at hotmail.com Sat Nov 12 19:16:48 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 12 Nov 2005 11:16:48 -0700 Subject: [Tutor] Can I use TKInter and Pygame together? Message-ID: Hey all, Can I use Pygame and TKInter together in the same application? I want to use TKInter for the message boxes, and Pygame for the actual game interface, but is this possible? Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051112/ad9985cd/attachment.html From dyoo at hkn.eecs.berkeley.edu Sat Nov 12 19:23:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 12 Nov 2005 10:23:31 -0800 (PST) Subject: [Tutor] calculus in python In-Reply-To: Message-ID: > do you know any module can calculate numeric integral and analytic > derivative of n-dimension function? Hi Mohammad, Your question is on a specialized math topic; we at Tutor probably won't be able to help you well. You might want to check with the Scientific Python folks instead: http://www.scipy.org/ I'm uncertain if there is a good Python symbolic math package. If you're willing to step out of the Python space, you may want to look at Maxima: http://maxima.sourceforge.net/ Good luck to you! From kent37 at tds.net Sat Nov 12 21:03:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 12 Nov 2005 15:03:29 -0500 Subject: [Tutor] Windows IDLE error msgs? In-Reply-To: References: Message-ID: <43764A91.6090201@tds.net> CPIM Ronin wrote: > I can get the standard Python error messages IF I execute a Python > script via the command line OR the script I'm running from IDLE passes > the initial syntax check and generates an execution error. However, if I > have a syntax error that's caught in the initial syntax checking phase, > IDLE merely goes to the particular line and highlights the line where > the error was detected. How do I get IDLE to say specifically what's wrong? Python syntax error messages are not very specific, I think IDLE is telling you all it knows. For me it pops up a dialog saying "invalid syntax" which is the same error I get running from the command line. Kent -- http://www.kentsjohnson.com From tim at johnsons-web.com Sat Nov 12 21:12:08 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 12 Nov 2005 11:12:08 -0900 Subject: [Tutor] iteritems() vs items() Message-ID: <20051112201208.GC2001@johnsons-web.com> I need to get up to speed on iterators. I learned python 1.5~ via Alan G's book ... For an example, I've written a subclass of dict where keys are kept in a ordered fashion is a list called __keys: #Here is my items function: def items(self): """ Return all pairs in order of addition""" return [(key,self.__dict[key]) for key in self.__keys] #And here is my iteritems function (currently does exactly the same thing) def iteritems(self): """ At this implementation, does exactly the same thing as method items()""" for key in self.__keys: yield (key,self.__dict[key]) I would welcome examples, comments, or pointers to docs that illustrate how I may use iteritems to extend functionality for this class. NOTE: An important thing about this class, is that iteration thru members must be done in the same manner in which key/value pairs were added. I'm currently using Python 2.3.4 on both workstation and internet servers and must keep backward compatible to that venue. Thanks tim -- Tim Johnson http://www.alaska-internet-solutions.com From kent37 at tds.net Sat Nov 12 23:21:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 12 Nov 2005 17:21:03 -0500 Subject: [Tutor] Can I use TKInter and Pygame together? In-Reply-To: References: Message-ID: <43766ACF.5080102@tds.net> Nathan Pinno wrote: > Hey all, > > Can I use Pygame and TKInter together in the same application? I want to > use TKInter for the message boxes, and Pygame for the actual game > interface, but is this possible? The 'slides' application from this page http://www.pygame.org/gamelets/ and this thread http://groups.google.com/group/comp.lang.python/browse_thread/thread/8aec74268b7a15e7/6f38602f5761bef%236f38602f5761bef?sa=X&oi=groupsr&start=0&num=3 suggest it's possible... Kent -- http://www.kentsjohnson.com From boyanpn at yahoo.com Sat Nov 12 23:44:25 2005 From: boyanpn at yahoo.com (Bojan Raicevic) Date: Sat, 12 Nov 2005 14:44:25 -0800 (PST) Subject: [Tutor] console text positioning Message-ID: <20051112224426.62551.qmail@web35501.mail.mud.yahoo.com> I'm not sure how explain my problem, but I'll try. I want to make something that looks like console quiz. So it would look somehow like this: print "Question one (a,b,c,d): " #user should answer with a,b,c or d - anything else inputed should result without reaction - **my problem** I DON'T want to see in console output repeated questions like: Question one (a,b,c,d): ftbryj Question one (a,b,c,d): asdf Question one (a,b,c,d): a Question two (1,2,3,4): b Question two (1,2,3,4): 5 Question two (1,2,3,4): 2 Question three (a,b,c): ... I want to see only: Question one (a,b,c,d): a Question two (1,2,3,4): 3 Question three (a,b,c): c Question four (1-10): 9 ... So basicly, I want to see in console output only correct answers. Any idea how to do this ?? __________________________________ Start your day with Yahoo! - Make it your home page! http://www.yahoo.com/r/hs From alan.gauld at freenet.co.uk Sat Nov 12 23:49:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 12 Nov 2005 22:49:56 -0000 Subject: [Tutor] Windows IDLE error msgs? References: Message-ID: <026801c5e7db$674b7660$0a01a8c0@xp> Are you sure you don't get an error? I get a dialog box that pops up containing exactly the same error message you get from the console. Alan G. ----- Original Message ----- From: "CPIM Ronin" To: Sent: Saturday, November 12, 2005 9:00 PM Subject: Re: [Tutor] Windows IDLE error msgs? > Alan, > > I just typed in the following code in IDLE (runing under Windows XP): > > a = 1 > b = 2 > if (a == b)): print "ok" > > And then hit F5 to save and run. It very properly highlights the second > ")" before the colon, but does NOT give an accompanying error msg. In this > case, the error is deliberate and obvious--mismatched ")". > > Keying in the very same code using the command line: >>>>a = 1 >>>>b = 2 >>>>if (a == b)): print "ok" > File "", line 1 > if (a == b)): print "ok" > ^ > SyntaxError: invalid syntax > > As you can see, I get an explicit "SyntacError: invalid syntax" error > message, when using command line, but not using IDLE. My question is, how > do I get IDLE to give me the same explicit error message as the command > line? > > Thanks. > > RC > > >>From: "Alan Gauld" >>To: "CPIM Ronin" , >>CC: >>Subject: Re: [Tutor] Windows IDLE error msgs? >>Date: Sat, 12 Nov 2005 17:48:48 -0000 >> >>>syntax check and generates an execution error. However, if I have a >>>syntax error that's caught in the initial syntax checking phase, IDLE >>>merely goes to the particular line and highlights the line where the >>>error was detected. >> >>Can you be more specific? Maybe include some short code that demonstrates >>the symptom. I'm not sure I've seen that - but then I rarely use IDLE >>nowadays. >> >>Alan G. >> > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today - it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > From alan.gauld at freenet.co.uk Sun Nov 13 01:01:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 13 Nov 2005 00:01:56 -0000 Subject: [Tutor] iteritems() vs items() References: <20051112201208.GC2001@johnsons-web.com> Message-ID: <028c01c5e7e5$7680d990$0a01a8c0@xp> >I need to get up to speed on iterators. I learned python 1.5~ via > Alan G's book ... Yeah, me too! iterators are one of the newer features of Python that I use but haven't really played with in depth. But I guess I really should get down to it and add a section to my tutor covering both iterators and generators! Timely reminder Tim, thanks! :-) Alan G. From alan.gauld at freenet.co.uk Sun Nov 13 01:10:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 13 Nov 2005 00:10:38 -0000 Subject: [Tutor] console text positioning References: <20051112224426.62551.qmail@web35501.mail.mud.yahoo.com> Message-ID: <029201c5e7e6$ad4fce30$0a01a8c0@xp> > problem** I DON'T want to see in console output > repeated questions like: > > Question one (a,b,c,d): ftbryj > Question one (a,b,c,d): asdf > Question one (a,b,c,d): a > Question two (1,2,3,4): b > Question two (1,2,3,4): 5 > Question two (1,2,3,4): 2 > Question three (a,b,c): > ... > > I want to see only: > > Question one (a,b,c,d): a > Question two (1,2,3,4): 3 > Question three (a,b,c): c > Question four (1-10): 9 > ... > > So basicly, I want to see in console output only > correct answers. > Any idea how to do this ?? I think the only way is to use the curses module (Unix only) Thee is no easy way to position the cursor on the previous line without curses that I know of. And basically you need to go up a line and redraw the line to avoid multiple input lines. No, wait a minute, thee is anothercway but its tricky to get right. You could use the getch() function from curses on Unix but also in msvcrt on Windows. That will read the character as the user types it without a newline. This is not what users normally expect however so might be more confusing than helpful, but even if you only used it to swallow the input up to a newline. As I said it needs some work to get right but could be made to do what you want. In pseudo code display prompt inp = '' data = '' while data == notValid() while inp != '\n': print inp inp = getch() data += inp # use data here... HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From cfaj at freeshell.org Sun Nov 13 01:57:47 2005 From: cfaj at freeshell.org (Chris F.A. Johnson) Date: Sat, 12 Nov 2005 19:57:47 -0500 (EST) Subject: [Tutor] console text positioning In-Reply-To: <20051112224426.62551.qmail@web35501.mail.mud.yahoo.com> References: <20051112224426.62551.qmail@web35501.mail.mud.yahoo.com> Message-ID: On Sat, 12 Nov 2005, Bojan Raicevic wrote: > I'm not sure how explain my problem, but I'll try. > > I want to make something that looks like console quiz. > So it would look somehow like this: > > print "Question one (a,b,c,d): " > #user should answer with a,b,c or d - anything else > inputed should result without reaction - **my > problem** I DON'T want to see in console output > repeated questions like: > > Question one (a,b,c,d): ftbryj > Question one (a,b,c,d): asdf > Question one (a,b,c,d): a > Question two (1,2,3,4): b > Question two (1,2,3,4): 5 > Question two (1,2,3,4): 2 > Question three (a,b,c): > ... > > I want to see only: > > Question one (a,b,c,d): a > Question two (1,2,3,4): 3 > Question three (a,b,c): c > Question four (1-10): 9 > ... > > So basicly, I want to see in console output only > correct answers. > Any idea how to do this ?? ANSI is the standard for terminal control, so I usually code for that, but put it in a separate module so that other terminals can easily be accommodated. Here is a short example: import sys import os COLUMNS = int(os.environ.get('COLUMNS')) LINES = int(os.environ.get('LINES')) ESC = '\033' CSI = ESC + "[" ## Command Sequence Introducer CLS = CSI + "H" + CSI + "2J" ## Clear screen NA = CSI + "0m" ## Clear text attributes ## set attributes set_attr = CSI + "%sm" set_bold = CSI + "1m" set_ul = CSI + "4m" set_rev = CSI + "7m" def printat(row,col,arg=""): sys.stdout.write( CSI + str(row) + ";" + str(col) + 'H' + str(arg)) ### Demo: row = 10 col = 30 print CLS printat( row, col, set_bold + "Hello, world" ) printat( LINES, COLUMNS - 6, NA + "Goodbye" ) printat( 1, 1) -- Chris F.A. Johnson =================================================================== Author: Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress) From python at venix.com Sun Nov 13 02:29:44 2005 From: python at venix.com (Python) Date: Sat, 12 Nov 2005 20:29:44 -0500 Subject: [Tutor] Using CGIHTTPServer on Windows to run Perl & Python scripts - POST to Perl fails Message-ID: <1131845384.22934.46.camel@www.venix.com> I should have included the REQUEST_METHOD before. Yes it is correct. This is a useful test perl script I downloaded from a Perl oriented site: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #!/usr/bin/perl use CGI; $cgi = new CGI; for $key ( $cgi->param() ) { $input{$key} = $cgi->param($key); } print qq{Content-type: text/html }; #print every key in the environment foreach $key (sort (keys %ENV)) { print $key, ' = ', $ENV{$key}, "
\n"; } for $key ( keys %input ) { print $key, ' = ', $input{$key}, "
\n"; } #print a couple of simple forms: a POST form and a GET form print qq{

}; print qq{
}; print qq{}; <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< I think I am pushing the limits of being on topic here, though having the Python CGI server work with Perl under Windows would be nice. I suppose it is possibly an issue with my Perl setup in Windows. It's Perl 5.8.7 from ActiveState binary build 813. The Windows version is (from sys.getwindowsversion): (5, 1, 2600, 2, 'Service Pack 2') Here is the webserver code: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> #! /usr/bin/env python # cgiserver.py import sets, posixpath, sys, os, urllib, select from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler from SocketServer import ThreadingMixIn class ThreadingServer(ThreadingMixIn, HTTPServer): pass class MyRequestHandler(CGIHTTPRequestHandler): '''I could not figure out how to convince the Python os.stat module that the perl scripts are executable so that the server would actually run them. The simple solution is to override is_executable to always return true. (The perl scripts are indeed executable and do run.) ''' def is_executable(self, path): return True serveraddr = ('',8000) srvr = ThreadingServer(serveraddr, MyRequestHandler) srvr.serve_forever() <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< I assume anyone with access to a Windows computer could try this. The server expects to be in a directory with a subdirectory of cgi-bin cgi-env.pl should be in the cgi-bin directory The URL to use cgi-env.pl is http://localhost:8000/cgi-bin/cgi-env.pl I'd be curious if this issue is peculiar to the version of Windows that I am dealing with here. I have no other Windows web server environment to check against. The CGIRequestHandler can't be doing anything terribly wrong, or the Python scripts would fail. I will see if I can use the cgi.pm source to figure something out. Python schrieb: > The Python scripts are OK. The Perl scripts do not receive the POST > parameters so they execute as though no parameters were supplied. I've > added logic to display the environment and that appears (to my Python > oriented eye) to be correct. In particular, the CONTENT_LENGTH and > CONTENT_TYPE are correct. GET requests work correctly. Could you post some code examples, i.e. the HTML form which does the POST request and the Perl code to handle it? Have you checked, that the REQUEST_METHOD is really POST? Chris -- Lloyd Kvam Venix Corp From samrobertsmith at gmail.com Sun Nov 13 04:33:15 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 19:33:15 -0800 Subject: [Tutor] output question In-Reply-To: References: <1d987df30511120302tfe0941ev64282b9a1858ded2@mail.gmail.com> Message-ID: <1d987df30511121933x6817cc27mfb6c55981716d39e@mail.gmail.com> On 11/12/05, Danny Yoo wrote: > > > So, you're successfull opening a file. Now, you need to read it > > > > > > for line in fsock: > > > print line > > > > > > Have a play with those. > > it works! thanks! > > > Hi Shi Mu, > > Ok, but let's go back to your original question now, just to make sure > we've learned something. You asked earlier: > > > > from the code: > > try: > > fsock = open("c:/TEMP/hello.txt") > > except IOError: > > print "The file does not exist, exiting gracefully" > > print "Yes!!! This line will always print" > > > > it means the code found there is hello.txt, why it does not show on the > > output. > > Do you know now why the original code didn't do what you want? Can you > explain why? I know it's seems like a silly question, but we are trying > to avoid a cargo-cult attitude here. What knowledge did you learn? > > > Again, I'm really not getting any sense whatsoever of knowing why you had > difficulty here. Personally, if I run into difficulty with a problem, > even if I hack out something that "works", I'm not satisified until I > understand the reasons why I got stuck. I've been bitten too many times > by being satisifed by the "right" answer for the wrong reasons. *grin* Hi Danny, I thought if the except situation does not happen, that means the try section works. At that time, I was a little confused that since the open statement works, why there is nothing showing. Now i know if i want to see a file's content on the screen, open statement is not enough. From dyoo at hkn.eecs.berkeley.edu Sun Nov 13 05:15:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 12 Nov 2005 20:15:47 -0800 (PST) Subject: [Tutor] output question In-Reply-To: <1d987df30511121933x6817cc27mfb6c55981716d39e@mail.gmail.com> Message-ID: > > > from the code: > > > try: > > > fsock = open("c:/TEMP/hello.txt") > > > except IOError: > > > print "The file does not exist, exiting gracefully" > > > print "Yes!!! This line will always print" > I thought if the except situation does not happen, that means the try > section works. At that time, I was a little confused that since the open > statement works, why there is nothing showing. Now i know if i want to > see a file's content on the screen, open statement is not enough. Hi Shi Mu, Ok, that sounds good. I second Alan's recommendation to go through his tutorial; it'll probably help introduce you to more of the programming constructs that you're not familiar with yet. One of the things that we all need to work on is identifying presumptions and figuring out how to recognize when those assumptions aren't being followed. If it looks like a function like open() doesn't do what you expect, it's a good idea to double check a tutorial that introduces that function, just to see if it's the assumption that needs revision. Are you going through a tutorial now? By the way, the exception handling above is probably not necessary; it's probably ok to start with: ####### fsock = open("c:/TEMP/hello.txt") ... ####### without the explicit exception handling. If it fails, it will fail gracefully with good debugging output anyway. If you're going to handle an exception by exiting, just let the exception escape out: it'll usually maintain very useful information like the stack trace. Best of wishes! From samrobertsmith at gmail.com Sun Nov 13 05:21:03 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Sat, 12 Nov 2005 20:21:03 -0800 Subject: [Tutor] output question In-Reply-To: References: <1d987df30511121933x6817cc27mfb6c55981716d39e@mail.gmail.com> Message-ID: <1d987df30511122021n34096cf2p7d209224248e8dc3@mail.gmail.com> On 11/12/05, Danny Yoo wrote: > > > > from the code: > > > > try: > > > > fsock = open("c:/TEMP/hello.txt") > > > > except IOError: > > > > print "The file does not exist, exiting gracefully" > > > > print "Yes!!! This line will always print" > > > I thought if the except situation does not happen, that means the try > > section works. At that time, I was a little confused that since the open > > statement works, why there is nothing showing. Now i know if i want to > > see a file's content on the screen, open statement is not enough. > > Hi Shi Mu, > > Ok, that sounds good. I second Alan's recommendation to go through his > tutorial; it'll probably help introduce you to more of the programming > constructs that you're not familiar with yet. > > One of the things that we all need to work on is identifying presumptions > and figuring out how to recognize when those assumptions aren't being > followed. If it looks like a function like open() doesn't do what you > expect, it's a good idea to double check a tutorial that introduces that > function, just to see if it's the assumption that needs revision. Are you > going through a tutorial now? > > > By the way, the exception handling above is probably not necessary; it's > probably ok to start with: > > ####### > fsock = open("c:/TEMP/hello.txt") > ... > ####### > > without the explicit exception handling. If it fails, it will fail > gracefully with good debugging output anyway. If you're going to handle > an exception by exiting, just let the exception escape out: it'll usually > maintain very useful information like the stack trace. > > > Best of wishes! > > Thanks a lot for your advice! i am reading the tutorial (http://www.freenetpages.co.uk/hp/alan.gauld/)now. From dyoo at hkn.eecs.berkeley.edu Sun Nov 13 05:34:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 12 Nov 2005 20:34:09 -0800 (PST) Subject: [Tutor] Can I use TKInter and Pygame together? In-Reply-To: Message-ID: On Sat, 12 Nov 2005, Nathan Pinno wrote: > Can I use Pygame and TKInter together in the same application? I want to > use TKInter for the message boxes, and Pygame for the actual game > interface, but is this possible? Hi Nathan, Yes; here's a link to an example that combines both Tkinter and Pygame. (It appears to be a chapter out of Deitel & Deitel's "Python How to Program" book.) http://www.informit.com/content/images/art_deitel_pigame/elementLinks/pythonhtp1_24_article.pdf ... oh, I forgot! This question came up about three years ago. Ah, found it. Here you go: http://mail.python.org/pipermail/tutor/2002-July/015679.html It's probably a good idea to talk with the pygame folks to integrate pygame-controlled widgets with tkinter-controlled widgets. Best of wishes! From kent37 at tds.net Sun Nov 13 06:24:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Nov 2005 00:24:15 -0500 Subject: [Tutor] iteritems() vs items() In-Reply-To: <20051112201208.GC2001@johnsons-web.com> References: <20051112201208.GC2001@johnsons-web.com> Message-ID: <4376CDFF.2040806@tds.net> Tim Johnson wrote: > I need to get up to speed on iterators. I learned python 1.5~ via > Alan G's book ... > For an example, I've written a subclass of dict where keys are kept in > a ordered fashion is a list called __keys: > > #Here is my items function: > def items(self): > """ Return all pairs in order of addition""" > return [(key,self.__dict[key]) for key in self.__keys] > > #And here is my iteritems function (currently does exactly the same thing) > def iteritems(self): > """ At this implementation, does exactly the same thing as > method items()""" > for key in self.__keys: > yield (key,self.__dict[key]) I think you have it right. Your two methods don't do the same thing - items() returns a list of key, value pairs; iteritems() returns a generator which yields key, value pairs. This is the correct behaviour. Kent -- http://www.kentsjohnson.com From wan at walrus.us Sun Nov 13 06:55:31 2005 From: wan at walrus.us (Vincent Wan) Date: Sat, 12 Nov 2005 20:55:31 -0900 Subject: [Tutor] problem calling a function Message-ID: <1EE3F3AA-641C-4908-9768-4DB77A013660@walrus.us> Dear all, I have a simple program that calls a function I got off of active state that draws a tree given a description of it in standard string form. My code generates a string description and calls the function to draw the tree. Instead of drawing the tree it echos the string. But when I call the function interactively with the same string it prints the tree! Why dosn't it work non-interactivly here is my IDLE run (((('0','9'),('4','6')),'2'),(('1',(('5','8'),'7')),'3')) (((('0','9'),('4','6')),'2'),(('1',(('5','8'),'7')),'3')) -- >>> printDendrogram((((('0','9'),('4','6')),'2'),(('1', (('5','8'),'7')),'3'))) 0 -----+ |--+ 9 -----+ | |--+ 4 -----+ | | |--+ | 6 -----+ | |--+ 2 -----------+ | |-- 1 --------+ | |--+ | 5 --+ | | | |--+ | | | 8 --+ | | | | |--+ | | 7 -----+ | | |--+ 3 -----------+ here is my code # Thesis_ex_gen6.py import random # constants that control the simulation MAX_LINAGES = 10 BRANCHING_PROBABILITY = 0.01 EXTINCTION_PROBABILITY = 0.01 def printDendrogram(T, sep=3): """Print dendrogram of a binary tree. Each tree node is represented by a length-2 tuple. routine written by David Eppstein from ActiveState Programers Network Last Updated: 2002/07/13""" def isPair(T): return type(T) == tuple and len(T) == 2 def maxHeight(T): if isPair(T): h = max(maxHeight(T[0]), maxHeight(T[1])) else: h = len(str(T)) return h + sep activeLevels = {} def traverse(T, h, isFirst): if isPair(T): traverse(T[0], h-sep, 1) s = [' ']*(h-sep) s.append('|') else: s = list(str(T)) s.append(' ') while len(s) < h: s.append('-') if (isFirst >= 0): s.append('+') if isFirst: activeLevels[h] = 1 else: del activeLevels[h] A = list(activeLevels) A.sort() for L in A: if len(s) < L: while len(s) < L: s.append(' ') s.append('|') print ''.join(s) if isPair(T): traverse(T[1], h-sep, 0) traverse(T, maxHeight(T), -1) for x in range(1): print '\n','run ', x+1, '\n' next_linage = 0 # next counter initalized linages = [0] # linages initalized num_linages = 1 # total linage counter initalized time = 0 # time initalized tree = "'0'" # tree initalized while (len(linages) != 0) and (num_linages < MAX_LINAGES): time += 1 "With BRANCHING_PROBABILITY creates a new linage and prints information" i = 0 while i < len(linages): if random.random() < BRANCHING_PROBABILITY: next_linage += 1 linages.append(next_linage) print 'At ', time,' linage ', linages[i], 'evolved ', next_linage parent = "'" + str(linages[i]) + "'" parent_and_child = '(' + parent + ",'" + str (next_linage) + "')" tree = tree.replace(parent, parent_and_child) num_linages += 1 if num_linages == 10: break i += 1 "With EXTINCTION_PROBABILITY kill a linage and print information" j = 0 while j < len(linages): if random.random() < EXTINCTION_PROBABILITY: print 'At ', time,' linage ', linages[j], 'died ' del linages[j] if len(linages) == 0: "restarts if fewer that 10 linages evolved" print '\n restart \n' next_linage = 0 # next counter initalized linages = [0] # linages initalized num_linages = 1 # total linage counter initalized time = 0 # time initalized tree = "'0'" j += 1 print tree printDendrogram(tree) Thank you, Vincent Wan ------------------------------------------------------------------------ -------------- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) From yncdonato at msn.com Sat Nov 12 16:29:07 2005 From: yncdonato at msn.com (mike donato) Date: Sat, 12 Nov 2005 11:29:07 -0400 Subject: [Tutor] Seeking PYTHON Mentor Message-ID: Greetings, I am an Information Technology student and am seeking a mentor for the Python Language. Primarily my areas of specialization have been Local Area Network and PC Tech Support however have a data structure class as a degree requirement. The class is in Python. I have downloaded python and am experimenting. However need to complete a series of given excercises. I believe in academic honesty and so I am not inclining to cheating just seeking support for the given language so I may develop the fundamental skills to work thru the excercises. Any assistance which can be provided will be greatly appreciated. Respectfully, Michael Donato _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From alan.gauld at freenet.co.uk Sun Nov 13 09:45:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 13 Nov 2005 08:45:53 -0000 Subject: [Tutor] console text positioning References: <20051112224426.62551.qmail@web35501.mail.mud.yahoo.com> Message-ID: <02a801c5e82e$a89bf560$0a01a8c0@xp> > ANSI is the standard for terminal control, so I usually code for > that, but put it in a separate module so that other terminals can > easily be accommodated. It certainly used to be under MS DOS but I find very few windows machines set up to use ANSI codes. Do you know any way to set ANSI controls under wIndows (that doesn't require a reboot ideally!) ISTR it involved putting the line DISPLAY=ANSI in the Config.sys file. Does that still work under XP? I suppose it should... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From matthew.williams at cancer.org.uk Sun Nov 13 11:09:46 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Sun, 13 Nov 2005 10:09:46 +0000 Subject: [Tutor] Symbolic maths In Python In-Reply-To: References: Message-ID: <1131876586.4371.2.camel@localhost.localdomain> I don't know if this will do anywhere near what you want... http://swiginac.berlios.de/ is a set of Python bindings to GiNaC, which handles symbolic maths in C/C++. Matt From rschroev_nospam_ml at fastmail.fm Sun Nov 13 11:33:56 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 13 Nov 2005 11:33:56 +0100 Subject: [Tutor] problem calling a function In-Reply-To: <1EE3F3AA-641C-4908-9768-4DB77A013660@walrus.us> References: <1EE3F3AA-641C-4908-9768-4DB77A013660@walrus.us> Message-ID: Vincent Wan wrote: > Dear all, > > I have a simple program that calls a function I got off of active > state that draws > a tree given a description of it in standard string form. > > My code generates a string description and calls the function to draw > the tree. > Instead of drawing the tree it echos the string. But when I call the > function > interactively with the same string it prints the tree! Why dosn't it > work non-interactivly > > here is my IDLE run > > (((('0','9'),('4','6')),'2'),(('1',(('5','8'),'7')),'3')) > (((('0','9'),('4','6')),'2'),(('1',(('5','8'),'7')),'3')) -- > > >>> printDendrogram((((('0','9'),('4','6')),'2'),(('1', > (('5','8'),'7')),'3'))) printDendrogram accepts tuples, not strings: >>> printDendrogram(((1, 2), (3, 4))) 1 --+ |--+ 2 --+ | |-- 3 --+ | |--+ 4 --+ >>> printDendrogram("((1, 2), (3, 4))") ((1, 2), (3, 4)) -- You'll have to modify your code so that it creates a tuple instead of a string. I made it work by changing printDendrogram(tree) to printDendrogram(eval(tree)) at the end of your code, but that's just a quick hack, not the recommended way of doing things. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From kent37 at tds.net Sun Nov 13 13:33:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Nov 2005 07:33:10 -0500 Subject: [Tutor] Seeking PYTHON Mentor In-Reply-To: References: Message-ID: <43773286.5040608@tds.net> mike donato wrote: > I believe in academic honesty and so I am not inclining to cheating just > seeking support for the given language so I may develop the fundamental > skills to work thru the excercises. > > Any assistance which can be provided will be greatly appreciated. Ask questions here on the list. The best questions show what you have tried so far so we can see where you are having trouble and help you with the next step. Did you find a tutorial you like? There is one that comes with Python when you download it and many others linked here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers?highlight=%28BeginnersGuide%2F%29 Kent -- http://www.kentsjohnson.com From rschroev_nospam_ml at fastmail.fm Sun Nov 13 14:11:17 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 13 Nov 2005 14:11:17 +0100 Subject: [Tutor] problem calling a function In-Reply-To: References: <1EE3F3AA-641C-4908-9768-4DB77A013660@walrus.us> Message-ID: Roel Schroeven wrote: > > You'll have to modify your code so that it creates a tuple instead of a > string. It seems that doing it without using a string complicates matters, or at least increases the line count. I tried it with a list, since you can't build a tuple on the go since tuples are immutable, but that didn't work out very well so I created a tree with nodes to store the branches: class Tree(object): class Node(object): def __init__(self, linage, left=None, right=None): self.linage = linage self.left = left self.right = right def AsTuple(self): if self.left and self.right: return self.left.AsTuple(), self.right.AsTuple() else: return self.linage def __init__(self, rootlinage): self.rootnode = Tree.Node(rootlinage) self.linagetonode = {rootlinage: self.rootnode} def AddBranch(self, linage, newlinage): node = self.linagetonode[linage] left = Tree.Node(linage) right = Tree.Node(newlinage) node.left = left node.right = right self.linagetonode[linage] = left self.linagetonode[newlinage] = right def AsTuple(self): return self.rootnode.AsTuple() In this data structure the nodes are stored as a tree, but are also accessible via the linage values. Branching is done by looking up the node via the linage and creating appropriate left and right children. Creating the tuple for printing the dendrogram can be done via simple recursion. I initialize the tree (both at the beginning and when restarting) by doing: tree = Tree('0') Branching becomes: next_linage += 1 linages.append(next_linage) print 'At ', time,' linage ', linages[i], 'evolved', next_linage tree.AddBranch(str(linages[i]), str(next_linage)) num_linages += 1 if num_linages == 10: break Printing the tree: printDendrogram(tree.AsTuple()) The whole program: # Thesis_ex_gen6.py import random # constants that control the simulation MAX_LINAGES = 10 BRANCHING_PROBABILITY = 0.01 EXTINCTION_PROBABILITY = 0.01 def printDendrogram(T, sep=3): """Print dendrogram of a binary tree. Each tree node is represented by a length-2 tuple. routine written by David Eppstein from ActiveState Programers Network Last Updated: 2002/07/13""" def isPair(T): return type(T) == tuple and len(T) == 2 def maxHeight(T): if isPair(T): h = max(maxHeight(T[0]), maxHeight(T[1])) else: h = len(str(T)) return h + sep activeLevels = {} def traverse(T, h, isFirst): if isPair(T): traverse(T[0], h-sep, 1) s = [' ']*(h-sep) s.append('|') else: s = list(str(T)) s.append(' ') while len(s) < h: s.append('-') if (isFirst >= 0): s.append('+') if isFirst: activeLevels[h] = 1 else: del activeLevels[h] A = list(activeLevels) A.sort() for L in A: if len(s) < L: while len(s) < L: s.append(' ') s.append('|') print ''.join(s) if isPair(T): traverse(T[1], h-sep, 0) traverse(T, maxHeight(T), -1) if __name__ == '__main__': for x in range(1): print '\n','run ', x+1, '\n' class Tree(object): class Node(object): def __init__(self, linage, left=None, right=None): self.linage = linage self.left = left self.right = right def AsTuple(self): if self.left and self.right: return self.left.AsTuple(), self.right.AsTuple() else: return self.linage def __init__(self, rootlinage): self.rootnode = Tree.Node(rootlinage) self.linagetonode = {rootlinage: self.rootnode} def AddBranch(self, linage, newlinage): node = self.linagetonode[linage] left = Tree.Node(linage) right = Tree.Node(newlinage) node.left = left node.right = right self.linagetonode[linage] = left self.linagetonode[newlinage] = right def AsTuple(self): return self.rootnode.AsTuple() next_linage = 0 # next counter initalized linages = [0] # linages initalized num_linages = 1 # total linage counter initalized time = 0 # time initalized tree = Tree('0') while (len(linages) != 0) and (num_linages < MAX_LINAGES): time += 1 "With BRANCHING_PROBABILITY creates a new linage and prints information" i = 0 while i < len(linages): if random.random() < BRANCHING_PROBABILITY: next_linage += 1 linages.append(next_linage) print 'At ', time,' linage ', linages[i], 'evolved', next_linage tree.AddBranch(str(linages[i]), str(next_linage)) num_linages += 1 if num_linages == 10: break i += 1 "With EXTINCTION_PROBABILITY kill a linage and print information" j = 0 while j < len(linages): if random.random() < EXTINCTION_PROBABILITY: print 'At ', time,' linage ', linages[j], 'died ' del linages[j] if len(linages) == 0: "restarts if fewer that 10 linages evolved" print '\n restart \n' next_linage = 0 # next counter initalized linages = [0] # linages initalized num_linages = 1 # total linage counter initalized time = 0 # time initalized tree = Tree('0') j += 1 print tree.AsTuple() printDendrogram(tree.AsTuple()) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From alan.gauld at freenet.co.uk Sun Nov 13 16:53:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 13 Nov 2005 15:53:15 -0000 Subject: [Tutor] Seeking PYTHON Mentor References: Message-ID: <02cb01c5e86a$5becf340$0a01a8c0@xp> Hi Mike, > Greetings, I am an Information Technology student and am seeking a mentor > for the Python Language. Treat this mailing list as a virtual mentor. We will take questions either theoretical, conceptual or practical. Tell us what you need help with, tell us what you've done to try to solve it yourself and we will point you in the right direction to find the answer. If the question involves code post the problem code and any error dumps you get. We don't normally do one-on-one mentoring because that way only one person benefits, on a list everyone gets answers - even to questions they might not have thought of asking! :-) And you get the benefit of many viewpoints and many, many years of accumulated experience. Enjoy, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tim at johnsons-web.com Sun Nov 13 18:25:54 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 13 Nov 2005 08:25:54 -0900 Subject: [Tutor] iteritems() vs items() In-Reply-To: <4376CDFF.2040806@tds.net> References: <20051112201208.GC2001@johnsons-web.com> <4376CDFF.2040806@tds.net> Message-ID: <20051113172554.GE2001@johnsons-web.com> * Kent Johnson [051112 20:33]: > Tim Johnson wrote: > >I need to get up to speed on iterators. I learned python 1.5~ via > >Alan G's book ... > >For an example, I've written a subclass of dict where keys are kept in > >a ordered fashion is a list called __keys: > > > >#Here is my items function: > > def items(self): > > """ Return all pairs in order of addition""" > > return [(key,self.__dict[key]) for key in self.__keys] > > > >#And here is my iteritems function (currently does exactly the same thing) > > def iteritems(self): > > """ At this implementation, does exactly the same thing as > > method items()""" > > for key in self.__keys: > > yield (key,self.__dict[key]) Ah. I did it right without know what I was doing. Now if I assign a value to the iteritems method, as in it = s.iteritems() I get an object of and dir(it) shows that (it) has one public method - next(). Question: Can one subclass an iterator object? thanks for making this a little clearer. tim > I think you have it right. Your two methods don't do the same thing - > items() returns a list of key, value pairs; iteritems() returns a generator > which yields key, value pairs. This is the correct behaviour. > > Kent > -- > http://www.kentsjohnson.com -- Tim Johnson http://www.alaska-internet-solutions.com From kent37 at tds.net Sun Nov 13 21:58:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Nov 2005 15:58:00 -0500 Subject: [Tutor] iteritems() vs items() In-Reply-To: <20051113172554.GE2001@johnsons-web.com> References: <20051112201208.GC2001@johnsons-web.com> <4376CDFF.2040806@tds.net> <20051113172554.GE2001@johnsons-web.com> Message-ID: <4377A8D8.5000905@tds.net> Tim Johnson wrote: > Question: Can one subclass an iterator object? > thanks for making this a little clearer. Most *classes* can be subclassed. What do you have in mind? -- http://www.kentsjohnson.com From john at fouhy.net Sun Nov 13 22:05:22 2005 From: john at fouhy.net (John Fouhy) Date: Mon, 14 Nov 2005 10:05:22 +1300 Subject: [Tutor] iteritems() vs items() In-Reply-To: <20051113172554.GE2001@johnsons-web.com> References: <20051112201208.GC2001@johnsons-web.com> <4376CDFF.2040806@tds.net> <20051113172554.GE2001@johnsons-web.com> Message-ID: <5e58f2e40511131305x1d10a490s@mail.gmail.com> On 14/11/05, Tim Johnson wrote: > Now if I assign a value to the iteritems method, as in > it = s.iteritems() > I get an object of > and dir(it) shows that (it) has one public method - next(). Yep. The normal way to use an iterator is in a for loop. So, if you've done 'it = s.iteritems()', you can then do: for key, value in it: # do something with key, value Of course, normally you would cut out the assignment step: for key, value in s.iteritems(): # do something with key, value When dealing with an iterator, a for loop is basically equivalent to this: it = s.iteritems() while True: try: key, value = it.next() except StopIteration: break # do something with key, value HTH! -- John. From tim at johnsons-web.com Sun Nov 13 22:33:45 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 13 Nov 2005 12:33:45 -0900 Subject: [Tutor] iteritems() vs items() In-Reply-To: <5e58f2e40511131305x1d10a490s@mail.gmail.com> References: <20051112201208.GC2001@johnsons-web.com> <4376CDFF.2040806@tds.net> <20051113172554.GE2001@johnsons-web.com> <5e58f2e40511131305x1d10a490s@mail.gmail.com> Message-ID: <20051113213345.GG2001@johnsons-web.com> * John Fouhy [051113 12:16]: > On 14/11/05, Tim Johnson wrote: > > Now if I assign a value to the iteritems method, as in > > it = s.iteritems() > > I get an object of > > and dir(it) shows that (it) has one public method - next(). > > Yep. The normal way to use an iterator is in a for loop. As soon as I saw the next() method, I recognized it from using a csv module ...... > So, if you've done 'it = s.iteritems()', you can then do: > > for key, value in it: > # do something with key, value > > Of course, normally you would cut out the assignment step: > > for key, value in s.iteritems(): > # do something with key, value > > When dealing with an iterator, a for loop is basically equivalent to this: > > it = s.iteritems() > while True: > try: > key, value = it.next() > except StopIteration: > break > # do something with key, value > > HTH! > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Sun Nov 13 22:36:35 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 13 Nov 2005 12:36:35 -0900 Subject: [Tutor] iteritems() vs items() In-Reply-To: <4377A8D8.5000905@tds.net> References: <20051112201208.GC2001@johnsons-web.com> <4376CDFF.2040806@tds.net> <20051113172554.GE2001@johnsons-web.com> <4377A8D8.5000905@tds.net> Message-ID: <20051113213635.GH2001@johnsons-web.com> * Kent Johnson [051113 12:04]: > Tim Johnson wrote: > > Question: Can one subclass an iterator object? > > thanks for making this a little clearer. > > Most *classes* can be subclassed. What do you have in mind? Oh, I'm just playing right now .... but what is the iterator object class name? thnx tj > -- > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From Liam.Clarke-Hutchinson at business.govt.nz Sun Nov 13 22:36:48 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Mon, 14 Nov 2005 10:36:48 +1300 Subject: [Tutor] iteritems() vs items() Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13DD@chbnt01.alpha.wd.govt.nz> Someone correct me if I'm wrong, but I believe there is no specific iterator object, but rather objects that have a method for __iter___... Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces+ml.cyresse=gmail.com at python.org [mailto:tutor-bounces+ml.cyresse=gmail.com at python.org] On Behalf Of Tim Johnson Sent: Monday, 14 November 2005 10:37 a.m. To: tutor at python.org Subject: Re: [Tutor] iteritems() vs items() * Kent Johnson [051113 12:04]: > Tim Johnson wrote: > > Question: Can one subclass an iterator object? > > thanks for making this a little clearer. > > Most *classes* can be subclassed. What do you have in mind? Oh, I'm just playing right now .... but what is the iterator object class name? thnx tj > -- > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From tim at johnsons-web.com Sun Nov 13 23:33:08 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 13 Nov 2005 13:33:08 -0900 Subject: [Tutor] iteritems() vs items() In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13DD@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13DD@chbnt01.alpha.wd.govt.nz> Message-ID: <20051113223308.GI2001@johnsons-web.com> * Liam Clarke-Hutchinson [051113 12:41]: > Someone correct me if I'm wrong, but I believe there is no specific iterator > object, but rather objects that have a method for __iter___... Some light is slowly dawning here (I think) .... from http://docs.python.org/ref/yield.html It appears that a generator, is an object, but not derived from a class, but from a generator function, using yield. > Liam Clarke-Hutchinson > > -----Original Message----- > From: tutor-bounces+ml.cyresse=gmail.com at python.org > [mailto:tutor-bounces+ml.cyresse=gmail.com at python.org] On Behalf Of Tim > Johnson > Sent: Monday, 14 November 2005 10:37 a.m. > To: tutor at python.org > Subject: Re: [Tutor] iteritems() vs items() > > > * Kent Johnson [051113 12:04]: > > Tim Johnson wrote: > > > Question: Can one subclass an iterator object? > > > thanks for making this a little clearer. > > > > Most *classes* can be subclassed. What do you have in mind? > > Oh, I'm just playing right now .... but what is the > iterator object class name? > thnx > tj > > > -- > > http://www.kentsjohnson.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Tim Johnson > http://www.alaska-internet-solutions.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. > > > > > http://www.govt.nz - connecting you to New Zealand central & local government services > > Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From kent37 at tds.net Mon Nov 14 00:39:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 13 Nov 2005 18:39:51 -0500 Subject: [Tutor] iteritems() vs items() In-Reply-To: <20051113223308.GI2001@johnsons-web.com> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13DD@chbnt01.alpha.wd.govt.nz> <20051113223308.GI2001@johnsons-web.com> Message-ID: <4377CEC7.2050905@tds.net> Tim Johnson wrote: > * Liam Clarke-Hutchinson [051113 12:41]: > >>Someone correct me if I'm wrong, but I believe there is no specific iterator >>object, but rather objects that have a method for __iter___... > > > Some light is slowly dawning here (I think) .... from > http://docs.python.org/ref/yield.html > > It appears that a generator, is an object, but > not derived from a class, but from a generator function, > using yield. I would say it is an object of a built-in class created by calling a generator function, which is a function that uses yield. You can create your own iterators by defining a class that defines the special methods __iter__() and next(). __iter__ just returs self, and next() returns the next item in the iteration or raises StopIteration. See http://docs.python.org/lib/typeiter.html Generators provide a convenient short-cut for creating many kinds of iterators because generator state is maintained implicitly. For example, a class for iterators that count from 1 to 10 might look like this: class counter: def __init__(self): self.count = 0 def __iter__(self): return self def next(self): if self.count < 10: self.count += 1 return self.count raise StopIteration The equivalent generator function could be def counter(): for count in range(1, 11): yield count or, maybe a fairer comparison would be def counter(): count = 0 if count < 10: count += 1 yield count which is still much shorter and easier to understand than the class version. Usage of all three is identical: for i in counter(): print i Kent From tim at johnsons-web.com Mon Nov 14 02:08:16 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 13 Nov 2005 16:08:16 -0900 Subject: [Tutor] iteritems() vs items() In-Reply-To: <4377CEC7.2050905@tds.net> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13DD@chbnt01.alpha.wd.govt.nz> <20051113223308.GI2001@johnsons-web.com> <4377CEC7.2050905@tds.net> Message-ID: <20051114010816.GJ2001@johnsons-web.com> Well put. Got it. Thanks Kent tj * Kent Johnson [051113 14:44]: > Tim Johnson wrote: > > * Liam Clarke-Hutchinson [051113 12:41]: > > > >>Someone correct me if I'm wrong, but I believe there is no specific iterator > >>object, but rather objects that have a method for __iter___... > > > > > > Some light is slowly dawning here (I think) .... from > > http://docs.python.org/ref/yield.html > > > > It appears that a generator, is an object, but > > not derived from a class, but from a generator function, > > using yield. > > I would say it is an object of a built-in class created by calling a generator function, which is a function that uses yield. > > You can create your own iterators by defining a class that defines the special methods __iter__() and next(). __iter__ just returs self, and next() returns the next item in the iteration or raises StopIteration. See > http://docs.python.org/lib/typeiter.html > > Generators provide a convenient short-cut for creating many kinds of iterators because generator state is maintained implicitly. For example, a class for iterators that count from 1 to 10 might look like this: > > class counter: > def __init__(self): > self.count = 0 > def __iter__(self): > return self > def next(self): > if self.count < 10: > self.count += 1 > return self.count > raise StopIteration > > The equivalent generator function could be > > def counter(): > for count in range(1, 11): > yield count > > or, maybe a fairer comparison would be > > def counter(): > count = 0 > if count < 10: > count += 1 > yield count > > which is still much shorter and easier to understand than the class version. Usage of all three is identical: > > for i in counter(): > print i > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From royb at ubiquity.com.au Mon Nov 14 05:09:26 2005 From: royb at ubiquity.com.au (Roy Bleasdale) Date: Mon, 14 Nov 2005 15:09:26 +1100 Subject: [Tutor] Converting a List/Tuple to delimited string Message-ID: <5.1.0.14.2.20051114145216.017182c0@localhost> I have a list of strings and wanted to output them as a single delimited string. Eg ('ab','cd','ef') becomes "ab:cd:ef" My first attempt was to do it as a function: def Addsomething(a): y = [] for x in a: y.append( x + ':') return "".join(y) I then converted the this to a lambda function and mapped it. "".join(map((lambda x: x + ":"),L)) And this works just fine BUT This somehow seems a little incongruous for Python and wondered if there was a simpler, more stylish way of achieving this. Are there any suggestions or is my solution good enough? From john at fouhy.net Mon Nov 14 05:11:16 2005 From: john at fouhy.net (John Fouhy) Date: Mon, 14 Nov 2005 17:11:16 +1300 Subject: [Tutor] Converting a List/Tuple to delimited string In-Reply-To: <5.1.0.14.2.20051114145216.017182c0@localhost> References: <5.1.0.14.2.20051114145216.017182c0@localhost> Message-ID: <5e58f2e40511132011i6d371ac1w@mail.gmail.com> On 14/11/05, Roy Bleasdale wrote: > I have a list of strings and wanted to output them as a single delimited > string. > > Eg > > ('ab','cd','ef') becomes "ab:cd:ef" You almost had it ... What about: >>> lst = ['ab', 'cd', 'ef'] >>> ':'.join(lst) 'ab:cd:ef' In general, foo.join(lst) (where foo is a string) is equivalent to: def join(foo, lst): if not lst: return '' s = lst[0] for item in lst[1:]: s += foo + item return s -- John. From wan at walrus.us Mon Nov 14 07:07:00 2005 From: wan at walrus.us (Vincent Wan) Date: Sun, 13 Nov 2005 21:07:00 -0900 Subject: [Tutor] problem calling a function Message-ID: <91CE18EC-79B3-4C60-8DC8-673A323713A9@walrus.us> Thank you Roel Schroeven I don't know how I missed the fact that the printDendrogram function needs tuples not strings. I didn't recognize that my string was a tuple so I didn't realize that when I pasted it interactively in IDEL I was allowing python to change the type. eval() changes the type from string to tuple. But, to my surprise tuple() does not yeild the tuple that is represented by the string but a tuple representation of the string. If eval() does convert correctly why not use it? The string will always be a valid tuple. Thank you for you elegant tree based representation. I'm sure I'll need help when it comes to adding support for more that two nodes. Of course, I'll also have to modify the drawing code. Thank you, thank you Vincent ------------------------------------------------------------------------ -------------- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) From tvbare at socket.net Mon Nov 14 07:20:27 2005 From: tvbare at socket.net (->Terry<-) Date: Mon, 14 Nov 2005 00:20:27 -0600 (CST) Subject: [Tutor] Looking for suggestions Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I have written a small peg game using Pygame. This is the first working version. I have a request and a couple of perhaps silly questions. To anyone willing to take the time to have a look at the code and offer any advice or suggestions, I would be much appreciative. I'm looking for code suggestions rather than game-play suggestions, although I'm open to any help. I haven't got my head really wrapped around the OO stuff, so I'm thinking rewriting it using classes would make a good project to learn with. Is this the sort of thing that one would use classes for? Or is is better left as simple as possible? Now here is the perhaps silly question. Is something like this need to have a license? What I mean is, as I play with and improve this game and want to share it with others, should I choose a license and add the legal stuff with the distributed product? I have learned so much reading this list. I hope I've asked my questions right. The game appears to also work on Windows also, but does require you to have Pygame installed. It was written on Slackware with Python 2.4.1 The code: And the images: Cheers, - -- Terry "Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind." -- Dr. Seuss -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFDeCyyQvSnsfFzkV0RAqnBAJ9TEwpP7gmUPt06ZWCS/vUJ9lLSXACbBhFl NxIKZYKxi4OK9vR13HYP7IA= =gYkg -----END PGP SIGNATURE----- From sfhaley at earthlink.net Mon Nov 14 07:29:19 2005 From: sfhaley at earthlink.net (Steve Haley) Date: Mon, 14 Nov 2005 01:29:19 -0500 Subject: [Tutor] Another Quick Question Message-ID: Folks, I'm one of the people new to Python who has started going through a beginner's book to learn the basics of the language ("Python Programming for the Absolute Beginner"). In the second chapter the author (Michael Dawson) illustrates the use of escape sequences with, among other things, the "\a" to sound the system bell. However, when I run the little program myself, the program runs but I get no sound - all is get is the word BEL in while letters on a blue background. I've turned the volume up all the way and still no sound. I know the speakers on my laptop work because I just finished my daily session trying to learn a little Spanish which involves sound. I went to the language reference which also seems to indicate I should get a sound with exactly what the author is saying. The exact line is: print "\a" I'm not sure why but this kind of thing bothers me. Can anyone suggest why my laptop won't produce a bell? Does the fact that I'm running version 2.1 have something to do with it? Does my laptop have something against me and just doesn't want to ring its bell for me? (just kidding with that last one) Thanks in advance. Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/725d715f/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Nov 14 07:52:32 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 13 Nov 2005 22:52:32 -0800 (PST) Subject: [Tutor] problem calling a function In-Reply-To: <91CE18EC-79B3-4C60-8DC8-673A323713A9@walrus.us> Message-ID: > eval() changes the type from string to tuple. But, to my surprise > tuple() does not yeild the tuple that is represented by the string but a > tuple representation of the string. > > If eval() does convert correctly why not use it? The string will always > be a valid tuple. Hi Vincent, Alternative question: can your program just pass the tuple itself to the function, or does it always have to turn things into strings? Your code in: http://mail.python.org/pipermail/tutor/2005-November/043208.html constructs a string that represents a tree near the bottom of the code. But can you modify it to construct the data structure that represents that tree? I haven't read the code too closely yet, but it looks like it's doing too much working in building a string representation. Take a look again at Roel Schroven's code in: http://mail.python.org/pipermail/tutor/2005-November/043214.html Does the approach there make sense to you? If that code is complex, we could probably simplify that code to expose the core idea more clearly. The core idea is to use real, enriched data structures: you don't have to treat everything as an anemic string. eval() is a dangerous function and almost always never appropriate as a data-structure parser. It does much more than just value conversion. We've written about this a week ago: http://mail.python.org/pipermail/tutor/2005-November/042838.html http://mail.python.org/pipermail/tutor/2005-November/042854.html so eva() is obviously the seductive solution, but it's wrong here. *grin* Hope this helps! From johan at accesstel.co.za Mon Nov 14 08:43:02 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 14 Nov 2005 09:43:02 +0200 Subject: [Tutor] Another Quick Question In-Reply-To: References: Message-ID: <43784006.6070001@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/84a8f987/attachment.html From ajikoe at gmail.com Mon Nov 14 08:50:30 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 14 Nov 2005 08:50:30 +0100 Subject: [Tutor] Another Quick Question In-Reply-To: <43784006.6070001@accesstel.co.za> References: <43784006.6070001@accesstel.co.za> Message-ID: I use windows, it works for me.... Have checked your sound card, volume before trying the code? pujo On 11/14/05, Johan Geldenhuys wrote: > > Could this be a OS thing? > I use Linux and it works here. > > Steve Haley wrote: > > Folks, > > I'm one of the people new to Python who has started going through a > beginner's book to learn the basics of the language ("Python Programming for > the Absolute Beginner"). In the second chapter the author (Michael Dawson) > illustrates the use of escape sequences with, among other things, the "\a" > to sound the system bell. However, when I run the little program myself, the > program runs but I get no sound ? all is get is the word BEL in while > letters on a blue background. I've turned the volume up all the way and > still no sound. I know the speakers on my laptop work because I just > finished my daily session trying to learn a little Spanish which involves > sound. > > I went to the language reference which also seems to indicate I should > get a sound with exactly what the author is saying. The exact line is: > > print "\a" > > I'm not sure why but this kind of thing bothers me. Can anyone suggest > why my laptop won't produce a bell? Does the fact that I'm running version > 2.1 have something to do with it? Does my laptop have something against me > and just doesn't want to ring its bell for me? (just kidding with that last > one) > > Thanks in advance. > > Steve > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/2e9fc6e8/attachment.htm From norman at littletank.org Mon Nov 14 09:08:47 2005 From: norman at littletank.org (Norman Silverstone) Date: Mon, 14 Nov 2005 08:08:47 +0000 Subject: [Tutor] Another Quick Question In-Reply-To: References: Message-ID: <1131955727.15812.17.camel@localhost.localdomain> > I?m one of the people new to Python who has started going through a > beginner?s book to learn the basics of the language (?Python > Programming for the Absolute Beginner?). In the second chapter the > author (Michael Dawson) illustrates the use of escape sequences with, > among other things, the ?\a? to sound the system bell. However, when > I run the little program myself, the program runs but I get no sound ? > all is get is the word BEL in while letters on a blue background. > I?ve turned the volume up all the way and still no sound. I know the > speakers on my laptop work because I just finished my daily session > trying to learn a little Spanish which involves sound. > > > > I went to the language reference which also seems to indicate I should > get a sound with exactly what the author is saying. The exact line > is: > > > > print ?\a? I think that the bell referred to is the sound played by the speaker inside the case and has nothing to do with sound cards, speakers etc. Norman From johan at accesstel.co.za Mon Nov 14 09:10:43 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon, 14 Nov 2005 10:10:43 +0200 Subject: [Tutor] Looking for suggestions In-Reply-To: References: Message-ID: <43784683.50406@accesstel.co.za> Haven't look at the code in detail, but it would be great exercise to write a web gui for this game like the one for Tick-Tack-Toe. Any suggestions where to start with something like this? Johan PS: Fun to play. ->Terry<- wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >I have written a small peg game using Pygame. >This is the first working version. I have a >request and a couple of perhaps silly questions. > >To anyone willing to take the time to have a >look at the code and offer any advice or >suggestions, I would be much appreciative. >I'm looking for code suggestions rather than >game-play suggestions, although I'm open to >any help. > >I haven't got my head really wrapped around the >OO stuff, so I'm thinking rewriting it using >classes would make a good project to learn >with. Is this the sort of thing that one would >use classes for? Or is is better left as >simple as possible? > >Now here is the perhaps silly question. Is >something like this need to have a license? >What I mean is, as I play with and improve >this game and want to share it with others, >should I choose a license and add the legal >stuff with the distributed product? > >I have learned so much reading this list. I >hope I've asked my questions right. > >The game appears to also work on Windows also, >but does require you to have Pygame installed. >It was written on Slackware with Python 2.4.1 > >The code: > > > >And the images: > > > > >Cheers, >- -- > Terry > > >"Be who you are and say what you feel, because those > who mind don't matter and those who matter don't mind." > -- Dr. Seuss >-----BEGIN PGP SIGNATURE----- >Version: GnuPG v1.2.7 (GNU/Linux) > >iD8DBQFDeCyyQvSnsfFzkV0RAqnBAJ9TEwpP7gmUPt06ZWCS/vUJ9lLSXACbBhFl >NxIKZYKxi4OK9vR13HYP7IA= >=gYkg >-----END PGP SIGNATURE----- > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Mon Nov 14 09:43:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Nov 2005 08:43:24 -0000 Subject: [Tutor] Another Quick Question References: Message-ID: <031801c5e8f7$7a20e730$0a01a8c0@xp> > I went to the language reference which also seems to indicate I should get > a > sound with exactly what the author is saying. The exact line is: > > print "\a" Escape characters are terminal settings so you need to be running in a terminal. Start up a command window and run the program there it should work. Running in IDLE or PythonwIn, which are windows environments, won't work. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From benjaminhk at mac.com Mon Nov 14 11:34:05 2005 From: benjaminhk at mac.com (Benjamin James) Date: Mon, 14 Nov 2005 18:34:05 +0800 Subject: [Tutor] Python / OS X recommendations Message-ID: Hello, I am looking for some advice about Python resources for the Mac OS X (Tiger) platform. I have done some googling and found some good stuff (Python IDE, MacPython), Just wondering if there is anything I am missing. I tried downloading the activestate python tool, but i cant seem to install it. Thanks, Ben. From kent37 at tds.net Mon Nov 14 12:10:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Nov 2005 06:10:37 -0500 Subject: [Tutor] Looking for suggestions In-Reply-To: References: Message-ID: <437870AD.9000504@tds.net> ->Terry<- wrote: > To anyone willing to take the time to have a > look at the code and offer any advice or > suggestions, I would be much appreciative. > I'm looking for code suggestions rather than > game-play suggestions, although I'm open to > any help. A couple of notes after a quick look: - As you note, def check_valid_jump(sel1, sel2) is really ugly. When I have code like this I look for a way to drive it from a table instead of a bunch of if/elif statements full of magic numbers. In this case it looks like you have one condition for each state. The conditions and results could be put in a list whose index is the state and whose values are the test values for sel1 and sel2. You would have a table that looks like this: jump_table = [ (1, 1, 4, 2), # (state # sel1 and sel2 values to check for state, return value) (2, 1, 6, 3), # etc for all the tests ] Then check_valid_jump() becomes def check_valid_jump(sel1, sel2): for st, sel1value, sel2value, result in jump_table: if sel1 == sel1value and sel2 == sel2value: if state[st] == 1: return result break return 0 - get_button() could be similarly simplified, only you don't even need a table, you are just returning the number of the peg_coords that was clicked. This should work: def get_button(click): for i, peg in peg_coords: if click in peg: return i+1 return 0 > > I haven't got my head really wrapped around the > OO stuff, so I'm thinking rewriting it using > classes would make a good project to learn > with. Is this the sort of thing that one would > use classes for? Or is is better left as > simple as possible? I'm a believer in "as simple as possible". One of the strengths of Python is that you don't *have* to use classes if they are not called for. Maybe there is some benefit in using classes in your program, for example a peg class might simplify it, I'm not sure. This essay talks about some of the reasons you might want to introduce classes into a program: http://personalpages.tds.net/~kent37/blog/stories/15.html Kent -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Mon Nov 14 12:45:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Nov 2005 11:45:01 -0000 Subject: [Tutor] Python / OS X recommendations References: Message-ID: <034401c5e910$dcad9880$0a01a8c0@xp> Benjamin, > I am looking for some advice about Python resources for the Mac OS X Can you tell us what background you have? Are you a MacOS programmer? Have you used Objective C or Java to build a Mac application for example? Do you already know Cocoa? There are loads of general MacOS programming sites which could be useful depending what your background is. THe obvious starting point is the Apple Developer site... http://developer.apple.com/ > missing. I tried downloading the activestate python tool, but i cant > seem to install it. I may be wrong but I thought ActiveState targeted Windows, do they have any MacOS tools? Which tool did you try to load? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Mon Nov 14 12:50:09 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 14 Nov 2005 06:50:09 -0500 Subject: [Tutor] Looking for suggestions In-Reply-To: References: Message-ID: <56639801876.20051114065009@columbus.rr.com> > To anyone willing to take the time to have a > look at the code and offer any advice or > suggestions, I would be much appreciative. I'm wondering if you can condense this: if sel1 == 1 and sel2 == 4: # This seems really ugly... if state[1] == 1: return 2 elif sel1 == 1 and sel2 == 6: if state[2] == 1: return 3 Into this: sel={(1,4): (1,3), (1,6): (2,2), etc.} if state[ sel[(sel1,sel2)][0] ] == 1: return sel[(sel1,sel2)][1] Alan From singletoned at gmail.com Mon Nov 14 13:19:00 2005 From: singletoned at gmail.com (Ed Singleton) Date: Mon, 14 Nov 2005 12:19:00 +0000 Subject: [Tutor] Inheriting from parent object Message-ID: <34bb7f5b0511140419u20af3cffi@mail.gmail.com> I want to create a property that will inherit it's value from the same property in it's parent object, but will check it's parent's propety everytime it is called. But that can be over-ridden, and I don't have to know what the objects parent is. For example: object.x = 3 object.subobject.x = inherit() print object.subobject.x #prints 3 object.x = 4 print object.subobject.x #prints 4 object.subobject.x = 5 print object.subobject.x #prints 5 What could I put in the inherit() function that would look for the same property of it's parent and return that, whilst keeping it as general as possible? Thanks Ed From kent37 at tds.net Mon Nov 14 13:51:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Nov 2005 07:51:38 -0500 Subject: [Tutor] Python / OS X recommendations In-Reply-To: References: Message-ID: <4378885A.7070209@tds.net> Benjamin James wrote: > Hello, > > I am looking for some advice about Python resources for the Mac OS X > (Tiger) platform. I have done some googling and found some good stuff > (Python IDE, MacPython), Just wondering if there is anything I am > missing. You might be interested in PyObjC which lets you write Cocoa programs in Python. http://pyobjc.sourceforge.net/ Kent -- http://www.kentsjohnson.com From K.Weinert at gmx.net Mon Nov 14 14:42:27 2005 From: K.Weinert at gmx.net (K.Weinert@gmx.net) Date: Mon, 14 Nov 2005 14:42:27 +0100 (MET) Subject: [Tutor] tkFileDialog.Directory Message-ID: <1789.1131975747@www93.gmx.net> Hello! I want to learn Tkinter and try to build a small File search dialog. Tkinter is nice, but here is a problem where I am stuck: I want to allow the dialog's user to pick a directory. The widget for this is tkFileDialog.Directory. But when I start the Directory-Window, it is possible move the focus back to my File Search dialog. Thus it is possible but not wanted to create several "Pick directory" windows. I tried to make the Directory instance modal by calling .grab_set() but this raises an attribute error. Here is a minimal example: --- snip --- import Tix from Tkconstants import * from tkFileDialog import Directory class FileSearchBase: def __init__(self, root): self.root = root self.top = None self.title= "File Search" def open(self): if not self.top: self.create_widgets() else: self.top.deiconify() self.top.tkraise() self.top.grab_set() def close(self, event=None): if self.top is not None: self.top.grab_release() self.top.withdraw() def create_widgets(self): top = Tix.Toplevel(self.root) top.resizable(0,0) top.bind("", self.close) top.protocol("WM_DELETE_WINDOW", self.close) top.wm_title(self.title) self.top = top pickButton= Tix.Button(top, text = 'Pick..', command = self.pick_dir) pickButton.grid(row= 0, column=1) def pick_dir(self): dir_dlg= Directory() #dir_dlg.grab_set() # AttributeError: grab_set #self.top.wait_window(dir_dlg) # AttributeError: _w dir= dir_dlg.show() print dir if __name__ == '__main__': root = Tix.Tk() root.title("File Search Demo") widget = FileSearchBase(root) searchButton = Tix.Button(root, text = 'Show search dialog', command = widget.open) searchButton.pack(padx = 8, pady = 8) root.mainloop() --- snip --- The above example allows to create several Directory dialogs. On the other hand, if I start the Directory dialog from the root window (from the Tix.Tk() instance), everything works fine. The following example works: --- snip --- import Tix from Tkconstants import * from tkFileDialog import Directory def pick_dir(): dir_dlg= Directory() dir= dir_dlg.show() print dir if __name__ == '__main__': root = Tix.Tk() root.title("File Search Demo") pickButton = Tix.Button(root, text = 'Choose Directory', command = pick_dir) pickButton.pack(side = 'bottom') root.mainloop() --- snip --- Would be nice if someone could help me with the first example... Kind regards, Karsten. -- Lust, ein paar Euro nebenbei zu verdienen? Ohne Kosten, ohne Risiko! Satte Provisionen für GMX Partner: http://www.gmx.net/de/go/partner From kent37 at tds.net Mon Nov 14 14:59:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Nov 2005 08:59:47 -0500 Subject: [Tutor] Looking for suggestions In-Reply-To: References: Message-ID: <43789853.3090105@tds.net> ->Terry<- wrote: > Now here is the perhaps silly question. Is > something like this need to have a license? > What I mean is, as I play with and improve > this game and want to share it with others, > should I choose a license and add the legal > stuff with the distributed product? Just a quick note about this. If you are planning to distribute casually maybe it doesn't matter. But for more formal distribution (e.g. a permanent web site) you do your readers a favor by explicitly stating the terms under which they can use your code. Absent a license, honest users must contact you before they can use your programs. Kent From nephish at xit.net Mon Nov 14 16:21:12 2005 From: nephish at xit.net (nephish) Date: Mon, 14 Nov 2005 15:21:12 +0000 Subject: [Tutor] question about serial coms Message-ID: <1131981672.28760.2.camel@localhost.localdomain> Hey there, i am developing on a linux computer with the serial module. Now, i already am able to recieve info from a serial RS232 device and process everything ok. What i need to do now is write to the serial device, but i also need to be able to not interrupt the script that is reading from it. I guess my question is, do i have to interrupt the reading script to write to the same RS232 device ? and if so, how do i do that? thanks, shawn From alan.gauld at freenet.co.uk Mon Nov 14 19:12:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Nov 2005 18:12:42 -0000 Subject: [Tutor] Any TurboGears users out there? Message-ID: <037e01c5e947$083862b0$0a01a8c0@xp> I just stumbled across TurboGears: http://www.macdevcenter.com/pub/a/mac/2005/11/08/turbogears.html Its based on CheryPy which consistently gets good reviews but adds SQL access and XML templates. Sounds interesting, possibly even a Zope rival for the medium sized as opposed to massive site.. Is anyone on the list using it? Or even looked at it? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From hugonz-lists at h-lab.net Mon Nov 14 19:35:50 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 12:35:50 -0600 Subject: [Tutor] question about serial coms In-Reply-To: <1131981672.28760.2.camel@localhost.localdomain> References: <1131981672.28760.2.camel@localhost.localdomain> Message-ID: <4378D906.600@h-lab.net> Hi Nephish, Are you using pyserial or rolling your own? Normally you can write and read to the /dev/ttySXX file at the same time; since they're special files, not ordinary files, the driver handles that. Handling both writing and reading in your program's flow control is a wholly different matter, though. You might need to use select() to avoid blocking. Are you using two completely different scripts for reding and writing? There is some valuable info, if not about python, in the Serial Programming howto, at: http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ Hugo nephish wrote: > Hey there, > i am developing on a linux computer with the serial module. Now, i > already am able to recieve info from a serial RS232 device and process > everything ok. What i need to do now is write to the serial device, but > i also need to be able to not interrupt the script that is reading from > it. > I guess my question is, do i have to interrupt the reading script to > write to the same RS232 device ? > and if so, how do i do that? > > thanks, > shawn > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Nov 14 19:37:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Nov 2005 13:37:36 -0500 Subject: [Tutor] Any TurboGears users out there? In-Reply-To: <037e01c5e947$083862b0$0a01a8c0@xp> References: <037e01c5e947$083862b0$0a01a8c0@xp> Message-ID: <4378D970.1080403@tds.net> Alan Gauld wrote: > I just stumbled across TurboGears: > > http://www.macdevcenter.com/pub/a/mac/2005/11/08/turbogears.html > > Its based on CheryPy which consistently gets good reviews but adds SQL > access and XML templates. Sounds interesting, possibly even a Zope rival > for the medium sized as opposed to massive site.. > > Is anyone on the list using it? Or even looked at it? I have looked at it to the extent of getting through the tutorial and a little more playing. It looks very promising to me. CherryPy, SQLObject and mochikit all have good reputations and TG seems to do a good job of gluing them together. Kid (the template engine) is not as mature as the others but it seems to work OK. I used CherryPy 1 for a small work project. It was very easy to build the web site. I found the built-in webserver lacking in some of the basics like a usable request log but I think this has been fixed in CP 2. Kent -- http://www.kentsjohnson.com From nephish at xit.net Mon Nov 14 19:51:05 2005 From: nephish at xit.net (nephish) Date: Mon, 14 Nov 2005 12:51:05 -0600 Subject: [Tutor] question about serial coms In-Reply-To: <4378D906.600@h-lab.net> References: <1131981672.28760.2.camel@localhost.localdomain> <4378D906.600@h-lab.net> Message-ID: <1131994265.2866.3.camel@localhost.localdomain> Yeah, i am using pyserial, i think, in debian its called python serial and i use import serial to get things going. Really easy, just wanted to know about this stuff before i start scrambling this like so many eggs. i will not be using two different scripts, but likely two threads in the same script. not sure i really get what select() is all about great link by the way, thanks. shawn On Mon, 2005-11-14 at 12:35 -0600, Hugo Gonz?lez Monteverde wrote: > Hi Nephish, > > Are you using pyserial or rolling your own? Normally you can write and > read to the /dev/ttySXX file at the same time; since they're special > files, not ordinary files, the driver handles that. > > Handling both writing and reading in your program's flow control is a > wholly different matter, though. You might need to use select() to > avoid blocking. > > Are you using two completely different scripts for reding and writing? > > There is some valuable info, if not about python, in the Serial > Programming howto, at: > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > Hugo > > nephish wrote: > > Hey there, > > i am developing on a linux computer with the serial module. Now, i > > already am able to recieve info from a serial RS232 device and process > > everything ok. What i need to do now is write to the serial device, but > > i also need to be able to not interrupt the script that is reading from > > it. > > I guess my question is, do i have to interrupt the reading script to > > write to the same RS232 device ? > > and if so, how do i do that? > > > > thanks, > > shawn > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > From tim at johnsons-web.com Mon Nov 14 20:25:23 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 14 Nov 2005 10:25:23 -0900 Subject: [Tutor] Any TurboGears users out there? In-Reply-To: <037e01c5e947$083862b0$0a01a8c0@xp> References: <037e01c5e947$083862b0$0a01a8c0@xp> Message-ID: <20051114192523.GO2001@johnsons-web.com> * Alan Gauld [051114 09:26]: > I just stumbled across TurboGears: > > http://www.macdevcenter.com/pub/a/mac/2005/11/08/turbogears.html > > Its based on CheryPy which consistently gets good reviews but adds SQL > access and XML templates. Sounds interesting, possibly even a Zope rival > for the medium sized as opposed to massive site.. > > Is anyone on the list using it? Or even looked at it? I have downloaded it, but have not yet done any testing. I'm interested in investigating AJAX features, which I believe it supports. I hope to do some testing in the next couple of days, time permitting. tj > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From matthew.williams at cancer.org.uk Mon Nov 14 21:01:14 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Mon, 14 Nov 2005 20:01:14 +0000 Subject: [Tutor] TurboGears - and some issues In-Reply-To: References: Message-ID: <1131998474.4471.5.camel@localhost.localdomain> Dear Alan, I haven't used it, but I've looked through it, and it looks v. interesting. One of the things I like is that it glues lots of different bits together (I came across it while looking at SQLObject), and so benefits from their advances. I was a bit surprised that you hadn't come across it before, as in general you seem to be one of the core team on the list (in that you tend to answer rather than ask most questions). This got me thinking about how we stay up with different, and new, python projects. I tend to look at the Daily Python URL, as well as some Technorati and del.icio.us tagged sites/blogs. Where else do other people look? Matt From kent37 at tds.net Mon Nov 14 21:19:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Nov 2005 15:19:58 -0500 Subject: [Tutor] TurboGears - and some issues In-Reply-To: <1131998474.4471.5.camel@localhost.localdomain> References: <1131998474.4471.5.camel@localhost.localdomain> Message-ID: <4378F16E.4010404@tds.net> Matt Williams wrote: > This got me thinking about how we stay up with different, and new, > python projects. I tend to look at the Daily Python URL, as well as some > Technorati and del.icio.us tagged sites/blogs. Where else do other > people look? The main places I hear about new stuff are Planet Python Python Cookbook CheeseShop python-announce The first three have RSS feeds, the last is a mailing list. See my blogroll for URLs and a complete list of blogs I read: http://personalpages.tds.net/~kent37/blog/ and of course there's comp.lang.python if you have the time for it... Kent -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Mon Nov 14 21:17:44 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Nov 2005 20:17:44 -0000 Subject: [Tutor] Inheriting from parent object References: <34bb7f5b0511140419u20af3cffi@mail.gmail.com> Message-ID: <03b701c5e958$79687590$0a01a8c0@xp> > I want to create a property that will inherit it's value from the same > property in it's parent object, but will check it's parent's propety > everytime it is called. But that can be over-ridden, and I don't have > to know what the objects parent is. Ed you are using a lot of OOP terminology here to decribe something that looks decidedly non OOP. Can you clarify exactly what you mean by the terms: object, property, inherit and parent. Also can you describe the problem you are trying to solve rather than the solution you think you need? It may be that there is a simpler paradigm you can use. I'm not sure I really understand what you are trying to achieve. > object.x = 3 > object.subobject.x = inherit() > print object.subobject.x #prints 3 > object.x = 4 > print object.subobject.x #prints 4 > object.subobject.x = 5 > print object.subobject.x #prints 5 object it the built-in object class that provides new-style classes, is that theone you are using here? Or is it just a generic name for illustration? Is object an instance or a class? > What could I put in the inherit() function that would look for the > same property of it's parent and return that, whilst keeping it as > general as possible? I also don't understand what the inherit() function is supposed to do. You provide it with no context in which to operate. Unless it relies on hard coded global variables there is no way it can know about object, subobject or x. Normal OOP inheritance relies on creating instances from classes, but you don't appear to want to do that, it looks more like you are building some kind of containment lattice. I think I need more background. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Hans.Dushanthakumar at navman.com Mon Nov 14 21:29:48 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 15 Nov 2005 09:29:48 +1300 Subject: [Tutor] question about serial coms Message-ID: <5667508E43F1B740BCFA57FF46E35300025BFBF5@nav-akl-exch-c.newton.navman.com> Ive worked on a similar application. I used one thread to read from the serial port and another one to handle the writes. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Hugo Gonz?lez Monteverde Sent: Tuesday, 15 November 2005 7:36 a.m. To: nephish Cc: tutor Subject: Re: [Tutor] question about serial coms Hi Nephish, Are you using pyserial or rolling your own? Normally you can write and read to the /dev/ttySXX file at the same time; since they're special files, not ordinary files, the driver handles that. Handling both writing and reading in your program's flow control is a wholly different matter, though. You might need to use select() to avoid blocking. Are you using two completely different scripts for reding and writing? There is some valuable info, if not about python, in the Serial Programming howto, at: http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ Hugo nephish wrote: > Hey there, > i am developing on a linux computer with the serial module. Now, i > already am able to recieve info from a serial RS232 device and process > everything ok. What i need to do now is write to the serial device, > but i also need to be able to not interrupt the script that is reading > from it. > I guess my question is, do i have to interrupt the reading script to > write to the same RS232 device ? > and if so, how do i do that? > > thanks, > shawn > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ajikoe at gmail.com Mon Nov 14 21:32:10 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 14 Nov 2005 21:32:10 +0100 Subject: [Tutor] Inheriting from parent object In-Reply-To: <03b701c5e958$79687590$0a01a8c0@xp> References: <34bb7f5b0511140419u20af3cffi@mail.gmail.com> <03b701c5e958$79687590$0a01a8c0@xp> Message-ID: if you want to copy object just use: import copy newobj = copy.deepcopy(objparent) or just create object which has direct correlation with the parent like: newobj = objparent Cheers, pujo On 11/14/05, Alan Gauld wrote: > > > I want to create a property that will inherit it's value from the same > > property in it's parent object, but will check it's parent's propety > > everytime it is called. But that can be over-ridden, and I don't have > > to know what the objects parent is. > > Ed you are using a lot of OOP terminology here to decribe > something that looks decidedly non OOP. Can you clarify exactly > what you mean by the terms: > object, property, inherit and parent. > > Also can you describe the problem you are trying to solve rather than > the solution you think you need? It may be that there is a simpler > paradigm you can use. I'm not sure I really understand what you > are trying to achieve. > > > object.x = 3 > > object.subobject.x = inherit() > > print object.subobject.x #prints 3 > > object.x = 4 > > print object.subobject.x #prints 4 > > object.subobject.x = 5 > > print object.subobject.x #prints 5 > > object it the built-in object class that provides new-style classes, > is that theone you are using here? Or is it just a generic name for > illustration? Is object an instance or a class? > > > What could I put in the inherit() function that would look for the > > same property of it's parent and return that, whilst keeping it as > > general as possible? > > I also don't understand what the inherit() function is supposed to do. > You provide it with no context in which to operate. > Unless it relies on hard coded global variables there is no > way it can know about object, subobject or x. > > Normal OOP inheritance relies on creating instances from classes, > but you don't appear to want to do that, it looks more like you > are building some kind of containment lattice. I think I need more > background. > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/77ef5992/attachment.htm From kent37 at tds.net Mon Nov 14 21:37:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Nov 2005 15:37:07 -0500 Subject: [Tutor] TurboGears - and some issues In-Reply-To: <1131998474.4471.5.camel@localhost.localdomain> References: <1131998474.4471.5.camel@localhost.localdomain> Message-ID: <4378F573.8000900@tds.net> Matt Williams wrote: > This got me thinking about how we stay up with different, and new, > python projects. I tend to look at the Daily Python URL, as well as some > Technorati and del.icio.us tagged sites/blogs. Where else do other > people look? One more - Dr Dobbs Python-URL (not the same as Daily Python URL). Subscribe here: http://www.ddj.com/topic/pythonurl/ Kent -- http://www.kentsjohnson.com From stever at insightbb.com Mon Nov 14 21:40:26 2005 From: stever at insightbb.com (Steve Robb) Date: Mon, 14 Nov 2005 14:40:26 -0600 Subject: [Tutor] Tutor Digest, Vol 21, Issue 60 In-Reply-To: References: Message-ID: <1132000827.31988.16.camel@localhost.localdomain> I have spent quite a bit of time looking at TurboGears. I have not used it in any production sense. Recently, there has developed a new TurboGears app which you may not have run across yet, but is very interesting in itself. It's called Catwalk. http://www.checkandshare.com/catwalk/download.html I have hacked it to give it access to other databases I have stored in MySQL and have started a generic version of it to display the MySQL database itself. Seems very cool. Steve > Message: 9 > Date: Mon, 14 Nov 2005 18:12:42 -0000 > From: "Alan Gauld" > Subject: [Tutor] Any TurboGears users out there? > To: "Python Tutor list" > Message-ID: <037e01c5e947$083862b0$0a01a8c0 at xp> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > I just stumbled across TurboGears: > > http://www.macdevcenter.com/pub/a/mac/2005/11/08/turbogears.html > > Its based on CheryPy which consistently gets good reviews but adds SQL > access and XML templates. Sounds interesting, possibly even a Zope rival > for the medium sized as opposed to massive site.. > > Is anyone on the list using it? Or even looked at it? > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > ------------------------------ > > Message: 11 > Date: Mon, 14 Nov 2005 13:37:36 -0500 > From: Kent Johnson > Subject: Re: [Tutor] Any TurboGears users out there? > Cc: Python Tutor list > Message-ID: <4378D970.1080403 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Alan Gauld wrote: > > I just stumbled across TurboGears: > > > > http://www.macdevcenter.com/pub/a/mac/2005/11/08/turbogears.html > > > > Its based on CheryPy which consistently gets good reviews but adds SQL > > access and XML templates. Sounds interesting, possibly even a Zope rival > > for the medium sized as opposed to massive site.. > > > > Is anyone on the list using it? Or even looked at it? > > I have looked at it to the extent of getting through the tutorial and a little more playing. It looks very promising to me. CherryPy, SQLObject and mochikit all have good reputations and TG seems to do a good job of gluing them together. Kid (the template engine) is not as mature as the others but it seems to work OK. > > I used CherryPy 1 for a small work project. It was very easy to build the web site. I found the built-in webserver lacking in some of the basics like a usable request log but I think this has been fixed in CP 2. > > Kent From klappnase at freenet.de Mon Nov 14 22:10:25 2005 From: klappnase at freenet.de (Michael Lange) Date: Mon, 14 Nov 2005 22:10:25 +0100 Subject: [Tutor] tkFileDialog.Directory In-Reply-To: <1789.1131975747@www93.gmx.net> References: <1789.1131975747@www93.gmx.net> Message-ID: <20051114221025.64feabf6.klappnase@freenet.de> On Mon, 14 Nov 2005 14:42:27 +0100 (MET) K.Weinert at gmx.net wrote: > Hello! > I want to learn Tkinter and try to build a small File search dialog. Tkinter > is nice, but here is a problem where I am stuck: > > I want to allow the dialog's user to pick a directory. The widget for this > is tkFileDialog.Directory. But when I start the Directory-Window, it is > possible move the focus back to my File Search dialog. Thus it is possible > but not wanted to create several "Pick directory" windows. I tried to make > the Directory instance modal by calling .grab_set() but this raises an > attribute error. Here is a minimal example: > Hi Karsten, I guess the tkFileDialog.Directory class isn't intended to be used directly. Try tkFileDialog.askdirectory() instead. If there are problems with the grab state, try passing "parent=self.top" to askdirectory(). I hope this helps Michael From wildcard2005 at comcast.net Mon Nov 14 22:17:12 2005 From: wildcard2005 at comcast.net (Terry Kemmerer) Date: Mon, 14 Nov 2005 13:17:12 -0800 Subject: [Tutor] TurboGears - and some issues Message-ID: <1132003032.5612.106.camel@c-24-16-68-31.hsd1.wa.comcast.net> TurboGears sounds pretty good. But, from the write up, TurboGears appears to be for MAC only. Or am I misreading the write up? Terry -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/5d7210f2/attachment.htm From alan.gauld at freenet.co.uk Mon Nov 14 22:30:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Nov 2005 21:30:38 -0000 Subject: [Tutor] TurboGears - and some issues References: <1131998474.4471.5.camel@localhost.localdomain> <4378F16E.4010404@tds.net> Message-ID: <03d401c5e962$a82522c0$0a01a8c0@xp> > The main places I hear about new stuff are > Planet Python > Python Cookbook > python-announce I know of them but rarely look. > CheeseShop New one on me! > The first three have RSS feeds, But I didn't know that... > and of course there's comp.lang.python if you have the time for it... And there's the rub. If I'm not busy I try to scan c.l.p but mostly its just too busy. Nonetheless its my primary source of new stuff, its fairly easy to scroll down lookling for subjects beginning [Ann:] However I have to say I'm pretty conservative when it comes to Python addons. I don't use many and I only look for them when I have a specific need. I only found the TurboGears stuff because someone asked about MacOS resources and Apple were highlighting TG on the developer page... It caught my interest because I'm exploring JSP/Tomcat and Struts just now for my day job, so anything related to Web frameworks... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From nephish at xit.net Mon Nov 14 22:47:04 2005 From: nephish at xit.net (nephish) Date: Mon, 14 Nov 2005 15:47:04 -0600 Subject: [Tutor] question about serial coms In-Reply-To: <5667508E43F1B740BCFA57FF46E35300025BFBF5@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E35300025BFBF5@nav-akl-exch-c.newton.navman.com> Message-ID: <1132004824.7149.0.camel@bitsbam.localdomain> well thats encouraging, did you have to do anything special to prevent an error when trying to read or write at the same time ? thanks sk On Tue, 2005-11-15 at 09:29 +1300, Hans Dushanthakumar wrote: > Ive worked on a similar application. I used one thread to read from the serial port and another one to handle the writes. > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Hugo Gonz?lez Monteverde > Sent: Tuesday, 15 November 2005 7:36 a.m. > To: nephish > Cc: tutor > Subject: Re: [Tutor] question about serial coms > > Hi Nephish, > > Are you using pyserial or rolling your own? Normally you can write and read to the /dev/ttySXX file at the same time; since they're special files, not ordinary files, the driver handles that. > > Handling both writing and reading in your program's flow control is a wholly different matter, though. You might need to use select() to avoid blocking. > > Are you using two completely different scripts for reding and writing? > > There is some valuable info, if not about python, in the Serial Programming howto, at: > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > Hugo > > nephish wrote: > > Hey there, > > i am developing on a linux computer with the serial module. Now, i > > already am able to recieve info from a serial RS232 device and process > > everything ok. What i need to do now is write to the serial device, > > but i also need to be able to not interrupt the script that is reading > > from it. > > I guess my question is, do i have to interrupt the reading script to > > write to the same RS232 device ? > > and if so, how do i do that? > > > > thanks, > > shawn > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Mon Nov 14 22:51:16 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 14 Nov 2005 21:51:16 -0000 Subject: [Tutor] new topic draft Message-ID: <03e001c5e965$8a671fb0$0a01a8c0@xp> I've just added an incomplete draft copy of my latest tutorial topic on using the Operating System from Python. The material that's there discusses the role of the OS and looks at file handling usng os/os.path/shutil etc. http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm If anyone would like to take a look and provide feedback on general direction/depth etc that'd be greatly appreciated. TIA, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Hans.Dushanthakumar at navman.com Mon Nov 14 22:58:57 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 15 Nov 2005 10:58:57 +1300 Subject: [Tutor] question about serial coms Message-ID: <5667508E43F1B740BCFA57FF46E35300025BFE28@nav-akl-exch-c.newton.navman.com> I believe that the drivers take care of that, however, I did use locks to make sure that there were no conflicts. In the listener thread I had something along the lines of: Acquire lock readline() from the ser port Release lock And in the sender thread, Acquire lock send msg over ser port Release lock Cheers Hans -----Original Message----- From: nephish [mailto:nephish at xit.net] Sent: Tuesday, 15 November 2005 10:47 a.m. To: Hans Dushanthakumar Cc: Hugo Gonz?lez Monteverde; tutor Subject: RE: [Tutor] question about serial coms well thats encouraging, did you have to do anything special to prevent an error when trying to read or write at the same time ? thanks sk On Tue, 2005-11-15 at 09:29 +1300, Hans Dushanthakumar wrote: > Ive worked on a similar application. I used one thread to read from the serial port and another one to handle the writes. > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > Behalf Of Hugo Gonz?lez Monteverde > Sent: Tuesday, 15 November 2005 7:36 a.m. > To: nephish > Cc: tutor > Subject: Re: [Tutor] question about serial coms > > Hi Nephish, > > Are you using pyserial or rolling your own? Normally you can write and read to the /dev/ttySXX file at the same time; since they're special files, not ordinary files, the driver handles that. > > Handling both writing and reading in your program's flow control is a wholly different matter, though. You might need to use select() to avoid blocking. > > Are you using two completely different scripts for reding and writing? > > There is some valuable info, if not about python, in the Serial Programming howto, at: > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > Hugo > > nephish wrote: > > Hey there, > > i am developing on a linux computer with the serial module. Now, i > > already am able to recieve info from a serial RS232 device and > > process everything ok. What i need to do now is write to the serial > > device, but i also need to be able to not interrupt the script that > > is reading from it. > > I guess my question is, do i have to interrupt the reading script > > to write to the same RS232 device ? > > and if so, how do i do that? > > > > thanks, > > shawn > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ukc802591034 at btconnect.com Mon Nov 14 23:07:44 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Mon, 14 Nov 2005 22:07:44 -0000 Subject: [Tutor] TurboGears - and some issues References: <1132003032.5612.106.camel@c-24-16-68-31.hsd1.wa.comcast.net> Message-ID: "Terry Kemmerer" wrote in message news:1132003032.5612.106.camel at c-24-16-68-31.hsd1.wa.comcast.net... > TurboGears sounds pretty good. But, from the write up, TurboGears > appears to be for MAC only. > Or am I misreading the write up? The writeup I posted was Mac focused but the project itself is multi platform. The downloads page has links to Windows, Mac and Linux/Unix versions. Alan G. From nick at javacat.f2s.com Mon Nov 14 23:16:16 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon, 14 Nov 2005 22:16:16 -0000 Subject: [Tutor] new topic draft In-Reply-To: <03e001c5e965$8a671fb0$0a01a8c0@xp> Message-ID: > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > Behalf Of Alan Gauld > > > I've just added an incomplete draft copy of my latest tutorial topic > on using the Operating System from Python. The material that's > there discusses the role of the OS and looks at file handling > usng os/os.path/shutil etc. > > http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm > > If anyone would like to take a look and provide feedback on > general direction/depth etc that'd be greatly appreciated. Thanks for that Alan. I always seem to get myself into difficulty with the os.walk routine, but you explained it brilliantly there. Have to admit, I couldn't be bothered to read the "So What is the Operating System" bit tho cos as you say on the page, we don't need to know it. Now if we were C programmers maybe .. :) Thanks again, Nick . From nephish at xit.net Mon Nov 14 23:22:33 2005 From: nephish at xit.net (nephish) Date: Mon, 14 Nov 2005 16:22:33 -0600 Subject: [Tutor] question about serial coms In-Reply-To: <5667508E43F1B740BCFA57FF46E35300025BFE28@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E35300025BFE28@nav-akl-exch-c.newton.navman.com> Message-ID: <1132006954.7204.2.camel@bitsbam.localdomain> ok, lock is something you wrote yourself ? i can't find it in the docs. However, i think i can essentially build the same thing. the serial module i use is pyserial. pyserial.sourceforge.net. the docs are a wee bit on the sparce side. But i think i can pull it off. Thanks for your help. shawn On Tue, 2005-11-15 at 10:58 +1300, Hans Dushanthakumar wrote: > I believe that the drivers take care of that, however, I did use locks to make sure that there were no conflicts. > > In the listener thread I had something along the lines of: > > Acquire lock > readline() from the ser port > Release lock > > And in the sender thread, > > Acquire lock > send msg over ser port > Release lock > > Cheers > Hans > > -----Original Message----- > From: nephish [mailto:nephish at xit.net] > Sent: Tuesday, 15 November 2005 10:47 a.m. > To: Hans Dushanthakumar > Cc: Hugo Gonz?lez Monteverde; tutor > Subject: RE: [Tutor] question about serial coms > > well thats encouraging, did you have to do anything special to prevent an error when trying to read or write at the same time ? > > thanks > sk > > > On Tue, 2005-11-15 at 09:29 +1300, Hans Dushanthakumar wrote: > > Ive worked on a similar application. I used one thread to read from the serial port and another one to handle the writes. > > > > -----Original Message----- > > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > > Behalf Of Hugo Gonz?lez Monteverde > > Sent: Tuesday, 15 November 2005 7:36 a.m. > > To: nephish > > Cc: tutor > > Subject: Re: [Tutor] question about serial coms > > > > Hi Nephish, > > > > Are you using pyserial or rolling your own? Normally you can write and read to the /dev/ttySXX file at the same time; since they're special files, not ordinary files, the driver handles that. > > > > Handling both writing and reading in your program's flow control is a wholly different matter, though. You might need to use select() to avoid blocking. > > > > Are you using two completely different scripts for reding and writing? > > > > There is some valuable info, if not about python, in the Serial Programming howto, at: > > > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > > > > Hugo > > > > nephish wrote: > > > Hey there, > > > i am developing on a linux computer with the serial module. Now, i > > > already am able to recieve info from a serial RS232 device and > > > process everything ok. What i need to do now is write to the serial > > > device, but i also need to be able to not interrupt the script that > > > is reading from it. > > > I guess my question is, do i have to interrupt the reading script > > > to write to the same RS232 device ? > > > and if so, how do i do that? > > > > > > thanks, > > > shawn > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > From Hans.Dushanthakumar at navman.com Mon Nov 14 23:27:26 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 15 Nov 2005 11:27:26 +1300 Subject: [Tutor] question about serial coms Message-ID: <5667508E43F1B740BCFA57FF46E35300025BFE9D@nav-akl-exch-c.newton.navman.com> Lock() is provided by the threading module. see http://docs.python.org/lib/module-threading.html & http://docs.python.org/lib/lock-objects.html Cheers Hans -----Original Message----- From: nephish [mailto:nephish at xit.net] Sent: Tuesday, 15 November 2005 11:23 a.m. To: Hans Dushanthakumar Cc: Hugo Gonz?lez Monteverde; tutor Subject: RE: [Tutor] question about serial coms ok, lock is something you wrote yourself ? i can't find it in the docs. However, i think i can essentially build the same thing. the serial module i use is pyserial. pyserial.sourceforge.net. the docs are a wee bit on the sparce side. But i think i can pull it off. Thanks for your help. shawn On Tue, 2005-11-15 at 10:58 +1300, Hans Dushanthakumar wrote: > I believe that the drivers take care of that, however, I did use locks to make sure that there were no conflicts. > > In the listener thread I had something along the lines of: > > Acquire lock > readline() from the ser port > Release lock > > And in the sender thread, > > Acquire lock > send msg over ser port > Release lock > > Cheers > Hans > > -----Original Message----- > From: nephish [mailto:nephish at xit.net] > Sent: Tuesday, 15 November 2005 10:47 a.m. > To: Hans Dushanthakumar > Cc: Hugo Gonz?lez Monteverde; tutor > Subject: RE: [Tutor] question about serial coms > > well thats encouraging, did you have to do anything special to prevent an error when trying to read or write at the same time ? > > thanks > sk > > > On Tue, 2005-11-15 at 09:29 +1300, Hans Dushanthakumar wrote: > > Ive worked on a similar application. I used one thread to read from the serial port and another one to handle the writes. > > > > -----Original Message----- > > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > > Behalf Of Hugo Gonz?lez Monteverde > > Sent: Tuesday, 15 November 2005 7:36 a.m. > > To: nephish > > Cc: tutor > > Subject: Re: [Tutor] question about serial coms > > > > Hi Nephish, > > > > Are you using pyserial or rolling your own? Normally you can write and read to the /dev/ttySXX file at the same time; since they're special files, not ordinary files, the driver handles that. > > > > Handling both writing and reading in your program's flow control is a wholly different matter, though. You might need to use select() to avoid blocking. > > > > Are you using two completely different scripts for reding and writing? > > > > There is some valuable info, if not about python, in the Serial Programming howto, at: > > > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > > > > Hugo > > > > nephish wrote: > > > Hey there, > > > i am developing on a linux computer with the serial module. Now, > > > i already am able to recieve info from a serial RS232 device and > > > process everything ok. What i need to do now is write to the > > > serial device, but i also need to be able to not interrupt the > > > script that is reading from it. > > > I guess my question is, do i have to interrupt the reading script > > > to write to the same RS232 device ? > > > and if so, how do i do that? > > > > > > thanks, > > > shawn > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Nov 14 23:33:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 14 Nov 2005 17:33:01 -0500 Subject: [Tutor] TurboGears - and some issues In-Reply-To: <03d401c5e962$a82522c0$0a01a8c0@xp> References: <1131998474.4471.5.camel@localhost.localdomain> <4378F16E.4010404@tds.net> <03d401c5e962$a82522c0$0a01a8c0@xp> Message-ID: <4379109D.9090006@tds.net> Alan Gauld wrote: >> CheeseShop > > New one on me! CheeseShop is formerly known as PyPI, the Python Package Index. It's a central repository for Python add-ons. http://www.python.org/pypi > If I'm not busy I try to scan c.l.p but mostly its > just too busy. Nonetheless its my primary source of new stuff, its > fairly easy to scroll down lookling for subjects beginning [Ann:] If that's all you want from c.l.p it's easier to subscribe to python-announce and the cheeseshop feed. > > However I have to say I'm pretty conservative when it comes to Python > addons. I don't use many and I only look for them when I have a specific > need. Maybe we should start a thread of favorite addons. For me, Jason Orendorff's path module is definitely #1 on the list, probably followed by Fredrik Lundh's ElementTree. http://www.jorendorff.com/articles/python/path/ http://effbot.org/zone/element-index.htm > I only found the TurboGears stuff because someone asked about > MacOS resources and Apple were highlighting TG on the developer page... > It caught my interest because I'm exploring JSP/Tomcat and Struts just > now for my day job, so anything related to Web frameworks... You have my deepest sympathy :-) Maybe you could use TurboGears instead. Kent From sfhaley at earthlink.net Mon Nov 14 23:56:44 2005 From: sfhaley at earthlink.net (Steve Haley) Date: Mon, 14 Nov 2005 17:56:44 -0500 Subject: [Tutor] Another Quick Question - Thanks again Message-ID: Thanks to all those who responded to my plea regarding how to make my laptop's bell ring with the print "\a" command. The secret turned out to be, as a couple of you suggested, that it won't work in the Python window environment. It works fine if I just double click the .py file in Windows Explorer or use the "Run" command. You live and learn. Thanks again. Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/39bfca1b/attachment.htm From enas_khalil at yahoo.com Tue Nov 15 00:09:23 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Mon, 14 Nov 2005 15:09:23 -0800 (PST) Subject: [Tutor] how to convert between type string and token Message-ID: <20051114230923.42243.qmail@web30505.mail.mud.yahoo.com> hello all when i run the code : # -*- coding: cp1256 -*- from nltk.tagger import * from nltk.corpus import brown from nltk.tokenizer import WhitespaceTokenizer # Tokenize ten texts from the Brown Corpus train_tokens = [] xx=Token(TEXT=open('fataha2.txt').read()) WhitespaceTokenizer().tokenize(xx) for l in xx: train_tokens.append(l) #Initialise and train a unigram tagger mytagger = UnigramTagger(SUBTOKENS='WORDS') for tok in train_tokens: mytagger.train(tok) #Once a UnigramTagger has been trained, the tag() method can be used to tag new text: text_token = Token(TEXT="????? ??? ?? ????????") WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token) mytagger.tag(text_token) print 'The first example : Using Unigram Tagger the reseults are : ' print acc = tagger_accuracy(mytagger, train_tokens) print ' With Accuracy :Accuracy = %4.1f%%,' % (100 * acc) i got the following error : Traceback (most recent call last): File "F:\MSC first Chapters\unigramgtag1.py", line 14, in -toplevel- for tok in train_tokens: mytagger.train(tok) File "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py", line 324, in train assert chktype(1, tagged_token, Token) File "C:\Python24\Lib\site-packages\nltk\chktype.py", line 316, in chktype raise TypeError(errstr) TypeError: Argument 1 to train() must have type: Token (got a str) please i want a help on how to recover this error , in other words how can i convert between type string and token , as im still new in python thanks in advance --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/89f8440e/attachment.html From falcon3166 at hotmail.com Tue Nov 15 00:37:07 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 14 Nov 2005 16:37:07 -0700 Subject: [Tutor] Do I have to initialize TKInter before I can use it? Message-ID: Hey all, Do I have to initialize TKInter before I can use it, and if so, how would I go about doing that? Thanks, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/969609ae/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051114/969609ae/attachment.gif From nephish at xit.net Tue Nov 15 00:40:59 2005 From: nephish at xit.net (nephish) Date: Mon, 14 Nov 2005 17:40:59 -0600 Subject: [Tutor] question about serial coms In-Reply-To: <5667508E43F1B740BCFA57FF46E35300025BFE9D@nav-akl-exch-c.newton.navman.com> References: <5667508E43F1B740BCFA57FF46E35300025BFE9D@nav-akl-exch-c.newton.navman.com> Message-ID: <1132011659.7300.2.camel@bitsbam.localdomain> ok, i think i got it. Thanks so much. let you know how it turns out. shawn On Tue, 2005-11-15 at 11:27 +1300, Hans Dushanthakumar wrote: > Lock() is provided by the threading module. > see > http://docs.python.org/lib/module-threading.html > & > http://docs.python.org/lib/lock-objects.html > > Cheers > Hans > > > -----Original Message----- > From: nephish [mailto:nephish at xit.net] > Sent: Tuesday, 15 November 2005 11:23 a.m. > To: Hans Dushanthakumar > Cc: Hugo Gonz?lez Monteverde; tutor > Subject: RE: [Tutor] question about serial coms > > ok, lock is something you wrote yourself ? > i can't find it in the docs. However, i think i can essentially build the same thing. > the serial module i use is pyserial. pyserial.sourceforge.net. > the docs are a wee bit on the sparce side. But i think i can pull it off. Thanks for your help. > > shawn > > > On Tue, 2005-11-15 at 10:58 +1300, Hans Dushanthakumar wrote: > > I believe that the drivers take care of that, however, I did use locks to make sure that there were no conflicts. > > > > In the listener thread I had something along the lines of: > > > > Acquire lock > > readline() from the ser port > > Release lock > > > > And in the sender thread, > > > > Acquire lock > > send msg over ser port > > Release lock > > > > Cheers > > Hans > > > > -----Original Message----- > > From: nephish [mailto:nephish at xit.net] > > Sent: Tuesday, 15 November 2005 10:47 a.m. > > To: Hans Dushanthakumar > > Cc: Hugo Gonz?lez Monteverde; tutor > > Subject: RE: [Tutor] question about serial coms > > > > well thats encouraging, did you have to do anything special to prevent an error when trying to read or write at the same time ? > > > > thanks > > sk > > > > > > On Tue, 2005-11-15 at 09:29 +1300, Hans Dushanthakumar wrote: > > > Ive worked on a similar application. I used one thread to read from the serial port and another one to handle the writes. > > > > > > -----Original Message----- > > > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On > > > Behalf Of Hugo Gonz?lez Monteverde > > > Sent: Tuesday, 15 November 2005 7:36 a.m. > > > To: nephish > > > Cc: tutor > > > Subject: Re: [Tutor] question about serial coms > > > > > > Hi Nephish, > > > > > > Are you using pyserial or rolling your own? Normally you can write and read to the /dev/ttySXX file at the same time; since they're special files, not ordinary files, the driver handles that. > > > > > > Handling both writing and reading in your program's flow control is a wholly different matter, though. You might need to use select() to avoid blocking. > > > > > > Are you using two completely different scripts for reding and writing? > > > > > > There is some valuable info, if not about python, in the Serial Programming howto, at: > > > > > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > > > > > > > Hugo > > > > > > nephish wrote: > > > > Hey there, > > > > i am developing on a linux computer with the serial module. Now, > > > > i already am able to recieve info from a serial RS232 device and > > > > process everything ok. What i need to do now is write to the > > > > serial device, but i also need to be able to not interrupt the > > > > script that is reading from it. > > > > I guess my question is, do i have to interrupt the reading script > > > > to write to the same RS232 device ? > > > > and if so, how do i do that? > > > > > > > > thanks, > > > > shawn > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > From john at fouhy.net Tue Nov 15 00:41:57 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 15 Nov 2005 12:41:57 +1300 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: References: Message-ID: <5e58f2e40511141541m2eff089bo@mail.gmail.com> On 15/11/05, Nathan Pinno wrote: > > Hey all, > > Do I have to initialize TKInter before I can use it, and if so, how would I > go about doing that? Generally, you need to create a Tkinter.Tk object before you create any other Tkinter objects. Are you having problems? -- John. From royb at ubiquity.com.au Tue Nov 15 00:48:19 2005 From: royb at ubiquity.com.au (Roy Bleasdale) Date: Tue, 15 Nov 2005 10:48:19 +1100 Subject: [Tutor] Converting a List/Tuple to delimited string Message-ID: <5.1.0.14.2.20051115100551.045c8ec0@localhost> Dear John, Thanks for your explanation. It is quite amazing, I had completely misunderstood what the join function was all about. An example in "Learning Python" which was something like "".join(L) , had led me to think it was a string concatenation function that extended the length of a string. Even when reading the manual my prejudice had interpreted the following as still being just that. My subconscious had skipped over the second sentence. "join(seq) Return a string which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method. " Fortunately my new Python instinct suggested what I was doing was not quite right, and thank you for correcting my misunderstanding. This Tutor service is an invaluable help for us lonely new to Python programmers. Thanks, Roy PS Despite this glitch I would still recommend Learning Python. Message: 5 Date: Mon, 14 Nov 2005 17:11:16 +1300 From: John Fouhy Subject: Re: [Tutor] Converting a List/Tuple to delimited string To: Tutor Message-ID: <5e58f2e40511132011i6d371ac1w at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On 14/11/05, Roy Bleasdale wrote: > I have a list of strings and wanted to output them as a single delimited > string. > > Eg > > ('ab','cd','ef') becomes "ab:cd:ef" You almost had it ... What about: >>> lst = ['ab', 'cd', 'ef'] >>> ':'.join(lst) 'ab:cd:ef' In general, foo.join(lst) (where foo is a string) is equivalent to: def join(foo, lst): if not lst: return '' s = lst[0] for item in lst[1:]: s += foo + item return s -- John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051115/e65bf321/attachment.html From boyanpn at yahoo.com Tue Nov 15 01:01:17 2005 From: boyanpn at yahoo.com (Bojan Raicevic) Date: Mon, 14 Nov 2005 16:01:17 -0800 (PST) Subject: [Tutor] How do you read this mailing list ?!? Message-ID: <20051115000117.57917.qmail@web35504.mail.mud.yahoo.com> It's a little confusing for me, are there some special programs for reading mailing lists or you use just basic mail client ? __________________________________ Start your day with Yahoo! - Make it your home page! http://www.yahoo.com/r/hs From lard at tardis.ed.ac.uk Tue Nov 15 01:09:15 2005 From: lard at tardis.ed.ac.uk (Alex Hunsley) Date: Tue, 15 Nov 2005 00:09:15 +0000 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: References: Message-ID: <4379272B.5090602@tardis.ed.ac.uk> Nathan Pinno wrote: > Hey all, > > Do I have to initialize TKInter before I can use it, and if so, how > would I go about doing that? > > Thanks, > Nathan Pinno Btw, your question would be a little more user-friendly if you don't post HTML, and don't post embedded images as well! (Not everyone has an email reader that renders HTML and graphics. And for those people, your email looks like a dogs dinner!) From dyoo at hkn.eecs.berkeley.edu Tue Nov 15 01:20:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Nov 2005 16:20:13 -0800 (PST) Subject: [Tutor] how to convert between type string and token In-Reply-To: <20051114230923.42243.qmail@web30505.mail.mud.yahoo.com> Message-ID: On Mon, 14 Nov 2005, enas khalil wrote: > hello all [program cut] Hi Enas, You may want to try talking with NTLK folks about this, as what you're dealing with is a specialized subject. Also, have you gone through the tokenization tutorial in: http://nltk.sourceforge.net/tutorial/tokenization/nochunks.html#AEN276 and have you tried to compare your program to the ones in the tutorial's examples? Let's look at the error message. > File "F:\MSC first Chapters\unigramgtag1.py", line 14, in -toplevel- > for tok in train_tokens: mytagger.train(tok) > File "C:\Python24\Lib\site-packages\nltk\tagger\__init__.py", line 324, in train > assert chktype(1, tagged_token, Token) > File "C:\Python24\Lib\site-packages\nltk\chktype.py", line 316, in chktype > raise TypeError(errstr) > TypeError: > Argument 1 to train() must have type: Token > (got a str) This error message implies that each element in your train_tokens list is a string and not a token. The 'train_tokens' variable gets its values in the block of code: ########################################### train_tokens = [] xx=Token(TEXT=open('fataha2.txt').read()) WhitespaceTokenizer().tokenize(xx) for l in xx: train_tokens.append(l) ########################################### Ok. I see something suspicious here. The for loop: ###### for l in xx: train_tokens.append(l) ###### assumes that we get tokens from the 'xx' token. Is this true? Are you sure you don't have to specifically say: ###### for l in xx['SUBTOKENS']: ... ###### The example in the tutorial explicitely does something like this to iterate across the subtokens of a token. But what you're doing instead is to iterate across all the property names of a token, which is almost certainly not what you want. From dyoo at hkn.eecs.berkeley.edu Tue Nov 15 01:42:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Nov 2005 16:42:31 -0800 (PST) Subject: [Tutor] how to convert between type string and token In-Reply-To: Message-ID: > Ok. I see something suspicious here. The for loop: > > ###### > for l in xx: > train_tokens.append(l) > ###### > > assumes that we get tokens from the 'xx' token. Is this true? Are you > sure you don't have to specifically say: > > ###### > for l in xx['SUBTOKENS']: > ... > ###### Hi Enas, I'm taking python-list again out of CC: my apologies to the others for not catching that sooner. Enas, please do not crosspost to multiple mailing lists. You have been doing this since at least June: http://mail.python.org/pipermail/python-list/2005-June/287371.html http://mail.python.org/pipermail/tutor/2005-June/039351.html http://mail.python.org/pipermail/tutor/2005-July/039642.html http://mail.python.org/pipermail/python-list/2005-July/289505.html http://mail.python.org/pipermail/tutor/2005-October/042155.html http://mail.python.org/pipermail/python-list/2005-October/303805.html If you crosspost, we at Tutor won't be able to see responses that go to python-list, and visa-versa. The end result clutters both lists and isn't friendly to either community. Please read: http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html and try to change your habits in this area. Anyway, just as a concrete example of this: ###### >>> from nltk.tokenizer import * >>> text_token = Token(TEXT='hello world this is a test') >>> text_token.keys() ['TEXT'] >>> WhitespaceTokenizer().tokenize(text_token) >>> text_token.keys() ['TEXT', 'SUBTOKENS'] >>> text_token['SUBTOKENS'] [, , , , , ] >>> type(text_token['SUBTOKENS'][0]) ###### Do you understand this code, or is there something here that you're not familar with? Good luck to you. From remailer at ka3nam.com Tue Nov 15 02:04:02 2005 From: remailer at ka3nam.com (Bennett, Joe) Date: Mon, 14 Nov 2005 17:04:02 -0800 (PST) Subject: [Tutor] question about serial coms In-Reply-To: <1132011659.7300.2.camel@bitsbam.localdomain> Message-ID: <20051115010402.41689.qmail@web81307.mail.mud.yahoo.com> I have been working with pyserial. One question I have is this. I have a loop that writes to the serial port and then waits about 500ms and then reads from the serial port. The first thing read from the serial port is ALWAYS the data written to the serial port... I must be missing something obvious, but I thuoght the two buffers were separate... Here is the code I'm using if that helps: while i == 0: line = parmfile.readline() line = string.rstrip(line) #print line if line == "": i = 1 break else: ser.write(line + "\r") #ser.write("\r\n") print "Sending: " + line time.sleep(1) data_in = ser.read(100) print "Response: " + data_in time.sleep(.2) print "Closing Serial Port\n" ser.close() -Joe --- nephish wrote: > ok, i think i got it. Thanks so much. > let you know how it turns out. > shawn > > > On Tue, 2005-11-15 at 11:27 +1300, Hans > Dushanthakumar wrote: > > Lock() is provided by the threading module. > > see > > http://docs.python.org/lib/module-threading.html > > & > > http://docs.python.org/lib/lock-objects.html > > > > Cheers > > Hans > > > > > > -----Original Message----- > > From: nephish [mailto:nephish at xit.net] > > Sent: Tuesday, 15 November 2005 11:23 a.m. > > To: Hans Dushanthakumar > > Cc: Hugo Gonz?lez Monteverde; tutor > > Subject: RE: [Tutor] question about serial coms > > > > ok, lock is something you wrote yourself ? > > i can't find it in the docs. However, i think i > can essentially build the same thing. > > the serial module i use is pyserial. > pyserial.sourceforge.net. > > the docs are a wee bit on the sparce side. But i > think i can pull it off. Thanks for your help. > > > > shawn > > > > > > On Tue, 2005-11-15 at 10:58 +1300, Hans > Dushanthakumar wrote: > > > I believe that the drivers take care of that, > however, I did use locks to make sure that there > were no conflicts. > > > > > > In the listener thread I had something along the > lines of: > > > > > > Acquire lock > > > readline() from the ser port > > > Release lock > > > > > > And in the sender thread, > > > > > > Acquire lock > > > send msg over ser port > > > Release lock > > > > > > Cheers > > > Hans > > > > > > -----Original Message----- > > > From: nephish [mailto:nephish at xit.net] > > > Sent: Tuesday, 15 November 2005 10:47 a.m. > > > To: Hans Dushanthakumar > > > Cc: Hugo Gonz?lez Monteverde; tutor > > > Subject: RE: [Tutor] question about serial coms > > > > > > well thats encouraging, did you have to do > anything special to prevent an error when trying to > read or write at the same time ? > > > > > > thanks > > > sk > > > > > > > > > On Tue, 2005-11-15 at 09:29 +1300, Hans > Dushanthakumar wrote: > > > > Ive worked on a similar application. I used > one thread to read from the serial port and another > one to handle the writes. > > > > > > > > -----Original Message----- > > > > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On > > > > Behalf Of Hugo Gonz?lez Monteverde > > > > Sent: Tuesday, 15 November 2005 7:36 a.m. > > > > To: nephish > > > > Cc: tutor > > > > Subject: Re: [Tutor] question about serial > coms > > > > > > > > Hi Nephish, > > > > > > > > Are you using pyserial or rolling your own? > Normally you can write and read to the /dev/ttySXX > file at the same time; since they're special files, > not ordinary files, the driver handles that. > > > > > > > > Handling both writing and reading in your > program's flow control is a wholly different matter, > though. You might need to use select() to avoid > blocking. > > > > > > > > Are you using two completely different scripts > for reding and writing? > > > > > > > > There is some valuable info, if not about > python, in the Serial Programming howto, at: > > > > > > > > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > > > > > > > > > > Hugo > > > > > > > > nephish wrote: > > > > > Hey there, > > > > > i am developing on a linux computer with > the serial module. Now, > > > > > i already am able to recieve info from a > serial RS232 device and > > > > > process everything ok. What i need to do now > is write to the > > > > > serial device, but i also need to be able to > not interrupt the > > > > > script that is reading from it. > > > > > I guess my question is, do i have to > interrupt the reading script > > > > > to write to the same RS232 device ? > > > > > and if so, how do i do that? > > > > > > > > > > thanks, > > > > > shawn > > > > > > > > > > > _______________________________________________ > > > > > Tutor maillist - Tutor at python.org > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nephish at xit.net Tue Nov 15 02:09:32 2005 From: nephish at xit.net (nephish) Date: Mon, 14 Nov 2005 19:09:32 -0600 Subject: [Tutor] question about serial coms In-Reply-To: <20051115010402.41689.qmail@web81307.mail.mud.yahoo.com> References: <20051115010402.41689.qmail@web81307.mail.mud.yahoo.com> Message-ID: <1132016972.7460.0.camel@bitsbam.localdomain> oh yeah, i will need this too! sk On Mon, 2005-11-14 at 17:04 -0800, Bennett, Joe wrote: > I have been working with pyserial. One question I have > is this. I have a loop that writes to the serial port > and then waits about 500ms and then reads from the > serial port. The first thing read from the serial port > is ALWAYS the data written to the serial port... I > must be missing something obvious, but I thuoght the > two buffers were separate... > > Here is the code I'm using if that helps: > > while i == 0: > line = parmfile.readline() > line = string.rstrip(line) > #print line > if line == "": > i = 1 > break > > else: > > ser.write(line + "\r") > #ser.write("\r\n") > print "Sending: " + line > > > > time.sleep(1) > data_in = ser.read(100) > print "Response: " + data_in > time.sleep(.2) > > > print "Closing Serial Port\n" > ser.close() > > > > -Joe > > > --- nephish wrote: > > > ok, i think i got it. Thanks so much. > > let you know how it turns out. > > shawn > > > > > > On Tue, 2005-11-15 at 11:27 +1300, Hans > > Dushanthakumar wrote: > > > Lock() is provided by the threading module. > > > see > > > http://docs.python.org/lib/module-threading.html > > > & > > > http://docs.python.org/lib/lock-objects.html > > > > > > Cheers > > > Hans > > > > > > > > > -----Original Message----- > > > From: nephish [mailto:nephish at xit.net] > > > Sent: Tuesday, 15 November 2005 11:23 a.m. > > > To: Hans Dushanthakumar > > > Cc: Hugo Gonz?lez Monteverde; tutor > > > Subject: RE: [Tutor] question about serial coms > > > > > > ok, lock is something you wrote yourself ? > > > i can't find it in the docs. However, i think i > > can essentially build the same thing. > > > the serial module i use is pyserial. > > pyserial.sourceforge.net. > > > the docs are a wee bit on the sparce side. But i > > think i can pull it off. Thanks for your help. > > > > > > shawn > > > > > > > > > On Tue, 2005-11-15 at 10:58 +1300, Hans > > Dushanthakumar wrote: > > > > I believe that the drivers take care of that, > > however, I did use locks to make sure that there > > were no conflicts. > > > > > > > > In the listener thread I had something along the > > lines of: > > > > > > > > Acquire lock > > > > readline() from the ser port > > > > Release lock > > > > > > > > And in the sender thread, > > > > > > > > Acquire lock > > > > send msg over ser port > > > > Release lock > > > > > > > > Cheers > > > > Hans > > > > > > > > -----Original Message----- > > > > From: nephish [mailto:nephish at xit.net] > > > > Sent: Tuesday, 15 November 2005 10:47 a.m. > > > > To: Hans Dushanthakumar > > > > Cc: Hugo Gonz?lez Monteverde; tutor > > > > Subject: RE: [Tutor] question about serial coms > > > > > > > > well thats encouraging, did you have to do > > anything special to prevent an error when trying to > > read or write at the same time ? > > > > > > > > thanks > > > > sk > > > > > > > > > > > > On Tue, 2005-11-15 at 09:29 +1300, Hans > > Dushanthakumar wrote: > > > > > Ive worked on a similar application. I used > > one thread to read from the serial port and another > > one to handle the writes. > > > > > > > > > > -----Original Message----- > > > > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On > > > > > Behalf Of Hugo Gonz?lez Monteverde > > > > > Sent: Tuesday, 15 November 2005 7:36 a.m. > > > > > To: nephish > > > > > Cc: tutor > > > > > Subject: Re: [Tutor] question about serial > > coms > > > > > > > > > > Hi Nephish, > > > > > > > > > > Are you using pyserial or rolling your own? > > Normally you can write and read to the /dev/ttySXX > > file at the same time; since they're special files, > > not ordinary files, the driver handles that. > > > > > > > > > > Handling both writing and reading in your > > program's flow control is a wholly different matter, > > though. You might need to use select() to avoid > > blocking. > > > > > > > > > > Are you using two completely different scripts > > for reding and writing? > > > > > > > > > > There is some valuable info, if not about > > python, in the Serial Programming howto, at: > > > > > > > > > > > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > > > > > > > > > > > > > Hugo > > > > > > > > > > nephish wrote: > > > > > > Hey there, > > > > > > i am developing on a linux computer with > > the serial module. Now, > > > > > > i already am able to recieve info from a > > serial RS232 device and > > > > > > process everything ok. What i need to do now > > is write to the > > > > > > serial device, but i also need to be able to > > not interrupt the > > > > > > script that is reading from it. > > > > > > I guess my question is, do i have to > > interrupt the reading script > > > > > > to write to the same RS232 device ? > > > > > > and if so, how do i do that? > > > > > > > > > > > > thanks, > > > > > > shawn > > > > > > > > > > > > > > _______________________________________________ > > > > > > Tutor maillist - Tutor at python.org > > > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > _______________________________________________ > > > > > Tutor maillist - Tutor at python.org > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From Hans.Dushanthakumar at navman.com Tue Nov 15 02:25:25 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Tue, 15 Nov 2005 14:25:25 +1300 Subject: [Tutor] question about serial coms Message-ID: <5667508E43F1B740BCFA57FF46E35300026022B8@nav-akl-exch-c.newton.navman.com> Just to make sure that I understood it right, Does this snippet mimic the problem that you have? Ive hardcoded "line". ========x================= import serial import time ser=serial.Serial(0,57600,timeout=0.1) i=0 line = ["Hi","There","Hans"] while i <= (len(line)-1): ser.write(line[i] + "\r") print "Sending: " + line[i] time.sleep(1) data_in = ser.read(100) print "Response: " + data_in time.sleep(.2) i = i + 1 print "Closing Serial Port\n" ser.close() =========x============================= Cheers Hans -----Original Message----- From: nephish [mailto:nephish at xit.net] Sent: Tuesday, 15 November 2005 2:10 p.m. To: remailer at ka3nam.com Cc: Hans Dushanthakumar; tutor Subject: Re: [Tutor] question about serial coms oh yeah, i will need this too! sk On Mon, 2005-11-14 at 17:04 -0800, Bennett, Joe wrote: > I have been working with pyserial. One question I have is this. I have > a loop that writes to the serial port and then waits about 500ms and > then reads from the serial port. The first thing read from the serial > port is ALWAYS the data written to the serial port... I must be > missing something obvious, but I thuoght the two buffers were > separate... > > Here is the code I'm using if that helps: > > while i == 0: > line = parmfile.readline() > line = string.rstrip(line) > #print line > if line == "": > i = 1 > break > > else: > > ser.write(line + "\r") > #ser.write("\r\n") > print "Sending: " + line > > > > time.sleep(1) > data_in = ser.read(100) > print "Response: " + data_in > time.sleep(.2) > > > print "Closing Serial Port\n" > ser.close() > > > > -Joe > > > --- nephish wrote: > > > ok, i think i got it. Thanks so much. > > let you know how it turns out. > > shawn > > > > > > On Tue, 2005-11-15 at 11:27 +1300, Hans Dushanthakumar wrote: > > > Lock() is provided by the threading module. > > > see > > > http://docs.python.org/lib/module-threading.html > > > & > > > http://docs.python.org/lib/lock-objects.html > > > > > > Cheers > > > Hans > > > > > > > > > -----Original Message----- > > > From: nephish [mailto:nephish at xit.net] > > > Sent: Tuesday, 15 November 2005 11:23 a.m. > > > To: Hans Dushanthakumar > > > Cc: Hugo Gonz?lez Monteverde; tutor > > > Subject: RE: [Tutor] question about serial coms > > > > > > ok, lock is something you wrote yourself ? > > > i can't find it in the docs. However, i think i > > can essentially build the same thing. > > > the serial module i use is pyserial. > > pyserial.sourceforge.net. > > > the docs are a wee bit on the sparce side. But i > > think i can pull it off. Thanks for your help. > > > > > > shawn > > > > > > > > > On Tue, 2005-11-15 at 10:58 +1300, Hans > > Dushanthakumar wrote: > > > > I believe that the drivers take care of that, > > however, I did use locks to make sure that there were no conflicts. > > > > > > > > In the listener thread I had something along the > > lines of: > > > > > > > > Acquire lock > > > > readline() from the ser port > > > > Release lock > > > > > > > > And in the sender thread, > > > > > > > > Acquire lock > > > > send msg over ser port > > > > Release lock > > > > > > > > Cheers > > > > Hans > > > > > > > > -----Original Message----- > > > > From: nephish [mailto:nephish at xit.net] > > > > Sent: Tuesday, 15 November 2005 10:47 a.m. > > > > To: Hans Dushanthakumar > > > > Cc: Hugo Gonz?lez Monteverde; tutor > > > > Subject: RE: [Tutor] question about serial coms > > > > > > > > well thats encouraging, did you have to do > > anything special to prevent an error when trying to read or write at > > the same time ? > > > > > > > > thanks > > > > sk > > > > > > > > > > > > On Tue, 2005-11-15 at 09:29 +1300, Hans > > Dushanthakumar wrote: > > > > > Ive worked on a similar application. I used > > one thread to read from the serial port and another one to handle > > the writes. > > > > > > > > > > -----Original Message----- > > > > > From: tutor-bounces at python.org > > [mailto:tutor-bounces at python.org] On > > > > > Behalf Of Hugo Gonz?lez Monteverde > > > > > Sent: Tuesday, 15 November 2005 7:36 a.m. > > > > > To: nephish > > > > > Cc: tutor > > > > > Subject: Re: [Tutor] question about serial > > coms > > > > > > > > > > Hi Nephish, > > > > > > > > > > Are you using pyserial or rolling your own? > > Normally you can write and read to the /dev/ttySXX file at the same > > time; since they're special files, not ordinary files, the driver > > handles that. > > > > > > > > > > Handling both writing and reading in your > > program's flow control is a wholly different matter, though. You > > might need to use select() to avoid blocking. > > > > > > > > > > Are you using two completely different scripts > > for reding and writing? > > > > > > > > > > There is some valuable info, if not about > > python, in the Serial Programming howto, at: > > > > > > > > > > > > http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ > > > > > > > > > > > > > > > Hugo > > > > > > > > > > nephish wrote: > > > > > > Hey there, > > > > > > i am developing on a linux computer with > > the serial module. Now, > > > > > > i already am able to recieve info from a > > serial RS232 device and > > > > > > process everything ok. What i need to do now > > is write to the > > > > > > serial device, but i also need to be able to > > not interrupt the > > > > > > script that is reading from it. > > > > > > I guess my question is, do i have to > > interrupt the reading script > > > > > > to write to the same RS232 device ? > > > > > > and if so, how do i do that? > > > > > > > > > > > > thanks, > > > > > > shawn > > > > > > > > > > > > > > _______________________________________________ > > > > > > Tutor maillist - Tutor at python.org > > > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > _______________________________________________ > > > > > Tutor maillist - Tutor at python.org > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From falcon3166 at hotmail.com Tue Nov 15 02:34:59 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 14 Nov 2005 18:34:59 -0700 Subject: [Tutor] Do I have to initialize TKInter before I can use it? References: Message-ID: John and all, I am having problems. The latest error message I got was: Traceback (most recent call last): File "D:\Python24\hockey.py", line 19, in -toplevel- tkMessageBox.showinfo("Hockey", NameError: name 'tkMessageBox' is not defined What do I have to do in this case? Nathan Pinno Date: Tue, 15 Nov 2005 12:41:57 +1300 From: John Fouhy > Subject: Re: [Tutor] Do I have to initialize TKInter before I can use it? To: Tutor > Message-ID: <5e58f2e40511141541m2eff089bo at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On 15/11/05, Nathan Pinno > wrote: > > Hey all, > > Do I have to initialize TKInter before I can use it, and if so, how would I > go about doing that? Generally, you need to create a Tkinter.Tk object before you create any other Tkinter objects. Are you having problems? -- John. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/335a903f/attachment.html From hugonz-lists at h-lab.net Tue Nov 15 02:50:57 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 19:50:57 -0600 Subject: [Tutor] What does Python gain by having immutable types? In-Reply-To: <017201c52f86$ab38b2b0$93c28651@xp> References: <20050322213503.3FD6A1E4018@bag.python.org> <8249c4ac0503221828789bf59b@mail.gmail.com> <017201c52f86$ab38b2b0$93c28651@xp> Message-ID: <43793F01.3040409@h-lab.net> > Quite often the only answer is "just because". Some features are > the way they are because that's Guido's pesonal preference. Others > may disagree with him but it's his language and he gets to pick > what he thinks is best - the benign dictator syndrome. There's also the issue that immutability is Python's way of dealing with "passing by value" and "passing by reference". And that removing the difference between mutable and immutable objects would mutate (no pun intended) the language in a big way. Hugo From john at fouhy.net Tue Nov 15 02:54:15 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 15 Nov 2005 14:54:15 +1300 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: References: Message-ID: <5e58f2e40511141754r80505dfg@mail.gmail.com> On 15/11/05, Nathan Pinno wrote: > > > John and all, > > I am having problems. The latest error message I got was: > Traceback (most recent call last): > File "D:\Python24\hockey.py", line 19, in -toplevel- > tkMessageBox.showinfo("Hockey", > NameError: name 'tkMessageBox' is not defined > > What do I have to do in this case? This means python doesn't know what a 'tkMessageBox' is. Names get bound to things in python in one of two main ways: 1. You bind the name yourself, usually by using an assignment statement. eg: >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> x = 3 >>> x 3 2. An import statement brings the name in. eg: >>> math Traceback (most recent call last): File "", line 1, in ? NameError: name 'math' is not defined >>> import math >>> math You can also use 'from ... import' to import specific names. >>> sin Traceback (most recent call last): File "", line 1, in ? NameError: name 'sin' is not defined >>> from math import sin >>> sin In your case, you probably want to bring tkMessageBox in using an import statement. I'm guessing you have done 'from Tkinter import *'. You can figure out what names that brings in by using dir: >>> import Tkinter >>> dir(Tkinter) ['ACTIVE', 'ALL', 'ANCHOR', 'ARC', 'At', 'AtEnd', 'AtInsert', 'AtSelFirst', 'AtSelLast', 'BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'BaseWidget', # etc If you look through that list, you will see that tkMessageBox is not there, which means that it is not part of the Tkinter module. Where did you find out about tkMessageBox? Have you looked at any documentation? -- John. From dyoo at hkn.eecs.berkeley.edu Tue Nov 15 03:38:55 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Nov 2005 18:38:55 -0800 (PST) Subject: [Tutor] What does Python gain by having immutable types? In-Reply-To: <43793F01.3040409@h-lab.net> Message-ID: > > Quite often the only answer is "just because". Some features are the > > way they are because that's Guido's pesonal preference. Others may > > disagree with him but it's his language and he gets to pick what he > > thinks is best - the benign dictator syndrome. Hi Hugo, There are a few languages that have immutable values. For example, C and Java both define string literals to be immutable: trying to mutate them causes an error. (Well, C is supposed to raise a segmentation fault.) There are strong advantages to immutability: one of the main ones is that side-effect-less programming is less prone to certain kinds of bugs. For example, let's say we wanted a function to squish values together: ###### >>> def squish(A, B): ... """Creates a new list containing the elements of A and B""" ... result = [] ... result.extend(A) ... result.extend(B) ... return result ... >>> squish(range(5), range(7, 9)) [0, 1, 2, 3, 4, 7, 8] ###### An alternative way to write this might be: ###### >>> def smash(A, B): ... """Creates a new list containing the elements of A and B. ... Smashes the existing list A.""" ... A.extend(B) ... return A ... >>> smash(range(5), range(7, 9)) [0, 1, 2, 3, 4, 7, 8] ###### These both appear to have the same behavior but of course we know that something must be different between the two. *grin* If we have two lists, like: ###### >>> firstNames = ['hugo', 'keanu'] >>> lastNames = ['weaving', 'reeves'] ###### we can squish() them together: ###### >>> squish(firstNames, lastNames) ['hugo', 'keanu', 'weaving', 'reeves'] >>> >>> firstNames ['hugo', 'keanu'] >>> lastNames ['weaving', 'reeves'] ###### ... or we can smash() them: ###### >>> smash(firstNames, lastNames) ['hugo', 'keanu', 'weaving', 'reeves'] >>> >>> firstNames ['hugo', 'keanu', 'weaving', 'reeves'] >>> lastNames ['weaving', 'reeves'] ###### Oh! Notice that smash() messes with the list named by firstNames; when we finish calling it, we see a side effect: firstNames is smashed. The issue here is that we've let ourselves mutate our input values. Of course this is an exaggerated example, but it tries to make a point: having mutable values means we have to think about mutation. Mutation introduces a kind of "leakage" between functions. To make the situation more extreme: if we are working with someone else's code, and if we pass a mutable value to that external code, then if we see a bug later on in our own program, we may have to wonder if the external code mutated our values. That can be a big pain. (C programmers have to worry about this ALL THE TIME because they have pointers that let anyone smash up everything. *grin*) If we guarantee, though, that we are working with immutable values, we can toss them with abandon at anyone and know that they won't get munged. That's why immutability is an important concept in a programming language, and an especially useful one in a collaborative language like Python. Does this make sense? If you have more questions, please feel free to ask. From singingxduck at gmail.com Tue Nov 15 04:11:48 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon, 14 Nov 2005 22:11:48 -0500 Subject: [Tutor] What does Python gain by having immutable types? In-Reply-To: <43793F01.3040409@h-lab.net> References: <20050322213503.3FD6A1E4018@bag.python.org> <8249c4ac0503221828789bf59b@mail.gmail.com> <017201c52f86$ab38b2b0$93c28651@xp> <43793F01.3040409@h-lab.net> Message-ID: <437951F4.5020401@gmail.com> Hugo Gonz?lez Monteverde wrote: >>Quite often the only answer is "just because". Some features are >>the way they are because that's Guido's pesonal preference. Others >>may disagree with him but it's his language and he gets to pick >>what he thinks is best - the benign dictator syndrome. >> >> > >There's also the issue that immutability is Python's way of dealing with > "passing by value" and "passing by reference". And that removing the >difference between mutable and immutable objects would mutate (no pun >intended) the language in a big way. > >Hugo >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > I've also heard the argument that, in the case where you want to be able to hash a sequence, you need an immutable sequence type. Otherwise, when you do something like: >>> dicta = {} >>> tupb = (1,2) >>> tupc = (1,2) >>> dicta[tupb] = "34" >>> tupb.append(3) # raises an AttributeError b/c tuples are immutable and don't have append functions >>> dicta[tupb] = "45" Would you expect dicta[tupb] to produce "34" or "45"? And what of dicta[tupc]? I believe this issue is one of whether to hash by identity or content. When hashing, the implied promise is that all objects whose contents are the same should produce the same value, but one also expects one key to map to one value. Without immutable types, where the identity and the content are intertwined, you get counterintuitive behavior a la the above mini-example (in reality, when you put two immutable objects with the same content in a dictionary, they both map to the same value - the last one assigned). I'm sure someone more knowledgeable will come along and shed the bright light of understanding where my feeble candle flickers, but till then, HTH. -Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From falcon3166 at hotmail.com Tue Nov 15 04:14:20 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 14 Nov 2005 20:14:20 -0700 Subject: [Tutor] How do I display a changing thing in text? Message-ID: How do I display a changing thing (i.e.. the score of the game) in text? I think it has something to do with this key: %, but I forget how to do it. Can someone show me how to do it again? Thanks, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051114/bc1326fb/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 862 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051114/bc1326fb/attachment.gif From hugonz-lists at h-lab.net Tue Nov 15 04:26:56 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 21:26:56 -0600 Subject: [Tutor] How do I display a changing thing in text? In-Reply-To: References: Message-ID: <43795580.8070102@h-lab.net> Hi Nathan, Take a look at string interpolation in the tutorial. I don't know what method you're following for learning Python, but I've found the 'official' tutorial a great resource, even when you already know Python, http://docs.python.org/tut/node9.html#SECTION009100000000000000000 Nathan Pinno wrote: > How do I display a changing thing (i.e.. the score of the game) in text? > I think it has something to do with this key: %, but I forget how to do > it. Can someone show me how to do it again? > > Thanks, > Nathan Pinno > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From remailer at ka3nam.com Tue Nov 15 04:43:01 2005 From: remailer at ka3nam.com (Bennett, Joe) Date: Mon, 14 Nov 2005 19:43:01 -0800 (PST) Subject: [Tutor] question about serial coms In-Reply-To: <5667508E43F1B740BCFA57FF46E35300026022B8@nav-akl-exch-c.newton.navman.com> Message-ID: <20051115034301.84506.qmail@web81310.mail.mud.yahoo.com> I think so, what I'm doing is opening a text file, reading line 1 and writing that text to the serial port. Then read line 2 and so on... So it mimics a string rather than a list or dictionary. But I would think this would give you a similiar result. I can try it to confirm. Here is the entire code: import serial import string import time parmfile = open('command_1.txt') ser = serial.Serial('/dev/ttyS1', 9600, timeout=1) ser.setRTS(1) ser.setDTR(1) i = 0 while i == 0: line = parmfile.readline() line = string.rstrip(line) #print line if line == "": i = 1 break else: ser.write(line + "\r") #ser.write("\r\n") print "Sending: " + line time.sleep(1) data_in = ser.read(100) print "Response: " + data_in time.sleep(.2) print "Closing Serial Port\n" ser.close() The 'command_1.txt' file is literally a text file with lines of text like such: command1 on command2 off command3 %4 command5 on etc.... -Joe --- Hans Dushanthakumar wrote: > Just to make sure that I understood it right, > > Does this snippet mimic the problem that you have? > Ive hardcoded "line". > > ========x================= > import serial > import time > ser=serial.Serial(0,57600,timeout=0.1) > i=0 > line = ["Hi","There","Hans"] > while i <= (len(line)-1): > > ser.write(line[i] + "\r") > print "Sending: " + line[i] > time.sleep(1) > data_in = ser.read(100) > print "Response: " + data_in > time.sleep(.2) > i = i + 1 > > print "Closing Serial Port\n" > ser.close() > =========x============================= > > Cheers > Hans From hugonz-lists at h-lab.net Tue Nov 15 04:45:14 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 21:45:14 -0600 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: References: Message-ID: <437959CA.6060700@h-lab.net> Hi Nathan, It is always better if you include what you're actually trying to do. I see you included one traceback error, but I see no reference to what you're coding or any of your code. In your case , it's likely that you did not import the tkMessageDialog module or something like this. But we had to find that out after two more posts, because neither your code example or error messages were in the original. Please, please read: http://www.catb.org/~esr/faqs/smart-questions.html Keep hacking away :) Hugo From falcon3166 at hotmail.com Tue Nov 15 04:48:56 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 14 Nov 2005 20:48:56 -0700 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: Message-ID: John, I learned it from the docs on pythonware.com - the introduction to TKInter - Standard Dialogs. Since it doesn't exist, how can I show a info box before the main part of my program? Nathan Date: Tue, 15 Nov 2005 14:54:15 +1300 From: John Fouhy Subject: Re: [Tutor] Do I have to initialize TKInter before I can use it? To: Tutor Message-ID: <5e58f2e40511141754r80505dfg at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On 15/11/05, Nathan Pinno wrote: > > > John and all, > > I am having problems. The latest error message I got was: > Traceback (most recent call last): > File "D:\Python24\hockey.py", line 19, in -toplevel- > tkMessageBox.showinfo("Hockey", > NameError: name 'tkMessageBox' is not defined > > What do I have to do in this case? This means python doesn't know what a 'tkMessageBox' is. Names get bound to things in python in one of two main ways: 1. You bind the name yourself, usually by using an assignment statement. eg: >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> x = 3 >>> x 3 2. An import statement brings the name in. eg: >>> math Traceback (most recent call last): File "", line 1, in ? NameError: name 'math' is not defined >>> import math >>> math You can also use 'from ... import' to import specific names. >>> sin Traceback (most recent call last): File "", line 1, in ? NameError: name 'sin' is not defined >>> from math import sin >>> sin In your case, you probably want to bring tkMessageBox in using an import statement. I'm guessing you have done 'from Tkinter import *'. You can figure out what names that brings in by using dir: >>> import Tkinter >>> dir(Tkinter) ['ACTIVE', 'ALL', 'ANCHOR', 'ARC', 'At', 'AtEnd', 'AtInsert', 'AtSelFirst', 'AtSelLast', 'BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'BaseWidget', # etc If you look through that list, you will see that tkMessageBox is not there, which means that it is not part of the Tkinter module. Where did you find out about tkMessageBox? Have you looked at any documentation? -- John. From hugonz-lists at h-lab.net Tue Nov 15 04:51:40 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 21:51:40 -0600 Subject: [Tutor] saving project In-Reply-To: <4384922E.6050405@kebikec.net> References: <4384922E.6050405@kebikec.net> Message-ID: <43795B4C.6060605@h-lab.net> If you do File... Save Then select the location for your file and just give it a name, a '.py' extension will be added to the file. It is not in a specific format, it is just a text file with a '.py' extension. From Explorer you will likely see just the name of the file. And after you save you'll see the coloring on your program, which helps you avoid programming mistakes. I'm assuming you're using Windows and not Linux. Hugo sener wrote: > hi everyone, > > Firstly I am a new programmer on python. I am using Python 2.4.1 > with IDLE 1.1.1 > I can't save my poject in my computer. how can I save my projects and > in which format I must save my projects. > > thanks a lot. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john at fouhy.net Tue Nov 15 04:53:14 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 15 Nov 2005 16:53:14 +1300 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: References: Message-ID: <5e58f2e40511141953u1706ffeel@mail.gmail.com> On 15/11/05, Nathan Pinno wrote: > John, > > I learned it from the docs on pythonware.com - the introduction to TKInter - > Standard Dialogs. > Since it doesn't exist, how can I show a info box before the main part of my > program? Ok, let's see what the pythonware docs say: http://www.pythonware.com/library/tkinter/introduction/standard-dialogs.htm """ Message Boxes The tkMessageBox module provides an interface to the message dialogs. """ This says that tkMessageBox is a module. How do you normally use modules? -- John. From hugonz-lists at h-lab.net Tue Nov 15 04:55:26 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 21:55:26 -0600 Subject: [Tutor] What does Python gain by having immutable types? In-Reply-To: <437951F4.5020401@gmail.com> References: <20050322213503.3FD6A1E4018@bag.python.org> <8249c4ac0503221828789bf59b@mail.gmail.com> <017201c52f86$ab38b2b0$93c28651@xp> <43793F01.3040409@h-lab.net> <437951F4.5020401@gmail.com> Message-ID: <43795C2E.5000909@h-lab.net> I believe the deal is that it is impossible (or at least extremely inefficient)to keep track of any places where a mutable object was hashed at the time of mutating it, so that ALL hashes can be updated. When the object is immutable, it implies that the hash will not change unless the id changes. Hugo > Would you expect dicta[tupb] to produce "34" or "45"? And what of > dicta[tupc]? I believe this issue is one of whether to hash by identity > or content. When hashing, the implied promise is that all objects whose > contents are the same should produce the same value, but one also > expects one key to map to one value. Without immutable types, where the > identity and the content are intertwined, you get counterintuitive > behavior a la the above mini-example (in reality, when you put two > immutable objects with the same content in a dictionary, they both map > to the same value - the last one assigned). I'm sure someone more > knowledgeable will come along and shed the bright light of understanding > where my feeble candle flickers, but till then, HTH. > > -Orri > From falcon3166 at hotmail.com Tue Nov 15 04:55:53 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 14 Nov 2005 20:55:53 -0700 Subject: [Tutor] How do I display a changing thing in text? In-Reply-To: <43795580.8070102@h-lab.net> Message-ID: Hugo and all, So in order to write what I wanted the correct code would be: "Computer = %1.0d Player = %1.0d" (a,b) Am I correct or is this wrong? Nathan Pinno -----Original Message----- From: Hugo Gonz?lez Monteverde [mailto:hugonz-lists at h-lab.net] Sent: November 14, 2005 8:27 PM To: Nathan Pinno Cc: Tutor mailing list Subject: Re: [Tutor] How do I display a changing thing in text? Hi Nathan, Take a look at string interpolation in the tutorial. I don't know what method you're following for learning Python, but I've found the 'official' tutorial a great resource, even when you already know Python, http://docs.python.org/tut/node9.html#SECTION009100000000000000000 Nathan Pinno wrote: > How do I display a changing thing (i.e.. the score of the game) in text? > I think it has something to do with this key: %, but I forget how to > do it. Can someone show me how to do it again? > > Thanks, > Nathan Pinno > > > ---------------------------------------------------------------------- > -- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hugonz-lists at h-lab.net Tue Nov 15 05:01:01 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 22:01:01 -0600 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: References: Message-ID: <43795D7D.5090000@h-lab.net> Hi Nathan, The interactive interpreter is your friend. I just displayed a simple dialog without creating a Tkinter App, complete with a mailoop or anything. But I won't tell you how... you need to import the module and then use one of its functions. But you need to try it yourself (be aware that this module only gives you basic dialogs, like a text message ona little window with an 'Accept' button...) Remember that you can use the dir() function and the help() function on the interactive interpreter. Hugo Nathan Pinno wrote: > John, > > I learned it from the docs on pythonware.com - the introduction to TKInter - > Standard Dialogs. > Since it doesn't exist, how can I show a info box before the main part of my > program? > \ From hugonz-lists at h-lab.net Tue Nov 15 05:05:06 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 14 Nov 2005 22:05:06 -0600 Subject: [Tutor] How do I display a changing thing in text? In-Reply-To: References: Message-ID: <43795E72.6020400@h-lab.net> The interactive intepreter is you friend. Of course I'm using actual numbers instead of variables for the examples. Let's see IDLE 1.0.3 >>> "Computer = %1.0d Player = %1.0d" (1,2) Traceback (most recent call last): File "", line 1, in -toplevel- "Computer = %1.0d Player = %1.0d" (1,2) TypeError: 'str' object is not callable HMMMM what is the problem? >>> "Computer = %1.0d Player = %1.0d"%(1,2) 'Computer = 1 Player = 2' >>> Here you go. You were missing the % sign after the string, with in this case is the operator... Hugo Nathan Pinno wrote: > Hugo and all, > So in order to write what I wanted the correct code would be: > "Computer = %1.0d Player = %1.0d" (a,b) > > Am I correct or is this wrong? > > Nathan Pinno > > -----Original Message----- > From: Hugo Gonz?lez Monteverde [mailto:hugonz-lists at h-lab.net] > Sent: November 14, 2005 8:27 PM > To: Nathan Pinno > Cc: Tutor mailing list > Subject: Re: [Tutor] How do I display a changing thing in text? > > Hi Nathan, > > Take a look at string interpolation in the tutorial. I don't know what > method you're following for learning Python, but I've found the 'official' > tutorial a great resource, even when you already know Python, > > http://docs.python.org/tut/node9.html#SECTION009100000000000000000 > > Nathan Pinno wrote: > >>How do I display a changing thing (i.e.. the score of the game) in text? >>I think it has something to do with this key: %, but I forget how to >>do it. Can someone show me how to do it again? >> >>Thanks, >>Nathan Pinno >> >> >>---------------------------------------------------------------------- >>-- >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at freenet.co.uk Tue Nov 15 05:24:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Nov 2005 04:24:27 -0000 Subject: [Tutor] Do I have to initialize TKInter before I can use it? References: Message-ID: <043a01c5e99c$77716fa0$0a01a8c0@xp> > Do I have to initialize TKInter before I can use it, and if so, how would > I > go about doing that? Yes, by calling Tk() Alan G. From alan.gauld at freenet.co.uk Tue Nov 15 05:34:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Nov 2005 04:34:56 -0000 Subject: [Tutor] Do I have to initialize TKInter before I can use it? References: Message-ID: <046401c5e99d$ee8e5610$0a01a8c0@xp> Nathan, > I am having problems. The latest error message I got was: > tkMessageBox.showinfo("Hockey", > NameError: name 'tkMessageBox' is not defined A NameError means Python doesn't recognise the name. Usually that's because either you didn't declare the variable or you forgot to import the module or you spelled it wrong. In this case I'd guess you forgot the import? Python error messages are really quite helpful if you just stop and think about what they are saying for a few minutes. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Nov 15 05:30:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Nov 2005 04:30:46 -0000 Subject: [Tutor] How do you read this mailing list ?!? References: <20051115000117.57917.qmail@web35504.mail.mud.yahoo.com> Message-ID: <044f01c5e99d$59901800$0a01a8c0@xp> > It's a little confusing for me, are there some special > programs for reading mailing lists or you use just > basic mail client ? Interesting question! The list comes in many flavours. The most basic form you just subscribe and it sends you emails which you read using your normal email client. Then you can set up digest delivery - which I use - where the list sends you the messages in bunches as a single email. YOu still use the basic client to read them but uyou have to open the digest message then open the inner messages from there. The list is also available as an archive on the web at both ActiveState and on the Python.org web sites. YOu can use a browser to read it there. And lastly gane make it available as a news feed (and web site) which you can access via any newsreader -I tend to use this when away from my PC. So your simple question has maby answers, choose whichever one you like! :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Nov 15 05:37:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 15 Nov 2005 04:37:19 -0000 Subject: [Tutor] How do I display a changing thing in text? References: Message-ID: <047001c5e99e$43c6be10$0a01a8c0@xp> > How do I display a changing thing (i.e.. the score of the game) in text? I > think it has something to do with this key: %, but I forget how to do it. > Can someone show me how to do it again? Take a look at the Simple Sequences page on my tutor for examples of using the % format string operatrion. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Tue Nov 15 05:42:32 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 14 Nov 2005 21:42:32 -0700 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: <046401c5e99d$ee8e5610$0a01a8c0@xp> Message-ID: Alan and all, I imported it, but its not there. I tried using the Message one found in it, but I got an error message: >>> import Tkinter >>> tk = Tkinter.Tk() >>> Tkinter.Message("Help","Help!") Traceback (most recent call last): File "", line 1, in -toplevel- Tkinter.Message("Help","Help!") File "D:\Python24\lib\lib-tk\Tkinter.py", line 2640, in __init__ Widget.__init__(self, master, 'message', cnf, kw) File "D:\Python24\lib\lib-tk\Tkinter.py", line 1862, in __init__ BaseWidget._setup(self, master, cnf) File "D:\Python24\lib\lib-tk\Tkinter.py", line 1840, in _setup self.tk = master.tk AttributeError: 'str' object has no attribute 'tk' What does this mean, and how can I get it working? Nathan -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: November 14, 2005 9:35 PM To: Nathan Pinno; Tutor Mailing List Subject: Re: [Tutor] Do I have to initialize TKInter before I can use it? Nathan, > I am having problems. The latest error message I got was: > tkMessageBox.showinfo("Hockey", > NameError: name 'tkMessageBox' is not defined A NameError means Python doesn't recognise the name. Usually that's because either you didn't declare the variable or you forgot to import the module or you spelled it wrong. In this case I'd guess you forgot the import? Python error messages are really quite helpful if you just stop and think about what they are saying for a few minutes. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ismaelgf at adinet.com.uy Tue Nov 15 05:55:29 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Tue, 15 Nov 2005 02:55:29 -0200 Subject: [Tutor] Favourite modules - Wiki Was Re: TurboGears - and some issues In-Reply-To: <4379109D.9090006@tds.net> References: <1131998474.4471.5.camel@localhost.localdomain> <4378F16E.4010404@tds.net> <03d401c5e962$a82522c0$0a01a8c0@xp> <4379109D.9090006@tds.net> Message-ID: <43796A41.5040206@adinet.com.uy> Kent Johnson wrote: >Maybe we should start a thread of favorite addons. For me, Jason Orendorff's path module is definitely #1 on the list, probably followed by Fredrik Lundh's ElementTree. >http://www.jorendorff.com/articles/python/path/ >http://effbot.org/zone/element-index.htm > > A wonderful idea! I have created a wiki page in Python.org with a list of such 'favourite' modules. Please take a look: http://wiki.python.org/moin/UsefulModules I put some of the modules I could remember being praised here. I hope I didn't miss any (well, save for web frameworks, I haven't been paying much attention) I hope I haven't made a mess, it was my first edit into python's wiki. I wasn't sure where to stick it, so I added it under DevelopmentTools. I hope the page helps somebody! (Today I'm "hopey" :) Bye, Ismael From dyoo at hkn.eecs.berkeley.edu Tue Nov 15 06:23:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 14 Nov 2005 21:23:33 -0800 (PST) Subject: [Tutor] How to learn to read error messages and generalize from examples [Was Re: Do I have to initialize TKInter before I can use it?] In-Reply-To: Message-ID: On Mon, 14 Nov 2005, Nathan Pinno wrote: > Alan and all, > > I imported it, but its not there. I tried using the Message one found in it, > but I got an error message: > >>> import Tkinter > >>> tk = Tkinter.Tk() > >>> Tkinter.Message("Help","Help!") Hi Nathan, According to the traceback: > Traceback (most recent call last): > File "", line 1, in -toplevel- > Tkinter.Message("Help","Help!") > File "D:\Python24\lib\lib-tk\Tkinter.py", line 2640, in __init__ > Widget.__init__(self, master, 'message', cnf, kw) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 1862, in __init__ > BaseWidget._setup(self, master, cnf) > File "D:\Python24\lib\lib-tk\Tkinter.py", line 1840, in _setup > self.tk = master.tk > AttributeError: 'str' object has no attribute 'tk' our program gets stuck on the line: Tkinter.Message("Help","Help!") If we assume that the rest of the traceback comes from the internals of Tkinter, and that those parts are fine, let's start off by assuming that there might be something on our own program's line that causes the bug. Our assumption might be wrong, but let's see how far this goes --- we have to start somewhere. What is that call to Tkinter.Message()? It's a call to make a Message widget. What arguments do we need to pass when we make such a thing? If we don't know this offhand --- and that's fine; that's what references are for --- then we can look at an example, like the one at: http://www.pythonware.com/library/tkinter/introduction/x59-details.htm The tutorial example makes a Label widget: from Tkinter import * root = Tk() w = Label(root, text="Hello, world!") We see that a Label widget needs the root window object as well as whatever configuration options we pass to customize that Label widget. Going back to our buggy code: Tkinter.Message("Help","Help!") can we think of what you might do to make this similar to the example in the tutorial? Where's the root object? What option are we trying to customize? Labels and Messages are similar enough that we can make analogies from the tutorial example to our program. You may find the detail pages for Labels and Messages useful: http://www.pythonware.com/library/tkinter/introduction/x5258-options.htm http://www.pythonware.com/library/tkinter/introduction/x6315-options.htm Good luck to you! From tvbare at socket.net Tue Nov 15 06:52:50 2005 From: tvbare at socket.net (->Terry<-) Date: Mon, 14 Nov 2005 23:52:50 -0600 (CST) Subject: [Tutor] Looking for suggestions - update In-Reply-To: <437870AD.9000504@tds.net> References: <437870AD.9000504@tds.net> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Today (Nov 14, 2005) at 6:10am, Kent Johnson spoke these wise words: - ->A couple of notes after a quick look: - -> - ->- As you note, def check_valid_jump(sel1, sel2) is really ugly. When I have code like this I look for a way to drive it from a table instead of a bunch of if/elif statements full of magic numbers. In this case it looks like you have one condition for each state. The conditions and results could be put in a list whose index is the state and whose values are the test values for sel1 and sel2. You would have a table that looks like this: - ->jump_table = [ - -> (1, 1, 4, 2), # (state # sel1 and sel2 values to check for state, return value) - -> (2, 1, 6, 3), - -> # etc for all the tests Thanks for the reply Kent and others. I've made some changes and the game is quite playable now. I've put the new version online at the same links if anyone wants to take a look. I agree with what someone else posted about earlier. This list is a great resource and is really appreciated. Cheers, - -- Terry "Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind." -- Dr. Seuss -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFDeXe6QvSnsfFzkV0RAlPEAJ4kPDDjXZZZyl0TJqbY5NCoReYlYACeKGW7 su+ZjZQeOyaFBvh67d6i6eU= =+qXo -----END PGP SIGNATURE----- From kent37 at tds.net Tue Nov 15 12:08:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Nov 2005 06:08:59 -0500 Subject: [Tutor] Looking for suggestions - update In-Reply-To: References: <437870AD.9000504@tds.net> Message-ID: <4379C1CB.3090404@tds.net> ->Terry<- wrote: > Thanks for the reply Kent and others. I've made some > changes and the game is quite playable now. I've put > the new version online at the same links if anyone > wants to take a look. A few more ideas: - I think you missed my earlier suggestion about simplifying get_button(). - You have the same code in two places to initialize the board. Code duplication is a strong "code smell" and it's generally a good idea to eliminate it. In this case it would be easy to make a function to initialize the board and call it in two places. The function can return the new board which you can then assign to the state variable. - I think the program would benefit from having a Button class. Buttons have several different states and behaviours which could all be bundled into a class. The state of a button includes its location and whether it has a peg in it. The behaviours of a Button are draw, add or remove a peg, and hit testing. If you make this change I would expect that peg_coords and state would both be replaced by a list of Buttons. get_button() would look like this: def get_button(click): for button in buttons: if click in button: return button redraw_screen() would become def redraw_screen(): screen.blit(board, (0, 0)) # Draw board for button in buttons: button.draw(screen) pygame.display.update() return Kent From python at venix.com Tue Nov 15 13:56:45 2005 From: python at venix.com (Python) Date: Tue, 15 Nov 2005 07:56:45 -0500 Subject: [Tutor] question about serial coms In-Reply-To: <20051115010402.41689.qmail@web81307.mail.mud.yahoo.com> References: <20051115010402.41689.qmail@web81307.mail.mud.yahoo.com> Message-ID: <1132059405.22934.200.camel@www.venix.com> The device at the far end of the serial connection is echoing what you write back to you. This is a convenience for someone typing at a terminal, but a nuisance when you are programming. The easier way out is to turn echoing off at the far device. Failing that, you will want to provide a copy of your output to the read routine so that it can filter your output out of the data stream coming back to you. Unfortunately there is no reliable error detection on a serial line, so line errors can complicate the task of matching the echoes to your output. On Mon, 2005-11-14 at 17:04 -0800, Bennett, Joe wrote: > I have been working with pyserial. One question I have > is this. I have a loop that writes to the serial port > and then waits about 500ms and then reads from the > serial port. The first thing read from the serial port > is ALWAYS the data written to the serial port... I > must be missing something obvious, but I thuoght the > two buffers were separate... (snipped) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From RPhillips at engineer.co.summit.oh.us Tue Nov 15 14:33:51 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Tue, 15 Nov 2005 08:33:51 -0500 Subject: [Tutor] Favourite modules - Wiki Was Re: TurboGears - and some issues Message-ID: >>> Ismael Garrido 11/14/2005 11:55 PM >>> Kent Johnson wrote: >Maybe we should start a thread of favorite addons. For me, Jason Orendorff's path module is definitely #1 on the list, probably followed by Fredrik Lundh's ElementTree. > http://www.jorendorff.com/articles/python/path/ > http://effbot.org/zone/element-index.htm > > A wonderful idea! I have created a wiki page in Python.org with a list of such 'favourite' modules. Please take a look: http://wiki.python.org/moin/UsefulModules I put some of the modules I could remember being praised here. I hope I didn't miss any (well, save for web frameworks, I haven't been paying much attention) I hope I haven't made a mess, it was my first edit into python's wiki. I wasn't sure where to stick it, so I added it under DevelopmentTools. I hope the page helps somebody! (Today I'm "hopey" :) Bye, Ismael +++++++++++++++++++++++++++++++++++++++ That is a good idea, and a nice page. Another would be to implement some "social tagging" as on del.icio.us. It's kind of a popularity contest, but that's really what's wanted here, I think. OTOH, the wiki is probably the first place anyone would look, and I saw most of the modules I already use, and I learned about a couple that look very promising. One that I use a lot is Amara (http://uche.ogbuji.net/tech/4suite/amara/manual) for making xml more pythonic. Not to take anything away from ElementTree, it's a fine package; but I find Amara easier to use. Some others that seem 'missing': PIL and NumPy. I didn't try to put it on the wiki page because I wanted the tutors to have a chance to comment first. Anyway, thanks for the page. I have it bookmarked! Ron From alberto.troiano at gmail.com Tue Nov 15 16:51:15 2005 From: alberto.troiano at gmail.com (Alberto Troiano) Date: Tue, 15 Nov 2005 11:51:15 -0400 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: Message-ID: Hey Nathan I think this is what you are looking for ####Code Below#### from Tkinter import * import tkMessageBox tkMessageBox._show("Windows Title","This is the description",icon=tkMessageBox.INFO,type=tkMessageBox.OK) ###End of Code#### Regards Alberto -----Mensaje original----- De: tutor-bounces at python.org [mailto:tutor-bounces at python.org] En nombre de Nathan Pinno Enviado el: Martes, 15 de Noviembre de 2005 00:43 Para: 'Alan Gauld'; 'Tutor Mailing List' Asunto: Re: [Tutor] Do I have to initialize TKInter before I can use it? Alan and all, I imported it, but its not there. I tried using the Message one found in it, but I got an error message: >>> import Tkinter >>> tk = Tkinter.Tk() >>> Tkinter.Message("Help","Help!") Traceback (most recent call last): File "", line 1, in -toplevel- Tkinter.Message("Help","Help!") File "D:\Python24\lib\lib-tk\Tkinter.py", line 2640, in __init__ Widget.__init__(self, master, 'message', cnf, kw) File "D:\Python24\lib\lib-tk\Tkinter.py", line 1862, in __init__ BaseWidget._setup(self, master, cnf) File "D:\Python24\lib\lib-tk\Tkinter.py", line 1840, in _setup self.tk = master.tk AttributeError: 'str' object has no attribute 'tk' What does this mean, and how can I get it working? Nathan -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: November 14, 2005 9:35 PM To: Nathan Pinno; Tutor Mailing List Subject: Re: [Tutor] Do I have to initialize TKInter before I can use it? Nathan, > I am having problems. The latest error message I got was: > tkMessageBox.showinfo("Hockey", > NameError: name 'tkMessageBox' is not defined A NameError means Python doesn't recognise the name. Usually that's because either you didn't declare the variable or you forgot to import the module or you spelled it wrong. In this case I'd guess you forgot the import? Python error messages are really quite helpful if you just stop and think about what they are saying for a few minutes. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From K.Weinert at gmx.net Tue Nov 15 17:03:24 2005 From: K.Weinert at gmx.net (K.Weinert@gmx.net) Date: Tue, 15 Nov 2005 17:03:24 +0100 (MET) Subject: [Tutor] tkFileDialog.Directory Message-ID: <30280.1132070604@www39.gmx.net> Hello! Michael Lange wrote: > I guess the tkFileDialog.Directory class isn't intended to be used directly. > Try tkFileDialog.askdirectory() instead. > If there are problems with the grab state, try passing "parent=self.top" to askdirectory(). That did it! Thanks a lot! I would like to ask another question. I don't understand the exception mechanism of Python when running a Tkinter app. If an exception happens (it does happen quite often at the moment..), a traceback is written to the console while the Tk window remains open and the application is still running. This is not what I expected -- I expected the application would end. Why is that? Is there a way to create an error handler for uncaught exceptions in Tkinter apps? In other words, can I change the behaviour from writing a traceback to the console to something else? Can I, for example, show a message box instead? Here is a small example: --- snip --- import Tix def raise_exception(): print 1/0 if __name__ == '__main__': root = Tix.Tk() root.title("Exception demo") Tix.Button(root, text = "Don't press", command = raise_exception).pack() try: root.mainloop() except: print "An error has occured." --- snip --- The except part gets never executed. Kind regards, Karsten. -- Telefonieren Sie schon oder sparen Sie noch? NEU: GMX Phone_Flat http://www.gmx.net/de/go/telefonie From python at venix.com Tue Nov 15 17:22:30 2005 From: python at venix.com (Python) Date: Tue, 15 Nov 2005 11:22:30 -0500 Subject: [Tutor] [Fwd: Re: question about serial coms] Message-ID: <1132071750.22934.224.camel@www.venix.com> (Forwarding to the list.) -- Lloyd Kvam Venix Corp -------------- next part -------------- An embedded message was scrubbed... From: "Bennett, Joe" Subject: Re: [Tutor] question about serial coms Date: Tue, 15 Nov 2005 07:51:46 -0800 (PST) Size: 2565 Url: http://mail.python.org/pipermail/tutor/attachments/20051115/304dc29f/attachment.mht From ismaelgf at adinet.com.uy Tue Nov 15 17:30:31 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Tue, 15 Nov 2005 14:30:31 -0200 Subject: [Tutor] Favourite modules - Wiki Was Re: TurboGears - and some issues In-Reply-To: References: Message-ID: <437A0D27.6050008@adinet.com.uy> Ron Phillips wrote: >That is a good idea, and a nice page. Another would be to implement >some "social tagging" as on del.icio.us. It's kind of a popularity >contest, but that's really what's wanted here, I think. > I believe the guys at PyPI were trying to do something similar. They're trying to measure the "pythoness" of modules. I'm hoping this list to become more about helping find the favourite modules. Like, if you got to process XML, what's the first module that comes to your mind? (ElementTree or Amara, but surely not the SAX/DOM parsers that Python has in the Std library) > OTOH, the wiki >is probably the first place anyone would look, and I saw most of the >modules I already use, and I learned about a couple that look very >promising. > >One that I use a lot is Amara >(http://uche.ogbuji.net/tech/4suite/amara/manual) for making xml more >pythonic. > I added it to the list. Looks very promising. >Not to take anything away from ElementTree, it's a fine >package; but I find Amara easier to use. Some others that seem >'missing': PIL and NumPy. > Added PIL. Not sure about NumPy... How's the deal between SciPy and NumPy? Isn't one part of the other? >Anyway, thanks for the page. I have it bookmarked! > > Glad you liked it :) Ismael From tvbare at socket.net Tue Nov 15 18:31:32 2005 From: tvbare at socket.net (->Terry<-) Date: Tue, 15 Nov 2005 11:31:32 -0600 (CST) Subject: [Tutor] Looking for suggestions - update In-Reply-To: <4379C1CB.3090404@tds.net> References: <437870AD.9000504@tds.net> <4379C1CB.3090404@tds.net> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Today (Nov 15, 2005) at 6:08am, Kent Johnson spoke these wise words: - ->->Terry<- wrote: - ->> Thanks for the reply Kent and others. I've made some - ->> changes and the game is quite playable now. I've put - ->> the new version online at the same links if anyone - ->> wants to take a look. - -> - ->A few more ideas: - -> - ->- I think you missed my earlier suggestion about simplifying get_button(). I tried your suggestion for changing get_button() and changed it to: def get_button(click): # What peg was clicked? for i, peg in peg_coords: if click in peg: return i + 1 return 0 but got this error. Traceback (most recent call last): File "test.py", line 120, in ? sel1 = check_valid_start() # Verify valid start File "test.py", line 40, in check_valid_start but = get_button([x, y]) # Determine which peg position 1-15 File "test.py", line 60, in get_button for i, peg in peg_coords: ValueError: too many values to unpack So I changed it back for now with plans to take a closer look again later. - ->- You have the same code in two places to initialize the board. Code duplication is a strong "code smell" and it's generally a good idea to eliminate it. In this case it would be easy to make a function to initialize the board and call it in two places. The function can return the new board which you can then assign to the state variable. Agreed. - ->- I think the program would benefit from having a Button class. Buttons have several different states and behaviours which could all be bundled into a class. The state of a button includes its location and whether it has a peg in it. The behaviours of a Button are draw, add or remove a peg, and hit testing. - -> - ->If you make this change I would expect that peg_coords and state would both be replaced by a list of Buttons. get_button() would look like this: - -> - ->def get_button(click): - -> for button in buttons: - -> if click in button: - -> return button - -> - ->redraw_screen() would become - -> - ->def redraw_screen(): - -> screen.blit(board, (0, 0)) # Draw board - -> for button in buttons: - -> button.draw(screen) - -> pygame.display.update() - -> return - -> - ->Kent Great! Thanks again for your suggestions and the link. Time to do more reading. There is so much to learn, but I'm gaining more confidence as I go. Have a good day! - -- Terry "Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind." -- Dr. Seuss -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFDeht5QvSnsfFzkV0RArnoAJ9UufSi0F0kO+Nup5siQmeMK3FYKQCfbivF 0hGFSAiEeiZOZ40bV35k7dY= =NDW8 -----END PGP SIGNATURE----- From klappnase at freenet.de Tue Nov 15 19:06:38 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 15 Nov 2005 19:06:38 +0100 Subject: [Tutor] tkFileDialog.Directory In-Reply-To: <30280.1132070604@www39.gmx.net> References: <30280.1132070604@www39.gmx.net> Message-ID: <20051115190638.41f3988a.klappnase@freenet.de> On Tue, 15 Nov 2005 17:03:24 +0100 (MET) K.Weinert at gmx.net wrote: > > I would like to ask another question. I don't understand the exception > mechanism > of Python when running a Tkinter app. If an exception happens (it does > happen quite often > at the moment..), a traceback is written to the console while the Tk window > remains open > and the application is still running. This is not what I expected -- I > expected the application > would end. Why is that? > > Is there a way to create an error handler for uncaught exceptions in Tkinter > apps? > In other words, can I change the behaviour from writing a traceback to the > console to > something else? Can I, for example, show a message box instead? > If you only want to see the traceback in your gui, I recommend using Pmw. Pmw pops up a Text window that shows the complete traceback, it doesn't catch the exception though. > Here is a small example: > > --- snip --- > import Tix > > def raise_exception(): > print 1/0 > > if __name__ == '__main__': > root = Tix.Tk() > root.title("Exception demo") > > Tix.Button(root, text = "Don't press", command = raise_exception).pack() > > try: > root.mainloop() > except: > print "An error has occured." > --- snip --- > > The except part gets never executed. > That's because the error isn't in the mainloop() method. Probably you meant something like def raise_exception(): try: print 1 / 0 except ZeroDivisionError: print "An error has occured." # or with a message box: # tkMessageBox.showerror(message='ZeroDivisionError') ? Thank god python is nice enough to raise the error where it actually happens; imagine your example would work, you would never know *where* the error happened nor could you create adequate handlers for different exceptions in different situations. I hope this helps Michael From hugonz-lists at h-lab.net Tue Nov 15 19:22:33 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 15 Nov 2005 12:22:33 -0600 Subject: [Tutor] Overloading comparisons Message-ID: <437A2769.5000000@h-lab.net> Hi all, I defined an object wich describes a video clip, like this class VideoSegment: def __init__(self, filename): # Attributes that have to be present self.filename = filename The thing is, I will define an array of these objects for a cache, and would like to keep that array having less than 1000 elements. Periodically I will check it, and remove the oldest element. suppose I have the modification time as an argument. self.time = os.stat(self.filename).st_mtime I can define the following for sorting the array: def __cmp__(self, other): """polymorph for comparisons""" if self.time < other.time: return -1 elif self.time > other.time: return 1 else: return 0 But then I want to test for existance doing if 'lala.avi' in myarray: and that has to be done by name. Is there any way this could work? My current __cmp__ of course treats objects with the same timestamp as identical objects. Any comments are greatly appreciates, maybe my OOP is just sloppy... Hugo From mm_priya6 at yahoo.com Tue Nov 15 19:22:47 2005 From: mm_priya6 at yahoo.com (sivapriya pasupathi) Date: Tue, 15 Nov 2005 10:22:47 -0800 (PST) Subject: [Tutor] Help me Message-ID: <20051115182247.25620.qmail@web35611.mail.mud.yahoo.com> Hi There, I am planning to start my career in computer programming.But i don't have specific resource(websire/book) to improve my basic computer programming skills.If you know any helpful resources,please let me know. Thanks in advance. Priya. --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051115/cb27626e/attachment.html From alan.gauld at freenet.co.uk Tue Nov 15 19:27:49 2005 From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 15 Nov 2005 18:27:49 -0000 Subject: [Tutor] saving project Message-ID: <380-2200511215182749116@freenet.co.uk> >>If you do >> >>File... Save >> >>Then select the location for your file and just give it a name, a >'.py' >>extension will be added to the file. But don't do this from the interactive shell! You need to create a new file (File->New) first and type your code in there. HTH, Alan G From matthew.williams at cancer.org.uk Tue Nov 15 19:47:19 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Tue, 15 Nov 2005 18:47:19 +0000 Subject: [Tutor] Favourite Modules - wiki In-Reply-To: References: Message-ID: <1132080439.2811.20.camel@localhost.localdomain> I think the Wiki's a great idea. del.icio.us already has a Python tagged page: http://del.icio.us/tag/python Other pages I use are: http://mechanicalcat.net/pyblagg.html http://www.planetpython.org/ I've added a couple of things to the Wiki - SQLObject and RSPython Matt From hugonz-lists at h-lab.net Tue Nov 15 19:54:24 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 15 Nov 2005 12:54:24 -0600 Subject: [Tutor] Overloading comparisons In-Reply-To: <437A2769.5000000@h-lab.net> References: <437A2769.5000000@h-lab.net> Message-ID: <437A2EE0.5040900@h-lab.net> I know it is rude to reply to myself. But I found the answer and wanted to share it. I did the following test: >>> class Lala: ... def __eq__(self, other): ... if self.name == other.name: ... return True ... ... def __cmp__(self, other): ... if self.time < other.time: ... return -1 ... elif self.time > other.time: ... return 1 ... else: ... return 0 ... >>> ins0 = Lala() >>> ins0.time = 11 >>> ins0.name = 'myname' >>> >>> >>> ins1 = Lala() >>> ins1.time = 10 >>> ins1.name = 'myname' >>> >>> ins1 == ins0 True >>> >>> ins0>> ins1>> >>> #See? They test correctly for greater and lesser than (time) ... #but they test equal as to time. ... >>> #I even tried sort, it works fine. The thing is to use the rich comparison functions. Hugo From dyoo at hkn.eecs.berkeley.edu Tue Nov 15 19:55:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 15 Nov 2005 10:55:17 -0800 (PST) Subject: [Tutor] Overloading comparisons In-Reply-To: <437A2769.5000000@h-lab.net> Message-ID: > I defined an object wich describes a video clip, like this > > class VideoSegment: > def __init__(self, filename): > # Attributes that have to be present > self.filename = filename [some text cut] > I can define the following for sorting the array: [some code cut] > But then I want to test for existance doing > > if 'lala.avi' in myarray: [some text cut] Hi Hugo, Rather than directly use a list to hold those VideoSegments, you may want to make a separate VideoContainer. A quick and dirty approach would look something like this: ######################################### class VideoContainer: def __init__(self): self.segments = [] def addSegment(self, segment): self.segments.append(segment) self.segments.sort() def deleteOldest(self): ... def __contains__(self, segmentName): ... ######################################### The idea is to squirrel away the sorted list in this VideoContainer, and not expose that implementation detail directly to people. Why do we use a list? Why not a hash? Why does the list have to be sorted? Those are implementation details that we want to hide, just in case we have to change our mind on how to effectively hold those Segments. As far as the world's concerned, a VideoContainer is something that we can put VideoSegments in, and where we can drop old segments off. (And if your operations are limited to this, you might even use something like the 'heapq' module if you're concerned about efficiency. See: http://www.python.org/doc/lib/module-heapq.html for details.) It should be the container's responsibility to keep the segments sorted any time we add a new segment in. The container can also know how to check for segments by name (with the __contains__() function.) Trying to have VideoSegment.__cmp__() to somehow juggle both the sorting role and the existence checking role might not be a good idea. You're doing two distinct things, and I think they should be two different methods. And from a design perspective, I think that existence-checking method should go in a class like VideoContainer. Best of wishes! From hugonz-lists at h-lab.net Tue Nov 15 20:03:02 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 15 Nov 2005 13:03:02 -0600 Subject: [Tutor] Overloading comparisons In-Reply-To: References: Message-ID: <437A30E6.2000209@h-lab.net> Hi Danny, That's nice. I do think I'm going this way I don't want the container to grow too big in memory, not bigger than 1k elements(it is a cache), but when deleting an element I need it to be the oldest files (again, because it is a cache) Thanks for the advice, I'm going this way. My OOP skills *are* sloppy... Hugo Danny Yoo wrote: > >>I defined an object wich describes a video clip, like this >> >>class VideoSegment: >> def __init__(self, filename): >> # Attributes that have to be present >> self.filename = filename > > From dyoo at hkn.eecs.berkeley.edu Tue Nov 15 20:16:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 15 Nov 2005 11:16:18 -0800 (PST) Subject: [Tutor] Help me In-Reply-To: <20051115182247.25620.qmail@web35611.mail.mud.yahoo.com> Message-ID: On Tue, 15 Nov 2005, sivapriya pasupathi wrote: > I am planning to start my career in computer programming.But i don't > have specific resource(websire/book) to improve my basic computer > programming skills.If you know any helpful resources,please let me know. Hi Priya, Welcome aboard! If you're looking for Python-specific resources, have you had a chance to look through the Python.org web site? There should be a lot of useful links from the Beginners Guide and the Non Programmers tutorial list: http://wiki.python.org/moin/BeginnersGuide http://wiki.python.org/moin/BeginnersGuide/NonProgrammers As far as books on paper, there's a good list here: http://wiki.python.org/moin/IntroductoryBooks I've used Learning Python, and from what I remember, it was a fine tutorial. Unfortunately, I came to Python with previous programming experience, so I might not be the best person to point out what books are friendly to people starting from scratch. *grin* Does anyone else have recommendations? From kent37 at tds.net Tue Nov 15 20:26:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Nov 2005 14:26:04 -0500 Subject: [Tutor] Looking for suggestions - update In-Reply-To: References: <437870AD.9000504@tds.net> <4379C1CB.3090404@tds.net> Message-ID: <437A364C.1000501@tds.net> ->Terry<- wrote: > Today (Nov 15, 2005) at 6:08am, Kent Johnson spoke these wise words: > - ->- I think you missed my earlier suggestion about simplifying get_button(). > > I tried your suggestion for changing get_button() and > changed it to: > > def get_button(click): # What peg was clicked? > for i, peg in peg_coords: > if click in peg: > return i + 1 > return 0 Ah, my mistake, should be for i, peg in enumerate(peg_coords): enumerate() is a very handy built-in, given a sequence it returns a sequence of pairs of (index, value) for each value in the list. Use it when you need the index of an item while iterating a sequence. Kent From Christian.Wyglendowski at greenville.edu Tue Nov 15 20:59:18 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue, 15 Nov 2005 13:59:18 -0600 Subject: [Tutor] Help me Message-ID: > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Danny Yoo > > On Tue, 15 Nov 2005, sivapriya pasupathi wrote: > > > I am planning to start my career in computer programming.But i don't > > have specific resource(websire/book) to improve my basic computer > > programming skills.If you know any helpful resources,please > let me know. > > Hi Priya, > > Welcome aboard! > [SNIP Danny's suggestions] > > Unfortunately, I came to Python with previous programming > experience, so I > might not be the best person to point out what books are friendly to > people starting from scratch. *grin* > > Does anyone else have recommendations? Python was my first programming language (I don't count PHP). I started learning about 4 years ago. I found the standard tutorial by Guido quite helpful. I had to read it a few times though, as it moves quite fast for a tutorial (for a raw beginner, at least). I also went through "How to Think Like a Computer Scientist". It is a great book that is freely available online. Finally, the interactive interpreter is sitting there just waiting for you to start typing stuff in. The help() and dir() functions are particularly helpful when playing around in the interpreter. Python Tutorial - http://docs.python.org/tut/tut.html How to Think Like a Computer Scientist - http://www.ibiblio.org/obp/thinkCSpy/ -also- The Python Cookbook - http://www.oreilly.com/catalog/pythoncook2/ Good luck and welcome to Python! Christian From nephish at xit.net Tue Nov 15 21:46:02 2005 From: nephish at xit.net (nephish) Date: Tue, 15 Nov 2005 14:46:02 -0600 Subject: [Tutor] question about ord Message-ID: <1132087562.1491.2.camel@localhost.localdomain> Hey there, i am using a script to change a byte into an integer like this: a = the byte value = ord(a) but i cant find the operation that can change it back to a byte. i am sure its easy, but i am missing how to do it. thanks for any tips sk From kent37 at tds.net Tue Nov 15 22:03:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Nov 2005 16:03:46 -0500 Subject: [Tutor] question about ord In-Reply-To: <1132087562.1491.2.camel@localhost.localdomain> References: <1132087562.1491.2.camel@localhost.localdomain> Message-ID: <437A4D32.2020303@tds.net> nephish wrote: > Hey there, > i am using a script to change a byte into an integer > like this: > a = the byte > value = ord(a) > > but i cant find the operation that can change it back to a byte. chr() See http://docs.python.org/lib/built-in-funcs.html Kent -- http://www.kentsjohnson.com From python at venix.com Tue Nov 15 22:04:41 2005 From: python at venix.com (Python) Date: Tue, 15 Nov 2005 16:04:41 -0500 Subject: [Tutor] question about ord In-Reply-To: <1132087562.1491.2.camel@localhost.localdomain> References: <1132087562.1491.2.camel@localhost.localdomain> Message-ID: <1132088681.22934.303.camel@www.venix.com> chr(value) >>> chr(ord('a')) == 'a' True On Tue, 2005-11-15 at 14:46 -0600, nephish wrote: > Hey there, > i am using a script to change a byte into an integer > like this: > a = the byte > value = ord(a) > > but i cant find the operation that can change it back to a byte. > i am sure its easy, but i am missing how to do it. > > thanks for any tips > > sk > > _______________________________________________ > Tutor maillist - Tutor at 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: 320-210-3409 -- Lloyd Kvam Venix Corp From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 15 22:05:04 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 16 Nov 2005 10:05:04 +1300 Subject: [Tutor] question about ord Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13F7@chbnt01.alpha.wd.govt.nz> Hmm, Never thought of doing it that way. try - import struct a = theByte value = ord(a) theByteReloaded = struct.pack("i",value) You nmay want to check the docs for the struct module at python.org on that pattern. Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of nephish Sent: Wednesday, 16 November 2005 9:46 a.m. To: tutor Subject: [Tutor] question about ord Hey there, i am using a script to change a byte into an integer like this: a = the byte value = ord(a) but i cant find the operation that can change it back to a byte. i am sure its easy, but i am missing how to do it. thanks for any tips sk _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From nephish at xit.net Tue Nov 15 22:14:52 2005 From: nephish at xit.net (nephish) Date: Tue, 15 Nov 2005 15:14:52 -0600 Subject: [Tutor] question about ord In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13F7@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B13F7@chbnt01.alpha.wd.govt.nz> Message-ID: <1132089292.2459.2.camel@localhost.localdomain> Thanks for all your help and the link, looking at the docs right now. slaute` shawn On Wed, 2005-11-16 at 10:05 +1300, Liam Clarke-Hutchinson wrote: > Hmm, > > Never thought of doing it that way. > > try - > > import struct > > a = theByte > value = ord(a) > theByteReloaded = struct.pack("i",value) > > You nmay want to check the docs for the struct module at python.org on that > pattern. > > > Liam Clarke-Hutchinson > > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of nephish > Sent: Wednesday, 16 November 2005 9:46 a.m. > To: tutor > Subject: [Tutor] question about ord > > > Hey there, > i am using a script to change a byte into an integer > like this: > a = the byte > value = ord(a) > > but i cant find the operation that can change it back to a byte. i am sure > its easy, but i am missing how to do it. > > thanks for any tips > > sk > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. > > > > > http://www.govt.nz - connecting you to New Zealand central & local government services > > Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From doublesix at ureach.com Tue Nov 15 22:17:53 2005 From: doublesix at ureach.com (Double Six) Date: Tue, 15 Nov 2005 16:17:53 -0500 Subject: [Tutor] Creating Tkinter Menubars Message-ID: <200511152117.QAA01831@www23.ureach.com> Hi, I am testing the following Tkinter code (attached at the end of this message) by Fredrik Lundh on a Mac OS X 10.4.2 with Python version 2.3. I do get a root window, but it is totally blank without the desirable menubars such as File and Edit. What am I missing? Any help will be highly appreciated. Thanks, Joe ========= from Tkinter import * class AppUI(Frame): def __init__(self, master=None): Frame.__init__(self, master, relief=SUNKEN, bd=2) self.menubar = Menu(self) menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="File", menu=menu) menu.add_command(label="New") menu = Menu(self.menubar, tearoff=0) self.menubar.add_cascade(label="Edit", menu=menu) menu.add_command(label="Cut") menu.add_command(label="Copy") menu.add_command(label="Paste") try: self.master.config(menu=self.menubar) except AttributeError: # master is a toplevel window (Python 1.4/Tkinter 1.63) self.master.tk.call(master, "config", "-menu", self.menubar) self.canvas = Canvas(self, bg="white", width=400, height=400, bd=0, highlightthickness=0) self.canvas.pack() root = Tk() app = AppUI(root) app.pack() root.mainloop() ________________________________________________ Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag From adam.jtm30 at gmail.com Tue Nov 15 22:33:48 2005 From: adam.jtm30 at gmail.com (Adam) Date: Tue, 15 Nov 2005 21:33:48 +0000 Subject: [Tutor] Help me In-Reply-To: <20051115182247.25620.qmail@web35611.mail.mud.yahoo.com> References: <20051115182247.25620.qmail@web35611.mail.mud.yahoo.com> Message-ID: On 15/11/05, sivapriya pasupathi wrote: > > Hi There, > I am planning to start my career in computer programming.But i don't have > specific resource(websire/book) to improve my basic computer programming > skills.If you know any helpful resources,please let me know. > Thanks in advance. > Priya. > I'd suggest Alan Gauld's tutorial as well, python was pretty much my first language (I don't count VB) and his tutorial really helped. http://www.freenetpages.co.uk/hp/alan.gauld/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051115/9841827f/attachment.html From ismaelgf at adinet.com.uy Wed Nov 16 00:10:33 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Tue, 15 Nov 2005 21:10:33 -0200 Subject: [Tutor] RTSP Message-ID: <437A6AE9.509@adinet.com.uy> Hi Does anyone know if there's any module able to download rtsp? Failing that, any command line app that could do the job? (Already tried with mplayer, it didn't work) I'm trying to download a series of streams automatically, I have already been able to open the page, parse all the links, and get to the rtsp:// address. But couldn't find any way to download them. Any suggestions greatly appreciated. Ismael From falcon3166 at hotmail.com Wed Nov 16 00:26:50 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 15 Nov 2005 16:26:50 -0700 Subject: [Tutor] Do I have to initialize TKInter before I can use it? In-Reply-To: Message-ID: Albertito and all, It worked! Thanks again! Thanks for all the help! Nathan Pinno, Owner/operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -----Original Message----- From: Alberto Troiano [mailto:alberto.troiano at gmail.com] Sent: November 15, 2005 8:51 AM To: 'Nathan Pinno'; 'Alan Gauld'; 'Tutor Mailing List' Subject: RE: [Tutor] Do I have to initialize TKInter before I can use it? Hey Nathan I think this is what you are looking for ####Code Below#### from Tkinter import * import tkMessageBox tkMessageBox._show("Windows Title","This is the description",icon=tkMessageBox.INFO,type=tkMessageBox.OK) ###End of Code#### Regards Alberto -----Mensaje original----- De: tutor-bounces at python.org [mailto:tutor-bounces at python.org] En nombre de Nathan Pinno Enviado el: Martes, 15 de Noviembre de 2005 00:43 Para: 'Alan Gauld'; 'Tutor Mailing List' Asunto: Re: [Tutor] Do I have to initialize TKInter before I can use it? Alan and all, I imported it, but its not there. I tried using the Message one found in it, but I got an error message: >>> import Tkinter >>> tk = Tkinter.Tk() >>> Tkinter.Message("Help","Help!") Traceback (most recent call last): File "", line 1, in -toplevel- Tkinter.Message("Help","Help!") File "D:\Python24\lib\lib-tk\Tkinter.py", line 2640, in __init__ Widget.__init__(self, master, 'message', cnf, kw) File "D:\Python24\lib\lib-tk\Tkinter.py", line 1862, in __init__ BaseWidget._setup(self, master, cnf) File "D:\Python24\lib\lib-tk\Tkinter.py", line 1840, in _setup self.tk = master.tk AttributeError: 'str' object has no attribute 'tk' What does this mean, and how can I get it working? Nathan -----Original Message----- From: Alan Gauld [mailto:alan.gauld at freenet.co.uk] Sent: November 14, 2005 9:35 PM To: Nathan Pinno; Tutor Mailing List Subject: Re: [Tutor] Do I have to initialize TKInter before I can use it? Nathan, > I am having problems. The latest error message I got was: > tkMessageBox.showinfo("Hockey", > NameError: name 'tkMessageBox' is not defined A NameError means Python doesn't recognise the name. Usually that's because either you didn't declare the variable or you forgot to import the module or you spelled it wrong. In this case I'd guess you forgot the import? Python error messages are really quite helpful if you just stop and think about what they are saying for a few minutes. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Wed Nov 16 01:00:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Nov 2005 19:00:07 -0500 Subject: [Tutor] RTSP In-Reply-To: <437A6AE9.509@adinet.com.uy> References: <437A6AE9.509@adinet.com.uy> Message-ID: <437A7687.6010803@tds.net> Ismael Garrido wrote: > Hi > > Does anyone know if there's any module able to download rtsp? > Failing that, any command line app that could do the job? (Already tried > with mplayer, it didn't work) > > I'm trying to download a series of streams automatically, I have already > been able to open the page, parse all the links, and get to the rtsp:// > address. But couldn't find any way to download them. Maybe something in the Python RTSP Proxy can help: http://www.onegoodidea.com/ Kent -- http://www.kentsjohnson.com From chris.arndt at web.de Wed Nov 16 02:20:00 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 16 Nov 2005 01:20:00 +0000 Subject: [Tutor] Favourite modules - Wiki Was Re: TurboGears - and some issues In-Reply-To: References: Message-ID: <437A8940.4030607@web.de> Ron Phillips schrieb: > A wonderful idea! I have created a wiki page in Python.org with a list > > of such 'favourite' modules. > Please take a look: > http://wiki.python.org/moin/UsefulModules Good idea! The GUI section might be problematic, though. I don't see that any of the main GUI alternatives (GTK,Qt,wxWindows,Tk,PythonCard,...) can claim a definite prefernce among the Python crowd and they are all more or less Pythonic (except maybe Tk). Probably better just to link to some other comprehensive list there. Maybe a section on Template engines (Cheetah)? And somewhere docutils belongs on that list, but i don't know where. Maybe source code documentation? But then you'd probably have to list epydoc, gendoc, etc. as well. Fact is, that there are a lot of domains, where a clear favourite or "standard" module has not emerged yet. E.g. audio, configuration file handling, HTML form generation/validation, postgres database access, and so on... Chris From chris.arndt at web.de Wed Nov 16 02:34:28 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 16 Nov 2005 01:34:28 +0000 Subject: [Tutor] new topic draft In-Reply-To: <03e001c5e965$8a671fb0$0a01a8c0@xp> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> Message-ID: <437A8CA4.1020909@web.de> Alan Gauld schrieb: > I've just added an incomplete draft copy of my latest tutorial topic > on using the Operating System from Python. The material that's > there discusses the role of the OS and looks at file handling > usng os/os.path/shutil etc. > > http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm "Most computer users know that their computer has an operating system [...]" I doubt that. Maybe you should say "Experienced computer users..." ;-) Chris From kent37 at tds.net Wed Nov 16 03:53:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 15 Nov 2005 21:53:28 -0500 Subject: [Tutor] Favourite modules - Wiki Was Re: TurboGears - and some issues In-Reply-To: <437A8940.4030607@web.de> References: <437A8940.4030607@web.de> Message-ID: <437A9F28.9020900@tds.net> Christopher Arndt wrote: > Good idea! The GUI section might be problematic, though. I don't see that any > of the main GUI alternatives (GTK,Qt,wxWindows,Tk,PythonCard,...) can claim a > definite prefernce among the Python crowd and they are all more or less > Pythonic (except maybe Tk). Probably better just to link to some other > comprehensive list there. > > Maybe a section on Template engines (Cheetah)? > > And somewhere docutils belongs on that list, but i don't know where. Maybe > source code documentation? But then you'd probably have to list epydoc, gendoc, > etc. as well. I think this page will be more useful as a list of favorites or things that beginners might want to take a look at than as an encyclopedic list - there are other places to list all the template engines, all the GUI toolkits, etc. Kent -- http://www.kentsjohnson.com From johan at accesstel.co.za Wed Nov 16 09:12:46 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed, 16 Nov 2005 10:12:46 +0200 Subject: [Tutor] new topic draft In-Reply-To: <03e001c5e965$8a671fb0$0a01a8c0@xp> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> Message-ID: <437AE9FE.3000106@accesstel.co.za> Alan, You may remember that I asked questions on killing a process, a while back, Sice this is relatedto the tutorial that yu are writing, this was the best solution that worked for me to killa process for a command that keeps on running like eg. 'tcpdump'. HTH Johan BTW, There will a be many a felllow Pythonists that will benefit from a tut like this, great work !! Alan Gauld wrote: >I've just added an incomplete draft copy of my latest tutorial topic >on using the Operating System from Python. The material that's >there discusses the role of the OS and looks at file handling >usng os/os.path/shutil etc. > >http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm > >If anyone would like to take a look and provide feedback on >general direction/depth etc that'd be greatly appreciated. > >TIA, > >Alan G >Author of the learn to program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- A non-text attachment was scrubbed... Name: kill_process.py Type: text/x-python Size: 1161 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051116/36ce6090/kill_process.py From spawn at postpi.com Wed Nov 16 10:19:43 2005 From: spawn at postpi.com (fade2blac) Date: Wed, 16 Nov 2005 16:19:43 +0700 Subject: [Tutor] Invisible Raw Input Message-ID: <20051116091943.GA19439@mf.smspi.com> Hi All, Is there any trick to either not echo or obscure password from raw_input() function? -- fade2blac From honza at dp.fce.vutbr.cz Wed Nov 16 10:51:12 2005 From: honza at dp.fce.vutbr.cz (Jan Martinek) Date: Wed, 16 Nov 2005 10:51:12 +0100 Subject: [Tutor] Invisible Raw Input In-Reply-To: <20051116091943.GA19439@mf.smspi.com> References: <20051116091943.GA19439@mf.smspi.com> Message-ID: <1132134672.2835.5.camel@jm.fyz.fce.vutbr.cz> On Wed, 2005-11-16 at 16:19 +0700, fade2blac wrote: > Hi All, > Is there any trick to either not echo or obscure password from raw_input() function? > Yes, try this: import getpass password = getpass.unix_getpass("Enter your password:") print password -- Jan Martinek > -- > fade2blac From K.Weinert at gmx.net Wed Nov 16 10:55:24 2005 From: K.Weinert at gmx.net (K.Weinert@gmx.net) Date: Wed, 16 Nov 2005 10:55:24 +0100 (MET) Subject: [Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory) Message-ID: <24337.1132134924@www4.gmx.net> Hello Michael, hello list, thanks for the info that pmw displays exceptions. What I don't understand is >> --- snip --- >> import Tix >> >> def raise_exception(): >> print 1/0 >> >> if __name__ == '__main__': >> root = Tix.Tk() >> root.title("Exception demo") >> >> Tix.Button(root, text = "Don't press", command = raise_exception).pack() >> >> try: >> root.mainloop() >> except: >> print "An error has occured." >> --- snip --- >> >> The except part gets never executed. > That's because the error isn't in the mainloop() method I thought the mainloop() function is something like def mainloop(): e= get_event() if e: for w in widgets: w.handle(e) but apparently it is not. It's not bad that the Tkinter windows don't destroy upon an exception, since it gives me the option to display an error window, but I feel unsafe unless I understand why it does not. -- Telefonieren Sie schon oder sparen Sie noch? NEU: GMX Phone_Flat http://www.gmx.net/de/go/telefonie From klappnase at freenet.de Wed Nov 16 11:17:45 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed, 16 Nov 2005 11:17:45 +0100 Subject: [Tutor] Creating Tkinter Menubars In-Reply-To: <200511152117.QAA01831@www23.ureach.com> References: <200511152117.QAA01831@www23.ureach.com> Message-ID: <20051116111745.6fee2d15.klappnase@freenet.de> On Tue, 15 Nov 2005 16:17:53 -0500 Double Six wrote: > Hi, > > I am testing the following Tkinter code (attached at the end of > this message) by Fredrik Lundh on a Mac OS X 10.4.2 with Python > version 2.3. I do get a root window, but it is totally blank > without the desirable menubars such as File and Edit. What am I > missing? > It works well for me (on linux, python-2.3), maybe a mac specific thing (sorry , I can't help then). Does the following, simpler code work for you? from Tkinter import * root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=menu) menu.add_command(label="New") menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Edit", menu=menu) menu.add_command(label="Cut") menu.add_command(label="Copy") menu.add_command(label="Paste") root.config(menu=menubar) root.mainloop() The only thing that looks a little starnge to me in the original code is that the menubar is created as a child of the AppUi class, which is basically a Frame, but then it is attached to that Frame's parent (the root window). Maybe the mac doesn't like this (just a thought)? Michael From klappnase at freenet.de Wed Nov 16 11:33:26 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed, 16 Nov 2005 11:33:26 +0100 Subject: [Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory) In-Reply-To: <24337.1132134924@www4.gmx.net> References: <24337.1132134924@www4.gmx.net> Message-ID: <20051116113326.4b0549e6.klappnase@freenet.de> On Wed, 16 Nov 2005 10:55:24 +0100 (MET) K.Weinert at gmx.net wrote: Hi Karsten, > I thought the mainloop() function is something like > > def mainloop(): > e= get_event() > if e: > for w in widgets: w.handle(e) > > but apparently it is not. > > It's not bad that the Tkinter windows don't destroy upon an exception, > since it gives me the option to display an error window, but I feel unsafe > unless I understand why it does not. > I am not enough of an expert to give you a "complete" answer for that, so anyone please correct me if I am wrong. As far as I understand, the mainloop() command just starts a tk shell and Tkinter gives you an interface to communicate with this tk shell. In fact Tkinter "translates" any widget command into a tk command and sends it to the tk shell, which itself sends it to the associated Tk window (or the related widget). The tk shell will run as long as a - Python decides to close it for you (e.g. after the main (Tk()) window has been destroyed) b - you explicitely close it calling the widget's quit() method c - a fatal tk error occurs, so the tk shell decides to quit itself Now most of the errors that occur happen of course on the python level and are caught by the python interpreter (that shows you the traceback) and there is no reason for python to inform the tk shell that it should quit. I hope this makes sense Michael From lumbricus at gmx.net Wed Nov 16 12:05:03 2005 From: lumbricus at gmx.net (Joerg Woelke) Date: Wed, 16 Nov 2005 12:05:03 +0100 Subject: [Tutor] RTSP In-Reply-To: <437A6AE9.509@adinet.com.uy> References: <437A6AE9.509@adinet.com.uy> Message-ID: <20051116110503.GA4702@localhost.localdomain> On Tue, Nov 15, 2005 at 09:10:33PM -0200, Ismael Garrido wrote: > Hi > > Does anyone know if there's any module able to download rtsp? > Failing that, any command line app that could do the job? (Already tried > with mplayer, it didn't work) $ mplayer rtsp://ravi.br-online.de:5050/ravi/alpha/centauri/v/050803.rm works for me. -- innovate, v.: To annoy people. From kent37 at tds.net Wed Nov 16 14:00:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Nov 2005 08:00:41 -0500 Subject: [Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory) In-Reply-To: <24337.1132134924@www4.gmx.net> References: <24337.1132134924@www4.gmx.net> Message-ID: <437B2D79.1060603@tds.net> K.Weinert at gmx.net wrote: > What I don't understand is >>>import Tix >>> >>>def raise_exception(): >>> print 1/0 >>> >>>if __name__ == '__main__': >>> root = Tix.Tk() >>> root.title("Exception demo") >>> >>> Tix.Button(root, text = "Don't press", command = > > raise_exception).pack() > >>> try: >>> root.mainloop() >>> except: >>> print "An error has occured." >>>--- snip --- >>> >>>The except part gets never executed. > > I thought the mainloop() function is something like > > def mainloop(): > e= get_event() > if e: > for w in widgets: w.handle(e) > > but apparently it is not. The main loop is probably more like this: def mainloop(): e= get_event() if e: try: for w in widgets: w.handle(e) except: traceback.print_exc() It's pretty common for GUI toolkits to trap exceptions in the event handler. This can help make a more robust application - in my experience I don't really want a bug in a handler to crash the whole app. There is an undocumented hook that lets you change this - the function Tk.report_callback_exception() is called to actually report the error. You can redefine this function to do what you want. Here are a couple of examples: http://zephyrfalcon.org/weblog/arch_d7_2003_01_04.html http://groups.google.com/group/comp.lang.python/browse_thread/thread/ce0036f41da8a22f/c62177e5bb59b09c%23c62177e5bb59b09c?sa=X&oi=groupsr&start=1&num=3 Kent -- http://www.kentsjohnson.com From doublesix at ureach.com Wed Nov 16 16:42:45 2005 From: doublesix at ureach.com (Double Six) Date: Wed, 16 Nov 2005 10:42:45 -0500 Subject: [Tutor] Creating Tkinter Menubars Message-ID: <200511161542.KAA20288@www21.ureach.com> Hi Michael, Thank you very much for the help. I tried the simpler code you provided, but unfortunatly I still got a blank window without any trace of menubars. Any other insights? Thanks, Joe ======== from Tkinter import * root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=menu) menu.add_command(label="New") menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Edit", menu=menu) menu.add_command(label="Cut") menu.add_command(label="Copy") menu.add_command(label="Paste") root.config(menu=menubar) root.mainloop() ________________________________________________ Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag ---- On Wed, 16 Nov 2005, Michael Lange (klappnase at freenet.de) wrote: > On Tue, 15 Nov 2005 16:17:53 -0500 > Double Six wrote: > > > Hi, > > > > I am testing the following Tkinter code (attached at the end of > > this message) by Fredrik Lundh on a Mac OS X 10.4.2 with Python > > version 2.3. I do get a root window, but it is totally blank > > without the desirable menubars such as File and Edit. What am I > > missing? > > > > > It works well for me (on linux, python-2.3), maybe a mac specific thing (sorry , I can't help then). > Does the following, simpler code work for you? > > from Tkinter import * > > root = Tk() > menubar = Menu(root) > menu = Menu(menubar, tearoff=0) > menubar.add_cascade(label="File", menu=menu) > menu.add_command(label="New") > menu = Menu(menubar, tearoff=0) > menubar.add_cascade(label="Edit", menu=menu) > menu.add_command(label="Cut") > menu.add_command(label="Copy") > menu.add_command(label="Paste") > root.config(menu=menubar) > root.mainloop() > > The only thing that looks a little starnge to me in the original code is > that the menubar is created as a child of the AppUi class, which is basically a Frame, > but then it is attached to that Frame's parent (the root window). > Maybe the mac doesn't like this (just a thought)? > > Michael From ewalker at micron.com Wed Nov 16 20:06:38 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 16 Nov 2005 12:06:38 -0700 Subject: [Tutor] class attributes Message-ID: <200511161206.38956.ewalker@micron.com> Hello, If I have some like the following: markersExp = ['big','boss','two','three'] for mark in markersExp: print y.mark Now I have an list of class objects that are in an outerloop. y is how I access it. The attributes names of the class objects match whats in markersExp. Can I do that print statement in a way to allow me to print the value of the class attribute? From kent37 at tds.net Wed Nov 16 20:19:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Nov 2005 14:19:00 -0500 Subject: [Tutor] class attributes In-Reply-To: <200511161206.38956.ewalker@micron.com> References: <200511161206.38956.ewalker@micron.com> Message-ID: <437B8624.5070608@tds.net> Eric Walker wrote: > Hello, > If I have some like the following: > > markersExp = ['big','boss','two','three'] > for mark in markersExp: > print y.mark > > Now I have an list of class objects that are in an outerloop. y is how I > access it. The attributes names of the class objects match whats in > markersExp. Can I do that print statement in a way to allow me to print the > value of the class attribute? Use getattr(): print getattr(y, mark) http://docs.python.org/lib/built-in-funcs.html#l2h-31 Kent -- http://www.kentsjohnson.com From chris.arndt at web.de Wed Nov 16 21:27:30 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 16 Nov 2005 20:27:30 +0000 Subject: [Tutor] Favourite modules - Wiki Was Re: TurboGears - and some issues In-Reply-To: <437A9F28.9020900@tds.net> References: <437A8940.4030607@web.de> <437A9F28.9020900@tds.net> Message-ID: <437B9632.7090409@web.de> Kent Johnson schrieb: >>And somewhere docutils belongs on that list, but i don't know where. Maybe >>source code documentation? But then you'd probably have to list epydoc, gendoc, >>etc. as well. > > > I think this page will be more useful as a list of favorites or things that beginners might want to take a look at than as an encyclopedic list - there are other places to list all the template engines, all the GUI toolkits, etc. Sorry, I wasn't suggesting to turn this into a comprehensive list of modules for every specific problem domain. But I don't see, why such a list would be only useful for beginners. Say, you're an experienced programmer, though not very seasoned in Python yet, it would be great to have a place were you can find answers for questions like "What do Python people normally use when handling x?" I was just saying, that for some domains there is a obivious choice and for some there isn't. Maybe it would be already helpful to include that information into the list, e.g. "There are many different GUI toolkits for Python and none seems to be vastly more favourite than the others. See a list of GUI modules here."* *Just an example, don't take this literally. Chris From lordvader at gmail.com Wed Nov 16 21:32:21 2005 From: lordvader at gmail.com (Fred Lionetti) Date: Wed, 16 Nov 2005 12:32:21 -0800 Subject: [Tutor] lambda in a loop In-Reply-To: <434140620511160936h6af180ccr956650166b93252e@mail.gmail.com> References: <434140620511160936h6af180ccr956650166b93252e@mail.gmail.com> Message-ID: <434140620511161232r33a1b4cfj427d4e5ecb5cb42c@mail.gmail.com> Hi everyone, If I have this code: -------------------------------- def doLambda(val): print "value 2:", val commands = [] for value in range(5): print "value 1:", value commands.append(lambda:doLambda(value)) for c in commands: c() ---------------------------------- my output is: value 1: 0 value 1: 1 value 1: 2 value 1: 3 value 1: 4 value 2: 4 value 2: 4 value 2: 4 value 2: 4 value 2: 4 Obviously, the lambda is using "value" at the end of the loop (4), rather than what I want, "value" during the loop (0,1,2,3). Is there any *simple* way around this? I'd prefer not to use a separate array with all the values ( i.e. commands.append(lambda:doLambda(values[commands.index(c)])) ) if possible. Thanks, Fred From srini_iyyer_bio at yahoo.com Wed Nov 16 21:58:36 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 16 Nov 2005 12:58:36 -0800 (PST) Subject: [Tutor] How to convert a list to tuple In-Reply-To: <20051116111745.6fee2d15.klappnase@freenet.de> Message-ID: <20051116205836.41954.qmail@web31606.mail.mud.yahoo.com> Dear all, Pardon me for asking a simple question. Sometimes brain gets blank and compells me to seek help from tutors. I have a list : >>>prcor ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] >>> prc = () >>>for line in prcor: cols = line.split('\t') (x,y) = (int(cols[0]),int(cols[1])) prc = (x,y) >>>prc (1471, 1495) Because the resulting element is a tuple, append is not working. How can I push all these elements in this list: ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] into a a big tuple : ((933,957),(955,979),(969,993),(1025,1049),(1052,1076),(1098,1122),(1136,1160), (1298,1322),(1406,1430),(1422,1446),(1471,1495)) Thank you. __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From alan.gauld at freenet.co.uk Wed Nov 16 21:57:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Nov 2005 20:57:58 -0000 Subject: [Tutor] new topic draft References: <03e001c5e965$8a671fb0$0a01a8c0@xp> <437AE9FE.3000106@accesstel.co.za> Message-ID: <000c01c5eaf0$6cd42420$0a01a8c0@xp> Thanks, I may use that as one of the example programs if you don't mind? Alan G. ----- Original Message ----- From: "Johan Geldenhuys" To: "Alan Gauld" Cc: "Python Tutor list" Sent: Wednesday, November 16, 2005 8:12 AM Subject: Re: [Tutor] new topic draft > Alan, > > You may remember that I asked questions on killing a process, a while > back, > > Sice this is relatedto the tutorial that yu are writing, this was the > best solution that worked for me to killa process for a command that > keeps on running like eg. 'tcpdump'. > > HTH > > Johan > BTW, There will a be many a felllow Pythonists that will benefit from a > tut like this, great work !! > > > Alan Gauld wrote: > >>I've just added an incomplete draft copy of my latest tutorial topic >>on using the Operating System from Python. The material that's >>there discusses the role of the OS and looks at file handling >>usng os/os.path/shutil etc. >> >>http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm >> >>If anyone would like to take a look and provide feedback on >>general direction/depth etc that'd be greatly appreciated. >> >>TIA, >> >>Alan G >>Author of the learn to program web tutor >>http://www.freenetpages.co.uk/hp/alan.gauld >> >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > -------------------------------------------------------------------------------- > """ > This class will execute the command, let it run for 5 seconds and kill > the process. > > ::Author: Johan Geldenhuys > johan at accesstel.co.za > > ::Version: 0.0.1 > > ::Date last updated: 2005-11-03 > > ::Changes: > > :: TODO: Capture the output from line 41 to a file. > """ > > import os, signal, time > > class command(object): > > def __init__(self): > > pass > > > def kill(self, pid, signal=signal.SIGTERM): > try: > > print "trying to kill pid...", pid > os.kill(pid, signal) > #os.waitpid(pid, 0) > print "Killed %d"%pid > except: > print "couldn't stop process" > > def main(self, interface): > > self.interface = interface > self.pid = os.fork() > > if self.pid == 0: > > os.execvp('tcpdump', ['tcpdump', '-npi', self.interface]) > > print 'PID: ',self.pid > print 'Let it run for 5 seconds...' > time.sleep(5) > self.kill(self.pid) > > > if __name__ == '__main__': > print "starting test" > c = command() > c.main('eth0') > > From 3dbernard at gmail.com Wed Nov 16 22:10:09 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 16 Nov 2005 16:10:09 -0500 Subject: [Tutor] Using lists as table-like structure Message-ID: <61d0e2b40511161310w3d380061l432a38ff256b2d4f@mail.gmail.com> Hello, I am wondering if can do this: Let say I have a list of lists. Each individual lists have a bunch of elements. Now I would like to either get or set the first element of each individual list. I could do a loop and/or list comprehension, but I was wondering if it was possible with something like: aList = [ [1,1,1], [2,2,2,], [3,3,3] ] aList[:][0] = 10 If I print aList[:], I get the list with the nested sublists. >>> aList[:] [[1, 1, 1], [2, 2, 2], [3, 3, 3]] But as soon as I introduce the [0], in an attempt to access the first element of each sublist, I get the first sublist in its entirety: >>> aList[:][0] [1, 1, 1] I would have hoped to get something like [1, 2, 3] Is this possible at all? Thanks Bernard From alan.gauld at freenet.co.uk Wed Nov 16 22:09:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Nov 2005 21:09:39 -0000 Subject: [Tutor] Creating Tkinter Menubars References: <200511152117.QAA01831@www23.ureach.com> Message-ID: <004501c5eaf2$0e7570d0$0a01a8c0@xp> > version 2.3. I do get a root window, but it is totally blank > without the desirable menubars such as File and Edit. What am I > missing? At a guess you forgot to pack() the menu? Thats usually whats wrong when widgets fail to appear as expected! :-) Alan G. From Liam.Clarke-Hutchinson at business.govt.nz Wed Nov 16 22:16:43 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Thu, 17 Nov 2005 10:16:43 +1300 Subject: [Tutor] How to convert a list to tuple Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B141B@chbnt01.alpha.wd.govt.nz> Does this work? (I can't check) listX = ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] listY = [ tuple(item.split("\t")) for item in listX] tupleY = tuple(listY) Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -----Original Message----- From: tutor-bounces+ml.cyresse=gmail.com at python.org [mailto:tutor-bounces+ml.cyresse=gmail.com at python.org] On Behalf Of Srinivas Iyyer Sent: Thursday, 17 November 2005 9:59 a.m. To: tutor at python.org Subject: [Tutor] How to convert a list to tuple Dear all, Pardon me for asking a simple question. Sometimes brain gets blank and compells me to seek help from tutors. I have a list : >>>prcor ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] >>> prc = () >>>for line in prcor: cols = line.split('\t') (x,y) = (int(cols[0]),int(cols[1])) prc = (x,y) >>>prc (1471, 1495) Because the resulting element is a tuple, append is not working. How can I push all these elements in this list: ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] into a a big tuple : ((933,957),(955,979),(969,993),(1025,1049),(1052,1076),(1098,1122),(1136,116 0), (1298,1322),(1406,1430),(1422,1446),(1471,1495)) Thank you. __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From srini_iyyer_bio at yahoo.com Wed Nov 16 22:22:16 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Wed, 16 Nov 2005 13:22:16 -0800 (PST) Subject: [Tutor] How to convert a list to tuple In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B141B@chbnt01.alpha.wd.govt.nz> Message-ID: <20051116212216.43198.qmail@web31608.mail.mud.yahoo.com> Thanks. It works. Thanks for simplifying it in list comprehension. Srini --- Liam Clarke-Hutchinson wrote: > Does this work? (I can't check) > > listX = ['933\t957', '955\t979', '969\t993', > '1025\t1049', '1052\t1076', > '1098\t1122', '1136\t1160', '1298\t1322', > '1406\t1430', '1422\t1446', > '1471\t1495'] > > listY = [ tuple(item.split("\t")) for item in listX] > tupleY = tuple(listY) > > Liam Clarke-Hutchinson| Contact Centre Advisor| > Ministry of Economic > Development > DDI +64 3 962 2639 | Fax +64 3 962 6220 > www.med.govt.nz > > > > -----Original Message----- > From: tutor-bounces+ml.cyresse=gmail.com at python.org > [mailto:tutor-bounces+ml.cyresse=gmail.com at python.org] > On Behalf Of Srinivas > Iyyer > Sent: Thursday, 17 November 2005 9:59 a.m. > To: tutor at python.org > Subject: [Tutor] How to convert a list to tuple > > > Dear all, > Pardon me for asking a simple question. Sometimes > brain gets blank and compells me to seek help from > tutors. > > I have a list : > >>>prcor > ['933\t957', '955\t979', '969\t993', '1025\t1049', > '1052\t1076', > '1098\t1122', '1136\t1160', '1298\t1322', > '1406\t1430', '1422\t1446', > '1471\t1495'] > >>> prc = () > >>>for line in prcor: > cols = line.split('\t') > (x,y) = (int(cols[0]),int(cols[1])) > prc = (x,y) > >>>prc > (1471, 1495) > > Because the resulting element is a tuple, append is > not working. > > How can I push all these elements in this list: > ['933\t957', '955\t979', '969\t993', '1025\t1049', > '1052\t1076', > '1098\t1122', '1136\t1160', '1298\t1322', > '1406\t1430', '1422\t1446', > '1471\t1495'] > > into a a big tuple : > > ((933,957),(955,979),(969,993),(1025,1049),(1052,1076),(1098,1122),(1136,116 > 0), > (1298,1322),(1406,1430),(1422,1446),(1471,1495)) > > > Thank you. > > > > > > __________________________________ > Yahoo! Mail - PC Magazine Editors' Choice 2005 > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > A new monthly electronic newsletter covering all > aspects of MED's work is now available. Subscribers > can choose to receive news from any or all of seven > categories, free of charge: Growth and Innovation, > Strategic Directions, Energy and Resources, Business > News, ICT, Consumer Issues and Tourism. See > http://news.business.govt.nz for more details. > > > > > http://www.govt.nz - connecting you to New Zealand > central & local government services > > Any opinions expressed in this message are not > necessarily those of the Ministry of Economic > Development. This message and any files transmitted > with it are confidential and solely for the use of > the intended recipient. If you are not the intended > recipient or the person responsible for delivery to > the intended recipient, be advised that you have > received this message in error and that any use is > strictly prohibited. Please contact the sender and > delete the message and any attachment from your > computer. > __________________________________ Yahoo! FareChase: Search multiple travel sites in one click. http://farechase.yahoo.com From lordvader at gmail.com Wed Nov 16 22:23:10 2005 From: lordvader at gmail.com (Fred Lionetti) Date: Wed, 16 Nov 2005 13:23:10 -0800 Subject: [Tutor] Using lists as table-like structure Message-ID: <434140620511161323q565f60f2m280e8d0b8d5a9a2d@mail.gmail.com> Hi Bernard, You can do this with Numeric (http://numeric.scipy.org/) import Numeric aList = [ [1,1,1], [2,2,2,], [3,3,3] ] bList = Numeric.array(aList, "i") print bList[:,0] displays-> [1 2 3] you can convert the array back to a list if you want like this: bList.tolist() so... result = Numeric.array(aList, "i")[:,0].tolist() should do what you want in one line. Fred > aList = [ [1,1,1], [2,2,2,], [3,3,3] ] > aList[:][0] = 10 > > > If I print aList[:], I get the list with the nested sublists. > > >>> aList[:] > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] > > > But as soon as I introduce the [0], in an attempt to access the first > element of each sublist, I get the first sublist in its entirety: > > >>> aList[:][0] > [1, 1, 1] > > > I would have hoped to get something like > [1, 2, 3] > > > Is this possible at all? > > Thanks > Bernard > From john at fouhy.net Wed Nov 16 22:32:49 2005 From: john at fouhy.net (John Fouhy) Date: Thu, 17 Nov 2005 10:32:49 +1300 Subject: [Tutor] Creating Tkinter Menubars In-Reply-To: <004501c5eaf2$0e7570d0$0a01a8c0@xp> References: <200511152117.QAA01831@www23.ureach.com> <004501c5eaf2$0e7570d0$0a01a8c0@xp> Message-ID: <5e58f2e40511161332x684fd15fg@mail.gmail.com> On 17/11/05, Alan Gauld wrote: > At a guess you forgot to pack() the menu? Thats usually whats wrong > when widgets fail to appear as expected! :-) You don't pack() menus --- you attach them to a Tk() or a Toplevel() by calling .config() with the menu= option (like in Michael's post, which also works for me). ...wait, hang on. I don't own a Mac, but isn't the standard for Macintoshes to stick the menu bar along the top of the screen? Is it appearing up there instead? -- John. From Christian.Wyglendowski at greenville.edu Wed Nov 16 22:39:44 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed, 16 Nov 2005 15:39:44 -0600 Subject: [Tutor] lambda in a loop Message-ID: > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Fred Lionetti > Sent: Wednesday, November 16, 2005 2:32 PM > To: tutor at python.org > Subject: [Tutor] lambda in a loop > > Hi everyone, Hello, > If I have this code: > > -------------------------------- > def doLambda(val): > print "value 2:", val > > commands = [] > for value in range(5): > print "value 1:", value > commands.append(lambda:doLambda(value)) > > for c in commands: > c() > ---------------------------------- > > my output is: > value 1: 0 > value 1: 1 > value 1: 2 > value 1: 3 > value 1: 4 > value 2: 4 > value 2: 4 > value 2: 4 > value 2: 4 > value 2: 4 > > Obviously, the lambda is using "value" at the end of the loop (4), > rather than what I want, "value" during the loop (0,1,2,3). Right. I think the issue is that your lambda calls another funtion. However, the function isn't called until the lambda is called later, when value == 4. > Is there > any *simple* way around this? I'd prefer not to use a separate array > with all the values ( i.e. > commands.append(lambda:doLambda(values[commands.index(c)])) ) if > possible. I'd use a closure rather than a lambda. def wrapper(val): def inner(): print "value 2:", val return inner commands = [] for value in range(5): print "value 1:", value commands.append(wrapper(value)) for c in commands: c() That way each item in commands is an "inner" function that has its own local copy of value. So it is really a variable scope issue. > Thanks, > Fred HTH, sorry it isn't more clear. Christian From alan.gauld at freenet.co.uk Wed Nov 16 22:53:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Nov 2005 21:53:21 -0000 Subject: [Tutor] class attributes References: <200511161206.38956.ewalker@micron.com> Message-ID: <008501c5eaf8$29bd7bc0$0a01a8c0@xp> > markersExp = ['big','boss','two','three'] > for mark in markersExp: > print y.mark > > Now I have an list of class objects that are in an outerloop. y is how I > access it. The attributes names of the class objects match whats in > markersExp. Do you have to use string versions of the class names? Why not: class Mark: mark = 42 class big(Mark): pass class boss(Mark): pass class two(Mark): pass class three(Mark): pass markersExp = [big,boss.two,three] for cls in markersExp: print cls.mark Classes are objects too! > Can I do that print statement in a way to allow me to print the > value of the class attribute? Or are we really talking about instances? In which case the usual solution is a dictionary. Alan g. From dyoo at hkn.eecs.berkeley.edu Wed Nov 16 23:02:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Nov 2005 14:02:33 -0800 (PST) Subject: [Tutor] lambda in a loop In-Reply-To: <434140620511161232r33a1b4cfj427d4e5ecb5cb42c@mail.gmail.com> Message-ID: > -------------------------------- > def doLambda(val): > print "value 2:", val > > commands = [] > for value in range(5): > print "value 1:", value > commands.append(lambda:doLambda(value)) > > for c in commands: > c() Hi Fred, Ah, this one of those unfrequently asked questions. lambdas in Python's for loop are a little tricky because the for loop rebinds the element variable. That is, what's happening is that all those lambda functions are just resetting the same 'value' variable: the loop is merely rebinding value to the elements of range(5). All the lambdas are sharing the same name binding, and that explains why we see this kind of aliasing behavior. One possible fix is to do this: ###### def makeDoLambda(value): def f(): return doLambda(value) return f ###### Once we have this makeDoLambda() function, then we can use it: commands.append(makeDoLambda(value)) The act of calling the makeDoLambda() function makes a fresh name binding to 'value', so that none of the lambda functions share the same binding. Another way to do this is to force our lambda to make a fresh binding with a default parameter: commands.append(lambda v=value: doLambda(v)) This is subtle, so if you have more questions, please feel free to ask. Slightly off-topic footnote: if you're familiar with the Scheme programming language, then what's happening can be simulated like this: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Simulates some of the essence of Python's for loop (define-syntax python-for-each (syntax-rules () ((_ (id list) e1 e2 ...) (let ((id #f)) (let loop ((L list)) (if (null? L) (void) (begin (set! id (car L)) e1 e2 ... (loop (cdr L))))))))) (begin (define commands '()) (python-for-each (i '(1 2 3 4 5)) (set! commands (cons (lambda () i) commands))) (for-each (lambda (f) (display (f)) (newline)) commands)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Python's loop has set!-ish behavior, and it's that rebinding behavior that causes the issues you are seeing. From ewalker at micron.com Wed Nov 16 23:02:43 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 16 Nov 2005 15:02:43 -0700 Subject: [Tutor] class attributes In-Reply-To: <008501c5eaf8$29bd7bc0$0a01a8c0@xp> References: <200511161206.38956.ewalker@micron.com> <008501c5eaf8$29bd7bc0$0a01a8c0@xp> Message-ID: <200511161502.43715.ewalker@micron.com> ahh, you just blew smoke in my face. :) I have a class with attributes. These attributes eventually have the value of some lines in a file. I am now going back through my object list of that class and assigning values to the attributes depending on another variable that will change and be the same names like the class attribute names. I want to use that change in name to be able to access the attribute and set its value. Did I say that right???? On Wednesday 16 November 2005 02:53 pm, Alan Gauld wrote: > > markersExp = ['big','boss','two','three'] > > for mark in markersExp: > > print y.mark > > > > Now I have an list of class objects that are in an outerloop. y is how I > > access it. The attributes names of the class objects match whats in > > markersExp. > > Do you have to use string versions of the class names? > Why not: > > class Mark: mark = 42 > class big(Mark): pass > class boss(Mark): pass > class two(Mark): pass > class three(Mark): pass > > markersExp = [big,boss.two,three] > > for cls in markersExp: print cls.mark > > Classes are objects too! > > > Can I do that print statement in a way to allow me to print the > > value of the class attribute? > > Or are we really talking about instances? In which case the usual solution > is a dictionary. > > Alan g. -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From chris.arndt at web.de Wed Nov 16 23:05:42 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 16 Nov 2005 22:05:42 +0000 Subject: [Tutor] new topic draft In-Reply-To: <000c01c5eaf0$6cd42420$0a01a8c0@xp> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> <437AE9FE.3000106@accesstel.co.za> <000c01c5eaf0$6cd42420$0a01a8c0@xp> Message-ID: <437BAD36.3090007@web.de> Alan Gauld schrieb: > Thanks, I may use that as one of the example programs if > you don't mind? I took the liberty of refactoring Johan's example a bit, to make it more reusable. See attached file. Chris -------------- next part -------------- A non-text attachment was scrubbed... Name: kill_process.py Type: text/x-python Size: 1299 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051116/0cb8fac6/kill_process.py From alan.gauld at freenet.co.uk Wed Nov 16 23:09:35 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Nov 2005 22:09:35 -0000 Subject: [Tutor] lambda in a loop References: <434140620511160936h6af180ccr956650166b93252e@mail.gmail.com> <434140620511161232r33a1b4cfj427d4e5ecb5cb42c@mail.gmail.com> Message-ID: <009101c5eafa$6e101b00$0a01a8c0@xp> -------------------------------- def doLambda(val): print "value 2:", val commands = [] for value in range(5): print "value 1:", value commands.append(lambda:doLambda(value)) Close but not quite. Try: commands.append(lambda v=value:doLambda(v)) value is a local variable in doLambda so when it executes it uses whatever the global 'value' is set at, which at the end of the loop will be 4. By using the default argument and passing that you freeze the value at whatever it is at the time of setting (a fortuitous by-product of how default parameters work!) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Nov 16 23:14:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Nov 2005 22:14:59 -0000 Subject: [Tutor] Using lists as table-like structure References: <61d0e2b40511161310w3d380061l432a38ff256b2d4f@mail.gmail.com> Message-ID: <009701c5eafb$2f310600$0a01a8c0@xp> > But as soon as I introduce the [0], in an attempt to access the first > element of each sublist, I get the first sublist in its entirety: > >>>> aList[:][0] > [1, 1, 1] aList[:] is the shorthand way of taking a copy of aList thus aList[:][0] is the same as saying aList[0] except you get a new item. Thus you could change the content of this version of [1,1,1] without affecting the original. Handy, but not what you want. I don't know any easy way of getting the first items except maybe a list comprehension: [lst[0] for lst in aList] You could turn that into a parameterised function def getRow(n): return [lst[n] for lst in aList] Does that help? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Wed Nov 16 23:19:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Nov 2005 14:19:49 -0800 (PST) Subject: [Tutor] Using lists as table-like structure In-Reply-To: <61d0e2b40511161310w3d380061l432a38ff256b2d4f@mail.gmail.com> Message-ID: On Wed, 16 Nov 2005, Bernard Lebel wrote: > Let say I have a list of lists. Each individual lists have a bunch of > elements. Now I would like to either get or set the first element of > each individual list. I could do a loop and/or list comprehension, but I > was wondering if it was possible with something like: > > aList = [ [1,1,1], [2,2,2,], [3,3,3] ] > aList[:][0] = 10 Hi Bernard, I think I see what you're trying to do; you're trying to clear the first column of each row in your matrix. Unfortunately, this is not done so easily in standard Python. However, if you use the third-party Numeric Python (numarray) package, you can use its array type to do what you want. > If I print aList[:], I get the list with the nested sublists. > > >>> aList[:] > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] Yes, sounds good so far. > But as soon as I introduce the [0], in an attempt to access the first > element of each sublist, I get the first sublist in its entirety: > > >>> aList[:][0] > [1, 1, 1] Let's do a quick substitution model thing here. You mentioned earlier that: > >>> aList[:] > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] So if we just plug that value into aList[:][0]: aList[:][0] ==> [[1, 1, 1,], [2, 2, 2], [3, 3, 3]] [0] then we see that we're just asking for the first element of aList[:], which is [1, 1, 1]. > I would have hoped to get something like [1, 2, 3] Take a look into Numeric Python: it'll give you the row/column slicing operations that you're expecting. As a concrete example: ###### >>> import numarray >>> a = numarray.array([[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9]]) >>> a[:, 0] array([1, 4, 7]) >>> a[:, 1] array([2, 5, 8]) >>> a[:, 2] array([3, 6, 9]) ###### Best of wishes! From kent37 at tds.net Wed Nov 16 23:38:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Nov 2005 17:38:58 -0500 Subject: [Tutor] class attributes In-Reply-To: <200511161502.43715.ewalker@micron.com> References: <200511161206.38956.ewalker@micron.com> <008501c5eaf8$29bd7bc0$0a01a8c0@xp> <200511161502.43715.ewalker@micron.com> Message-ID: <437BB502.9020009@tds.net> Eric Walker wrote: > ahh, you just blew smoke in my face. :) > > I have a class with attributes. These attributes eventually have the value of > some lines in a file. I am now going back through my object list of that > class and assigning values to the attributes depending on another variable > that will change and be the same names like the class attribute names. I > want to use that change in name to be able to access the attribute and set > its value. Did I say that right???? Use getattr() to read an attribute by name and setattr() to set it. Kent From alan.gauld at freenet.co.uk Wed Nov 16 23:38:35 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed, 16 Nov 2005 22:38:35 -0000 Subject: [Tutor] class attributes References: <200511161206.38956.ewalker@micron.com> <008501c5eaf8$29bd7bc0$0a01a8c0@xp> <200511161502.43715.ewalker@micron.com> Message-ID: <009b01c5eafe$7b6979f0$0a01a8c0@xp> > I have a class with attributes Are they class attributes - shared by all instances of the class or are they instance attributes - unique values in each instance? > I am now going back through my object list of that > class So you have a list of all the instances of the class and modifying values. Since you do it on a per instance basis I assume that means the attributres are instance attributes(ie created inside an init method)? > assigning values to the attributes depending on another variable > that will change and be the same names like the class attribute names. So the names are names of attributes not names of classes? In that case I think you need to use setattr() I think... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Nov 16 23:46:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 16 Nov 2005 17:46:00 -0500 Subject: [Tutor] lambda in a loop In-Reply-To: References: Message-ID: <437BB6A8.3050406@tds.net> Christian Wyglendowski wrote: >>-----Original Message----- >>From: tutor-bounces at python.org >> If I have this code: >> Obviously, the lambda is using "value" at the end of the loop (4), >>rather than what I want, "value" during the loop (0,1,2,3). > > Right. I think the issue is that your lambda calls another funtion. > However, the function isn't called until the lambda is called later, > when value == 4. No, the problem is not when the function is called, but when value is bound into the closure. > I'd use a closure rather than a lambda. The original solution does use a closure. The problem is that variables are not bound into a closure until the scope of the variable exits. That is why using a separate factory function works - the closure is bound when the factory function exits which happens each time through the loop. In the case of closures in a loop the closure is not bound until exiting the scope containing the loop and all the closures are bound to the same value. Kent -- http://www.kentsjohnson.com From ewalker at micron.com Thu Nov 17 01:49:48 2005 From: ewalker at micron.com (Eric Walker) Date: Wed, 16 Nov 2005 17:49:48 -0700 Subject: [Tutor] class attributes In-Reply-To: <009b01c5eafe$7b6979f0$0a01a8c0@xp> References: <200511161206.38956.ewalker@micron.com> <200511161502.43715.ewalker@micron.com> <009b01c5eafe$7b6979f0$0a01a8c0@xp> Message-ID: <200511161749.49923.ewalker@micron.com> > Are they class attributes - shared by all instances of the class or are > they instance attributes - unique values in each instance? all instances of the class share these attributes. > So you have a list of all the instances of the class and modifying values. > Since you do it on a per instance basis I assume that means the attributres > are instance attributes(ie created inside an init method)? yes they are created with an __init__ method > > > assigning values to the attributes depending on another variable > > that will change and be the same names like the class attribute names. > > So the names are names of attributes not names of classes? > In that case I think you need to use setattr() Yes, they are names of the attributes, and yes I am using setattr and getattr now. thanks you all for your great advice.... -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 From dyoo at hkn.eecs.berkeley.edu Thu Nov 17 01:56:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Nov 2005 16:56:21 -0800 (PST) Subject: [Tutor] lambda in a loop In-Reply-To: <437BB6A8.3050406@tds.net> Message-ID: > The original solution does use a closure. The problem is that variables > are not bound into a closure until the scope of the variable exits. That > is why using a separate factory function works - the closure is bound > when the factory function exits which happens each time through the > loop. In the case of closures in a loop the closure is not bound until > exiting the scope containing the loop and all the closures are bound to > the same value. [Warning: really subtle concepts ahead. You should probably skip this if you're a newcomer to programming, because this is not really going to make sense at all. *grin* This message is also really long. Sorry, but I haven't figured out how to talk about this concisely yet.] Hi Kent, There's some confusion here. People are making an artificial distinction between the "closure" values built by lambda vs the function values built by 'def'. They're the same kind of thing. ###### >>> commands = [] >>> def sayNumber(n): ... print n ... >>> for i in range(5): ... commands.append((lambda v: lambda: sayNumber(v))(i)) ... >>> >>> for c in commands: ... c() ... 0 1 2 3 4 ###### Kent's explanation here: > In the case of closures in a loop the closure is not bound until exiting > the scope containing the loop and all the closures are bound to the same > value. makes it sounds like closures somehow twiddle their thumbs and wait till things go out of scope before closing on their environment. This is not what is happening. They capture the environment as soon as they're constructed. The issue, then, isn't "when" closures are constructed: it's "what": what's in the environment when we make a closure? Just to make sure we all have the same conceptual model: Python's toplevel environment can be seen as thing that attaches names to values --- a namespace. Let's dive into that model and make sure we understand how it works. [Side note: the following is adapted from material in SICP, http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html#%_sec_3.2] We can see the keys of that namespace by doing dir(): ###### >>> dir() ['__builtins__', '__doc__', '__name__'] ###### Just to be able to talk about things, let's give a name to the global namespace as: "G". Whenever we call a function, we build a new environment that's chained up to the one we're in at the time of function construction. This corresponds to what people's ideas of the "stack frame" is. ###### >>> def x(): ... print dir() ... >>> x() [] ###### When we're calling x(), let's give a name to that environmental frame as "X". (I'm sorry for doing the uppercase-lowercase thing, but it makes it easier for me to remember what environment goes with what function!) "X" is empty, but that doesn't prevent our x function from calling global stuff, because "X" is chained up to "G". Let me use some funky notation to draw the state of the environments: [X | ] ----> [G | __builtins__=...] When we try to access a name in X, if the lookup fails, the hunt will continue down the chain of environments toward the global environment G. The above diagram using an ad-hoc bracket/pipe notation to try to visually what an environment frame might be. It tries to make it clear that G has bindings to things like __builtins__, and that the frames can be chained up together. Let's try a slightly different example: ###### >>> def y(): ... someNumber = 42 ... print dir() ... >>> y() ['someNumber'] ###### y() was also created at toplevel, so whenever we call y(), we'll create a new environment "Y" that get's chained up to the toplevel environment "G". We see that assigning local variables adds bindings to "Y", so at the end of calling y(), right before we return, our world looks like this: [Y | someNumber=42] ----> [G | __builtins__=...] Let's take a look at something that touches on what people think of as a closure: ###### >>> def z(): ... someNumber = 5 ... def inner(): ... print someNumber ... return inner ... ###### When we create z(), we're at the toplevel environment G again, so whenever Z gets called, it'll make a new environment frame whose parent is "G". Ok, let's call z(): ###### >>> value = z() ###### When we call z(), we create a fresh new environment frame "Z" that's attached to G. our environment looks like: [Z |] ----> [G | __builtins__=...] We then add the someNumber binding to "Z". Our environment now looks like: [Z | someNumber=5] ----> [G | __builtins__=...] Then we hit the 'def inner(): ...' call: that's a function construction. When we define inner(), that function will remember it's origin environment: [Z | someNumber=5] ----> [G | __builtins__=...] And whenever we call that inner() function, it'll make a fresh environment I attached to that origin environment. We captures that function in 'value', so let's call that now from the toplevel: ###### >>> value() 5 ###### When we call value(), as it starts up, it remembers its origin. It builds a new environment frame which we'll call "I", and chains it up to that origin. Our world will look like this: [I |] ----> [Z | someNumber=5] ----> [G | __builtins__=...] When we try to print someNumber, the reason that we can see someNumber is because, although that name binding doesn't exist in "I", it does exist in Z. So the lookup of someNumber succeeds, and things run happily. Let's make the example a little different: ###### >>> counter = 0 >>> def make_f(): ... def inner(): ... print counter ... return inner ... >>> f1 = make_f() >>> counter = counter + 1 >>> f2 = make_f() >>> counter = counter + 1 >>> f3 = make_f() ###### We've extended our global environment G with a new name 'counter'. [G | counter=0, __builtins__=...] When we call make_f() three times, each call builds a unique environment which we'll call M1, M2, and M3. f1's origin environment is: [M1 |] --> G f2's origin environment is: [M2 |] --> G f3's origin environment is: [M3 |] --> G f1, f2, and f3 are functions whose environments all get their 'counter' out of "G", so if we make a change to that, as we do with: counter = counter + 1 that will be seen by all of the functions: ###### >>> f1() 2 ###### And it's this aliasing behavior that started this whole conversation. Finally, let's cover what happens with: ###### >>> def make_f(counter): ... def inner(): ... print counter ... return inner ###### When we define make_f(), it's attached to our global environment 'G' as before: make_f()'s origin environment is: [G |counter=2, __builtins__=...] Let's call make_f() once. ###### >>> f1 = make_f(7) ###### When we call make_f() here, we construct an environment which we'll call N: [N | counter=7] ---> [G | counter=2, __builtins__=...] We hit the definition of inner, so it creates a function value whose origin environment is this, and f1 is bound to that function value. So we'll say that: f1's origin environment is: [N | counter=7] ---> [G | counter=2, __builtins__=...] We call f1(). ###### >>> f1() 7 ###### What happened here? When we called f1() here, we first constructed an environment that we'll call O. [O |] ---> [N | counter=7] ---> [G | counter=2, __builtins__=...] Any name lookups that we do while we're calling f1() will follow this general chain. Since 'counter' is bound in N, that's how we get seven, and not two, even though 'counter' is in the global environment frame. Ok, done. Whew. The devil's in the details, and these are the details that implement: "Functions remember their environments." *grin* Best of wishes! From dyoo at hkn.eecs.berkeley.edu Thu Nov 17 02:30:16 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 16 Nov 2005 17:30:16 -0800 (PST) Subject: [Tutor] lambda in a loop In-Reply-To: Message-ID: > Just to be able to talk about things, let's give a name to the global > namespace as: "G". > > Whenever we call a function, we build a new environment that's chained up > to the one we're in at the time of function construction. This > corresponds to what people's ideas of the "stack frame" is. Argh. Scratch that last sentence in there; I thought I deleted that part. The environment model has nothing to do with the stack traceback; my apologies! From adisegna at gmail.com Thu Nov 17 03:21:06 2005 From: adisegna at gmail.com (Adisegna) Date: Wed, 16 Nov 2005 21:21:06 -0500 Subject: [Tutor] Passing HTTP commands through Telnet using Python for web site testing? Message-ID: <6571c3530511161821l434263bnd0ce43cb082995a1@mail.gmail.com> Hi, I just started learning Python and would like to try writing a monitoring script. What I would like to do is use Telnet to send a GET via port 80 to a status page in a directory to verify my site is up. Psuedo code: Connect = telnet website.com 80 Send = GET /folder/folder/test.asp HTTP/1.1 Host: website.com Pipe the Response to a file (overwriting it each time): HTTP/1.1 400 Bad Request Server: Server: Microsoft-IIS/5.0 Date: Wed, 16 Nov 2005 20:15:20 GMT X-Powered-By: ASP.NET Connection: close Server: website.com Content-Length: 102 Content-Type: text/html GREP "HTTP/1.1 400 Bad Request" from the file and | append >> it into a log. This tells me the connection was valid. Timestamping the line would be nice. The other error code could be "HTTP/1.1 404 Not Found" if the directory went missing or possibly "Cound not open connection" if the connection could not be made. If the above GREP is found in the file do nothing. If not send an email stating the error. End Anyway, Can someone point me in the right direction on getting the Telnet working? Or if you have a better way to get what I am trying to do accomplished. Is there a Python Telnet module? Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051116/ee3006f7/attachment.htm From adisegna at gmail.com Thu Nov 17 05:13:02 2005 From: adisegna at gmail.com (Adisegna) Date: Wed, 16 Nov 2005 23:13:02 -0500 Subject: [Tutor] Passing HTTP commands through Telnet using Python for web site testing? Message-ID: <6571c3530511162013r7639d220o2ee7b725281997ed@mail.gmail.com> So far this is what I have come up with doing some research. import urllib for line in urllib.urlopen('http://mywebsit.com/folder/folder/test.asp'): if '400 Bad Request' in line: text_file = open("mysite.log", "a") text_file.writelines(line) text_file.writelines("\n") text_file.close() This writes the to a new line each time the script is run. Now I have to figure out an "if then else" to write the other possible error codes and appending a timestamp followed by a space each time it runs. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051116/4e586720/attachment.html From janos.juhasz at VELUX.com Thu Nov 17 08:27:32 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 17 Nov 2005 08:27:32 +0100 Subject: [Tutor] split a tuple In-Reply-To: Message-ID: Hi, I couldn't get idea how to make the next thing >>> n=4 #split into so long parts >>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split >>> [l[i:i+n] for i in range(0,len(l),n)] [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)] But I have to make it like this [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)] because i use it later in this >>> result = [l[i:i+n] for i in range(0,len(l),n)] >>> zip(*result) [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)] and as you can see it, the last element is missing here. Yours sincerely, ______________________________ J?nos Juh?sz From kent37 at tds.net Thu Nov 17 12:13:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Nov 2005 06:13:49 -0500 Subject: [Tutor] Passing HTTP commands through Telnet using Python for web site testing? In-Reply-To: <6571c3530511161821l434263bnd0ce43cb082995a1@mail.gmail.com> References: <6571c3530511161821l434263bnd0ce43cb082995a1@mail.gmail.com> Message-ID: <437C65ED.6050406@tds.net> Adisegna wrote: > Hi, > > I just started learning Python and would like to try writing a > monitoring script. > > What I would like to do is use Telnet to send a GET via port 80 to a > status page in a directory to verify my site is up. I use httplib for this. You can probably do it with urllib2 also but I don't know how to get the status codes from urllib2. Here is an incomplete snippet: try: if self.method == 'http': conn = HTTPConnection(self.server) else: conn = HTTPSConnection(self.server) conn.request('GET', self.path) resp = conn.getresponse() data = resp.read() status = resp.status conn.close() if status == 200: success = self.successText in data except socket.timeout: clientErrorMsg = 'Ping failed due to timeout (%s seconds)' % timeout except socket.error, msg: clientErrorMsg = 'Ping failed with error ' + str(msg) except: clientErrorMsg = ''.join(traceback.format_exception(*sys.exc_info())) Kent -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Thu Nov 17 13:13:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Nov 2005 12:13:00 -0000 Subject: [Tutor] Passing HTTP commands through Telnet using Python for website testing? References: <6571c3530511161821l434263bnd0ce43cb082995a1@mail.gmail.com> Message-ID: <00fc01c5eb70$40c9d200$0a01a8c0@xp> > Anyway, Can someone point me in the right direction on getting the Telnet > working? Or if you have a better way to get what I am trying to do > accomplished. Is there a Python Telnet module? I think the urllib module will be easier. Just open the url and read the output into a list. check the line and if necessary write to the log file Psuedocode: import urllib as url import time logfile = open('log.txt','a;') # append mode page = url.open('www.whatever.com/wherever').read() page = page.split() if '404' in page[0]: # will it be the first line? logfile.write('Whoops it went missing at: ' + str(time.strtime(time.time())) url.close() Does that look like the kind of thing? Alan G. From alan.gauld at freenet.co.uk Thu Nov 17 13:15:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Nov 2005 12:15:00 -0000 Subject: [Tutor] Passing HTTP commands through Telnet using Python forweb site testing? References: <6571c3530511162013r7639d220o2ee7b725281997ed@mail.gmail.com> Message-ID: <010401c5eb70$8ace0830$0a01a8c0@xp> Looks like you pretty well figured it out. for the timestamp there is the basic timemodule, the datetime module or the extra module mxdatetime. Each more sophisticated than the last... Alan G ----- Original Message ----- From: "Adisegna" To: Sent: Thursday, November 17, 2005 4:13 AM Subject: Re: [Tutor] Passing HTTP commands through Telnet using Python forweb site testing? So far this is what I have come up with doing some research. import urllib for line in urllib.urlopen('http://mywebsit.com/folder/folder/test.asp'): if '400 Bad Request' in line: text_file = open("mysite.log", "a") text_file.writelines(line) text_file.writelines("\n") text_file.close() This writes the to a new line each time the script is run. Now I have to figure out an "if then else" to write the other possible error codes and appending a timestamp followed by a space each time it runs. Thanks From smiles at worksmail.net Thu Nov 17 13:30:29 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Thu, 17 Nov 2005 06:30:29 -0600 Subject: [Tutor] split a tuple References: Message-ID: <001501c5eb72$be7c1850$4e2c4fca@csmith> | Hi, | | I couldn't get idea how to make the next thing | |||| n=4 #split into so long parts |||| l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split |||| [l[i:i+n] for i in range(0,len(l),n)] | [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)] | | But I have to make it like this | [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)] | because i use it later in this | |||| result = [l[i:i+n] for i in range(0,len(l),n)] |||| zip(*result) | [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)] | | and as you can see it, the last element is missing here. | Since it will always be the last one that is not the correct length; can you just add another line to extend the length of the last one by the correct number of default values (that number being the difference between how many you want and how many you have)? ###### >>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) >>> n=4 >>> regrouped = [l[i:i+n] for i in range(0,len(l),n)] >>> default = 'default' >>> regrouped[-1]=list(regrouped[-1]) >>> regrouped[-1].extend([default]*(n-len(regrouped[-1]))) >>> regrouped[-1]=tuple(regrouped[-1]) >>> regrouped [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')] >>> >>> ['a']*3 #so you can see what the rhs multiply does ['a', 'a', 'a'] ###### Since tuples cannot be changed, you have to go through the tuple<->list conversion steps. If you can work with a list instead, then these two steps could be eliminated: ###### >>> l = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] #using a list instead >>> regrouped = [l[i:i+n] for i in range(0,len(l),n)] >>> regrouped[-1].extend([default]*(n-len(regrouped[-1]))) >>> regrouped [[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2], [3, 4, 5, 'default']] >>> ###### /c From kent37 at tds.net Thu Nov 17 13:57:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Nov 2005 07:57:31 -0500 Subject: [Tutor] Passing HTTP commands through Telnet using Python for web site testing? In-Reply-To: <6571c3530511162013r7639d220o2ee7b725281997ed@mail.gmail.com> References: <6571c3530511162013r7639d220o2ee7b725281997ed@mail.gmail.com> Message-ID: <437C7E3B.1040608@tds.net> Adisegna wrote: > So far this is what I have come up with doing some research. > > import urllib > for line in urllib.urlopen('http://mywebsit.com/folder/folder/test.asp'): > if '400 Bad Request' in line: > > text_file = open("mysite.log", "a") > text_file.writelines(line) > text_file.writelines("\n") > text_file.close() You are counting on the HTTP status code being part of the body of the response. This will depend on the details of the server. Better is to look at the actual HTTP status. Here is an example of retrieving a page with urllib2 and capturing HTTP status codes: http://mail.python.org/pipermail/python-list/2003-July/175455.html Kent -- http://www.kentsjohnson.com From srini_iyyer_bio at yahoo.com Thu Nov 17 15:32:18 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 17 Nov 2005 06:32:18 -0800 (PST) Subject: [Tutor] how to identify a list element is in the range of a tuple element or a list element In-Reply-To: <4384922E.6050405@kebikec.net> Message-ID: <20051117143219.83986.qmail@web31613.mail.mud.yahoo.com> Dear group, I have a list of numbers: a = [10,3,4.6,2.3,4.8,10.8,4.1] b = ['1-4','4.1-8','8.1-12','12.1-16'] c = ((1,4),(4.1,8),(8.1-12),(12.1,16)) Now I want to find if elements of list a are in the range of list b and in the range of tuple b. I know (and my limited knowledge on range function) is not allowing me to think of a new way. Could any one please help me. I wish to have the answer as: 10 8.1-12 3 1-4 etc. Thank you for help in advance. srini __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From kent37 at tds.net Thu Nov 17 15:53:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 17 Nov 2005 09:53:10 -0500 Subject: [Tutor] how to identify a list element is in the range of a tuple element or a list element In-Reply-To: <20051117143219.83986.qmail@web31613.mail.mud.yahoo.com> References: <20051117143219.83986.qmail@web31613.mail.mud.yahoo.com> Message-ID: <437C9956.1050706@tds.net> Srinivas Iyyer wrote: > Dear group, > > I have a list of numbers: > > a = [10,3,4.6,2.3,4.8,10.8,4.1] > b = ['1-4','4.1-8','8.1-12','12.1-16'] > c = ((1,4),(4.1,8),(8.1-12),(12.1,16)) > > Now I want to find if elements of list a are in the > range of list b and in the range of tuple b. > > I know (and my limited knowledge on range function) is > not allowing me to think of a new way. > > Could any one please help me. > > I wish to have the answer as: > > 10 8.1-12 > 3 1-4 > etc. > A brute-force approach is straighforward. I ignore b since it has the same values as c, and I corrected the third entry in c to be a tuple. >>> a = [10,3,4.6,2.3,4.8,10.8,4.1] >>> c = ((1,4),(4.1,8),(8.1, 12),(12.1,16)) >>> for x in a: ... for lower, upper in c: ... if lower <= x <= upper: ... print '%-5s%s-%s' % (x, lower, upper) ... 10 8.1-12 3 1-4 4.6 4.1-8 2.3 1-4 4.8 4.1-8 10.8 8.1-12 4.1 4.1-8 If a and c are large this could be slow, it could be optimized by searching in c instead of exhaustive search, or by terminating the inner loop when a match is found or when lower > x. Kent -- http://www.kentsjohnson.com From Christian.Wyglendowski at greenville.edu Thu Nov 17 15:58:33 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 17 Nov 2005 08:58:33 -0600 Subject: [Tutor] lambda in a loop Message-ID: Fred said: > >> Obviously, the lambda is using "value" at the end of the loop (4), > >>rather than what I want, "value" during the loop (0,1,2,3). Christian said: > > Right. I think the issue is that your lambda calls another funtion. > > However, the function isn't called until the lambda is called later, > > when value == 4. Kent said: > No, the problem is not when the function is called, but when > value is bound into the closure. I don't think that the value is being bound into the closure, though. It is using the global 'value', which is why I said "the function isn't called until the lambda is called later, when value == 4". I should have been more clear and said "when global value == 4". I think this can be demonstrated by adding a "del value" statement after the loop. Here is the traceback I get after adding that statement: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py" , line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\cwyglendowski\Desktop\cp_playground\lambdatest.py", line 12, in ? c() File "C:\Documents and Settings\cwyglendowski\Desktop\cp_playground\lambdatest.py", line 7, in commands.append(lambda:doLambda(value)) NameError: global name 'value' is not defined Christian said: > > I'd use a closure rather than a lambda. Kent said: > The original solution does use a closure. Thanks for pointing that out. I don't use lambda often and didn't think about how you can create closures with lambda statements. Kent said: > The problem is that > variables are not bound into a closure until the scope of the > variable exits. That is why using a separate factory function > works - the closure is bound when the factory function exits > which happens each time through the loop. In the case of > closures in a loop the closure is not bound until exiting the > scope containing the loop and all the closures are bound to > the same value. I'm not even going to go there ... Danny just wrote an excellent book on this :-) Thanks to all for the great discussion. Christian From ajikoe at gmail.com Thu Nov 17 16:13:37 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Thu, 17 Nov 2005 16:13:37 +0100 Subject: [Tutor] how to identify a list element is in the range of a tuple element or a list element In-Reply-To: <437C9956.1050706@tds.net> References: <20051117143219.83986.qmail@web31613.mail.mud.yahoo.com> <437C9956.1050706@tds.net> Message-ID: for b you can use this code: a = [10,3,4.6,2.3,4.8,10.8,4.1] b = ['1-4','4.1-8','8.1-12','12.1-16'] for x in a: for y in b: low,up = y.split('-') if float(low) < x < float(up): print '%s %s - %s' % (x, low, up) break Cheers, pujo On 11/17/05, Kent Johnson wrote: > > Srinivas Iyyer wrote: > > Dear group, > > > > I have a list of numbers: > > > > a = [10,3,4.6,2.3,4.8,10.8,4.1] > > b = ['1-4','4.1-8','8.1-12','12.1-16'] > > c = ((1,4),(4.1,8),(8.1-12),(12.1,16)) > > > > Now I want to find if elements of list a are in the > > range of list b and in the range of tuple b. > > > > I know (and my limited knowledge on range function) is > > not allowing me to think of a new way. > > > > Could any one please help me. > > > > I wish to have the answer as: > > > > 10 8.1-12 > > 3 1-4 > > etc. > > > > A brute-force approach is straighforward. I ignore b since it has the same > values as c, and I corrected the third entry in c to be a tuple. > > >>> a = [10,3,4.6,2.3,4.8,10.8,4.1] > >>> c = ((1,4),(4.1,8),(8.1, 12),(12.1,16)) > >>> for x in a: > ... for lower, upper in c: > ... if lower <= x <= upper: > ... print '%-5s%s-%s' % (x, lower, upper) > ... > 10 8.1-12 > 3 1-4 > 4.6 4.1-8 > 2.3 1-4 > 4.8 4.1-8 > 10.8 8.1-12 > 4.1 4.1-8 > > If a and c are large this could be slow, it could be optimized by > searching in c instead of exhaustive search, or by terminating the inner > loop when a match is found or when lower > x. > > Kent > > -- > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051117/5d6aac23/attachment-0001.html From janos.juhasz at VELUX.com Thu Nov 17 16:46:37 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 17 Nov 2005 16:46:37 +0100 Subject: [Tutor] split a tuple In-Reply-To: Message-ID: Hi Chris, Thanks your response. I have just found another way. >>> import math >>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) >>> n = 4 >>> extended = l + ('default',)*int(n - math.fmod(len(l),n)) >>> [extended[i:i+n] for i in range(0,len(extended),n)] [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')] >>>| Hi, >>>| >>>| I couldn't get idea how to make the next thing >>>| >>>|||| n=4 #split into so long parts >>>|||| l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split >>>|||| [l[i:i+n] for i in range(0,len(l),n)] >>>| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)] >>>| >>>| But I have to make it like this >>>| [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)] >>>| because i use it later in this >>>| >>>|||| result = [l[i:i+n] for i in range(0,len(l),n)] >>>|||| zip(*result) >>>| [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)] >>>| >>>| and as you can see it, the last element is missing here. >>>| >>> >>>Since it will always be the last one that is not the correct length; can you just add another line to extend the >>>length of the last one by the correct number of default values (that number being the difference between how many >>>you want and how many you have)? >>> >>>###### >>>>>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) >>>>>> n=4 >>>>>> regrouped = [l[i:i+n] for i in range(0,len(l),n)] >>>>>> default = 'default' >>>>>> regrouped[-1]=list(regrouped[-1]) >>>>>> regrouped[-1].extend([default]*(n-len(regrouped[-1]))) >>>>>> regrouped[-1]=tuple(regrouped[-1]) >>>>>> regrouped >>>[(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, 'default')] >>>>>> >>>>>> ['a']*3 #so you can see what the rhs multiply does >>>['a', 'a', 'a'] >>> >>>###### >>> >>>Since tuples cannot be changed, you have to go through the tuple<->list conversion steps. If you can work with a >>>list instead, then these two steps could be eliminated: >>> >>>###### >>>>>> l = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] #using a list instead >>>>>> regrouped = [l[i:i+n] for i in range(0,len(l),n)] >>>>>> regrouped[-1].extend([default]*(n-len(regrouped[-1]))) >>>>>> regrouped >>>[[1, 2, 3, 4], [5, 1, 2, 3], [4, 5, 1, 2], [3, 4, 5, 'default']] >>>>>> >>>###### >>> >>>/c Yours sincerely, ______________________________ J?nos Juh?sz From 3dbernard at gmail.com Thu Nov 17 16:53:14 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 17 Nov 2005 10:53:14 -0500 Subject: [Tutor] Using lists as table-like structure In-Reply-To: References: <61d0e2b40511161310w3d380061l432a38ff256b2d4f@mail.gmail.com> Message-ID: <61d0e2b40511170753t513e363bsf8b3726cff96d6b0@mail.gmail.com> Thanks to everyone for the answers. I'll definitely check Numeric Python. Cheers Bernard On 11/16/05, Danny Yoo wrote: > > > On Wed, 16 Nov 2005, Bernard Lebel wrote: > > > Let say I have a list of lists. Each individual lists have a bunch of > > elements. Now I would like to either get or set the first element of > > each individual list. I could do a loop and/or list comprehension, but I > > was wondering if it was possible with something like: > > > > aList = [ [1,1,1], [2,2,2,], [3,3,3] ] > > aList[:][0] = 10 > > > Hi Bernard, > > I think I see what you're trying to do; you're trying to clear the first > column of each row in your matrix. Unfortunately, this is not done so > easily in standard Python. However, if you use the third-party Numeric > Python (numarray) package, you can use its array type to do what you want. > > > > If I print aList[:], I get the list with the nested sublists. > > > > >>> aList[:] > > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] > > Yes, sounds good so far. > > > > But as soon as I introduce the [0], in an attempt to access the first > > element of each sublist, I get the first sublist in its entirety: > > > > >>> aList[:][0] > > [1, 1, 1] > > > Let's do a quick substitution model thing here. You mentioned earlier > that: > > > >>> aList[:] > > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] > > So if we just plug that value into aList[:][0]: > > aList[:][0] ==> [[1, 1, 1,], [2, 2, 2], [3, 3, 3]] [0] > > then we see that we're just asking for the first element of aList[:], > which is [1, 1, 1]. > > > > > I would have hoped to get something like [1, 2, 3] > > Take a look into Numeric Python: it'll give you the row/column slicing > operations that you're expecting. As a concrete example: > > ###### > >>> import numarray > >>> a = numarray.array([[1, 2, 3], > ... [4, 5, 6], > ... [7, 8, 9]]) > >>> a[:, 0] > array([1, 4, 7]) > >>> a[:, 1] > array([2, 5, 8]) > >>> a[:, 2] > array([3, 6, 9]) > ###### > > > Best of wishes! > > From singletoned at gmail.com Thu Nov 17 18:11:09 2005 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 17 Nov 2005 17:11:09 +0000 Subject: [Tutor] Newb ? In-Reply-To: References: Message-ID: <34bb7f5b0511170911h507085d2g@mail.gmail.com> These both work (though neither is very graceful). text = "hello" message = "" for i in range(len(text)): message = message + text[(len(text)-i-1)] print message lst = list(text) newstr = "" for item in text: newstr += (lst.pop()) print newstr On 16/11/05, Chad Everett wrote: > Hello all, > > Have a problem here with a challenge from a book I am reading. > Any help is much appreciated. > > I am trying to run a program that asks the user for a statement and then > prints it out backwards. > this is what I have. > It does not print anything out. I assume that I have something out of whack > with my high and low statements. > > Thanks for you help. > > > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > > high = len(message) > low = -len(message) > print > print message[high:low] > print > print raw_input("Please Press Enter to Exit") > > > -- > http://mail.python.org/mailman/listinfo/python-list > From lantal at tmail.com Thu Nov 17 18:27:41 2005 From: lantal at tmail.com (Laszlo Antal) Date: Thu, 17 Nov 2005 09:27:41 -0800 Subject: [Tutor] How to remove Html from list. References: <1132246685.1E2ED4A8@ba12.dngr.org> Message-ID: <1132248464.202335B5@dk12.dngr.org> Hi, This is what I would like to do.: 1: Read in an Html file as a list with readlines, 2: Loop through the list, 3: Take out the text or number that is between the Html, 4: Insert the text or number into a new list, 5: print out the new list with the text. I have a problem with section 3 ! I can not figure out what kind of expresion I need to use to find Html code. Any help would be great. Thank you Laszlo Antal From mosinu at gmail.com Thu Nov 17 18:45:47 2005 From: mosinu at gmail.com (Will Harris) Date: Thu, 17 Nov 2005 12:45:47 -0500 Subject: [Tutor] slices Message-ID: <5faf36700511170945k31acf7d7v9eb0afbe0b4777dd@mail.gmail.com> Is there an easy way to slice the last set of characters off a string when I don't know the length of the string? For example say I have a list of words like this though weather I want to get the last 2 characters from each. But so far nothing I have tried has seemed to work. Currently I am doing something like: #!/usr/bin/python import sys for word in sys.argv[1:]: print word[-3:-1] I have tried to change the numbers around but I always seem to end up at the wrong place of the string. If I new the length each time I could just do a positive. Doesn't this work in the form of: t h i s 0 1 2 3 -4 -3 -2 -1 Did I miss something somewhere in some tutorial that someone would be kind enough to point me to? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051117/2fed30a8/attachment.htm From mosinu at gmail.com Thu Nov 17 18:49:06 2005 From: mosinu at gmail.com (Will Harris) Date: Thu, 17 Nov 2005 12:49:06 -0500 Subject: [Tutor] slices In-Reply-To: <5faf36700511170945k31acf7d7v9eb0afbe0b4777dd@mail.gmail.com> References: <5faf36700511170945k31acf7d7v9eb0afbe0b4777dd@mail.gmail.com> Message-ID: <5faf36700511170949v2a79932ay639fff26a602b5bb@mail.gmail.com> Blah brain freeze I saw my mistake as I hit send. It should just be word[-2:] So #!/usr/bin/python import sys for word in sys.argv[1:]: print word[-2:] Works now. Thanks! On 11/17/05, Will Harris wrote: > > Is there an easy way to slice the last set of characters off a string when > I don't know the length of the string? For example say I have a list of > words like > this > though > weather > I want to get the last 2 characters from each. But so far nothing I have > tried has seemed to work. Currently I am doing something like: > > #!/usr/bin/python > import sys > > for word in sys.argv[1:]: > print word[-3:-1] > > I have tried to change the numbers around but I always seem to end up at > the wrong place of the string. If I new the length each time I could just do > a positive. > Doesn't this work in the form of: > > t h i s > 0 1 2 3 > -4 -3 -2 -1 > > Did I miss something somewhere in some tutorial that someone would be kind > enough to point me to? > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051117/95e00ead/attachment.htm From johan at accesstel.co.za Thu Nov 17 18:56:05 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 17 Nov 2005 19:56:05 +0200 Subject: [Tutor] new topic draft In-Reply-To: <000c01c5eaf0$6cd42420$0a01a8c0@xp> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> <437AE9FE.3000106@accesstel.co.za> <000c01c5eaf0$6cd42420$0a01a8c0@xp> Message-ID: <437CC435.4090309@accesstel.co.za> That will be great. In the "@TODO" part you will see that I still need to take the output from the command and capture that into a file. Can you help me with that? Johan Alan Gauld wrote: > Thanks, I may use that as one of the example programs if > you don't mind? > > Alan G. > > > ----- Original Message ----- From: "Johan Geldenhuys" > > To: "Alan Gauld" > Cc: "Python Tutor list" > Sent: Wednesday, November 16, 2005 8:12 AM > Subject: Re: [Tutor] new topic draft > > >> Alan, >> >> You may remember that I asked questions on killing a process, a while >> back, >> >> Sice this is relatedto the tutorial that yu are writing, this was the >> best solution that worked for me to killa process for a command that >> keeps on running like eg. 'tcpdump'. >> >> HTH >> >> Johan >> BTW, There will a be many a felllow Pythonists that will benefit from a >> tut like this, great work !! >> >> >> Alan Gauld wrote: >> >>> I've just added an incomplete draft copy of my latest tutorial topic >>> on using the Operating System from Python. The material that's >>> there discusses the role of the OS and looks at file handling >>> usng os/os.path/shutil etc. >>> >>> http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm >>> >>> If anyone would like to take a look and provide feedback on >>> general direction/depth etc that'd be greatly appreciated. >>> >>> TIA, >>> >>> Alan G >>> Author of the learn to program web tutor >>> http://www.freenetpages.co.uk/hp/alan.gauld >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> > > > -------------------------------------------------------------------------------- > > > >> """ >> This class will execute the command, let it run for 5 seconds and >> kill the process. >> >> ::Author: Johan Geldenhuys >> johan at accesstel.co.za >> >> ::Version: 0.0.1 >> >> ::Date last updated: 2005-11-03 >> >> ::Changes: >> >> :: TODO: Capture the output from line 41 to a file. >> """ >> >> import os, signal, time >> >> class command(object): >> >> def __init__(self): >> >> pass >> >> >> def kill(self, pid, signal=signal.SIGTERM): >> try: >> >> print "trying to kill pid...", pid >> os.kill(pid, signal) >> #os.waitpid(pid, 0) >> print "Killed %d"%pid >> except: >> print "couldn't stop process" >> >> def main(self, interface): >> >> self.interface = interface >> self.pid = os.fork() >> >> if self.pid == 0: >> >> os.execvp('tcpdump', ['tcpdump', '-npi', self.interface]) >> >> print 'PID: ',self.pid >> print 'Let it run for 5 seconds...' >> time.sleep(5) >> self.kill(self.pid) >> >> >> if __name__ == '__main__': >> print "starting test" >> c = command() >> c.main('eth0') >> >> > > From johan at accesstel.co.za Thu Nov 17 19:20:00 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 17 Nov 2005 20:20:00 +0200 Subject: [Tutor] new topic draft In-Reply-To: <437BAD36.3090007@web.de> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> <437AE9FE.3000106@accesstel.co.za> <000c01c5eaf0$6cd42420$0a01a8c0@xp> <437BAD36.3090007@web.de> Message-ID: <437CC9D0.8090708@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051117/eee0805d/attachment-0001.html From chris.arndt at web.de Thu Nov 17 19:33:31 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 17 Nov 2005 18:33:31 +0000 Subject: [Tutor] new topic draft In-Reply-To: <437CC9D0.8090708@accesstel.co.za> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> <437AE9FE.3000106@accesstel.co.za> <000c01c5eaf0$6cd42420$0a01a8c0@xp> <437BAD36.3090007@web.de> <437CC9D0.8090708@accesstel.co.za> Message-ID: <437CCCFB.7010804@web.de> Johan Geldenhuys wrote: > What is this line supposedto do? > > cmd.run('www.python.org') Run the command that was defined at object creation ('ping -c 10') with the argument 'www.python.org'. Chris From johan at accesstel.co.za Thu Nov 17 19:33:50 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu, 17 Nov 2005 20:33:50 +0200 Subject: [Tutor] new topic draft In-Reply-To: <437BAD36.3090007@web.de> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> <437AE9FE.3000106@accesstel.co.za> <000c01c5eaf0$6cd42420$0a01a8c0@xp> <437BAD36.3090007@web.de> Message-ID: <437CCD0E.1070306@accesstel.co.za> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051117/0dd4f54d/attachment.html From alan.gauld at freenet.co.uk Thu Nov 17 19:53:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 17 Nov 2005 18:53:56 -0000 Subject: [Tutor] How to remove Html from list. References: <1132246685.1E2ED4A8@ba12.dngr.org> <1132248464.202335B5@dk12.dngr.org> Message-ID: <003801c5eba8$43c6c3e0$0a01a8c0@xp> > I can not figure out what kind of expresion I need to use to find Html > code. Take a look at the regular expressions topic in my tutorial which gives an example of stripping stuff from HTML> However be aware that using regular expressions on html is never reliable and a proper parser like BeautifulSoup or ElemTree will do a much better job. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From lordvader at gmail.com Thu Nov 17 20:29:07 2005 From: lordvader at gmail.com (Fred Lionetti) Date: Thu, 17 Nov 2005 11:29:07 -0800 Subject: [Tutor] compiled images Message-ID: <434140620511171129s13e6ddb6h9f392ffb346ee8b3@mail.gmail.com> Hi everyone, Thanks everyone for the help with lambda expressions! Your suggestions and discussions were great! I've got another question I think you may have come across before. I'm planning on purchasing a license to use some stock icons in an application I'm developing. The problem is the license requires this: "Where an application is to be distributed, the graphical media must be compiled into the application binary file or its associated data files, documentation files, or components." Anyone have any idea as to how I could basically "compile" all my artwork into a data file for a python application? Would this require compiling them into a *.dll/*.so? It seems like there must be any easier way--Also, I need my application to work on windows + linux (and mac). Any suggestions/experience would be greatly appreciated! Thanks, Fred From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 17 20:51:59 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 18 Nov 2005 08:51:59 +1300 Subject: [Tutor] Newb ? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B142F@chbnt01.alpha.wd.govt.nz> How about - print "\n\nWelcome to the Backwards Message Display." print message = raw_input("\nPlease Enter a Message.") msgAsList = [ char for char in message] msgAsList.reverse() reversedMessage = ''.join(msgAsList) I can't test that, but it should work. But, with regard to - > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > > high = len(message) > low = -len(message) > print > print message[high:low] > print > print raw_input("Please Press Enter to Exit") low will always be the first char of the string, won't it? In which case, It'd always be 0. or len(message) - len(message) ! -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Ed Singleton Sent: Friday, 18 November 2005 6:11 a.m. To: tutor at python.org Subject: Re: [Tutor] Newb ? These both work (though neither is very graceful). text = "hello" message = "" for i in range(len(text)): message = message + text[(len(text)-i-1)] print message lst = list(text) newstr = "" for item in text: newstr += (lst.pop()) print newstr On 16/11/05, Chad Everett wrote: > Hello all, > > Have a problem here with a challenge from a book I am reading. Any > help is much appreciated. > > I am trying to run a program that asks the user for a statement and > then prints it out backwards. this is what I have. > It does not print anything out. I assume that I have something out of whack > with my high and low statements. > > Thanks for you help. > > > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > > high = len(message) > low = -len(message) > print > print message[high:low] > print > print raw_input("Please Press Enter to Exit") > > > -- > http://mail.python.org/mailman/listinfo/python-list > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 17 20:57:38 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 18 Nov 2005 08:57:38 +1300 Subject: [Tutor] compiled images Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1430@chbnt01.alpha.wd.govt.nz> Hehe, Sounds like someone's license was designed for C/C++. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Fred Lionetti Sent: Friday, 18 November 2005 8:29 a.m. To: tutor at python.org Subject: [Tutor] compiled images Hi everyone, Thanks everyone for the help with lambda expressions! Your suggestions and discussions were great! I've got another question I think you may have come across before. I'm planning on purchasing a license to use some stock icons in an application I'm developing. The problem is the license requires this: "Where an application is to be distributed, the graphical media must be compiled into the application binary file or its associated data files, documentation files, or components." Anyone have any idea as to how I could basically "compile" all my artwork into a data file for a python application? Would this require compiling them into a *.dll/*.so? It seems like there must be any easier way--Also, I need my application to work on windows + linux (and mac). Any suggestions/experience would be greatly appreciated! Thanks, Fred _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Christian.Wyglendowski at greenville.edu Thu Nov 17 21:31:14 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 17 Nov 2005 14:31:14 -0600 Subject: [Tutor] Newb ? Message-ID: Liam said: > > How about - > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > msgAsList = [ char for char in message] You could also do: msgAsList = list(message) list() takes any iterable and returns a list object. > msgAsList.reverse() > reversedMessage = ''.join(msgAsList) In Python 2.4, the following is also possible: reversedMessage = ''.join(reversed(list(message))) It's amazing how in Python even one-liners can be so pretty :-) Christian From Liam.Clarke-Hutchinson at business.govt.nz Thu Nov 17 21:43:57 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 18 Nov 2005 09:43:57 +1300 Subject: [Tutor] Newb ? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1438@chbnt01.alpha.wd.govt.nz> >list() takes any iterable and returns a list object. Hmm, I did not know that the list(str) thing worked that way.That'll reduce the list comprehensions, but is it intuitive? Would a newbie see that and think that list("Hi") returns ["Hi"] or ["H","i"] ? >reversedMessage = ''.join(reversed(list(message))) Yes, but for clarity when demonstrating a concept, one-liners should be minimised, I think. ;) But I agree, you can create some obscenely complicated one liners, which are still understandable. I find I have to force myself sometimes to refactor some of the ones I come up with, however. Good rule of thumb is when you're feeling impressed with your own cleverness, you probably need to refactor. (Thanks c2 wiki, for teaching me that.) -----Original Message----- From: Christian Wyglendowski [mailto:Christian.Wyglendowski at greenville.edu] Sent: Friday, 18 November 2005 9:31 a.m. To: Liam Clarke-Hutchinson; tutor at python.org Subject: RE: [Tutor] Newb ? Liam said: > > How about - > print "\n\nWelcome to the Backwards Message Display." > print > message = raw_input("\nPlease Enter a Message.") > msgAsList = [ char for char in message] You could also do: msgAsList = list(message) list() takes any iterable and returns a list object. > msgAsList.reverse() > reversedMessage = ''.join(msgAsList) In Python 2.4, the following is also possible: reversedMessage = ''.join(reversed(list(message))) It's amazing how in Python even one-liners can be so pretty :-) Christian A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From Christian.Wyglendowski at greenville.edu Thu Nov 17 21:45:43 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 17 Nov 2005 14:45:43 -0600 Subject: [Tutor] compiled images Message-ID: Fred said: > [snip] > I've got another question I think you may have come across before. > I'm planning on purchasing a license to use some stock icons in an > application I'm developing. The problem is the license requires this: > > "Where an application is to be distributed, the graphical media must > be compiled into the application binary file or its associated data > files, documentation files, or components." > > Anyone have any idea as to how I could basically "compile" all my > artwork into a data file for a python application? Would this require > compiling them into a *.dll/*.so? It seems like there must be any > easier way--Also, I need my application to work on windows + linux > (and mac). Hhhmm...from what I remember, getting at icons in DLLs is pretty easy. I think that is where windows stores a lot of its icons actually. If they are just looking to dissuade the "casual icon theft" maybe they would be ok if you included the images as base64 encoded strings in your source code: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52264 You could even take that further by having a resource file or something that contained pickled base64 encoded image strings. Maybe that would be "compiled" enough for them? > Any suggestions/experience would be greatly appreciated! Hope some of this helps. I guess asking them how they have dealt with interpreted languages in the past might help. Christian From singingxduck at gmail.com Thu Nov 17 21:53:42 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Thu, 17 Nov 2005 15:53:42 -0500 Subject: [Tutor] Newb ? In-Reply-To: References: Message-ID: <437CEDD6.1030409@gmail.com> Christian Wyglendowski wrote: >Liam said: > > >>How about - >>print "\n\nWelcome to the Backwards Message Display." >>print >>message = raw_input("\nPlease Enter a Message.") >>msgAsList = [ char for char in message] >> >> > >You could also do: > >msgAsList = list(message) > >list() takes any iterable and returns a list object. > > > >>msgAsList.reverse() >>reversedMessage = ''.join(msgAsList) >> >> > >In Python 2.4, the following is also possible: > >reversedMessage = ''.join(reversed(list(message))) > >It's amazing how in Python even one-liners can be so pretty :-) > >Christian >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Or you could just do the following: >>> print "\n\nWelcome to the Backwards Message Display." >>> print >>> message = raw_input("\nPlease Enter a Message.") >>> print message[::-1] This is the equivalent of print ''.join(reversed(message)), since reversed works on any iterable sequence, including strings. In any case, the syntax for this sort of thing in general is: sequence[start:stop:step], with start defaulting to 0, step defaulting to sys.maxint (which, for all intents and purposes, means the end of the string), and step defaulting to 1. However, when step is negative, start and end switch defaults. So by doing [::-1], you're telling Python to return the values of the sequence that can be found from the end to the start Another way to do this would be: >>> import sys >>> for i in range(len(sequence)-1,-1,-1): sys.stdout.write(sequence[i]) # to remove spaces between elements, # which would be produced by the more # intuitive "print sequence[i]," technique So, the first time around, i is len(sequence)-1, or the last element, because that's the start value. Next, it's len(sequence)-2, or the second to last element, because the step is -1. etc . . . Until the last round when i is 0, after which step is added to i and i==-1, so the loop is not re-entered. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From Christian.Wyglendowski at greenville.edu Thu Nov 17 22:08:15 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu, 17 Nov 2005 15:08:15 -0600 Subject: [Tutor] Newb ? Message-ID: Orri said: > Or you could just do the following: > > >>> print "\n\nWelcome to the Backwards Message Display." > >>> print > >>> message = raw_input("\nPlease Enter a Message.") > >>> print message[::-1] Interesting. I forgot about the 'step' option when slicing. > This is the equivalent of print ''.join(reversed(message)), since > reversed works on any iterable sequence, including strings. Ha! Good call. Makes it even clearer. > In any > case, the syntax for this sort of thing in general is: > sequence[start:stop:step], with start defaulting to 0, step > defaulting > to sys.maxint (which, for all intents and purposes, means the > end of the > string), and step defaulting to 1. However, when step is negative, > start and end switch defaults. So by doing [::-1], you're telling > Python to return the values of the sequence that can be found > from the > end to the start Cool. Thanks for this explanation. Christian From john at fouhy.net Thu Nov 17 22:27:06 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 18 Nov 2005 10:27:06 +1300 Subject: [Tutor] compiled images In-Reply-To: <434140620511171129s13e6ddb6h9f392ffb346ee8b3@mail.gmail.com> References: <434140620511171129s13e6ddb6h9f392ffb346ee8b3@mail.gmail.com> Message-ID: <5e58f2e40511171327k72bcc868u@mail.gmail.com> On 18/11/05, Fred Lionetti wrote: > Anyone have any idea as to how I could basically "compile" all my > artwork into a data file for a python application? Would this require > compiling them into a *.dll/*.so? It seems like there must be any > easier way--Also, I need my application to work on windows + linux > (and mac). Maybe you could use shelve? For instance, if you have myIcon1.gif, myIcon2.gif, myIcon3.gif: #### import shelve shelf = shelve.open('iconData') for fn in ['myIcon1.gif', 'myIcon2.gif', 'myIcon3.gif']: shelf[fn] = file(fn, 'rb').read() #### Then, in future, you should be able to access your icons by just: shelf = shelve.open('iconData') doSomething(shelf['myIcon2.gif']) (and if your methods require a file-like object instead of just a binary string, you can use the StringIO module) There may be space or time issues --- you might want to experiment :-) --- but it will definitely be cross-platform. -- John. From chris.arndt at web.de Fri Nov 18 00:12:00 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 17 Nov 2005 23:12:00 +0000 Subject: [Tutor] new topic draft In-Reply-To: <437CCD0E.1070306@accesstel.co.za> References: <03e001c5e965$8a671fb0$0a01a8c0@xp> <437AE9FE.3000106@accesstel.co.za> <000c01c5eaf0$6cd42420$0a01a8c0@xp> <437BAD36.3090007@web.de> <437CCD0E.1070306@accesstel.co.za> Message-ID: <437D0E40.5020408@web.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Johan Geldenhuys schrieb: > This script was not intended to be used from the command line, but to > be called from elsewhere. It was only a test piece of code. > If you use the ping command with the args that you are calling it with, > there is no need to kill the process, it will terminate after 10 > requests. 8-) Yes, that's right. It was just an example and I wanted it to terminate wether the killing of the process succeeded or not. I just thought I might be of help in turning an interesting idea into something instantly reusable. Chris -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) Comment: Seeing only garbage? Get my OpenPGP key here: http://chrisarndt.de/contact.html iD8DBQFDfQ4/XWGCGKl166oRAuP5AJ97+yt1C79AC1XUGn2oWtuDUmN3KgCfcQPu hAZibDiEVrdDtzBJDv+hWWo= =EukF -----END PGP SIGNATURE----- From ewalker at micron.com Fri Nov 18 00:31:29 2005 From: ewalker at micron.com (Eric Walker) Date: Thu, 17 Nov 2005 16:31:29 -0700 Subject: [Tutor] opts and try except Message-ID: <200511171631.29817.ewalker@micron.com> All, I have a program now that works just like I want it. Now I want to integerate something to say print usage info when the user puts in the wrong number or type of options. Also print usage say if you type program name and -h or -H. I currently just have functions defined and at the bottom make a function call. Do I need to do like the def main(): and then the if __name__ == "__main__"? I need an example of how to implement this. Thanks in advance. python newbie..... From wan at walrus.us Fri Nov 18 02:20:33 2005 From: wan at walrus.us (Vincent Wan) Date: Thu, 17 Nov 2005 16:20:33 -0900 Subject: [Tutor] building nonbinary trees Message-ID: I would like to have a tree data structure with trees whose nodes could have an arbitrary number of descendants and that I could iterate over by the names of nodes I'v got a start but I'm stuck because I don't understand how to call a tree's nodes by name. Here is the code I have so far: import random # constants that control the simulation NUMBER_REPS = 10 # run's the simulation MAX_LINAGES = 10 # number of species in each run BRANCHING_PROBABILITY = 0.5 class Tree(object): numLinages = 0 class Node(object): def __init__(self, name): self.name = name self.alive = True self.descendents = [] Tree.numLinages += 1 def __init__(self): self.rootnode = Tree.Node(0) def AddBranch(self, linage, offspring): new = Tree.Node(offspring) self.descendents.append(new) def NumLinages( ): return Tree.numLinages NumLinages = staticmethod(NumLinages) currentTree = Tree() print Tree.NumLinages() for i in range(NUMBER_REPS): j = 0 while j <= currentTree.NumLinages(): if random.random() >= BRANCHING_PROBABILITY: currentTree.AddBranch(j, currentTree.NumLinages() + 1) j += 1 thank you, Vincent Wan ------------------------------------------------------------------------ -------------- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) From Liam.Clarke-Hutchinson at business.govt.nz Fri Nov 18 02:29:32 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Fri, 18 Nov 2005 14:29:32 +1300 Subject: [Tutor] building nonbinary trees Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1444@chbnt01.alpha.wd.govt.nz> Erm, a dictionary of names to references? -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Vincent Wan Sent: Friday, 18 November 2005 2:21 p.m. To: tutor at python.org Subject: [Tutor] building nonbinary trees I would like to have a tree data structure with trees whose nodes could have an arbitrary number of descendants and that I could iterate over by the names of nodes I'v got a start but I'm stuck because I don't understand how to call a tree's nodes by name. Here is the code I have so far: import random # constants that control the simulation NUMBER_REPS = 10 # run's the simulation MAX_LINAGES = 10 # number of species in each run BRANCHING_PROBABILITY = 0.5 class Tree(object): numLinages = 0 class Node(object): def __init__(self, name): self.name = name self.alive = True self.descendents = [] Tree.numLinages += 1 def __init__(self): self.rootnode = Tree.Node(0) def AddBranch(self, linage, offspring): new = Tree.Node(offspring) self.descendents.append(new) def NumLinages( ): return Tree.numLinages NumLinages = staticmethod(NumLinages) currentTree = Tree() print Tree.NumLinages() for i in range(NUMBER_REPS): j = 0 while j <= currentTree.NumLinages(): if random.random() >= BRANCHING_PROBABILITY: currentTree.AddBranch(j, currentTree.NumLinages() + 1) j += 1 thank you, Vincent Wan ------------------------------------------------------------------------ -------------- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From wan at walrus.us Fri Nov 18 03:41:29 2005 From: wan at walrus.us (Vincent Wan) Date: Thu, 17 Nov 2005 17:41:29 -0900 Subject: [Tutor] building non binary trees CLARIFIED Message-ID: <0A911816-A843-40E8-B499-CA7BB879733B@walrus.us> Let me try to clarify my problem. I would like to have a tree data structure with trees whose nodes could have an arbitrary number of descendants and that I could iterate over by the names of nodes this is the first time I've used objects. I tried to model my code on a binary tree data structure Roel Schroeven wrote in reply to an earlier post of mine http://mail.python.org/pipermail/tutor/2005-November/043214.html but I don't understand what's happening in his code on the line commented # what's happening here class Tree(object): class Node(object): def __init__(self, linage, left=None, right=None): self.linage = linage self.left = left self.right = right def __init__(self, rootlinage): self.rootnode = Tree.Node(rootlinage) self.linagetonode = {rootlinage: self.rootnode} # what's happening here def AddBranch(self, linage, newlinage): node = self.linagetonode[linage] left = Tree.Node(linage) right = Tree.Node(newlinage) node.left = left node.right = right self.linagetonode[linage] = left self.linagetonode[newlinage] = right my code seems to barf because when I call Tree's AddBranch method I'm not telling it which node to add to. I don't know how to go from the name of a node (here a integer) to reference to the node with that name to pass to AddBranch. my code import random # constants that control the simulation NUMBER_REPS = 10 # run's the simulation MAX_LINAGES = 10 # number of species in each run BRANCHING_PROBABILITY = 0.5 class Tree(object): numLinages = 0 class Node(object): def __init__(self, name): self.name = name self.alive = True self.descendents = [] Tree.numLinages += 1 def __init__(self): self.rootnode = Tree.Node(0) def AddBranch(self, linage, offspring): new = Tree.Node(offspring) self.descendents.append(new) def NumLinages( ): return Tree.numLinages NumLinages = staticmethod(NumLinages) currentTree = Tree() print Tree.NumLinages() for i in range(NUMBER_REPS): j = 0 while j <= currentTree.NumLinages(): if random.random() >= BRANCHING_PROBABILITY: currentTree.AddBranch(j, currentTree.NumLinages() + 1) j += 1 Vincent Wan ------------------------------------------------------------------------ -------------- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) From gregor at mail.uajy.ac.id Fri Nov 18 04:53:37 2005 From: gregor at mail.uajy.ac.id (Gregorius Gede Wiranarada) Date: Fri, 18 Nov 2005 10:53:37 +0700 Subject: [Tutor] displaying properties/methods Message-ID: <20051118035337.14128.qmail@mail.uajy.ac.id> Hi all, i'm a newbie to python and now learning OOP. How do i display methods or properties that is owned by a class or a module? for example: i know that module sys has a property/method called path. i want to know what other methods it has, how do i find them from python command line? thx. regards, Gregor _______________________________________________________________________ Dibuka pendaftaran Program Magister dan Double Degree Pascasarjana UAJY (MM - MTF atau sebaliknya; M.Hum - MTF; M.Hum - MM; MTS. - MM). Penerimaan mahasiswa setiap Mei, September dan Januari. From alan.gauld at freenet.co.uk Fri Nov 18 06:30:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Nov 2005 05:30:53 -0000 Subject: [Tutor] building nonbinary trees References: Message-ID: <001801c5ec01$3ed228d0$0a01a8c0@xp> > I'v got a start but I'm stuck because I don't understand how to call > a tree's nodes by name. Every time you see call by name, think dictionary. class Node: def __init__(self): self.children = {} def addChild(self,child,name): self.children[name] = child etc... HTH, Alan G. From alan.gauld at freenet.co.uk Fri Nov 18 06:31:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 18 Nov 2005 05:31:57 -0000 Subject: [Tutor] displaying properties/methods References: <20051118035337.14128.qmail@mail.uajy.ac.id> Message-ID: <001e01c5ec01$64c2af10$0a01a8c0@xp> > Hi all, i'm a newbie to python and now learning OOP. How do i display > methods or properties that is owned by a class or a module? for example: i > know that module sys has a property/method called path. i want to know > what other methods it has, how do i find them from python command line? Try: import sys dir(sys) help(sys) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Fri Nov 18 06:49:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 17 Nov 2005 21:49:09 -0800 (PST) Subject: [Tutor] opts and try except In-Reply-To: <200511171631.29817.ewalker@micron.com> Message-ID: On Thu, 17 Nov 2005, Eric Walker wrote: > I have a program now that works just like I want it. Now I want to > integerate something to say print usage info when the user puts in the > wrong number or type of options. Also print usage say if you type > program name and -h or -H. I currently just have functions defined and > at the bottom make a function call. Do I need to do like the def main(): > and then the if __name__ == "__main__"? I need an example of how to > implement this. Hi Eric, Yes, there's a whole option-parsing system called 'optparse' that handles option-parsing and the -h documentation generator: http://www.python.org/doc/lib/module-optparse.html The examples in the documentation there should help you get started. If you have more questions, though, please feel free to ask. Good luck! From smiles at worksmail.net Fri Nov 18 16:19:48 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 18 Nov 2005 09:19:48 -0600 Subject: [Tutor] Tutor Digest, Vol 21, Issue 79 References: Message-ID: <006e01c5ec53$b57399e0$352c4fca@csmith> Orri Ganel wrote: Another way to do this would be: | |||| import sys |||| for i in range(len(sequence)-1,-1,-1): | sys.stdout.write(sequence[i]) || It might be interesting to note that although this *range* works for accessing the indices, you can't do the same directly in slice notation: ###### >>> 'abc'[2:-1:-1] '' >>> 'abc'[2:0:-1] 'cb' >>> 'abc'[::-1] 'cba' ###### In the first case the -1 refers to the same position in the string as the 2 so this is a null slice. And in the second case, we miss the first character because the indices only go up *to* the zero (thus through 1) and not through 0. Fortunately, we can let Python handle the problem by just leaving off the indices as has already been pointed out and is shown in the 3rd example. /c From k.weinert at gmx.net Fri Nov 18 16:32:15 2005 From: k.weinert at gmx.net (K. Weinert) Date: Fri, 18 Nov 2005 16:32:15 +0100 Subject: [Tutor] Tkinter mainloop Message-ID: <437DF3FF.5020006@gmx.net> Hello, Thanks a lot for the pointers, Kent, and the explanations, Michael! > There is an undocumented hook that lets you change this - the function > Tk.report_callback_exception() is called to actually report the error. > You can redefine this function to do what you want. Here are a couple > of examples: > http://zephyrfalcon.org/weblog/arch_d7_2003_01_04.html > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ce0036f41da8a22f/c62177e5bb59b09c%23c62177e5bb59b09c?sa=X&oi=groupsr&start=1&num=3 I think I see much clearer now. My little filesearch dialog makes progress. Have a nice weekend! Karsten. From smiles at worksmail.net Fri Nov 18 16:34:25 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 18 Nov 2005 09:34:25 -0600 Subject: [Tutor] Newbie ? Message-ID: <007f01c5ec55$d925b6f0$352c4fca@csmith> Orri Ganel wrote: Another way to do this would be: | |||| import sys |||| for i in range(len(sequence)-1,-1,-1): | sys.stdout.write(sequence[i]) || It might be interesting to note that although this *range* works for accessing the indices, you can't do the same directly in slice notation: ###### >>> 'abc'[2:-1:-1] '' >>> 'abc'[2:0:-1] 'cb' >>> 'abc'[::-1] 'cba' ###### In the first case the -1 refers to the same position in the string as the 2 so this is a null slice. And in the second case, we miss the first character because the indices only go up *to* the zero (thus through 1) and not through 0. Fortunately, we can let Python handle the problem by just leaving off the indices as has already been pointed out and is shown in the 3rd example. /c From wescpy at gmail.com Sat Nov 19 01:27:42 2005 From: wescpy at gmail.com (w chun) Date: Fri, 18 Nov 2005 16:27:42 -0800 Subject: [Tutor] displaying properties/methods In-Reply-To: <001e01c5ec01$64c2af10$0a01a8c0@xp> References: <20051118035337.14128.qmail@mail.uajy.ac.id> <001e01c5ec01$64c2af10$0a01a8c0@xp> Message-ID: <78b3a9580511181627n618fdd60q4b622a332d8092dc@mail.gmail.com> > dir(sys) > help(sys) to further elaborate, dir() will tell you what it has, and help() will dump pretty-printed doc strings for you. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From lists at janeden.org Sat Nov 19 16:45:50 2005 From: lists at janeden.org (Jan Eden) Date: Sat, 19 Nov 2005 16:45:50 +0100 Subject: [Tutor] Dynamic inheritance? Message-ID: Hi, I have a number of classes, each of which should inherit from a related superclass in another module: class A(Super.A): ... class B(Super.B): ... class C(Super.C): ... Is there a way to dynamically determine the value of Super at runtime? Background: Depending on certain object attributes which are set during the object initialization, I need to use a different set of templates for the respective object. Example: If a page object belongs to site A, it needs to inherit from the template class SiteA.Page, a gallery object belonging to site B should inherit from SiteB.Gallery etc. The problem is that the template classes are not self contained, i.e. SiteB.Gallery inherits from SiteB.List, SiteB.Base etc. Thanks in advance, Jan -- Any sufficiently advanced technology is insufficiently documented. From python at venix.com Sat Nov 19 18:23:14 2005 From: python at venix.com (Python) Date: Sat, 19 Nov 2005 12:23:14 -0500 Subject: [Tutor] Dynamic inheritance? In-Reply-To: References: Message-ID: <1132420994.26889.29.camel@www.venix.com> On Sat, 2005-11-19 at 16:45 +0100, Jan Eden wrote: > > Is there a way to dynamically determine the value of Super at runtime? Background: Depending on certain object attributes which are set during the object initialization, I need to use a different set of templates for the respective object. > If you use new style classes, then there is a super function that can be used to automatically resolve a superclass reference. You can force new style classes by: inherit from object easy to see, but repetitive __metaclass__ = type put before the class statements super(Myclass,self).__init__(...) will search through the inheritance tree and (in this case) invoke __init__. Use __bases__ to run up the inheritance yourself. >>> class A: ... pass ... >>> class B(A): ... pass ... >>> b.__class__.__bases__ (,) >>> B.__bases__ (,) The "magic" class attributes don't get listed by the dir command so you need to search the documentation to find this. http://docs.python.org/lib/specialattrs.html >>> dir(B) ['__doc__', '__module__'] >>> b = B() >>> dir(b) ['__doc__', '__module__'] -- Lloyd Kvam Venix Corp From kent37 at tds.net Sat Nov 19 18:53:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 Nov 2005 12:53:11 -0500 Subject: [Tutor] Dynamic inheritance? In-Reply-To: References: Message-ID: <437F6687.8010409@tds.net> Jan Eden wrote: > Hi, > > I have a number of classes, each of which should inherit from a > related superclass in another module: > > class A(Super.A): ... > > class B(Super.B): ... > > class C(Super.C): ... > > Is there a way to dynamically determine the value of Super at > runtime? Background: Depending on certain object attributes which are > set during the object initialization, I need to use a different set > of templates for the respective object. Sure, just import the correct template module conditionally and give it a new name: if site == 'siteA': import SiteA as Super else import SiteB as Super class A(Super.A): etc. If you need to do the import based on a string use the __import__() function: http://www.python.org/doc/current/lib/built-in-funcs.html > The problem is that the template classes are not self contained, i.e. > SiteB.Gallery inherits from SiteB.List, SiteB.Base etc.> > Thanks in advance, I don't see why that is a problem? Kent -- http://www.kentsjohnson.com From lists at janeden.org Sat Nov 19 22:15:46 2005 From: lists at janeden.org (Jan Eden) Date: Sat, 19 Nov 2005 22:15:46 +0100 Subject: [Tutor] Dynamic inheritance? In-Reply-To: <437F6687.8010409@tds.net> Message-ID: Hi Kent, Kent Johnson wrote on 19.11.2005: >Jan Eden wrote: >> Is there a way to dynamically determine the value of Super at >> runtime? Background: Depending on certain object attributes which are >> set during the object initialization, I need to use a different set >> of templates for the respective object. > >Sure, just import the correct template module conditionally and give it a new >name: > >if site == 'siteA': > import SiteA as Super >else > import SiteB as Super > >class A(Super.A): > >etc. > >If you need to do the import based on a string use the __import__() function: >http://www.python.org/doc/current/lib/built-in-funcs.html > Excellent. This is exactly what I need. I was not aware of the fact that you can rename modules upon importing them. >> The problem is that the template classes are not self contained, i.e. >> SiteB.Gallery inherits from SiteB.List, SiteB.Base etc.> >> Thanks in advance, > >I don't see why that is a problem? > Please disregard the last statement in my first message: There is indeed no problem with this requirement. Thanks for your help, Jan -- Common sense is what tells you that the world is flat. From dyoo at hkn.eecs.berkeley.edu Sun Nov 20 00:23:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 19 Nov 2005 15:23:02 -0800 (PST) Subject: [Tutor] Dynamic inheritance? In-Reply-To: Message-ID: On Sat, 19 Nov 2005, Jan Eden wrote: > I have a number of classes, each of which should inherit from a related > superclass in another module: > > class A(Super.A): > ... > > class B(Super.B): > ... > > class C(Super.C): > ... > > Is there a way to dynamically determine the value of Super at runtime? Here's a small example that shows how classes can be treated just like any other value in Python: ######################################### def makeYa(superclass): class Ya(superclass): def sayHi(self): superclass.sayHi(self) print "ya" return Ya class ValleyPerson: def sayHi(self): print "like, so, oh my gosh, hi?" FrankensteinClass = makeYa(ValleyPerson) instance = FrankensteinClass() instance.sayHi() ######################################### So there's no need to do trickery with conditional imports; Python treats classes as first-class objects that can be passed around. Best of wishes! From boyanpn at yahoo.com Sun Nov 20 00:54:39 2005 From: boyanpn at yahoo.com (Bojan Raicevic) Date: Sat, 19 Nov 2005 15:54:39 -0800 (PST) Subject: [Tutor] How should I store data ? Message-ID: <20051119235439.43899.qmail@web35508.mail.mud.yahoo.com> I want to store data in the shape of (for example): First name, Last name, Age, ... few more characteristics. I must be able to search data by any of this fields. For example, search for age, or name ... etc Also, I want to put option in main program to change (update), add and remove that data. How do I do that (easiest way, please) ? --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051119/653c262e/attachment.htm From python at venix.com Sun Nov 20 01:46:46 2005 From: python at venix.com (Python) Date: Sat, 19 Nov 2005 19:46:46 -0500 Subject: [Tutor] Dynamic inheritance? In-Reply-To: References: Message-ID: <1132447606.26889.40.camel@www.venix.com> On Sat, 2005-11-19 at 15:23 -0800, Danny Yoo wrote: > Here's a small example that shows how classes can be treated just like any > other value in Python: > > ######################################### > def makeYa(superclass): > class Ya(superclass): > def sayHi(self): > superclass.sayHi(self) > print "ya" > return Ya > Sorry I totally misunderstood. Essentially, you want the super class(es) in the class statement to be variables. It's a good thing Danny and Kent were around. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From adisegna at gmail.com Sun Nov 20 03:33:52 2005 From: adisegna at gmail.com (Adisegna) Date: Sat, 19 Nov 2005 21:33:52 -0500 Subject: [Tutor] smtplib alternative??? Message-ID: <6571c3530511191833u7c7da631w7fcbe20ed8f19c47@mail.gmail.com> Hello, I found this script to send mail online. It works fine but requires me to enter an mail server. I'm looking for something else that doesn't require and SMTP server. Having to specify a mail server prohibits me from sending to alternate domains. Thanks in advance smtpserver = 'my.mailserver.com ' RECIPIENTS = ['myaddress at goeshere.com'] SENDER = 'Somethin at something.com' mssg = SomeVariable session = smtplib.SMTP(smtpserver) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051119/774336a2/attachment.html From kent37 at tds.net Sun Nov 20 03:46:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 19 Nov 2005 21:46:37 -0500 Subject: [Tutor] Dynamic inheritance? In-Reply-To: References: Message-ID: <437FE38D.3040709@tds.net> Danny Yoo wrote: > Here's a small example that shows how classes can be treated just like any > other value in Python: > > ######################################### > def makeYa(superclass): > class Ya(superclass): > def sayHi(self): > superclass.sayHi(self) > print "ya" > return Ya > > class ValleyPerson: > def sayHi(self): > print "like, so, oh my gosh, hi?" > > FrankensteinClass = makeYa(ValleyPerson) > instance = FrankensteinClass() > instance.sayHi() > ######################################### Yeah, that'll work too :-) Or even def makeAB(moduleContainingSuperClass): class A(moduleContainingSuperClass.A): pass class B(moduleContainingSuperClass.B) pass return A, B A, B = makeAB(siteA) > So there's no need to do trickery with conditional imports; Python treats > classes as first-class objects that can be passed around. Trickery? ;) It's just using modules as first-class objects that are bound to names same as anything else. Which solution is better depends on whether you want to choose at the module level or with finer control. Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Sun Nov 20 07:43:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 19 Nov 2005 22:43:41 -0800 (PST) Subject: [Tutor] How should I store data ? In-Reply-To: <20051119235439.43899.qmail@web35508.mail.mud.yahoo.com> Message-ID: On Sat, 19 Nov 2005, Bojan Raicevic wrote: > I want to store data in the shape of (for example): > First name, Last name, Age, ... few more characteristics. > I must be able to search data by any of this fields. For example, > search for age, or name ... etc > Also, I want to put option in main program to change (update), add and > remove that data. > How do I do that (easiest way, please) ? Hi Bojan, If you're not bound to use Python directly, I'd recommend looking into a relational database. Relational databases may solve the problem you're describing: to search by any field, to handle storage and loading, and to support those operations efficiently. There are few free ones available that you can experiment with. One popular one is sqlite. http://www.sqlite.org/ If you want to then write a nice interface around the database, you can take advantage of the pysqlite module: http://initd.org/projects/pysqlite If you have more questions, please feel free to ask. From dyoo at hkn.eecs.berkeley.edu Sun Nov 20 08:03:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 19 Nov 2005 23:03:04 -0800 (PST) Subject: [Tutor] smtplib alternative??? In-Reply-To: <6571c3530511191833u7c7da631w7fcbe20ed8f19c47@mail.gmail.com> Message-ID: On Sat, 19 Nov 2005, Adisegna wrote: > I found this script to send mail online. It works fine but requires me > to enter an mail server. I'm looking for something else that doesn't > require and SMTP server. Having to specify a mail server prohibits me > from sending to alternate domains. Hi Adisegna, I've always assumed that emails have to talk with some SMTP server. RFC821 seems to confirm this: http://www.faqs.org/rfcs/rfc821.html so what you're asking, to be able to send mail without an SMTP server, may not be possible. There is an 'smtpd' module that comes with Python: http://www.python.org/doc/lib/module-smtpd.html I'm also not sure I understand the reason you're trying to avoid talking to an outside smtp server. But again, I'm unfamiliar enough with how the SMTP email protocol really works that perhaps I'm just overlooking something. From lists at janeden.org Sun Nov 20 08:41:53 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 20 Nov 2005 08:41:53 +0100 Subject: [Tutor] Dynamic inheritance? In-Reply-To: <437FE38D.3040709@tds.net> Message-ID: Kent Johnson wrote on 19.11.2005: >Danny Yoo wrote: >>Here's a small example that shows how classes can be treated just >>like any other value in Python: >> >> ######################################### >> def makeYa(superclass): >> class Ya(superclass): >> def sayHi(self): >> superclass.sayHi(self) >> print "ya" >> return Ya >> >> class ValleyPerson: >> def sayHi(self): >> print "like, so, oh my gosh, hi?" >> >> FrankensteinClass = makeYa(ValleyPerson) >> instance = FrankensteinClass() >> instance.sayHi() >> ######################################### > >Yeah, that'll work too :-) Or even > >def makeAB(moduleContainingSuperClass): > class A(moduleContainingSuperClass.A): > pass > class B(moduleContainingSuperClass.B) > pass > return A, B > >A, B = makeAB(siteA) > >>So there's no need to do trickery with conditional imports; Python >>treats classes as first-class objects that can be passed around. > >Trickery? ;) It's just using modules as first-class objects that are >bound to names same as anything else. Which solution is better >depends on whether you want to choose at the module level or with >finer control. Hm, sounds like there's more than one way to do it. ;-) Thanks a lot for your examples. I hate to confess that I incorrectly described my requirements. It turns out that I am better off with a (variant of the) state design pattern. But I am stuck there, too. The situation is this: For every object, two string attributes are determined during initialization (one being read from a database, the other inherited as a superclass attribute). The first contains the site name, the second the object type. I'd like to set the template attribute to the proper class: import Templates self.site_name = 'SiteA' self.template_type = 'Page' self.template = ??? self.template should refer to Templates.SiteA.Page in this case (where SiteA is a module of package Templates, and Page is a class within that module). Danny already said that classes can be treated just like any other object - but how do I get from a string to a class or module name? Thanks for all your help, and sorry for my ignorance, Jan -- Any sufficiently advanced technology is indistinguishable from a Perl script. - Programming Perl From johan at accesstel.co.za Sun Nov 20 09:05:34 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Sun, 20 Nov 2005 10:05:34 +0200 Subject: [Tutor] opts and try except In-Reply-To: <200511171631.29817.ewalker@micron.com> References: <200511171631.29817.ewalker@micron.com> Message-ID: <43802E4E.2020509@accesstel.co.za> Maybe this recipe will help. Here I used and tested the arguments that the user must enter before using the module: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440476 Johan Eric Walker wrote: >All, >I have a program now that works just like I want it. Now I want to >integerate something to say print usage info when the user puts in the wrong >number or type of options. Also print usage say if you type program name and >-h or -H. I currently just have functions defined and at the bottom make a >function call. Do I need to do like the def main(): and then the if __name__ >== "__main__"? I need an example of how to implement this. > >Thanks in advance. > > >python newbie..... >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > From alan.gauld at freenet.co.uk Sun Nov 20 09:08:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 20 Nov 2005 08:08:27 -0000 Subject: [Tutor] How should I store data ? References: <20051119235439.43899.qmail@web35508.mail.mud.yahoo.com> Message-ID: <002501c5eda9$969aa3e0$0a01a8c0@xp> >I want to store data in the shape of (for example): > First name, Last name, Age, ... few more characteristics. > I must be able to search data by any of this fields. For example, search > for age, or name ... etc For small quantities you can store the data in a list or tuple or dictionary. You can then just write (orPickle) the container to a file. See my file handling tutorial topic for an example of an address book. > Also, I want to put option in main program to change (update), add and > remove that data. > How do I do that (easiest way, please) ? If there is a lot of data you should use a database, see the Working with Databases topic for the address book example revisited. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sun Nov 20 13:30:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Nov 2005 07:30:28 -0500 Subject: [Tutor] Dynamic inheritance? In-Reply-To: References: Message-ID: <43806C64.1020002@tds.net> Jan Eden wrote: > The situation is this: > > For every object, two string attributes are determined during > initialization (one being read from a database, the other inherited > as a superclass attribute). The first contains the site name, the > second the object type. I'd like to set the template attribute to the > proper class: > > import Templates > > self.site_name = 'SiteA' > self.template_type = 'Page' > > self.template = ??? > > self.template should refer to Templates.SiteA.Page in this case > (where SiteA is a module of package Templates, and Page is a class > within that module). Danny already said that classes can be treated > just like any other object - but how do I get from a string to a > class or module name? Use getattr() to access attributes by name. SiteA is an attribute of Templates and Page is an attribute of SiteA so you can get use getattr() twice to get what you want: site = getattr(Templates, self.site_name) self.template = getattr(site, self.template_type) > Thanks for all your help, and sorry for my ignorance, No problem, this list is for beginners! Kent -- http://www.kentsjohnson.com From enas_khalil at yahoo.com Sun Nov 20 14:35:19 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Sun, 20 Nov 2005 05:35:19 -0800 (PST) Subject: [Tutor] need help in how to make my script read arabic lang In-Reply-To: Message-ID: <20051120133519.86033.qmail@web30515.mail.mud.yahoo.com> hello , i want to know if yu please how can i use python code in tagging arabic text file my code is as follow : # -*- coding: cp1256 -*- import codecs from nltk.tagger import * from nltk.corpus import brown from nltk.tokenizer import WhitespaceTokenizer from nltk import * from nltk.tokenreader.tagged import TaggedTokenReader # Tokenize ten texts from the Brown Corpus train_tokens = [] text_str = (open('fataha2.txt').read()) #codecs.encode(text_str,'cp1256') reader = TaggedTokenReader(SUBTOKENS='WORDS') text_token = reader.read_token(text_str) print text_token['WORDS'] for l in text_token['WORDS']: train_tokens.append(l) #Initialise and train a unigram tagger mytagger = UnigramTagger(SUBTOKENS='WORDS') for xx in train_tokens: cc = reader.read_token(xx['TEXT']) # print cc.keys() cc['SUBTOKENS']= cc['WORDS'] mytagger.train(cc) #Once a UnigramTagger has been trained, the tag() method can be used to tag new text: text_token = Token(TEXT="????? ??? ?? ????????") WhitespaceTokenizer(SUBTOKENS='WORDS').tokenize(text_token) mytagger.tag(text_token) #print 'The first example : Using Unigram Tagger the reseults are : ' print print text_token and i got the following error : Traceback (most recent call last): File "I:/examples/unigramgtag1update1.py", line 13, in ? codecs.encode(text_str,'cp1256') File "C:\Python24\lib\encodings\cp1256.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 0: ordinal not in range(128) please help --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051120/1e29fceb/attachment.htm From adisegna at gmail.com Sun Nov 20 15:26:24 2005 From: adisegna at gmail.com (Adisegna) Date: Sun, 20 Nov 2005 09:26:24 -0500 Subject: [Tutor] smtplib alternative??? In-Reply-To: References: <6571c3530511191833u7c7da631w7fcbe20ed8f19c47@mail.gmail.com> Message-ID: <6571c3530511200626n78fe5bb9pbb0247a6a9c4a01@mail.gmail.com> Hi Danny, Yes, when sending an email your mail client will always send the email to the mail server specified by the MX record in the authoritive domain. Usually the domain specificed after the @ symbol. The problem with smtplib is that I have to specify the mail server I'm sending email too. What if I wanted to send an email to 3 different people on three different domains hosted by 3 different mail servers? Smtlib prohibits this functionality. Do you see what I mean now...? Thanks for replying... On 11/20/05, Danny Yoo wrote: > > > > On Sat, 19 Nov 2005, Adisegna wrote: > > > I found this script to send mail online. It works fine but requires me > > to enter an mail server. I'm looking for something else that doesn't > > require and SMTP server. Having to specify a mail server prohibits me > > from sending to alternate domains. > > Hi Adisegna, > > I've always assumed that emails have to talk with some SMTP server. > RFC821 seems to confirm this: > > http://www.faqs.org/rfcs/rfc821.html > > so what you're asking, to be able to send mail without an SMTP server, may > not be possible. There is an 'smtpd' module that comes with Python: > > http://www.python.org/doc/lib/module-smtpd.html > > I'm also not sure I understand the reason you're trying to avoid talking > to an outside smtp server. But again, I'm unfamiliar enough with how the > SMTP email protocol really works that perhaps I'm just overlooking > something. > > -- Arthur DiSegna Network Operations Center Authentium, Inc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051120/34b7d68b/attachment.htm From lists at janeden.org Sun Nov 20 15:59:28 2005 From: lists at janeden.org (Jan Eden) Date: Sun, 20 Nov 2005 15:59:28 +0100 Subject: [Tutor] Dynamic inheritance? In-Reply-To: <43806C64.1020002@tds.net> Message-ID: Kent Johnson wrote on 20.11.2005: >Use getattr() to access attributes by name. SiteA is an attribute of Templates >and Page is an attribute of SiteA so you can get use getattr() twice to get what >you want: > >site = getattr(Templates, self.site_name) >self.template = getattr(site, self.template_type) > Thank you! I did not take into account that modules and classes can be treated just like data attributes. - Jan -- Remember: use logout to logout. From merries at comcast.net Sun Nov 20 16:34:30 2005 From: merries at comcast.net (Merrie) Date: Sun, 20 Nov 2005 10:34:30 -0500 Subject: [Tutor] Can Phython... Message-ID: <000601c5ede7$e659f2d0$0400a8c0@superstar> Hello everyone, thank you for having this list. I have a couple of starting questions as I learn Python. My goal is to create something similar to Phaos, a browser controlled text base game written in PHP and MySQL. http://www.3eproductions.com/games.php But as Python is easier to learn and I know there is a specific DB that is Python friendly this is what I wish to work with. I have also seen a 'module?' that allows you to place Python code into HTML. So a few of my starting questions. 1 - Is what I have described above possible? 2 - What modules or components will I need? 3 - Is there a book or reference tutorial to help me gain the knowledge needed? Thank you for your assistance. Merrie Schonbach -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051120/152af07a/attachment.html From nick at javacat.f2s.com Sun Nov 20 16:39:53 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun, 20 Nov 2005 15:39:53 -0000 Subject: [Tutor] smtplib alternative??? In-Reply-To: <6571c3530511200626n78fe5bb9pbb0247a6a9c4a01@mail.gmail.com> Message-ID: Hi Adisegna, Lets say that you are someone at abc.com and you want to send email to a at abc.com, b at xyz.com and c at duff.com . You setup SMTPLib to talk to the MX server for abc.com which all users on abc.com use to send email. SMTP connects to that email server and you can send emails to anyone you like (unless theyre blacklisted). So by telling python to use mailserver at abc.com (your ISP's mail server) you can send email to a at abc.com (obviously), b at xyz.com (because your a member of abc.com) and c at duff.com (again cos your a member of abc.com). However, if you want your emails to be received with a different address, ie your using the isp abc.com and you want to send an email to b at xyz.com and it to appear to have come from you at pinkstuff.com then you will need to tell pythons smptlib to connect to the MX server for pinkstuff.com to send the email, and you'll probably have to be dialled in to pinkstuff.com. Webmail MX servers differ in that they require authentication so it doesnt matter which ISP your dialled in from. Generally smtp servers are only configured to send to or from domains in which they belong. Hope that helps, Nick . -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of Adisegna Sent: 20 November 2005 14:26 To: Danny Yoo Cc: tutor at python.org Subject: Re: [Tutor] smtplib alternative??? Hi Danny, Yes, when sending an email your mail client will always send the email to the mail server specified by the MX record in the authoritive domain. Usually the domain specificed after the @ symbol. The problem with smtplib is that I have to specify the mail server I'm sending email too. What if I wanted to send an email to 3 different people on three different domains hosted by 3 different mail servers? Smtlib prohibits this functionality. Do you see what I mean now...? Thanks for replying... On 11/20/05, Danny Yoo < dyoo at hkn.eecs.berkeley.edu> wrote: On Sat, 19 Nov 2005, Adisegna wrote: > I found this script to send mail online. It works fine but requires me > to enter an mail server. I'm looking for something else that doesn't > require and SMTP server. Having to specify a mail server prohibits me > from sending to alternate domains. Hi Adisegna, I've always assumed that emails have to talk with some SMTP server. RFC821 seems to confirm this: http://www.faqs.org/rfcs/rfc821.html so what you're asking, to be able to send mail without an SMTP server, may not be possible. There is an 'smtpd' module that comes with Python: http://www.python.org/doc/lib/module-smtpd.html I'm also not sure I understand the reason you're trying to avoid talking to an outside smtp server. But again, I'm unfamiliar enough with how the SMTP email protocol really works that perhaps I'm just overlooking something. -- Arthur DiSegna Network Operations Center Authentium, Inc. From alan.gauld at freenet.co.uk Sun Nov 20 17:54:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 20 Nov 2005 16:54:36 -0000 Subject: [Tutor] Dynamic inheritance? References: Message-ID: <001501c5edf3$1722a730$0a01a8c0@xp> > import Templates > > self.site_name = 'SiteA' > self.template_type = 'Page' > > self.template = ??? How about a dictionary holding references to the classes against their names? The dictionary could be a class attribute of the top level superclass or a module level dictionary. It should be updated ideally by the class definition or more simply by hard coding a registration fuinction. Something like class Root: subclasses = {'Root': Root} @classmethod def registerSubclass(name, aClass): #could check it really is a subclass here... Root.subclasses[name] = aClass class Sub(Root): pass Root.registerSubclass("Sub",Sub) Now your code becomes: self.site_name = 'SiteA' self.template_type = 'Page' self.template = Root.subclasses[self.template_name]() # instance of Page In fact it could just be a dictionary of templates, it needn't be subclasses at all, however for the sake of clean polymorphism its probably better if they are. HTH Alan G. From adisegna at gmail.com Sun Nov 20 18:26:28 2005 From: adisegna at gmail.com (Adisegna) Date: Sun, 20 Nov 2005 12:26:28 -0500 Subject: [Tutor] Website monitoring program. Message-ID: <6571c3530511200926p38714df3m64c138f3c1204474@mail.gmail.com> I guess I should keep the same subject line (above) from now on since my last few posts (urllib, smtplib) are about the same program. My question is how to use a loop to go through a tuple of URLs. Please feel free to suggest an easier way to do the same thing. Here is my rudimentary program so far. ------------------------------------------------------- import urllib, smtplib urls = ("http://website0.net/imalive.asp", "http://website1.net/imalive.asp", "http://website2.net/imalive.asp", "http://website3.net/imalive.asp", "http://website4.net/imalive.asp",) # I added these just to make the loop work and be more readable qa = urls[0] n4k = urls[1] metro = urls[4] for i in urls: # <-- this obviously doens't work because I have to specify a value "metro" below for site in urllib.urlopen(metro): #<----- What can I use here to loop through the 'urls' tupple good = "400 Bad Request" bad = "Invalid Hostname" smtpserver = 'mail.authentium.com ' RECIPIENTS = ['my at address.com'] SENDER = 'website-Verification at address.com' mssg = site if good in site: print "OK" text_file = open("test.log", "a") text_file.writelines('sometext : ') text_file.writelines(site) text_file.writelines("\n") text_file.close() elif bad in site: print "NOT OK" text_file = open("test.log", "a") text_file.writelines('metro-ams : ') text_file.writelines(site) text_file.writelines("\n") text_file.close() session = smtplib.SMTP(smtpserver) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr else: text_file = open("test.log", "a") text_file.writelines('Another type of error occurred : ') text_file.writelines(site) text_file.writelines("\n") text_file.close() ----------------------------------------------------------------------------------- Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051120/48ba3201/attachment.html From alan.gauld at freenet.co.uk Sun Nov 20 18:44:49 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 20 Nov 2005 17:44:49 -0000 Subject: [Tutor] Can Phython... References: <000601c5ede7$e659f2d0$0400a8c0@superstar> Message-ID: <002a01c5edfa$1b20f9c0$0a01a8c0@xp> > My goal is to create a browser controlled text base game ... >So a few of my starting questions. > 1 - Is what I have described above possible? Yes > 2 - What modules or components will I need? That depends onthe gane to some extent, I don;t know it. But for HTML/Web apps you need to decide if the basic cgi module is good enough or whether you want to use a more sophisticated framework (like CherryPy say) Also you will need the database driver for your database (Python can support a wide variety of databases, I'm not sure which you have in mind) Then you might find uses for the random module, or maybe the math one. It just depends on how sophisticated the game is. The best thing is a) get an understanding of Python itself b) try producing a console based version of your game c) port it to the web. At each stage when you find a specific problem send us a mail message with the question, any code that reproduces it and any error messages. > 3 - Is there a book or reference tutorial to help me gain the knowledge > needed? Check out the Python web site. \Depending on whether you have programmed in any other language or not will deternine which tutoriakl suits you best. If you are a complete beginner you might find mine useful(see .sig), but there are others if you dont like my style. If you have programmed before then try the official tutorial, its pretty good. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From enas_khalil at yahoo.com Sun Nov 20 21:52:18 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Sun, 20 Nov 2005 12:52:18 -0800 (PST) Subject: [Tutor] need a tutorial in tokens ,different types In-Reply-To: Message-ID: <20051120205218.61945.qmail@web30507.mail.mud.yahoo.com> hello all could any one suggest me tutorials in different tokenizations and clear describtion of how can i use token type and assign diff attributes to tokens ,also good tutorials in diff data types in python thanks every body enas --------------------------------- Yahoo! FareChase - Search multiple travel sites in one click. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051120/4a1d4102/attachment.html From kent37 at tds.net Sun Nov 20 22:24:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Nov 2005 16:24:35 -0500 Subject: [Tutor] Website monitoring program. In-Reply-To: <6571c3530511200926p38714df3m64c138f3c1204474@mail.gmail.com> References: <6571c3530511200926p38714df3m64c138f3c1204474@mail.gmail.com> Message-ID: <4380E993.3040005@tds.net> Adisegna wrote: > > I guess I should keep the same subject line (above) from now on since my > last few posts (urllib, smtplib) are about the same program. My preference is to start a new subject for each new question. > > My question is how to use a loop to go through a tuple of URLs. Please > feel free to suggest an easier way to do the same thing. > > Here is my rudimentary program so far. > > ------------------------------------------------------- > import urllib, smtplib > > urls = ("http://website0.net/imalive.asp", > "http://website1.net/imalive.asp", > "http://website2.net/imalive.asp", > "http://website3.net/imalive.asp", > "http://website4.net/imalive.asp" > ,) > > # I added these just to make the loop work and be more readable > > qa = urls[0] > n4k = urls[1] > metro = urls[4] > > for i in urls: # <-- this obviously doens't work because I have to > specify a value "metro" below > > for site in urllib.urlopen(metro): #<----- What can I use here to > loop through the 'urls' tupple I'm not sure I understand but I think what you want is for url in urls: # url will take on each value from urls site = urllib.urlopen(url).read() # site will have the entire text from the page you opened You might also be interested in EDDIE which seems to support building this kind of monitoring app fairly easily. http://eddie-tool.net/doc/manual.html Kent > > good = "400 Bad Request" > bad = "Invalid Hostname" > smtpserver = 'mail.authentium.com ' > RECIPIENTS = ['my at address.com '] > SENDER = 'website-Verification at address.com > ' > mssg = site > > if good in site: > print "OK" > text_file = open("test.log", "a") > text_file.writelines('sometext : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > > elif bad in site: > print "NOT OK" > text_file = open("test.log", "a") > text_file.writelines('metro-ams : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > session = smtplib.SMTP(smtpserver) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], > smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > > else: > text_file = open("test.log", "a") > text_file.writelines('Another type of error occurred : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > > ----------------------------------------------------------------------------------- > > Thanks > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://www.kentsjohnson.com From jason.massey at gmail.com Sun Nov 20 22:54:09 2005 From: jason.massey at gmail.com (Jason Massey) Date: Sun, 20 Nov 2005 15:54:09 -0600 Subject: [Tutor] UnboundLocal Error Message-ID: <7e3eab2c0511201354x6ec26627gd3fec69cf3a258e9@mail.gmail.com> I've got a problem with scope that I can't say I've ever encountered. The comments explain the situation pretty well. import player class Game: def __init__(self,screen): self.market = Market.Market() self.countries = pickle.load(open("sup.coords",'r')) self.deck = deck.Deck() self.players = {} print player.Player('foo') # this line works fine, prints out a player instance self.setupPlayers() # want to set up all the players so... self.screen = screen def setupPlayers(self): print player.Player('bar') # this line fails, with the unbound local error for super_power in SUPER_POWERS: self.players[super_power] = player.Player(super_power) for position,card in enumerate(self.deck): if card.location in SUPER_POWERS[super_power]: Ouput and traceback: Traceback (most recent call last): File "C:\Python24\sup.py", line 199, in ? game = Game(screen) File "C:\Python24\sup.py", line 51, in __init__ self.setupPlayers() File "C:\Python24\sup.py", line 56, in setupPlayers print player.Player('bar') UnboundLocalError: local variable 'player' referenced before assignment Something blindingly obvious probably, but I'm at a loss. thanks, jason From merries at comcast.net Sun Nov 20 23:25:06 2005 From: merries at comcast.net (Merrie) Date: Sun, 20 Nov 2005 17:25:06 -0500 Subject: [Tutor] Random Numbers Message-ID: <002a01c5ee21$429ddaa0$0400a8c0@superstar> Ok first thing I need a direction on is random number generation, I looked through the Python manual and I must be missing it. What Im looking for, needing is a random generation 1 through 10 + modifier, example like rolling a 1d10 +1 Not sure what syntex to use. Thanks! Merrie -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051120/f4d536b8/attachment.htm From john at fouhy.net Sun Nov 20 23:35:53 2005 From: john at fouhy.net (John Fouhy) Date: Mon, 21 Nov 2005 11:35:53 +1300 Subject: [Tutor] Random Numbers In-Reply-To: <002a01c5ee21$429ddaa0$0400a8c0@superstar> References: <002a01c5ee21$429ddaa0$0400a8c0@superstar> Message-ID: <5e58f2e40511201435v763bf310x@mail.gmail.com> On 21/11/05, Merrie wrote: > Ok first thing I need a direction on is random number generation, I looked > through the Python manual and I must be missing it. > > What Im looking for, needing is a random generation 1 through 10 + modifier, > example like rolling a 1d10 +1 Hi Merrie, The manual section you want is the random module: http://docs.python.org/lib/module-random.html In particular, the randrange() function will help you out here. random.randrange() is equivalent to generating a list using the builtin function range(), and then choosing one element from that list at random. For example, I can generate some random numbers in the range 0..9 like this: >>> import random >>> for i in range(10): ... print random.randrange(10) ... 8 2 0 9 7 5 8 0 7 9 >>> HTH! -- John. From hugonz-lists at h-lab.net Sun Nov 20 23:37:15 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sun, 20 Nov 2005 16:37:15 -0600 Subject: [Tutor] Random Numbers In-Reply-To: <002a01c5ee21$429ddaa0$0400a8c0@superstar> References: <002a01c5ee21$429ddaa0$0400a8c0@superstar> Message-ID: <4380FA9B.30000@h-lab.net> Hi, Take a look at the random module, function randint: >>> import random >>> random.randint(1, 10) 7 >>> random.randint(1, 10) 9 >>> random.randint(1, 10) 1 >>> random.randint(1, 10) 8 >>> random.randint(1, 10) 7 >>> random.randint(1, 10) 9 >>> random.randint(1, 10) 1 >>> random.randint(1, 10) 1 >>> random.randint(1, 10) 7 >>> random.randint(1, 10) 2 >>> random.randint(1, 10) 9 >>> Hugo Merrie wrote: > Ok first thing I need a direction on is random number generation, I > looked through the Python manual and I must be missing it. > > What Im looking for, needing is a random generation 1 through 10 + > modifier, example > like rolling a 1d10 +1 > > Not sure what syntex to use. > > Thanks! > Merrie > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Liam.Clarke-Hutchinson at business.govt.nz Mon Nov 21 00:21:24 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Mon, 21 Nov 2005 12:21:24 +1300 Subject: [Tutor] Website monitoring program. Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B144E@chbnt01.alpha.wd.govt.nz> Ah, this kind of programme would be so much simpler if Last-Modified and ETag were commonly used.... *sigh*. Unfortunately, advertising kinda killed it... I recommend www.watchthispage.com if you just need a quick update without killing your own bandwidth. Regards, Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Sent: Monday, 21 November 2005 10:25 a.m. Cc: tutor at python.org Subject: Re: [Tutor] Website monitoring program. Adisegna wrote: > > I guess I should keep the same subject line (above) from now on since > my > last few posts (urllib, smtplib) are about the same program. My preference is to start a new subject for each new question. > > My question is how to use a loop to go through a tuple of URLs. Please > feel free to suggest an easier way to do the same thing. > > Here is my rudimentary program so far. > > ------------------------------------------------------- > import urllib, smtplib > > urls = ("http://website0.net/imalive.asp", > "http://website1.net/imalive.asp", > "http://website2.net/imalive.asp", > "http://website3.net/imalive.asp", > "http://website4.net/imalive.asp" > ,) > > # I added these just to make the loop work and be more readable > > qa = urls[0] > n4k = urls[1] > metro = urls[4] > > for i in urls: # <-- this obviously doens't work because I have to > specify a value "metro" below > > for site in urllib.urlopen(metro): #<----- What can I use here to > loop through the 'urls' tupple I'm not sure I understand but I think what you want is for url in urls: # url will take on each value from urls site = urllib.urlopen(url).read() # site will have the entire text from the page you opened You might also be interested in EDDIE which seems to support building this kind of monitoring app fairly easily. http://eddie-tool.net/doc/manual.html Kent > > good = "400 Bad Request" > bad = "Invalid Hostname" > smtpserver = 'mail.authentium.com ' > RECIPIENTS = ['my at address.com '] > SENDER = 'website-Verification at address.com > ' > mssg = site > > if good in site: > print "OK" > text_file = open("test.log", "a") > text_file.writelines('sometext : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > > elif bad in site: > print "NOT OK" > text_file = open("test.log", "a") > text_file.writelines('metro-ams : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > session = smtplib.SMTP(smtpserver) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], > smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > > else: > text_file = open("test.log", "a") > text_file.writelines('Another type of error occurred : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > > ---------------------------------------------------------------------- > ------------- > > Thanks > > > ---------------------------------------------------------------------- > -- > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://www.kentsjohnson.com _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From kent37 at tds.net Mon Nov 21 00:24:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Nov 2005 18:24:37 -0500 Subject: [Tutor] UnboundLocal Error In-Reply-To: <7e3eab2c0511201354x6ec26627gd3fec69cf3a258e9@mail.gmail.com> References: <7e3eab2c0511201354x6ec26627gd3fec69cf3a258e9@mail.gmail.com> Message-ID: <438105B5.8080708@tds.net> Jason Massey wrote: > I've got a problem with scope that I can't say I've ever encountered. My guess is that later in setupPlayers() you assign to a variable 'player'. When you do this, every reference to the variable in the function is a local reference. For example: >>> x=1 >>> def bump(): ... print x ... x = x + 1 ... >>> bump() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in bump UnboundLocalError: local variable 'x' referenced before assignment Because x is assigned in bump(), the x in print x is a local variable and it is not bound a the time of use. Kent > > The comments explain the situation pretty well. > > > import player > > class Game: > def __init__(self,screen): > self.market = Market.Market() > self.countries = pickle.load(open("sup.coords",'r')) > self.deck = deck.Deck() > self.players = {} > print player.Player('foo') # this line works fine, prints out a > player instance > self.setupPlayers() # want to set up all the players so... > > self.screen = screen > > def setupPlayers(self): > print player.Player('bar') # this line fails, with the unbound local error > for super_power in SUPER_POWERS: > self.players[super_power] = player.Player(super_power) > for position,card in enumerate(self.deck): > if card.location in SUPER_POWERS[super_power]: > > > Ouput and traceback: > > > Traceback (most recent call last): > File "C:\Python24\sup.py", line 199, in ? > game = Game(screen) > File "C:\Python24\sup.py", line 51, in __init__ > self.setupPlayers() > File "C:\Python24\sup.py", line 56, in setupPlayers > print player.Player('bar') > UnboundLocalError: local variable 'player' referenced before assignment > > > Something blindingly obvious probably, but I'm at a loss. > > thanks, > > jason > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com From alan.gauld at freenet.co.uk Mon Nov 21 00:21:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 20 Nov 2005 23:21:56 -0000 Subject: [Tutor] need a tutorial in tokens ,different types References: <20051120205218.61945.qmail@web30507.mail.mud.yahoo.com> Message-ID: <004301c5ee29$338f8240$0a01a8c0@xp> > could any one suggest me tutorials in different tokenizations and > clear describtion of how can i use token type and assign diff attributes > to tokens What kind of tokens? Are we talking l;exical tokens in a parser or security tokens or what? > also good tutorials in diff data types in python The official documentaton explains most of it. You can try the Raw Materials topic in my tutorial if you like. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Nov 21 00:33:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 20 Nov 2005 23:33:27 -0000 Subject: [Tutor] UnboundLocal Error References: <7e3eab2c0511201354x6ec26627gd3fec69cf3a258e9@mail.gmail.com> Message-ID: <004901c5ee2a$cecac700$0a01a8c0@xp> > The comments explain the situation pretty well. Unfortunately the formatting has been lost so I'm not totally clear whats going on. BUT it does look like you have posted the class definition but not the driver code that actually causes the error. > class Game: > def __init__(self,screen): > print player.Player('foo') # this line works fine, prints out a > self.setupPlayers() # want to set up all the players so... >self.screen = screen >def setupPlayers(self): > print player.Player('bar') # this line fails, with the unbound local error > Ouput and traceback: > > > Traceback (most recent call last): > File "C:\Python24\sup.py", line 199, in ? > game = Game(screen) where is this line? its nowhere above? is it in a separate file? or lower in the same file? It looks like its the same file but much later on. > File "C:\Python24\sup.py", line 56, in setupPlayers > print player.Player('bar') > UnboundLocalError: local variable 'player' referenced before assignment which looks like the import hasn't worked, except the previous print statement did work. That seems odd I agree. > Something blindingly obvious probably, but I'm at a loss. Me too, but I'd start by checking I don;t have a conflict of variable names. you don't for example del(player) at some point? strange, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Liam.Clarke-Hutchinson at business.govt.nz Mon Nov 21 01:29:55 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Mon, 21 Nov 2005 13:29:55 +1300 Subject: [Tutor] smtplib alternative??? Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B144F@chbnt01.alpha.wd.govt.nz> >Generally smtp servers are only configured to send to or from domains in which they belong. Hmmm... several ISP's I've used allow any value in the "From" header field. I'd also like to mention that while many SMTP servers will only allow a valid domain address in the From field, there is usually no such restriction on what you stick in the "Reply-To" header field. (I'd like to point out that using fake "From" addresses gets boring after about the fifth prank email from big_Billy.G at microsoft.com to your friends...) The ability to change a "From" field is very useful for automated emailing. (By which I don't mean spam, but those emails from noreply at foo.com...) Regards, Liam Clarke -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf Of Adisegna Sent: 20 November 2005 14:26 To: Danny Yoo Cc: tutor at python.org Subject: Re: [Tutor] smtplib alternative??? Hi Danny, Yes, when sending an email your mail client will always send the email to the mail server specified by the MX record in the authoritive domain. Usually the domain specificed after the @ symbol. The problem with smtplib is that I have to specify the mail server I'm sending email too. What if I wanted to send an email to 3 different people on three different domains hosted by 3 different mail servers? Smtlib prohibits this functionality. Do you see what I mean now...? Thanks for replying... On 11/20/05, Danny Yoo < dyoo at hkn.eecs.berkeley.edu> wrote: On Sat, 19 Nov 2005, Adisegna wrote: > I found this script to send mail online. It works fine but requires me > to enter an mail server. I'm looking for something else that doesn't > require and SMTP server. Having to specify a mail server prohibits me > from sending to alternate domains. Hi Adisegna, I've always assumed that emails have to talk with some SMTP server. RFC821 seems to confirm this: http://www.faqs.org/rfcs/rfc821.html so what you're asking, to be able to send mail without an SMTP server, may not be possible. There is an 'smtpd' module that comes with Python: http://www.python.org/doc/lib/module-smtpd.html I'm also not sure I understand the reason you're trying to avoid talking to an outside smtp server. But again, I'm unfamiliar enough with how the SMTP email protocol really works that perhaps I'm just overlooking something. -- Arthur DiSegna Network Operations Center Authentium, Inc. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From python at venix.com Mon Nov 21 02:03:04 2005 From: python at venix.com (Python) Date: Sun, 20 Nov 2005 20:03:04 -0500 Subject: [Tutor] smtplib alternative??? In-Reply-To: <6571c3530511200626n78fe5bb9pbb0247a6a9c4a01@mail.gmail.com> References: <6571c3530511191833u7c7da631w7fcbe20ed8f19c47@mail.gmail.com> <6571c3530511200626n78fe5bb9pbb0247a6a9c4a01@mail.gmail.com> Message-ID: <1132534984.26889.52.camel@www.venix.com> On Sun, 2005-11-20 at 09:26 -0500, Adisegna wrote: > Hi Danny, > > Yes, when sending an email your mail client will always send the email > to the mail server specified by the MX record in the authoritive > domain. Usually the domain specificed after the @ symbol. The problem > with smtplib is that I have to specify the mail server I'm sending > email too. No. It is asking you to specify the server that the email will be coming from. Your email to the list went through the gmail server. If you look at the email headers, you will see entries from the mail servers that handled the message. Your local smtp server will handle the MX lookups. Simply specify the mail server provided by the ISP that provides your Internet connection, if you do not run a mail server yourself. > What if I wanted to send an email to 3 different people on three > different domains hosted by 3 different mail servers? Smtlib prohibits > this functionality. Do you see what I mean now...? > > Thanks for replying... If you have a conventional email program (e.g. Thunderbird, Evolution, Outlook Express) then the smtp server listed in that config should work with your Python script. -- Lloyd Kvam Venix Corp From adisegna at gmail.com Mon Nov 21 03:15:21 2005 From: adisegna at gmail.com (Adisegna) Date: Sun, 20 Nov 2005 21:15:21 -0500 Subject: [Tutor] Website monitoring program. In-Reply-To: <6571c3530511200926p38714df3m64c138f3c1204474@mail.gmail.com> References: <6571c3530511200926p38714df3m64c138f3c1204474@mail.gmail.com> Message-ID: <6571c3530511201815m6c92d1c4gdc6a62d078ff0053@mail.gmail.com> How do I get the counting loop to come back around? It makes one pass fine. How do I get it to come back up and go through again? Thanks ------------------------------------------------------- import urllib, smtplib urls = ("http://website0.net/imalive.asp", "http://website1.net/imalive.asp", "http://website2.net/imalive.asp", "http://website3.net/imalive.asp", "http://website4.net/imalive.asp" ,) count = 0 for i in urls: web = urls[count] for site in urllib.urlopen(web): good = "400 Bad Request" bad = "Invalid Hostname" smtpserver = 'mail.authentium.com ' RECIPIENTS = ['my at address.com'] SENDER = 'website-Verification at address.com' mssg = site if good in site: print "OK" text_file = open("test.log", "a") text_file.writelines('sometext : ') text_file.writelines(site) text_file.writelines("\n") text_file.close() elif bad in site: print "NOT OK" text_file = open("test.log", "a") text_file.writelines('metro-ams : ') text_file.writelines(site) text_file.writelines("\n") text_file.close() session = smtplib.SMTP(smtpserver) smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr else: text_file = open("test.log", "a") text_file.writelines('Another type of error occurred : ') text_file.writelines(site) text_file.writelines("\n") text_file.close() print web count +=1 print count ----------------------------------------------------------------------------------- Thanks -- Arthur DiSegna Network Operations Center Authentium, Inc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051120/55684598/attachment-0001.htm From kent37 at tds.net Mon Nov 21 04:26:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 20 Nov 2005 22:26:10 -0500 Subject: [Tutor] Website monitoring program. In-Reply-To: <6571c3530511201815m6c92d1c4gdc6a62d078ff0053@mail.gmail.com> References: <6571c3530511200926p38714df3m64c138f3c1204474@mail.gmail.com> <6571c3530511201815m6c92d1c4gdc6a62d078ff0053@mail.gmail.com> Message-ID: <43813E52.5010708@tds.net> Adisegna wrote: > How do I get the counting loop to come back around? It makes one pass > fine. How do I get it to come back up and go through again? You have to indent the statement 'count += 1' so it is part of the loop. But you misunderstand the for loop - the count variable is not needed at all. Your variable 'i' will receive each element of urls, one each time through the loop. For a simpler example, >>> u = ['a', 'b', 'c'] >>> for letter in u: ... print letter ... a b c So instead of count = 0 for i in urls: web = urls[count] you can write simply for web in urls: See the Python tutorial for more examples of for loops: http://docs.python.org/tut/node6.html#SECTION006200000000000000000 Kent > > Thanks > > ------------------------------------------------------- > import urllib, smtplib > > urls = ("http://website0.net/imalive.asp", > "http://website1.net/imalive.asp", > "http://website2.net/imalive.asp", > "http://website3.net/imalive.asp", > "http://website4.net/imalive.asp" > ,) > > count = 0 > for i in urls: > web = urls[count] > > for site in urllib.urlopen(web): > > good = "400 Bad Request" > bad = "Invalid Hostname" > smtpserver = 'mail.authentium.com ' > RECIPIENTS = ['my at address.com '] > SENDER = 'website-Verification at address.com > ' > mssg = site > > if good in site: > print "OK" > text_file = open("test.log", "a") > text_file.writelines('sometext : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > > elif bad in site: > print "NOT OK" > text_file = open("test.log", "a") > text_file.writelines('metro-ams : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > session = smtplib.SMTP(smtpserver) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], > smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > > else: > text_file = open("test.log", "a") > text_file.writelines('Another type of error occurred : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > print web > count +=1 > print count > ----------------------------------------------------------------------------------- > > Thanks > > > -- > Arthur DiSegna > Network Operations Center > Authentium, Inc. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://www.kentsjohnson.com From tvbare at socket.net Mon Nov 21 05:52:20 2005 From: tvbare at socket.net (->Terry<-) Date: Sun, 20 Nov 2005 22:52:20 -0600 (CST) Subject: [Tutor] Trouble with classes - Pypeg again Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ok, I've got my peg game roughed out and I'm having problems. The error is: Traceback (most recent call last): File "pypeg.py", line 113, in ? main() File "pypeg.py", line 107, in main x.draw_board() # Refresh screen File "pypeg.py", line 30, in draw_board screen.blit(Peg.peg, (Peg.pegs[i])) # Blit it. AttributeError: class Peg has no attribute 'peg' The new code is at: I'm confused as to why. The whole OO picture has my head reeling, but I thought I had some grasp of the basics. Now I'm not so sure. d:^) Thanks much, - -- Terry "Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind." -- Dr. Seuss -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.7 (GNU/Linux) iD8DBQFDgVKHQvSnsfFzkV0RAnlyAJ9snqBt0GOWS7IpimsMkB2xaBqu2gCbBovs ATTVhm0JbWiz+VfKSxXrGqY= =oGAu -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Mon Nov 21 06:46:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 20 Nov 2005 21:46:49 -0800 (PST) Subject: [Tutor] need a tutorial in tokens ,different types In-Reply-To: <004301c5ee29$338f8240$0a01a8c0@xp> Message-ID: Taking python-list out of CC yet again. Enas, please fix your email client setup. I really don't want to threaten, but as a power-hungry dictatorial list admin, I have an responsibility to help maintain a healthy mailing list. You been warned twice now not to crosspost. You continue to crosspost the same question to several mailing lists, not only to comp.lang.python, but also to NLTK's developer list. http://sourceforge.net/mailarchive/forum.php?thread_id=9019717&forum_id=959 so I doubt your behavior is accidental now: it looks pretty deliberate to me. Enas, please don't push me into the Bad Cop role. Change your behavior: you've violating community norms. If you don't correct yourself, I will moderate your messsages. I hate threatening you like this. Don't make me follow through with the threat. On Sun, 20 Nov 2005, Alan Gauld wrote: > > could any one suggest me tutorials in different tokenizations and > > clear describtion of how can i use token type and assign diff > > attributes to tokens > > What kind of tokens? Are we talking lexical tokens in a parser or > security tokens or what? Anyway, I think we are talking about the tokens defined by the NLTK natural language toolkit. I'm not sure we can do much better than recommend the tutorials that come with NLTK: http://nltk.sourceforge.net/lite/doc/ http://nltk.sourceforge.net/tutorial/index.html They go through several examples of assigning attributes to tokens. If you has questions about NLTK, again, Enas may be better off asking on an NLTK-specific mailing list. There's one specifically set up for help: http://sourceforge.net/forum/forum.php?forum_id=97413 > > also good tutorials in diff data types in python > > The official documentaton explains most of it. > > You can try the Raw Materials topic in my tutorial if you like. Those tutorials are here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers They should give enough grounding to understand how NLTK works better. Again, if you has any questions relating to learning how to program, we're glad to be of help. But take some time to learn how to use your email client. Also, if people have not recommend it, read through: http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html http://www.catb.org/~esr/faqs/smart-questions.html so that you have a sense of what kind of community norms are expected of you when you ask for help. Violating them impovershes the entire community, which is why I take this so seriously. From janos.juhasz at VELUX.com Mon Nov 21 08:20:02 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 21 Nov 2005 08:20:02 +0100 Subject: [Tutor] reduce with comprehension Message-ID: Hi, I can't imagine how this could be made with list comprehension. >>> import operator >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>> reduce(operator.add, a) # it makes a long list now ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]) When I make list comprehension, the list hierarchy is allways the same or deeper than the original hierarchy. But now it should be reduced with one level. >>> [item for item in a] # the deepnes is the same [([1], [2], [3, 31, 32], [4]), ([5], [6], [7, 71, 72]), ([8], [9])] >>> [(item, item) for item in a] # it is deeper with one level >>> Is it possible to substitute reduce with comprehension anyway ? Yours sincerely, ______________________________ J?nos Juh?sz From benvinger at yahoo.co.uk Mon Nov 21 09:20:12 2005 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Mon, 21 Nov 2005 08:20:12 +0000 (GMT) Subject: [Tutor] Website monitoring program. In-Reply-To: <6571c3530511200926p38714df3m64c138f3c1204474@mail.gmail.com> Message-ID: <20051121082013.89168.qmail@web25804.mail.ukl.yahoo.com> Below is a program I found at http://starship.python.net/crew/neale/ (though it does not seem to be there anymore.) It uses a seperate file for the URLs --- Adisegna wrote: > My question is how to use a loop to go through a > tuple of URLs. Please feel > free to suggest an easier way to do the same thing. #!/usr/bin/env python """watch.py -- Web site change notification tool Author: Neale Pickett Time-stamp: <2003-01-24 13:52:13 neale> This is something you can run from a cron job to notify you of changes to a web site. You just set up a ~/.watchrc file, and run watcher.py from cron. It mails you when a page has changed. I use this to check for new software releases on sites that just change web pages; my wife uses it to check pages for classes she's in. You'll want a ~/.watchrc that looks something like this: to: your.email.address at example.com http://www.example.com/path/to/some/page.html The 'to:' line tells watch.py where to send change notification email. You can also specify 'from:' for an address the message should come from (defaults to whatever to: is), and 'host:' for what SMTP server to send the message through (defaults to localhost). When watch.py checks a URL for the first time, it will send you a message (so you know it's working) and write some funny characters after the URL in the .watchrc file. This is normal--watch.py uses these characters to remember what the page looked like the last time it checked. """ import os.path import urllib2 as urllib import sha import smtplib rc = '~/.watchrc' host = 'localhost' fromaddr = None toaddr = None def hash(data): return sha.new(data).hexdigest() def notify(url): msg = """From: URL Watcher <%(from)s> To: %(to)s Subject: %(url)s changed %(url)s has changed! """ % {'from': fromaddr, 'to': toaddr, 'url': url} s = smtplib.SMTP(host) s.sendmail(fromaddr, toaddr, msg) s.quit() fn = os.path.expanduser(rc) f = open(fn) outlines = [] for line in f.xreadlines(): if line[0] == '#': continue line = line.strip() if not line: continue splits = line.split(' ', 1) url = splits[0] if url == 'from:': fromaddr = splits[1] elif url == 'to:': toaddr = splits[1] if not fromaddr: fromaddr = toaddr elif url == 'host:': host = splits[1] else: if (not fromaddr) or (not toaddr): raise ValueError("must set to: before any urls") page = urllib.urlopen(url).read() ph = hash(page) try: h = splits[1] except IndexError: h = None if h != ph: notify(url) line = '%s %s' % (url, ph) outlines.append(line) f.close() f = open(fn, 'w') f.write('\n'.join(outlines) + '\n') f.close() ___________________________________________________________ Yahoo! Model Search 2005 - Find the next catwalk superstars - http://uk.news.yahoo.com/hot/model-search/ From negroup at gmail.com Mon Nov 21 10:26:04 2005 From: negroup at gmail.com (Negroup -) Date: Mon, 21 Nov 2005 10:26:04 +0100 Subject: [Tutor] Lists with just an item Message-ID: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> Hi all. In my application I have chosen as data structure a list of dictionaries. Each dictionary has just one key and the corresponding value. structure = [{'field1': lenght1}, {'field2': lenght2}, ........] Initially, to obtain the key and the value I used this code, for structure in record_structure: field_name = structure.keys()[0] displacement = structure[field_name] but after some thoughts I arrived to: field_name, displacement = structure.items()[0] which to me seems a lot better. At this point I don't like much that [0] to access a list that I know always contains a single element. Can I improve the code with something better? Thanks! From broek at cc.umanitoba.ca Mon Nov 21 10:28:45 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 21 Nov 2005 03:28:45 -0600 Subject: [Tutor] reduce with comprehension In-Reply-To: References: Message-ID: <4381934D.8010706@cc.umanitoba.ca> J?nos Juh?sz said unto the world upon 2005-11-21 01:20: > Hi, > > I can't imagine how this could be made with list comprehension. > > >>>>import operator >>>>a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>>>reduce(operator.add, a) # it makes a long list now > > ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]) > > When I make list comprehension, the list hierarchy is allways the same or > deeper than the original hierarchy. But now it should be reduced with one > level. > > > >>>>[item for item in a] # the deepnes is the same > > [([1], [2], [3, 31, 32], [4]), ([5], [6], [7, 71, 72]), ([8], [9])] > >>>>[(item, item) for item in a] # it is deeper with one level >>>> > > > > Is it possible to substitute reduce with comprehension anyway ? > > > Yours sincerely, > ______________________________ > J?nos Juh?sz > Hi J?nos, I think it is. >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>> b = [] >>> [b.extend(x) for x in a] [None, None, None] >>> b [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] But don't do that :-) Seems very poor form to me, as the desired operation is a side effect of the creation of the list via the comprehension. If, however, you are just trying to avoid reduce: >>> b=[] >>> for x in a: b.extend(x) >>> b [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] >>> Notice, too, that these ways result in a list of lists, whereas yours provided a tuple of lists. HTH, Brian vdB From broek at cc.umanitoba.ca Mon Nov 21 10:35:48 2005 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Mon, 21 Nov 2005 03:35:48 -0600 Subject: [Tutor] Lists with just an item In-Reply-To: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> References: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> Message-ID: <438194F4.6020904@cc.umanitoba.ca> Negroup - said unto the world upon 2005-11-21 03:26: > Hi all. > In my application I have chosen as data structure a list of > dictionaries. Each dictionary has just one key and the corresponding > value. > > structure = [{'field1': lenght1}, {'field2': lenght2}, ........] > > Initially, to obtain the key and the value I used this code, > > for structure in record_structure: > field_name = structure.keys()[0] > displacement = structure[field_name] > > but after some thoughts I arrived to: > field_name, displacement = structure.items()[0] > > which to me seems a lot better. > > At this point I don't like much that [0] to access a list that I know > always contains a single element. Can I improve the code with > something better? > > Thanks! Hi Negroup, why not just make structure a dict: structure = {'field1': lenght1, 'field2': lenght2} What does having a list of dicts all with a single key add but a layer of referencing when you want to access? If you are trying to preserve order and your key examples are real: >>> structure = {'field1': 1, 'field2': 2, 'field3': 3} >>> for item in sorted(structure.items()): print item ('field1', 1) ('field2', 2) ('field3', 3) >>> Best, Brian vdB From ajikoe at gmail.com Mon Nov 21 10:38:45 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 21 Nov 2005 10:38:45 +0100 Subject: [Tutor] Lists with just an item In-Reply-To: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> References: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> Message-ID: Hi, mydic = {'one': 1, 'two': 2} # to access key: for x in mydic.keys(): print x # to access value --> use key print mydic['one'] Cheers, pujo On 11/21/05, Negroup - wrote: > > Hi all. > In my application I have chosen as data structure a list of > dictionaries. Each dictionary has just one key and the corresponding > value. > > structure = [{'field1': lenght1}, {'field2': lenght2}, ........] > > Initially, to obtain the key and the value I used this code, > > for structure in record_structure: > field_name = structure.keys()[0] > displacement = structure[field_name] > > but after some thoughts I arrived to: > field_name, displacement = structure.items()[0] > > which to me seems a lot better. > > At this point I don't like much that [0] to access a list that I know > always contains a single element. Can I improve the code with > something better? > > Thanks! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051121/fb4f20da/attachment-0001.htm From alan.gauld at freenet.co.uk Mon Nov 21 11:05:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 21 Nov 2005 10:05:32 -0000 Subject: [Tutor] reduce with comprehension References: Message-ID: <002e01c5ee83$1c427110$0a01a8c0@xp> >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>> reduce(operator.add, a) # it makes a long list now ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]) When I make list comprehension, the list hierarchy is allways the same or >>> [item for item in a] # the deepnes is the same [([1], [2], [3, 31, 32], [4]), ([5], [6], [7, 71, 72]), ([8], [9])] >>> [(item, item) for item in a] # it is deeper with one level You are not using operator add anywhere in there. So you won't reduce anything! But reduce is tricky to reproduce using comprehensions because it involves combining two elements using an operation. And one of the elements is the running result. So count = 0 [count + item for item in alist] won't work because we never change count - and assignments aren't allowed inside a comprehension. There may be a clever way of doing it but I can't think of it and certainly not a way that would be as readable as reduce()! Do you have any particular need to avoid reduce? Or is it just curiosity? Alan g From alan.gauld at freenet.co.uk Mon Nov 21 11:09:13 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 21 Nov 2005 10:09:13 -0000 Subject: [Tutor] Lists with just an item References: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> Message-ID: <003401c5ee83$a9614da0$0a01a8c0@xp> > Each dictionary has just one key and the corresponding > value. > > structure = [{'field1': lenght1}, {'field2': lenght2}, ........] I'd use a tuple rather than a dictionary here: structure = [('field1', lenght1), ('field2', lenght2), ........] > but after some thoughts I arrived to: > field_name, displacement = structure.items()[0] > >At this point I don't like much that [0] to access a list that I know > always contains a single element. Can I improve the code with you can now do for field_name, displacement in structure: # work with values here Is that any better? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From negroup at gmail.com Mon Nov 21 11:26:59 2005 From: negroup at gmail.com (Negroup -) Date: Mon, 21 Nov 2005 11:26:59 +0100 Subject: [Tutor] Lists with just an item In-Reply-To: <438194F4.6020904@cc.umanitoba.ca> References: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> <438194F4.6020904@cc.umanitoba.ca> Message-ID: <2fdabf190511210226v6efa7a88q@mail.gmail.com> 2005/11/21, Brian van den Broek : > Hi Negroup, > > why not just make structure a dict: > > structure = {'field1': lenght1, 'field2': lenght2} > > What does having a list of dicts all with a single key add but a layer > of referencing when you want to access? > > If you are trying to preserve order and your key examples are real: > > >>> structure = {'field1': 1, 'field2': 2, 'field3': 3} > >>> for item in sorted(structure.items()): print item At first I used a unique dictionary, but as you told, the point is that I need to preserve the order of items, so I switched to list of dictionaries. I neither can rely on sorting 'field1', 'field2', ..., as these are not real key names and instead vary from case to case (they are obtained splitting in chunks the header line of a file submitted by a user, that may be different each time). So I'm going to think that my solution is at least "acceptable", wow ;-) > Best, > > Brian vdB Thanks From negroup at gmail.com Mon Nov 21 11:34:35 2005 From: negroup at gmail.com (Negroup -) Date: Mon, 21 Nov 2005 11:34:35 +0100 Subject: [Tutor] Lists with just an item In-Reply-To: <003401c5ee83$a9614da0$0a01a8c0@xp> References: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> <003401c5ee83$a9614da0$0a01a8c0@xp> Message-ID: <2fdabf190511210234m2d1d5b06m@mail.gmail.com> 2005/11/21, Alan Gauld : > > Each dictionary has just one key and the corresponding > > value. > > > > structure = [{'field1': lenght1}, {'field2': lenght2}, ........] > > I'd use a tuple rather than a dictionary here: Of course, this makes a lot of sense. [cut] > you can now do > > for field_name, displacement in structure: > # work with values here > > Is that any better? Yes, it is exactly what I was looking for! Probably due to the lacking of experience, but each time I code a datastructure I am never satisfied, and I have the feeling that I'm not on the right way.. Thanks a lot for your opinion. From kent37 at tds.net Mon Nov 21 11:55:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Nov 2005 05:55:25 -0500 Subject: [Tutor] reduce with comprehension In-Reply-To: References: Message-ID: <4381A79D.8070101@tds.net> J?nos Juh?sz wrote: > Hi, > > I can't imagine how this could be made with list comprehension. > >>>>import operator >>>>a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>>>reduce(operator.add, a) # it makes a long list now > > Is it possible to substitute reduce with comprehension anyway ? Not that I know. Why are you trying to eliminate reduce()? If it is for compatibility with Python 3.0, PEP 3000 recommends replacing reduce() with an explicit loop. http://www.python.org/peps/pep-3000.html#built-in-namespace Kent -- http://www.kentsjohnson.com From ajikoe at gmail.com Mon Nov 21 13:57:38 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 21 Nov 2005 13:57:38 +0100 Subject: [Tutor] Numeric array incosistence in unittest Message-ID: hello, I found that if I use Numeric.array into unittest it is not consistance, Is that normal ? import unittest import Numeric class myTest(unittest.TestCase): def runTest(self): var1 = Numeric.array([1,22]) var2 = Numeric.array([1,33]) self.assertEqual(var1,var2) if __name__ == '__main__': unittest.main() This will not raise any error ??? Any idea? Sincerely Yours, pujo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051121/2c26b085/attachment.htm From K.Weinert at gmx.net Mon Nov 21 16:19:26 2005 From: K.Weinert at gmx.net (K.Weinert@gmx.net) Date: Mon, 21 Nov 2005 16:19:26 +0100 (MET) Subject: [Tutor] Tkinter modal dialogs Message-ID: <27269.1132586366@www34.gmx.net> Hello tutors! My file search dialog is working now! I attach a copy of the module. It would be nice, if someone could look over it and make suggestions to improve it. There are at least two points I find not very elegant in the program: 1. The dialog is ended by raising a SystemExit exception. (I found the idea searching www.koders.com for Tkinter programs.) Here is a small example of the technique: --- snip --- import Tix from Tkconstants import * class YesNo: def __init__(self, root, title="", question=""): self.top= Tix.Toplevel(root) self.top.title(title) self.top.withdraw() # don't show Tix.Label(self.top, text=question).pack() Tix.Button(self.top, text="Yes", command=self.yes_cmd).pack(side=LEFT) Tix.Button(self.top, text="No", command=self.no_cmd).pack(side=RIGHT) def ask(self): self.top.deiconify() self.top.tkraise() self.top.grab_set() try: self.top.mainloop() except SystemExit, answer: self.top.grab_release() self.top.withdraw() return answer def yes_cmd(self, event=None): raise SystemExit, True def no_cmd(self, event=None): raise SystemExit, False if __name__=="__main__": def set_label(): global yes_no_dlg, yes_no_label answer= yes_no_dlg.ask() yes_no_label["text"]= str(answer) yes_no_label.update_idletasks() root = Tix.Tk() root.title("Modal Dialog Demo") yes_no_dlg = YesNo(root, "Question", "Do you find this approach elegant?") yes_no_label= Tix.Label(root, text="Unknown.") yes_no_label.pack() Tix.Button(root, text = 'Question..', command = set_label).pack() Tix.Button(root, text = 'Exit', command = root.destroy).pack() root.mainloop() --- snip --- This is deceiving. A SystemExit exception should, in my opinion, exit the program. Is there an other way to do this? 2. The Listbox in the file search dialog seems to have two selection modes. When scrolling with the page-up/page-down keys, only the underlined selection moves, while the other selection (indicated by a different background color) remains where it is unless I press the space key. That is imo too complicated. Is there a Listbox with only one selection type (or an option to Tix.ScrolledListbox)? Kind regards, Karsten. -- 10 GB Mailbox, 100 FreeSMS/Monat http://www.gmx.net/de/go/topmail +++ GMX - die erste Adresse für Mail, Message, More +++ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: searchdlg.py Url: http://mail.python.org/pipermail/tutor/attachments/20051121/ccd2ca4b/searchdlg.asc -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: grep_mod.py Url: http://mail.python.org/pipermail/tutor/attachments/20051121/ccd2ca4b/grep_mod.pot From lopoff at gmx.net Mon Nov 21 16:23:35 2005 From: lopoff at gmx.net (lmac) Date: Mon, 21 Nov 2005 16:23:35 +0100 Subject: [Tutor] again... regular expression Message-ID: <4381E677.3010305@gmx.net> Hallo. I want to parse a website for links of this type: http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22"> --------------------------------------------------------------------- re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+">') for a in file: z = re_site.search(a) if z != None: print z.group(0) --------------------------------------------------------------------- I still don't understand RE-Expressions. I tried some other expressions but didn't get it work. The End of the link is ">. So it should not be a problem to extract the link but it is. Thank you for the help. mac From kent37 at tds.net Mon Nov 21 16:48:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Nov 2005 10:48:46 -0500 Subject: [Tutor] again... regular expression In-Reply-To: <4381E677.3010305@gmx.net> References: <4381E677.3010305@gmx.net> Message-ID: <4381EC5E.4020301@tds.net> lmac wrote: > Hallo. > I want to parse a website for links of this type: > > http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22"> > > --------------------------------------------------------------------- > re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+">') . and ? have special meaning in re's so they should be escaped with \ You should use a non-greedy match at the end so you match the *first* "> So I would try re_site = re.compile(r'http://\w+\.\w+\.\w+\./good.php\?.+?">') > for a in file: > z = re_site.search(a) > if z != None: > print z.group(0) > > --------------------------------------------------------------------- > > I still don't understand RE-Expressions. I tried some other expressions > but didn't get it work. There is a handy re tester that comes with Python, look for C:\Python24\Tools\Scripts\redemo.py Kent -- http://www.kentsjohnson.com From lopoff at gmx.net Mon Nov 21 18:33:42 2005 From: lopoff at gmx.net (lmac) Date: Mon, 21 Nov 2005 18:33:42 +0100 Subject: [Tutor] again... regular expression Message-ID: <438204F6.3030101@gmx.net> Ok. There is an error i made. The links in the HTML-Site are starting with good.php so there was no way ever to find an link. re_site = re.compile(r"good\.php.+'") for a in file: z = re_site.search(a) if z != None: print z.group(0) This will give me every line starting with "good.php" but does contain not the first ' at the end, there are more tags and text which ends with ' too. So how can i tell in an regex to stop at the first found ' after good.php ??? Thank you. > Hallo. > I want to parse a website for links of this type: > > http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22"> > > --------------------------------------------------------------------- > re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+">') > for a in file: > z = re_site.search(a) > if z != None: > print z.group(0) > > --------------------------------------------------------------------- > > I still don't understand RE-Expressions. I tried some other expressions > but didn't get it work. > > The End of the link is ">. So it should not be a problem to extract the > link but it is. > > Thank you for the help. > > mac > From kent37 at tds.net Mon Nov 21 19:19:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Nov 2005 13:19:24 -0500 Subject: [Tutor] again... regular expression In-Reply-To: <438204F6.3030101@gmx.net> References: <438204F6.3030101@gmx.net> Message-ID: <43820FAC.3090004@tds.net> lmac wrote: > Ok. There is an error i made. The links in the HTML-Site are starting > with good.php so there was no way ever to find an link. > > re_site = re.compile(r"good\.php.+'") > for a in file: > z = re_site.search(a) > if z != None: > print z.group(0) > > > This will give me every line starting with "good.php" but does contain > not the first ' at the end, there are more tags and text which ends with > ' too. So how can i tell in an regex to stop at the first found ' after > good.php ??? Use a non-greedy match. Normally + will match the longest possible string; if you put a ? after it, it will match the shortest string. So r"good\.php.+?'" will match just to the first '. Kent > > Thank you. > > > >>Hallo. >>I want to parse a website for links of this type: >> >>http://www.example.com/good.php?test=anything&egal=total&nochmal=nummer&so=site&seite=22"> >> >>--------------------------------------------------------------------- >>re_site = re.compile(r'http://\w+.\w+.\w+./good.php?.+">') >>for a in file: >> z = re_site.search(a) >> if z != None: >> print z.group(0) >> >>--------------------------------------------------------------------- >> >>I still don't understand RE-Expressions. I tried some other expressions >> but didn't get it work. >> >>The End of the link is ">. So it should not be a problem to extract the >>link but it is. >> >>Thank you for the help. >> >>mac >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com From bgailer at alum.rpi.edu Mon Nov 21 19:45:16 2005 From: bgailer at alum.rpi.edu (bob) Date: Mon, 21 Nov 2005 10:45:16 -0800 Subject: [Tutor] Trouble with classes - Pypeg again In-Reply-To: References: Message-ID: <7.0.0.16.0.20051121104308.0227d938@alum.rpi.edu> At 08:52 PM 11/20/2005, ->Terry<- wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >Ok, I've got my peg game roughed out and I'm having >problems. > >The error is: > >Traceback (most recent call last): > File "pypeg.py", line 113, in ? > main() > File "pypeg.py", line 107, in main > x.draw_board() # Refresh screen > File "pypeg.py", line 30, in draw_board > screen.blit(Peg.peg, (Peg.pegs[i])) # Blit it. >AttributeError: class Peg has no attribute 'peg' screen.blit(Peg.peg, (Peg.pegs[i])) Peg is the name of a class rather than an instance of a class. Instances of Peg have the attribute peg. The class itself does not. Without analyzing your code in detail I'm not sure of the fix, except to suggest you put an instance of Peg in place of Pe. >The new code is at: > > > >I'm confused as to why. The whole OO picture >has my head reeling, but I thought I had some >grasp of the basics. Now I'm not so sure. d:^) > >Thanks much, >- -- > Terry > > >"Be who you are and say what you feel, because those > who mind don't matter and those who matter don't mind." > -- Dr. Seuss >-----BEGIN PGP SIGNATURE----- >Version: GnuPG v1.2.7 (GNU/Linux) > >iD8DBQFDgVKHQvSnsfFzkV0RAnlyAJ9snqBt0GOWS7IpimsMkB2xaBqu2gCbBovs >ATTVhm0JbWiz+VfKSxXrGqY= >=oGAu >-----END PGP SIGNATURE----- > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051121/8fe27c30/attachment.htm From hugonz-lists at h-lab.net Mon Nov 21 20:17:02 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 21 Nov 2005 13:17:02 -0600 Subject: [Tutor] Lists with just an item In-Reply-To: <2fdabf190511210234m2d1d5b06m@mail.gmail.com> References: <2fdabf190511210126g7d0fcc68i@mail.gmail.com> <003401c5ee83$a9614da0$0a01a8c0@xp> <2fdabf190511210234m2d1d5b06m@mail.gmail.com> Message-ID: <43821D2E.70504@h-lab.net> > Probably due to the lacking of experience, but each time I code a > datastructure I am never satisfied, and I have the feeling that I'm > not on the right way.. The same thing happens to me. I actually have a very similar problem to yours now, and I'm rather considering a list of two-element tuples. Greetings, Hugo From pythontut at pusspaws.net Mon Nov 21 20:59:33 2005 From: pythontut at pusspaws.net (dave) Date: Mon, 21 Nov 2005 19:59:33 +0000 Subject: [Tutor] smtplib problems ? Message-ID: <200511211959.33672.pythontut@pusspaws.net> Hi all, I am not sure if this is a Python problem not not but here goes.... I wrote the following small script to email by boss 'email_addr' a rather important reminder and also send a copy to myself 'email_addr2' several times a day. #!/usr/bin/env python # -*- coding: iso8859_1 -*- from smtplib import SMTP from time import sleep import sys email_SMTP = 'mail.pusspaws.net' email_addr = 'XXXX at chubb.co.uk' email_addr2 = 'XXXX at pusspaws.net' def email_remind(): ? ? ? for trys in xrange(10): ? ? ? ? try: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? mail_server = SMTP(email_SMTP) ? ? ? ? ? ? ? ? ? ? ? ? # email the office with a full email ? ? ? ? ? ? blog="""\n\nHi,\n\nHi,This is just a reminder, can you sort me out a date for my re-grade exam as soon as possible. I have tied an email script into my cron (time scheduling) daemon to remind you an ever increasing number of times a day ;) - Got to love Linux\n\nCheers\n\nDave""" ? ? ? ? ? ? ? ? ? ? ? ? msg = ('Subject: Friendly reminder :)\r\nFrom: Dave Selby\r\nTo: '+\ ? ? ? ? ? ? email_addr+'\r\n\r\n'+blog+'\r\n\r\n') ? ? ? ? ? ? ? ? ? ? ? ? mail_server.sendmail('Friendly reminder :)', email_addr, msg) ? ? ? ? ? ? mail_server.sendmail('Friendly reminder :)', email_addr2, msg) ? ? ? ? ? ? ? ? ? ? ? ? mail_server.quit() ? ? ? ? ? ? ? ? ? ? ? ? # If we get to here, all is well, drop out of the loop ? ? ? ? ? ? break ? ? ? ? ? ? ? ? ? ? except: ? ? ? ? ? ? print 'Mailing error ... Re-trying ... '+str(trys+1)+' of 10\n' ? ? ? ? ? ? sleep(300) ? ? ? ? ? ? ? ? if trys==9: ? ? ? ? raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) ? ? email_remind() It does the job (regrade exam now booked :)) but It succeeds in sending emails only about 50% of the time. The other 50% I get ... Mailing error ... Re-trying ... 1 of 10 Mailing error ... Re-trying ... 2 of 10 Mailing error ... Re-trying ... 3 of 10 Mailing error ... Re-trying ... 4 of 10 Mailing error ... Re-trying ... 5 of 10 Mailing error ... Re-trying ... 6 of 10 Mailing error ... Re-trying ... 7 of 10 Mailing error ... Re-trying ... 8 of 10 Mailing error ... Re-trying ... 9 of 10 Mailing error ... Re-trying ... 10 of 10 Traceback (most recent call last): ? File "/home/dave/my files/andrew_torture/email_remind.py", line 49, in ? ? ? email_remind() ? File "/home/dave/my files/andrew_torture/email_remind.py", line 43, in email_remind ? ? raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) Mail Failure smtplib.SMTPRecipientsRefused {'XXXX at chubb.co.uk': (553, "sorry, that domain isn't in my list of allowed rcpthosts (#5.7.1)")} I do not know if the is me not using the SMTP function correctly, I have noticed the emails arrive and kmail cannot work out when they were sent, or if the problem lies elsewear. Any suggestions gratefully recieved Cheers Dave From python at venix.com Mon Nov 21 21:15:56 2005 From: python at venix.com (Python) Date: Mon, 21 Nov 2005 15:15:56 -0500 Subject: [Tutor] smtplib problems ? In-Reply-To: <200511211959.33672.pythontut@pusspaws.net> References: <200511211959.33672.pythontut@pusspaws.net> Message-ID: <1132604156.26889.151.camel@www.venix.com> On Mon, 2005-11-21 at 19:59 +0000, dave wrote: > Traceback (most recent call last): > File "/home/dave/my files/andrew_torture/email_remind.py", line 49, in ? > email_remind() > File "/home/dave/my files/andrew_torture/email_remind.py", line 43, in > email_remind > raise 'Mail Failure\n'+str(sys.exc_type)+'\n'+str(sys.exc_value) > Mail Failure > smtplib.SMTPRecipientsRefused > {'XXXX at chubb.co.uk': (553, "sorry, that domain isn't in my list of allowed > rcpthosts (#5.7.1)")} http://www.greenend.org.uk/rjk/2000/05/21/smtp-replies.html It is a standard SMTP error message. Essentially the mail server is trying to prevent relaying. Your script is working correctly. This SMTP server, since it works some of the time, probably uses POP before SMTP to authenticate your request. So if you login to the POP server using your mailbox name and password, it will authenticate your IP address as permitted to relay. This authentication will time out after a few minutes. Test this by checking your email on that server and then see if your script runs successfully. If you can use an SMTP server from your ISP that uses IP addresses to control relaying, you can avoid the need to login to the POP server. -- Lloyd Kvam Venix Corp From john at fouhy.net Mon Nov 21 23:17:35 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 22 Nov 2005 11:17:35 +1300 Subject: [Tutor] Tkinter modal dialogs In-Reply-To: <27269.1132586366@www34.gmx.net> References: <27269.1132586366@www34.gmx.net> Message-ID: <5e58f2e40511211417w1b37bac5n@mail.gmail.com> Hi Karsten, You might want to look at Python MegaWidgets: http://pmw.sourceforge.net/ PMW is an alternative to Tix, built using only python and basic Tkinter. It has a scrolled listbox widget and a way of easily creating modal dialogs. -- John. From john at fouhy.net Mon Nov 21 23:26:03 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 22 Nov 2005 11:26:03 +1300 Subject: [Tutor] reduce with comprehension In-Reply-To: References: Message-ID: <5e58f2e40511211426h1396609dj@mail.gmail.com> On 21/11/05, J?nos Juh?sz wrote: > I can't imagine how this could be made with list comprehension. > > >>> import operator > >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) > >>> reduce(operator.add, a) # it makes a long list now > ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]) Everything is possible with list comprehensions! >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) >>> [x for y in a for x in y] [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] We can even go a level deeper! >>> [x for z in a for y in z for x in y] [1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9] Just make sure your depth is consistent throughout. And remember that that single-line expression is hiding nested FOR loops! -- John. From dyoo at hkn.eecs.berkeley.edu Mon Nov 21 23:40:16 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Nov 2005 14:40:16 -0800 (PST) Subject: [Tutor] O/T:META: Crossposting In-Reply-To: <20051121092457.22402.qmail@web30508.mail.mud.yahoo.com> Message-ID: On Mon, 21 Nov 2005, enas khalil wrote: > i want to confirm with you that the right addresses to send to are : > python-list at python.org > tutor at python.org > arent they ? [Keeping Tutor in CC; if I'm out of line, I want to make sure someone calls me on it and keeps me grounded.] Hi Enas, I can't help but feel we're having a language issue here. (If there's anything below that confuses you, please ask for clarification, because I feel like I've been repeating this several times now, and I don't know what I'm saying wrong.) When I use the term "crosspost", I mean the act of posting the same question to more than one mailing list at once. The two addresses you've listed above are two distinct mailing lists. 1. The one we're on now is Python-tutor (tutor at python.org). 2. python-list at python.org is a gateway to the comp.lang.python general discussion newsgroup. You have been missing the whole point when I asked you not to crosspost: the main point is not topicality, but verbosity. Your questions would fit in both comp.lang.python and Python-Tutor. But just choose one: don't ask both at the same time. Don't flood all possible avenues at once: if everyone did this, all of the mailing lists would get clogged, and no one would be satisfied. We're trying to avoid a "tragedy of the commons" situation here. The research strategy you've been using to get answers, by flooding all channels for help at once, is ineffective and, frankly, annoying. And because everyone who helps here does so by free will --- this is not a day job --- we must make sure things aren't annoying, or else helpers will stop helping. Again, I want to emphasize that we want to help you learn how to program Python, and we are happy to get good questions from you. But please change your behavior so that you are not the only one who benefits. See: http://www.catb.org/~esr/faqs/smart-questions.html#forum http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html#SECTION00070000000000000000 From dyoo at hkn.eecs.berkeley.edu Tue Nov 22 01:18:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 21 Nov 2005 16:18:50 -0800 (PST) Subject: [Tutor] O/T:META: Crossposting In-Reply-To: <20051121230738.78292.qmail@web30514.mail.mud.yahoo.com> Message-ID: On Mon, 21 Nov 2005, enas khalil wrote: > thanks again ,sir > i finally understand what you mean > sorry for annoying you several times ,promise not to do this again > > execuse me can i ask you aquestion about how can i use codecs in read > and tag an arabic text file > thanks again [Forwarding to tutor to see if anyone else is interested. I'm too busy to research this for Enas. Thanks.] From hugonz-lists at h-lab.net Tue Nov 22 03:02:55 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 21 Nov 2005 20:02:55 -0600 Subject: [Tutor] Ellipsis syntax Message-ID: <43827C4F.7070600@h-lab.net> Hi all, I have looked for any references of ellipsis '...' syntax for Python slices, but I keep finding the same BNF grammar in the LanguageRreference. Is there any page with examples on how to do this, or is this just very obscure? I remember reading something about this syntax somewhere, long ago. I don't even know how it is supposed to be used, but it is in the grammar... Any help would be appreciated. Hugo From john at fouhy.net Tue Nov 22 03:27:14 2005 From: john at fouhy.net (John Fouhy) Date: Tue, 22 Nov 2005 15:27:14 +1300 Subject: [Tutor] Ellipsis syntax In-Reply-To: <43827C4F.7070600@h-lab.net> References: <43827C4F.7070600@h-lab.net> Message-ID: <5e58f2e40511211827k10ef315dv@mail.gmail.com> On 22/11/05, Hugo Gonz?lez Monteverde wrote: > I have looked for any references of ellipsis '...' syntax for Python > slices, but I keep finding the same BNF grammar in the > LanguageRreference. Is there any page with examples on how to do this, > or is this just very obscure? Wow, funky. I found some links from when someone asked this last year: Main thread: http://mail.python.org/pipermail/python-list/2004-November/thread.html#252683 Good posts: http://mail.python.org/pipermail/python-list/2004-November/252614.html http://mail.python.org/pipermail/python-list/2004-November/252616.html http://mail.python.org/pipermail/python-list/2004-November/252622.html It seems that python slicing syntax supports slices like a[1, 2, ...], but no builtin types (list, string, tuple, etc) are capable of decoding slices like that. But you can implement your own classes if you want (say, if you want to implement multidimensional arrays). -- John. From kent37 at tds.net Tue Nov 22 03:46:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 21 Nov 2005 21:46:58 -0500 Subject: [Tutor] Ellipsis syntax In-Reply-To: <43827C4F.7070600@h-lab.net> References: <43827C4F.7070600@h-lab.net> Message-ID: <438286A2.5060002@tds.net> Hugo Gonz?lez Monteverde wrote: > Hi all, > > I have looked for any references of ellipsis '...' syntax for Python > slices, but I keep finding the same BNF grammar in the > LanguageRreference. Is there any page with examples on how to do this, > or is this just very obscure? ellipsis is used by Numeric for more flexible slicing. See the bottom of this page: http://numeric.scipy.org/numpydoc/numpy-6.html#pgfId-37311 Kent -- http://www.kentsjohnson.com From hugonz-lists at h-lab.net Tue Nov 22 03:50:45 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Mon, 21 Nov 2005 20:50:45 -0600 Subject: [Tutor] Ellipsis syntax In-Reply-To: <5e58f2e40511211827k10ef315dv@mail.gmail.com> References: <43827C4F.7070600@h-lab.net> <5e58f2e40511211827k10ef315dv@mail.gmail.com> Message-ID: <43828785.6050204@h-lab.net> Ok, now I know I don't need them just now *grin* Next time I will remember to search the newsgroup.... Now I think it was the perlish skeletons in my closet coming back to me. Thanks a lot for that, Hugo From adisegna at gmail.com Tue Nov 22 04:07:07 2005 From: adisegna at gmail.com (Adisegna) Date: Mon, 21 Nov 2005 22:07:07 -0500 Subject: [Tutor] Website monitoring program. Message-ID: <6571c3530511211907m4c413982pf22dac8e1ef8c5fc@mail.gmail.com> I need to add the count statement to give urllib access the tuple of urls. urllib needs to be given a different value each time in order to check all the urls. This is the only way I could get the value (web) in urllib to change each time. I tried indenting the count statement and it runs without error but still only makes one pass. Thanks Message: 1 Date: Sun, 20 Nov 2005 22:26:10 -0500 From: Kent Johnson Subject: Re: [Tutor] Website monitoring program. Cc: tutor at python.org Message-ID: <43813E52.5010708 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Adisegna wrote: > How do I get the counting loop to come back around? It makes one pass > fine. How do I get it to come back up and go through again? You have to indent the statement 'count += 1' so it is part of the loop. But you misunderstand the for loop - the count variable is not needed at all. Your variable 'i' will receive each element of urls, one each time through the loop. For a simpler example, >>> u = ['a', 'b', 'c'] >>> for letter in u: ... print letter ... a b c So instead of count = 0 for i in urls: web = urls[count] you can write simply for web in urls: See the Python tutorial for more examples of for loops: http://docs.python.org/tut/node6.html#SECTION006200000000000000000 Kent > > Thanks > > ------------------------------ ------------------------- > import urllib, smtplib > > urls = ("http://website0.net/imalive.asp", > "http://website1.net/imalive.asp", > "http://website2.net/imalive.asp", > "http://website3.net/imalive.asp", > "http://website4.net/imalive.asp" > ,) > > count = 0 > for i in urls: > web = urls[count] > > for site in urllib.urlopen(web): > > good = "400 Bad Request" > bad = "Invalid Hostname" > smtpserver = 'mail.authentium.com < http://mail.authentium.com>' > RECIPIENTS = ['my at address.com '] > SENDER = 'website-Verification at address.com > ' > mssg = site > > if good in site: > print "OK" > text_file = open("test.log", "a") > text_file.writelines('sometext : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > > elif bad in site: > print "NOT OK" > text_file = open("test.log", "a") > text_file.writelines('metro-ams : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > session = smtplib.SMTP(smtpserver) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], > smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > > else: > text_file = open("test.log", "a") > text_file.writelines('Another type of error occurred : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > print web > count +=1 > print count -- Arthur DiSegna Network Operations Center Authentium, Inc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051121/da8405d5/attachment.html From adisegna at gmail.com Tue Nov 22 05:00:41 2005 From: adisegna at gmail.com (Adisegna) Date: Mon, 21 Nov 2005 23:00:41 -0500 Subject: [Tutor] Fwd: Website monitoring program. In-Reply-To: <6571c3530511211907m4c413982pf22dac8e1ef8c5fc@mail.gmail.com> References: <6571c3530511211907m4c413982pf22dac8e1ef8c5fc@mail.gmail.com> Message-ID: <6571c3530511212000h38969c4dqa6e2da68377b13e1@mail.gmail.com> This worked for me..... Thanks! ------------------------------------------ for web in urls: for site in urllib.urlopen(web): ----------------------------------------------- You have to indent the statement 'count += 1' so it is part of the loop. But you misunderstand the for loop - the count variable is not needed at all. Your variable 'i' will receive each element of urls, one each time through the loop. For a simpler example, >>> u = ['a', 'b', 'c'] >>> for letter in u: ... print letter ... a b c So instead of count = 0 for i in urls: web = urls[count] you can write simply for web in urls: See the Python tutorial for more examples of for loops: http://docs.python.org/tut/node6.html#SECTION006200000000000000000 Kent > > Thanks > > ------------------------------ ------------------------- > import urllib, smtplib > > urls = ("http://website0.net/imalive.asp ", > "http://website1.net/imalive.asp", > " http://website2.net/imalive.asp", > "http://website3.net/imalive.asp", > "http://website4.net/imalive.asp" > < http://website4.net/imalive.asp%22>,) > > count = 0 > for i in urls: > web = urls[count] > > for site in urllib.urlopen(web): > > good = "400 Bad Request" > bad = "Invalid Hostname" > smtpserver = 'mail.authentium.com ' > RECIPIENTS = ['my at address.com '] > SENDER = 'website-Verification at address.com > ' > mssg = site > > if good in site: > print "OK" > text_file = open("test.log", "a") > text_file.writelines('sometext : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > > elif bad in site: > print "NOT OK" > text_file = open("test.log", "a") > text_file.writelines('metro-ams : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > session = smtplib.SMTP(smtpserver) > smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg) > if smtpresult: > errstr = "" > for recip in smtpresult.keys(): > errstr = """Could not delivery mail to: %s > > Server said: %s > %s > > %s""" % (recip, smtpresult[recip][0], > smtpresult[recip][1], errstr) > raise smtplib.SMTPException, errstr > > > else: > text_file = open("test.log", "a") > text_file.writelines('Another type of error occurred : ') > text_file.writelines(site) > text_file.writelines("\n") > text_file.close() > print web > count +=1 > print count -- Arthur DiSegna Network Operations Center Authentium, Inc. -- Arthur DiSegna Network Operations Center Authentium, Inc. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051121/6d1dc621/attachment-0001.htm From wan at walrus.us Tue Nov 22 05:38:25 2005 From: wan at walrus.us (Vincent Wan) Date: Mon, 21 Nov 2005 19:38:25 -0900 Subject: [Tutor] Help with objects Message-ID: I'm trying to write a tree data structure as part of my first object oriented program I have an error "can't assign to function call" caused by this line: Tree.nodeList(self.name) = self however, nodeList is a dictionary I'm trying to index. Beyond the error I'm still not sure I understand how to make and use a tree data structure using objects. Thank you for the help Here is my code # obj_tree1.py import random # constants that control the simulation NUMBER_REPS = 10 # run's the simulation MAX_LINAGES = 10 # number of species in each run BRANCHING_PROBABILITY = 0.5 class Tree(object): numLinages = 0 # keeps track of how many nodes there are nodeList = {} # keeps track of the nodes class Node(object): def __init__(self, name): self.name = name # an integer self.alive = True self.descendents = {} # nodes descending from self Tree.numLinages += 1 # records node creation Tree.nodeList(self.name) = self # makes node accesable from tree def __init__(self): nodeList(0) = Tree.Node(0) # adds a root node 0 to the tree def AddBranch(self, offspring): self.descendents(offspring) = Tree.Node(offspring) # adds a descendent node def NumLinages( ): return Tree.numLinages NumLinages = staticmethod(NumLinages) currentTree = Tree() for i in range(NUMBER_REPS): j = 0 while j <= currentTree.NumLinages(): # checks all node because their names are sequential integers if j.alive: if random.random() >= BRANCHING_PROBABILITY: currentTree.AddBranch(j, (currentTree.NumLinages() + 1)) # creates a new node j += 1 Vincent Wan ------------------------------------------------------------------------ -------------- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) From bgailer at alum.rpi.edu Tue Nov 22 05:52:53 2005 From: bgailer at alum.rpi.edu (bob) Date: Mon, 21 Nov 2005 20:52:53 -0800 Subject: [Tutor] Help with objects In-Reply-To: References: Message-ID: <7.0.0.16.0.20051121205227.03420ac8@alum.rpi.edu> At 08:38 PM 11/21/2005, Vincent Wan wrote: >I'm trying to write a tree data structure as part of my first >object oriented program > >I have an error "can't assign to function call" caused by this line: >Tree.nodeList(self.name) = self Tree.nodeList[self.name] = self >however, nodeList is a dictionary I'm trying to index. > >Beyond the error I'm still not sure I understand how to make and >use a tree data structure using objects. > >Thank you for the help > >Here is my code > ># obj_tree1.py > >import random > ># constants that control the simulation >NUMBER_REPS = 10 # run's the simulation >MAX_LINAGES = 10 # number of species in each run >BRANCHING_PROBABILITY = 0.5 > >class Tree(object): > numLinages = 0 # keeps track of how many nodes there are > nodeList = {} # keeps track of the nodes > class Node(object): > def __init__(self, name): > self.name = name # an integer > self.alive = True > self.descendents = {} # nodes descending from self > Tree.numLinages += 1 # records node creation > Tree.nodeList(self.name) = self # makes node >accesable from tree > def __init__(self): > nodeList(0) = Tree.Node(0) # adds a root node 0 to the tree > def AddBranch(self, offspring): > self.descendents(offspring) = Tree.Node(offspring) # adds >a descendent node > def NumLinages( ): > return Tree.numLinages > NumLinages = staticmethod(NumLinages) > >currentTree = Tree() > >for i in range(NUMBER_REPS): > j = 0 > while j <= currentTree.NumLinages(): # checks all node because >their names are sequential integers > if j.alive: > if random.random() >= BRANCHING_PROBABILITY: > currentTree.AddBranch(j, (currentTree.NumLinages() + >1)) # creates a new node > j += 1 > > >Vincent Wan > >------------------------------------------------------------------------ >-------------- >PhD Candidate >Committee on the Conceptual and Historical Studies of Science >University of Chicago > >PO Box 73727 >Fairbanks, AK 99707 > >wan AT walrus DOT us (change CAPS to @ and . ) > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From wan at walrus.us Tue Nov 22 06:04:41 2005 From: wan at walrus.us (Vincent Wan) Date: Mon, 21 Nov 2005 20:04:41 -0900 Subject: [Tutor] Help with objects In-Reply-To: <7.0.0.16.0.20051121205227.03420ac8@alum.rpi.edu> References: <7.0.0.16.0.20051121205227.03420ac8@alum.rpi.edu> Message-ID: <4D175B79-0962-4227-8B1D-2A1044538297@walrus.us> Thank you bob. I fixed the errors where I tried to index a dictionary with name() so so that they say name[] >> Beyond the error I'm still not sure I understand how to make and >> use a tree data structure using objects. There is a new error as well Traceback (most recent call last): File "/Users/Wally/obj_tree1.py", line 28, in -toplevel- currentTree = Tree() File "/Users/Wally/obj_tree1.py", line 21, in __init__ nodeList[0] = Tree.Node(0) # adds a root node 0 to the tree NameError: global name 'nodeList' is not defined Code with error bob fixed fixed throughout # obj_tree1.py import random # constants that control the simulation NUMBER_REPS = 10 # run's the simulation MAX_LINAGES = 10 # number of species in each run BRANCHING_PROBABILITY = 0.5 class Tree(object): numLinages = 0 # keeps track of how many nodes there are nodeList = {} # keeps track of the nodes class Node(object): def __init__(self, name): self.name = name # an integer self.alive = True self.descendents = {} # nodes descending from self Tree.numLinages += 1 # records node creation Tree.nodeList[self.name] = self # makes node accesable from tree def __init__(self): nodeList[0] = Tree.Node(0) # adds a root node 0 to the tree def AddBranch(self, offspring): self.descendents[offspring] = Tree.Node(offspring) # adds a descendent node def NumLinages( ): return Tree.numLinages NumLinages = staticmethod(NumLinages) currentTree = Tree() for i in range(NUMBER_REPS): j = 0 while j <= currentTree.NumLinages(): # checks all node because their names are sequential integers if j.alive: if random.random() >= BRANCHING_PROBABILITY: currentTree.AddBranch(j, (currentTree.NumLinages() + 1)) # creates a new node j += 1 Thank you for the help Vincent Wan ------------------------------------------------------------------------ -------------- PhD Candidate Committee on the Conceptual and Historical Studies of Science University of Chicago PO Box 73727 Fairbanks, AK 99707 wan AT walrus DOT us (change CAPS to @ and . ) From samrobertsmith at gmail.com Tue Nov 22 06:45:19 2005 From: samrobertsmith at gmail.com (Shi Mu) Date: Mon, 21 Nov 2005 21:45:19 -0800 Subject: [Tutor] about global definition Message-ID: <1d987df30511212145q60d8fb2ds95025b557008477@mail.gmail.com> I have a code here. I understand i can not draw lines without the global definition of lastX and lastY. But still confused by its use. when should we use global definition? from Tkinter import * root = Tk() c = Canvas(root, bg='#0e2e0e', height=500, width=1000) frame = c lastX="" lastY="" def click(event): global lastX, lastY if lastX != "": c.create_line(lastX,lastY,event.x,event.y,fill="white") lastX = event.x lastY = event.y c.bind('<1>',click) c.pack() root.mainloop() From janos.juhasz at VELUX.com Tue Nov 22 08:19:12 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 22 Nov 2005 08:19:12 +0100 Subject: [Tutor] reduce with comprehension In-Reply-To: <5e58f2e40511211426h1396609dj@mail.gmail.com> Message-ID: Hi John, thanks it. It is great. I looked for it, but I couldn't made it. I have tried it with wrong order: # I have tried it so [x for x in y for y in a] [[8], [8], [8], [9], [9], [9]] # that is wrong, # Instead of that you wrote [x for y in a for x in y] [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] Yours sincerely, ______________________________ J?nos Juh?sz jfouhy at gmail.com wrote on 2005.11.21 23:26:03: > On 21/11/05, J?nos Juh?sz wrote: > > I can't imagine how this could be made with list comprehension. > > > > >>> import operator > > >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) > > >>> reduce(operator.add, a) # it makes a long list now > > ([1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]) > Everything is possible with list comprehensions! > >>> a = (([1],[2],[3,31,32],[4]), ([5],[6],[7, 71, 72]), ([8],[9])) > >>> [x for y in a for x in y] > [[1], [2], [3, 31, 32], [4], [5], [6], [7, 71, 72], [8], [9]] > We can even go a level deeper! > >>> [x for z in a for y in z for x in y] > [1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9] > Just make sure your depth is consistent throughout. > And remember that that single-line expression is hiding nested FOR loops! > -- > John. From dyoo at hkn.eecs.berkeley.edu Tue Nov 22 09:18:07 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 22 Nov 2005 00:18:07 -0800 (PST) Subject: [Tutor] Help with objects In-Reply-To: <4D175B79-0962-4227-8B1D-2A1044538297@walrus.us> Message-ID: On Mon, 21 Nov 2005, Vincent Wan wrote: > Thank you bob. I fixed the errors where I tried to index a dictionary > with name() so so that they say name[] > > >> Beyond the error I'm still not sure I understand how to make and use > >> a tree data structure using objects. > > There is a new error as well > > Traceback (most recent call last): > File "/Users/Wally/obj_tree1.py", line 28, in -toplevel- > currentTree = Tree() > File "/Users/Wally/obj_tree1.py", line 21, in __init__ > nodeList[0] = Tree.Node(0) # adds a root node 0 to the tree > NameError: global name 'nodeList' is not defined Hi Vincent, You may want to look at places in your code where assigning nodeList does appear to work. For example, Node.__init__ appears to do: Tree.nodeList[self.name] = self Check the line that's raising an error: nodeList[0] = Tree.Node(0) as well as the content of the error message: NameError: global name 'nodeList' is not defined Do you understand what the error message is trying to say? You may also want to go through a formal tutorial that talks about data structures like trees. For example, How to Think like a Computer Scientist has a whole chapter on trees: http://www.ibiblio.org/obp/thinkCSpy/chap20.htm Although this concentrates on binary trees, the examples can be adjusted to do an arbitrary tree of any branching width. Rather than have each node have a link to their 'left' and 'right' children, we can do links to the "first child" and "next sibling". The implementation you have should be fine, but I did promise you an alternative implementation of trees. As a quick and dirty example of what this might look like, I'll strip it down so that there's minimal class stuff. ###### class Node: def __init__(self, id): self.id = id self.firstChild = None self.nextSibling = None def addChild(node, childId): child = Node(childId) child.nextSibling = node.firstChild node.firstChild = child return child ###### (The only reason I'm making a class definition at all is just to treat it as a data structure with labeled attributes. But everything else I write here will be a function, since you probably have a good foundation with them.) Once we have something like this, then if we wanted to represent a node with three children: 1 /|\ / | \ 2 3 4 then we can do something like this: ###### >>> node1 = Node(1) >>> addChild(node1, 2) <__main__.Node instance at 0x733a0> >>> addChild(node1, 3) <__main__.Node instance at 0x73620> >>> addChild(node1, 4) <__main__.Node instance at 0x737d8> ###### Does this work? Let's inspect what we have so far: ###### >>> node1.firstChild <__main__.Node instance at 0x73558> >>> node1.firstChild.id 4 >>> node1.firstChild.nextSibling.id 3 >>> node1.firstChild.nextSibling.nextSibling.id 2 >>> >>> node1.firstChild.nextSibling.nextSibling.nextSibling.id Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'id' ###### There they are. And, of course, if we jump off the list, as in the last example, we'll get an error. We should be careful to look before jumping. If it seems awkward to go through the list of children like this, we can abstract away the linked list traversal by writing a helper function, like this: ###### def children(node): """Returns the children of a node.""" children = [] child = node.firstChild while child != None: children.append(child) child = child.nextSibling return children ###### And now we can more easily see that node1 has three children: ###### >>> for child in children(node1): ... print child.id ... 4 3 2 ###### The staticmethods and nested classes that you have now seem slightly over-the-top to me, which is why I'm trying to counterbalance that with the simplest generalized tree example I can think of. *grin* I guess I'm trying to say: if you're doing tree stuff, you don't even need to use much sophisticated class stuff --- I think that simple functions should suffice at the moment. Good luck to you. From tanner at real-time.com Tue Nov 22 09:22:40 2005 From: tanner at real-time.com (Bob Tanner) Date: Tue, 22 Nov 2005 02:22:40 -0600 Subject: [Tutor] Delete an attribute using Beautiful Soup? Message-ID: <200511220222.41617.tanner@real-time.com> I'd like to delete an attribute of tag, the BGCOLOR to the BODY tag to be exact. I see Tag.__delitem__(self, key), but I cannot seem to figure out how to use it. Any help? class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def __init__(self, name, attrs=None, parent=Null, previous=Null): "Basic constructor." self.name = name if attrs == None: attrs = [] self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." for item in self.attrs: if item[0] == key: self.attrs.remove(item) #We don't break because bad HTML can define the same #attribute multiple times. self._getAttrMap() if self.attrMap.has_key(key): del self.attrMap[key] -- Bob Tanner | Phone : (952)943-8700 http://www.real-time.com, Minnesota, Linux | Fax : (952)943-8500 Key fingerprint = AB15 0BDF BCDE 4369 5B42 1973 7CF1 A709 2CC1 B288 From tanner at real-time.com Tue Nov 22 09:34:53 2005 From: tanner at real-time.com (Bob Tanner) Date: Tue, 22 Nov 2005 02:34:53 -0600 Subject: [Tutor] Delete an attribute using Beautiful Soup? References: <200511220222.41617.tanner@real-time.com> Message-ID: Bob Tanner wrote: > I'd like to delete an attribute of tag, the BGCOLOR to the BODY tag to be > exact. I believe I answered my own question. Looking for confirmation this is the "right" solution. del(soup.body['bgcolor']) -- Bob Tanner | Phone : (952)943-8700 http://www.real-time.com, Minnesota, Linux | Fax : (952)943-8500 Key fingerprint = AB15 0BDF BCDE 4369 5B42 1973 7CF1 A709 2CC1 B288 From lists at janeden.org Tue Nov 22 12:56:12 2005 From: lists at janeden.org (Jan Eden) Date: Tue, 22 Nov 2005 12:56:12 +0100 Subject: [Tutor] Dynamic inheritance? In-Reply-To: <43806C64.1020002@tds.net> Message-ID: Hi, Kent Johnson wrote on 20.11.2005: > >Use getattr() to access attributes by name. SiteA is an attribute of >Templates and Page is an attribute of SiteA so you can get use >getattr() twice to get what you want: > >site = getattr(Templates, self.site_name) self.template = >getattr(site, self.template_type) > Unfortunately, this does not seem to work if Templates is a package, not a module. Python complains: AttributeError: 'module' object has no attribute 'SiteA' ??????args?= ("'module' object has no attribute 'SiteA'",) even though there is a module SiteA within package Templates. When manually importing SiteA from Templates, everything is good. From your previous message, I read that modules are treated just like classes or any other attribute - did I misinterpret your advice? Thanks, Jan -- I was gratified to be able to answer promptly, and I did. I said I didn't know. - Mark Twain From singletoned at gmail.com Tue Nov 22 13:41:11 2005 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 22 Nov 2005 12:41:11 +0000 Subject: [Tutor] Inheriting from parent object In-Reply-To: <380-2200511215181948691@freenet.co.uk> References: <380-2200511215181948691@freenet.co.uk> Message-ID: <34bb7f5b0511220441x6251d7cag@mail.gmail.com> Thanks for this. I hadn't really considered that I would have to explicitly store parent/child relationships. Having been browsing for something else, I came across this page about Unifying types and classes: http://www.python.org/2.2.3/descrintro.html >From it, it looks like I could do something like: class Page(object): def __init__(self, parent): self.__header = None self.parent = parent def getheader(self): if not self._header and self.parent: return self.parent.header else: return self.__header def setheader(self, header): self.__header = header header = property(getheader, setheader) Which I think would end up doing exactly what I want. I still don't think I'm clear on the use of self though. Can I only use it in class definitions? I think it might be that myPage = Page(parentPage) is highly deceptive. Shouldn't it really be: new Page(myPage, parentPage) or myPage = new Page(myPage, parentPage) or am I getting really, really confused? Ed On 15/11/05, alan.gauld at freenet.co.uk wrote: > >>Sorry, I didn't really explain myself clearly. > > Thats OK its easy to get buried in the depths and > forget everyone else is coming at it cold. But > the use of non standard terms confused things > even more! > > >>I want to create a kind of website ... > >>I want to have a root object, which > >>has page objects. The page objects > > will have various properties > >like header, footer, body and an order > > Sounds like a job for classes. Create a > Page class with the various properties. > Initialise objects with their parent > (ie containing) object. > > >>to inherit the attribute from their parent page (ie if it is > >>root.chapter3.page5 then chapter3 is the parent of page5). > > >>I guess the psuedo code would be: > >> > >>def inherit() > >> return this.parent.attribute > >> > > Just put code like this in the init method: > > Class Page: > def __init__(self, parent = None): > self.parent = parent # and handle default too! > def getHeader(self): > return self.parent.header > > etc... > > Then create > > Chapter3 = Page() > Chapter3.header = '''

some long string here....''' > Chapter3.getHeader() > p2 = Page(Chapter3) > p2.getHeader() # returns Chapter3.header > > etc > > >>(I know Python doesn't really have a 'this' > > But it does have self.... and you can use > this if you prefer! > > > >>knowing who the function was called by). > > Thats not really needed if you use objects. > Although self does point at the specific > Page whose method is being invoked. > > HTH, > > Alan G > > From fant at pobox.com Tue Nov 22 16:58:13 2005 From: fant at pobox.com (Andrew Fant) Date: Tue, 22 Nov 2005 10:58:13 -0500 Subject: [Tutor] Application Templates? Message-ID: <43834015.3060602@pobox.com> I am about to start work on my first significant coding projects in some time (and first ever in python). Does anyone have any standard templates that they use to lay out new projects that they might be willing to share? By templates, I am not asking about complex libraries and OO things that I don't fully understand, but rather a file that sets up a common base for applications like file handling, customary command line handling and such things. Essentially a file that you can start plugging your core logic into and start working from. Thanks, Andy From bgailer at alum.rpi.edu Tue Nov 22 17:11:57 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 22 Nov 2005 08:11:57 -0800 Subject: [Tutor] Help with objects In-Reply-To: <4D175B79-0962-4227-8B1D-2A1044538297@walrus.us> References: <7.0.0.16.0.20051121205227.03420ac8@alum.rpi.edu> <4D175B79-0962-4227-8B1D-2A1044538297@walrus.us> Message-ID: <7.0.0.16.0.20051122080519.011c0b80@alum.rpi.edu> At 09:04 PM 11/21/2005, Vincent Wan wrote: >Thank you bob. I fixed the errors where I tried to index a dictionary >with name() >so so that they say name[] > >>>Beyond the error I'm still not sure I understand how to make and >>>use a tree data structure using objects. > >There is a new error as well > >Traceback (most recent call last): > File "/Users/Wally/obj_tree1.py", line 28, in -toplevel- > currentTree = Tree() > File "/Users/Wally/obj_tree1.py", line 21, in __init__ > nodeList[0] = Tree.Node(0) # adds a root node 0 to the tree >NameError: global name 'nodeList' is not defined > >Code with error bob fixed fixed throughout > ># obj_tree1.py > >import random > ># constants that control the simulation >NUMBER_REPS = 10 # run's the simulation >MAX_LINAGES = 10 # number of species in each run >BRANCHING_PROBABILITY = 0.5 > >class Tree(object): > numLinages = 0 # keeps track of how many nodes there are > nodeList = {} # keeps track of the nodes nodeList is a property of class Tree. > class Node(object): > def __init__(self, name): > self.name = name # an integer > self.alive = True > self.descendents = {} # nodes descending from self > Tree.numLinages += 1 # records node creation > Tree.nodeList[self.name] = self # makes node > accesable from tree > def __init__(self): > nodeList[0] = Tree.Node(0) # adds a root node 0 to the tree To refer to a property of the class: Tree.nodeList[0] = Tree.Node(0) # adds a root node 0 to the tree > def AddBranch(self, offspring): > self.descendents[offspring] = Tree.Node(offspring) # > adds a descendent node > def NumLinages( ): > return Tree.numLinages > NumLinages = staticmethod(NumLinages) > >currentTree = Tree() > >for i in range(NUMBER_REPS): > j = 0 > while j <= currentTree.NumLinages(): # checks all node because >their names are sequential integers > if j.alive: > if random.random() >= BRANCHING_PROBABILITY: > currentTree.AddBranch(j, (currentTree.NumLinages() + >1)) # creates a new node > j += 1 > >Thank you for the help > > >Vincent Wan > >------------------------------------------------------------------------ >-------------- >PhD Candidate >Committee on the Conceptual and Historical Studies of Science >University of Chicago > >PO Box 73727 >Fairbanks, AK 99707 > >wan AT walrus DOT us (change CAPS to @ and . ) From alan.gauld at freenet.co.uk Tue Nov 22 19:02:00 2005 From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 22 Nov 2005 18:02:00 -0000 Subject: [Tutor] about global definition Message-ID: <380-22005112221820841@freenet.co.uk> >>I have a code here. I understand i can not draw lines without the >>global definition of lastX and lastY. But still confused by its use. >>when should we use global definition? If you don't use classes then you will need to use global variables any time you want to pass information between functions and the functions have a predetermined interface that precludes making the data parameters. Thus in your case the callback click(event) can only take the one parameter, event so you must use global variables. Similarly you need to use globals where you need to maintain state between function calls (even of the same function) Otherwisde you should be able to avoid globals. Using OOP allows you to hide the global functions inside an object which solves both of the above problems. HTH, Alan G. From lists at janeden.org Tue Nov 22 20:01:02 2005 From: lists at janeden.org (Jan Eden) Date: Tue, 22 Nov 2005 20:01:02 +0100 Subject: [Tutor] Dynamic inheritance? In-Reply-To: Message-ID: Hi, Jan Eden wrote on 22.11.2005: >Hi, > >Kent Johnson wrote on 20.11.2005: >> >>Use getattr() to access attributes by name. SiteA is an attribute >>of Templates and Page is an attribute of SiteA so you can get use >>getattr() twice to get what you want: >> >>site = getattr(Templates, self.site_name) self.template = >>getattr(site, self.template_type) >> > >Unfortunately, this does not seem to work if Templates is a package, >not a module. Python complains: > >AttributeError: 'module' object has no attribute 'SiteA' >??????args?= ("'module' object has no attribute 'SiteA'",) > >even though there is a module SiteA within package Templates. When >manually importing SiteA from Templates, everything is good. > Found a solution: import Templates #... def GetTemplates(self): __import__('Templates.', globals(), locals(), [self.identifier]) site = getattr(Templates, self.identifier) self.template = getattr(site, self.template_type) works. Thanks, Jan -- He who would give up a little liberty in return for a little security deserves neither liberty nor security. - Benjamin Franklin From python at patm.net Tue Nov 22 20:08:39 2005 From: python at patm.net (Pat Martin) Date: Tue, 22 Nov 2005 11:08:39 -0800 Subject: [Tutor] python-ldap Message-ID: <43836CB7.90306@patm.net> I am new to python and fairly new to programming. I have written some ldap scripts in perl and am trying to learn how to do that in python. I found some code on the net using the python-ldap module (the unaltered code is at the bottom of this email) and have adapted it to my needs, the code works fine. I want to learn what some of the things in the code are. The two things I don't understand are ldap.SCOPE_SUBTREE and ldap.RES_SEARCH_ENTRY when I print those out I get integers 2 and 100 respectively, I am not sure if they change but that is what they start out at. I am figuring other modules use similar things (variables?), can someone point me to where I can understand what more about what these are. The help documentation didn't really explain about these. Thanks Pat code: import ldap ## first you must open a connection to the server try: l = ldap.open("127.0.0.1") ## searching doesn't require a bind in LDAP V3. If you're using LDAP v2, set the next line appropriately ## and do a bind as shown in the above example. # you can also set this to ldap.VERSION2 if you're using a v2 directory # you should set the next option to ldap.VERSION2 if you're using a v2 directory l.protocol_version = ldap.VERSION3 except ldap.LDAPError, e: print e # handle error however you like ## The next lines will also need to be changed to support your search requirements and directory baseDN = "ou=Customers, ou=Sales, o=anydomain.com" searchScope = ldap.SCOPE_SUBTREE ## retrieve all attributes - again adjust to your needs - see documentation for more options retrieveAttributes = None searchFilter = "cn=*jack*" try: ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes) result_set = [] while 1: result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): break else: ## here you don't have to append to a list ## you could do whatever you want with the individual entry ## The appending to list is just for illustration. if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) print result_set except ldap.LDAPError, e: print e From EDouglass at gaylordhotels.com Tue Nov 22 15:03:08 2005 From: EDouglass at gaylordhotels.com (Douglass, Erik) Date: Tue, 22 Nov 2005 08:03:08 -0600 Subject: [Tutor] Newbie question Message-ID: <566E54419328A642A3A6E91376E885B1027AC185@txex.tx.get> I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work :-().. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051122/c711ace8/attachment.htm From mjekl at clix.pt Tue Nov 22 17:27:44 2005 From: mjekl at clix.pt (Miguel Lopes) Date: Tue, 22 Nov 2005 16:27:44 +0000 Subject: [Tutor] Problem using easy_install Message-ID: <20051122162744.14641.qmail@maboque.srv.clix.pt> An embedded and charset-unspecified text was scrubbed... Name: not available Url: http://mail.python.org/pipermail/tutor/attachments/20051122/4f829e5b/attachment.asc From dyoo at hkn.eecs.berkeley.edu Tue Nov 22 21:19:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 22 Nov 2005 12:19:10 -0800 (PST) Subject: [Tutor] Newbie question In-Reply-To: <566E54419328A642A3A6E91376E885B1027AC185@txex.tx.get> Message-ID: On Tue, 22 Nov 2005, Douglass, Erik wrote: > I am trying to follow some online first timer tutorials, and I am > writing the practice scripts in notepad (only w32 at work :-().. I save > the script with a .py extension, and when I run it it opens for a brief > moment in a command prompt then closes before I even have a chance to > see what it says. This may seem trivial, but Python also happens to be > my first language so this is all new to me. Using Python 2.4.2 Hi Erik, No problem. What's happening is that Windows is closing down any program that's finished. Usually, that's what you want, except while you're learning how to program. Most of the programs you will be writing will be short, terminate quickly, and close down before you can see your program's results! *grin* If you run your programs through IDLE, you should be able to see them run to completion without closing down. I wrote an introduction to IDLE here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html It's a little outdated, but most of the information there is still relevant. (The menu option for running scripts now lives in the Module menu, I think.) One other way to get around the program-terminating-closes-window problem is to keep your program from terminating. Some people will add a last statement to their program, like the infamous: ###### raw_input("Please press enter to continue...") ###### which should pause until the user presses the enter key. Best of wishes to you! From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 22 21:20:45 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 23 Nov 2005 09:20:45 +1300 Subject: [Tutor] Newbie question Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1465@chbnt01.alpha.wd.govt.nz> Hi Eric, Either - add this line to the end of your scripts - discard = raw_input("Press enter to finish.") Or - Click on Start > Run... type cmd.exe and use DOS to move to the directory where your scripts are stored and run them via Python there. It's not trivial when you're starting. :-) Regards, Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Douglass, Erik Sent: Wednesday, 23 November 2005 3:03 a.m. To: tutor at python.org Subject: [Tutor] Newbie question I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work :-().. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051123/54bf7b47/attachment.htm From dyoo at hkn.eecs.berkeley.edu Tue Nov 22 21:26:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 22 Nov 2005 12:26:21 -0800 (PST) Subject: [Tutor] Delete an attribute using Beautiful Soup? In-Reply-To: Message-ID: On Tue, 22 Nov 2005, Bob Tanner wrote: > Bob Tanner wrote: > > > I'd like to delete an attribute of tag, the BGCOLOR to the BODY tag to be > > exact. > > I believe I answered my own question. Looking for confirmation this is the > "right" solution. > > del(soup.body['bgcolor']) Yes, del should do it. del is the deletion statement that lets us do things like remove keys from a dictionary: ###### >>> states = {'TX' : 'Texas', ... 'CA' : 'California', ... 'PL' : 'Pluto'} ###### If we want to get rid of an intergalactic mistake, we can use del: ###### >>> del states['PL'] >>> states {'CA': 'California', 'TX': 'Texas'} ###### Good luck! From Barry.Carroll at psc.com Tue Nov 22 21:44:46 2005 From: Barry.Carroll at psc.com (Carroll, Barry) Date: Tue, 22 Nov 2005 12:44:46 -0800 Subject: [Tutor] Newbie question Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C3590@eugsrv400.psc.pscnet.com> Hello, Erik, Welcome to the maillist. >From your description, is sounds like you are attempting to run the scripts by double clicking on them from Windows Explorer, or from the Run dialog on the Start menu. Both these methods open a command window in a new process, run the script, then terminate the process as soon as the script ends. Try opening a command window manually, changing to the directory where the script resides, and running the program from there. That way the window will remain after the script has finished, and you can see the results. One way to get to a command prompt window is to use the XP start menu: Start->All Programs->Accessories->Command Prompt HTH BGC ================================== > Date: Tue, 22 Nov 2005 08:03:08 -0600 > From: "Douglass, Erik" > Subject: [Tutor] Newbie question > To: tutor at python.org > Message-ID: <566E54419328A642A3A6E91376E885B1027AC185 at txex.tx.get> > Content-Type: text/plain; charset="us-ascii" > > I am trying to follow some online first timer tutorials, and I am > writing the practice scripts in notepad (only w32 at work :-().. I > save the script with a .py extension, and when I run it it opens for a > brief moment in a command prompt then closes before I even have a chance > to see what it says. This may seem trivial, but Python also happens to > be my first language so this is all new to me. Using Python 2.4.2 > > > > Thanks for any help. > > > > Erik > From hugonz-lists at h-lab.net Tue Nov 22 22:04:07 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 22 Nov 2005 15:04:07 -0600 Subject: [Tutor] python-ldap In-Reply-To: <43836CB7.90306@patm.net> References: <43836CB7.90306@patm.net> Message-ID: <438387C7.5090006@h-lab.net> Hi, Looks like they are just constants. There is really no point in printing or making any sense of their content, just use them as they are defined in the module. This is like a C #define But this is all LDAP specific... let's see: > > ## The next lines will also need to be changed to support your search > requirements and directory > baseDN = "ou=Customers, ou=Sales, o=anydomain.com" > searchScope = ldap.SCOPE_SUBTREE SCOPE_SUBTREE is one of the avaliable search scopes. According to this(http://linuxjournal.com/article/6988) it should search for the object and its descendants.. > if result_type == ldap.RES_SEARCH_ENTRY: > result_set.append(result_data) Reading it as it is, looks like the result may be something different, but only those results that are of type RES_SEARCH_ENTRY are meaningful. That's why you check it. read, read, read. This is what I understand, not knowing crap about LDAP, and just using Google. Check the following docs: ` http://www.ldapman.org/ldap_rfcs.html http://www.cse.ohio-state.edu/cs/Services/rfc/rfc-text/rfc1823.txt Bingo! This is the LDAP application programming interface from which the Python LDAP implementation has been 'stolen' All these definitions are explained. For instance: " Parameters are: ld The connection handle; base The dn of the entry at which to start the search; scope One of LDAP_SCOPE_BASE, LDAP_SCOPE_ONELEVEL, or LDAP_SCOPE_SUBTREE, indicating the scope of the search; Upon successful completion, ldap_result() returns the type of the result returned in the res parameter. This will be one of the following constants. LDAP_RES_BIND LDAP_RES_SEARCH_ENTRY LDAP_RES_SEARCH_RESULT LDAP_RES_MODIFY LDAP_RES_ADD LDAP_RES_DELETE LDAP_RES_MODRDN LDAP_RES_COMPARE " Google is your friend, and going through you may find most of your answers... Hope that help, Hugo From dan at tangledhelix.com Tue Nov 22 22:18:29 2005 From: dan at tangledhelix.com (Dan Lowe) Date: Tue, 22 Nov 2005 16:18:29 -0500 Subject: [Tutor] python-ldap In-Reply-To: <43836CB7.90306@patm.net> References: <43836CB7.90306@patm.net> Message-ID: <48521C5C-7FF4-4B97-83C7-69CBB96304BB@tangledhelix.com> On Nov 22, 2005, at 2:08 PM, Pat Martin wrote: > I am new to python and fairly new to programming. I have written some > ldap scripts in perl and am trying to learn how to do that in > python. I > found some code on the net using the python-ldap module (the unaltered > code is at the bottom of this email) and have adapted it to my needs, > the code works fine. I want to learn what some of the things in the > code > are. The two things I don't understand are > ldap.SCOPE_SUBTREE and > ldap.RES_SEARCH_ENTRY > when I print those out I get integers 2 and 100 respectively, I am not > sure if they change but that is what they start out at. I am figuring > other modules use similar things (variables?), can someone point me to > where I can understand what more about what these are. SCOPE_SUBTREE is one of three possible scopes you can use. Remember that LDAP is a tree-based heirarchy (arranged much like the old Windows Explorer file tree view). So that tree is divided into branches, sub branches, etc. How you limit your search depends on two things: 1. The starting branch point (the base) 2. The scope (which is applied to the base). So say you have ou=foo,ou=bar,o=root. There are three bases you could choose to start from. o=root ou=bar,o=root ou=foo,ou=bar,o=root If you used base o=root with a scope of SCOPE_BASE, the only possible entry that could be returned is o=root itself. SCOPE_BASE indicates that the scope of the search should be limited to the base itself - not to any of its sub branches or sub entries. Just itself. If you used base o=root with a scope of SCOPE_ONE, you would be able to obtain entries like this: ou=bar,o=root cn=something,o=root cn=another,o=root cn=third,o=root In other words, given a base, you can get entries one level below; the entries immediately subordinate to your base (but not the base itself). You could not get back ou=foo,ou=bar,o=root because that is not immediately beneath o=root. If you used base o=root with a scope of SCOPE_SUBTREE, you would be able to obtain any entry anywhere in the tree, including the base. This translates to: start the base, anything further down the line is okay. Therefore, if you used a base of ou=bar,o=root, you could get these entries: ou=bar,o=root cn=something,ou=bar,o=root cn=something-else,ou=foo,ou=bar,o=root But you could not get: o=root Because that is outside the scope (at a higher level than the base). Behind the scenes, the scopes have different numbers, which is why you get the integer value when you printed SCOPE_SUBTREE. These numbers don't really matter; they're just values used by the libraries. Just ignore them and use the constants SCOPE_BASE, SCOPE_ONE, SCOPE_SUBTREE. Unless you have a specific reason to use another scope, subtree is usually the default choice. I've had plenty of occasion to use the other two scopes, though. RES_SEARCH_ENTRY is, as far as I know, just a way to test if something is an LDAP entry object. So if you are iterating through a set of results, you can say if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) Which means, append the entry to the result set only if it actually is an entry object. More information here: http://python-ldap.sourceforge.net/doc/python-ldap/ldap-objects.html -dan -- Television is one of the Six Fundamental Forces of the Universe; with the other five being Gravity, Duct Tape, Whining, Remote Control, and the Force That Pulls Dogs Toward the Groins of Stranges. -Dave Barry From doublesix at ureach.com Tue Nov 22 22:40:11 2005 From: doublesix at ureach.com (Double Six) Date: Tue, 22 Nov 2005 16:40:11 -0500 Subject: [Tutor] command in menu and button Message-ID: <200511222140.QAA30716@www20.ureach.com> Hi all, I'm puzzled by the 'command' option in menu and Button of Tkinter. With the following lines, menu.add_command(label="Open Viewer", command=os.system("Open my viewer &")) Button(toolbar, text='Open Viewer', command=os.system("Open my viewer &")).pack(side=LEFT) I wanted to open a graphical viewer from the prompt (that is why I used os.system("Open viewer &")) once the user selects the option from the menu, or clicks the button, but this gets implements whenever the GUI is launched instead. Why is this? And how can I make it work? Many thanks, Joe ________________________________________________ Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag From bgailer at alum.rpi.edu Tue Nov 22 22:43:30 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 22 Nov 2005 13:43:30 -0800 Subject: [Tutor] Newbie question In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1465@chbnt01.alpha.wd. govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1465@chbnt01.alpha.wd.govt.nz> Message-ID: <7.0.0.16.0.20051122134210.0341d640@alum.rpi.edu> At 12:20 PM 11/22/2005, Liam Clarke-Hutchinson wrote: >Hi Eric, > >Either - > >add this line to the end of your scripts - >discard = raw_input("Press enter to finish.") > >Or - > >Click on Start > Run... type cmd.exe and use DOS to move to the >directory where your scripts are stored and run them via Python there. This is preferred, since any exception traceback will remain visible. > It's not trivial when you're starting. :-) > >Regards, > >Liam Clarke-Hutchinson > >-----Original Message----- >From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On >Behalf Of Douglass, Erik >Sent: Wednesday, 23 November 2005 3:03 a.m. >To: tutor at python.org >Subject: [Tutor] Newbie question > >I am trying to follow some online first timer tutorials, and I am >writing the practice scripts in notepad (only w32 at work L).. I >save the script with a .py extension, and when I run it it opens for >a brief moment in a command prompt then closes before I even have a >chance to see what it says. This may seem trivial, but Python also >happens to be my first language so this is all new to me. Using Python 2.4.2 > > > >Thanks for any help. > > > >Erik > > > >A new monthly electronic newsletter covering all aspects of MED's >work is now available. Subscribers can choose to receive news from >any or all of seven categories, free of charge: Growth and >Innovation, Strategic Directions, Energy and Resources, Business >News, ICT, Consumer Issues and Tourism. See >http://news.business.govt.nz for more details. > > > > > > > > >govt.nz - connecting you to New Zealand central >& local government services > > >---------- >Any opinions expressed in this message are not necessarily those of >the Ministry of Economic Development. This message and any files >transmitted with it are confidential and solely for the use of the >intended recipient. If you are not the intended recipient or the >person responsible for delivery to the intended recipient, be >advised that you have received this message in error and that any >use is strictly prohibited. Please contact the sender and delete the >message and any attachment from your computer. > >---------- >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051122/e649ce8d/attachment.htm From Hans.Dushanthakumar at navman.com Tue Nov 22 23:00:24 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Wed, 23 Nov 2005 11:00:24 +1300 Subject: [Tutor] Newbie question Message-ID: <5667508E43F1B740BCFA57FF46E353000277D1F9@nav-akl-exch-c.newton.navman.com> A short-cut if you dont want to use DOS to traverse to your directory or if you are feeling too lazy to type in the entire path & script name. You can right-click on the script file in the Windows explorer and choose "Send to -> Command prompt". This opens a command prompt with the path already set to the one that you want, and the name of the script already typed in. Now, just cursor to the left untill you reach the ">" prompt and type in "python ". So now your command prompt reads "C:\whatever path>python yourfile.py". Press enter to run the script. ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of bob Sent: Wednesday, 23 November 2005 10:44 a.m. To: Liam Clarke-Hutchinson; 'Douglass, Erik'; 'tutor at python.org' Subject: Re: [Tutor] Newbie question At 12:20 PM 11/22/2005, Liam Clarke-Hutchinson wrote: Hi Eric, Either - add this line to the end of your scripts - discard = raw_input("Press enter to finish.") Or - Click on Start > Run... type cmd.exe and use DOS to move to the directory where your scripts are stored and run them via Python there. This is preferred, since any exception traceback will remain visible. It's not trivial when you're starting. :-) Regards, Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [ mailto:tutor-bounces at python.org ] On Behalf Of Douglass, Erik Sent: Wednesday, 23 November 2005 3:03 a.m. To: tutor at python.org Subject: [Tutor] Newbie question I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work :-().. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services ________________________________ Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ________________________________ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051123/7d322b5d/attachment.html From john at fouhy.net Tue Nov 22 23:00:27 2005 From: john at fouhy.net (John Fouhy) Date: Wed, 23 Nov 2005 11:00:27 +1300 Subject: [Tutor] command in menu and button In-Reply-To: <5e58f2e40511221359o4e3c4dbbq@mail.gmail.com> References: <200511222140.QAA30716@www20.ureach.com> <5e58f2e40511221359o4e3c4dbbq@mail.gmail.com> Message-ID: <5e58f2e40511221400h1b046f0au@mail.gmail.com> Apologies to Double Six for getting this twice; I forgot to cc: tutor.. On 23/11/05, Double Six wrote: > menu.add_command(label="Open Viewer", command=os.system("Open my > viewer &")) Hi Joe, This is a fairly common gotcha. Think about what happens when python executes a function call: Firstly, it evaluates each of the arguments to the function. Then, it calls the function. So, with your line above, here's what python does: 1. Evaluate "Open Viewer". This is easy; it just produces a string. 2. Evaluate os.system("Open my viewer &"). Since this is a function call, in order to evaluate it, python calls the function to get its return value. 3. Call menu.add_command with the arguments it has just evaluated. Do you see what is happening now? What python wants is a _callable_ --- this is like a function that hasn't been called yet. Functions are first-class objects in python. That means you can do things like this: >>> def hello(): ... print 'hello world!' ... >>> hello() hello world! >>> f = hello # assign to f the function hello. >>> f() # f is now a function, so we can call it. hello world! Or, I could make a quit button like this: b = Button(self, text='Quit program', command=self.quit) # assuming 'self' is a Frame or Tk or something. Note the lack of () after self.quit: We're passing a reference to the method itself. So, to your specific problem: menu.add_command(label="Open Viewer", command=os.system("Open my viewer &")) It's a bit more difficult, because you want to pass an argument to os.system. And when Tkinter calls a menu callback, it doesn't give it any arguments. But, that's OK. You can just define a new function: def callback(): os.system("Open my viewer &") menu.add_command(label="Open Viewer", command=callback) Does this help? -- John. From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 22 23:05:30 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 23 Nov 2005 11:05:30 +1300 Subject: [Tutor] Newbie question Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B1469@chbnt01.alpha.wd.govt.nz> Ooer, weird keystrokes... my apologies Bob. >This is preferred, since any exception traceback will remain visible. That's a really good point... I believe associating a Python batch file using pause would allow tracebacks to remain also. @echo off c:\Python24\Python %1 %2 %3 %4 %5 %6 %7 %8 %9 pause or similar... Regards, Liam Clarke-Hutchinson www.med.govt.nz -----Original Message----- From: bob [mailto:bgailer at alum.rpi.edu] Sent: Wednesday, 23 November 2005 10:44 a.m. To: Liam Clarke-Hutchinson; 'Douglass, Erik'; 'tutor at python.org' Subject: Re: [Tutor] Newbie question At 12:20 PM 11/22/2005, Liam Clarke-Hutchinson wrote: Hi Eric, Either - add this line to the end of your scripts - discard = raw_input("Press enter to finish.") Or - Click on Start > Run... type cmd.exe and use DOS to move to the directory where your scripts are stored and run them via Python there. It's not trivial when you're starting. :-) Regards, Liam Clarke-Hutchinson -----Original Message----- From: tutor-bounces at python.org [ mailto:tutor-bounces at python.org ] On Behalf Of Douglass, Erik Sent: Wednesday, 23 November 2005 3:03 a.m. To: tutor at python.org Subject: [Tutor] Newbie question I am trying to follow some online first timer tutorials, and I am writing the practice scripts in notepad (only w32 at work :-().. I save the script with a .py extension, and when I run it it opens for a brief moment in a command prompt then closes before I even have a chance to see what it says. This may seem trivial, but Python also happens to be my first language so this is all new to me. Using Python 2.4.2 Thanks for any help. Erik A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. govt.nz - connecting you to New Zealand central & local government services _____ Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. _____ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051123/9f3c86e7/attachment-0001.htm From alan.gauld at freenet.co.uk Tue Nov 22 23:39:35 2005 From: alan.gauld at freenet.co.uk (alan.gauld@freenet.co.uk) Date: Tue, 22 Nov 2005 22:39:35 -0000 Subject: [Tutor] command in menu and button Message-ID: <380-2200511222223935535@freenet.co.uk> >>I'm puzzled by the 'command' option in menu and Button of >>Tkinter. With the following lines, The command value needs to be a *reference* to a function. That is not the function call itself but a reference to the function that will be \called. Let me illustrate the difference: def f(): print 'Its me!' f() # prints the message g = f # this assigns a reference to f g() # this now calls that reference, so calling g() is the same as calling f() >>menu.add_command(label="Open Viewer", command=os.system("Open my viewer &")) Here you assign the result of the os.system() call to command, in fact you want to assign a reference to a call of os.system which will be executed when the menu/button is activated. The more straightforward way to do that is to define a short function that calls os.system: def callSystem(): os.system(Mycommand) And make the menu/button reference callSystem: >>menu.add_command(label="Open Viewer", command=callSystem) Notice no parens, just the name of the function. Because we can wind up with loads of these little wrapper functions there is a shortcut called lambda. With lambda we can avoid defining a new mini function: >>menu.add_command(label="Open Viewer", command=lambda : os.system("Open my viewer &")) the thing that follows the lambda is what gets executed when the widget activates. Does that help? Alan G. http://www.freenetpages.co.uk/hp/alan.gauld From yncdonato at msn.com Tue Nov 22 23:41:22 2005 From: yncdonato at msn.com (mike donato) Date: Tue, 22 Nov 2005 18:41:22 -0400 Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED Message-ID: Greetings, I am new student to programming and am experimenting with PYTHON. >From what I have read, seems to be a very versatile language. In the following excercise I am getting an error class String(str, Object): shift = 6 mask = ~0 << (31 - shift) def __hash__(self): result = 0 for c in self: result = ((result & String.mask) ^ result << String.shift ^ ord(c)) & sys.maxint return result # ... Traceback (most recent call last): File "", line 11, in -toplevel- class String(str, Object): NameError: name 'Object' is not defined >>> _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From dyoo at hkn.eecs.berkeley.edu Tue Nov 22 23:46:14 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 22 Nov 2005 14:46:14 -0800 (PST) Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED In-Reply-To: Message-ID: On Tue, 22 Nov 2005, mike donato wrote: > Greetings, I am new student to programming and am experimenting with > PYTHON. From what I have read, seems to be a very versatile language. > In the following excercise I am getting an error > > class String(str, Object): [class definition cut] > > Traceback (most recent call last): > File "", line 11, in -toplevel- > class String(str, Object): > NameError: name 'Object' is not defined Hi Mike, The error is true: Python doesn't know of any class named 'Object'. What you may be looking for is the 'object' class (lowercase 'o'). Good luck! From dyoo at hkn.eecs.berkeley.edu Tue Nov 22 23:59:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 22 Nov 2005 14:59:37 -0800 (PST) Subject: [Tutor] Problem using easy_install In-Reply-To: <20051122162744.14641.qmail@maboque.srv.clix.pt> Message-ID: On Tue, 22 Nov 2005, Miguel Lopes wrote: > I'm trying to get a handle on Python eggs using Easy Install. [question cut] Hi Miguel, Unfortunately, I don't think we here at Tutor will be able to help effectively with setuptools. I see that you're trying to do stuff with the PEAK stuff: http://peak.telecommunity.com/DevCenter/setuptools but since this is so specialized, you may want to talk with the setuptools folks instead. Try the PEAK developer list: http://www.eby-sarna.com/mailman/listinfo/PEAK/ They should be better able to help you figure out what's going on. Good luck! From Hans.Dushanthakumar at navman.com Wed Nov 23 00:04:29 2005 From: Hans.Dushanthakumar at navman.com (Hans Dushanthakumar) Date: Wed, 23 Nov 2005 12:04:29 +1300 Subject: [Tutor] Using py2exe Message-ID: <5667508E43F1B740BCFA57FF46E353000277D394@nav-akl-exch-c.newton.navman.com> Hi, Im trying to convert a python program to a stand-alone executable that I can distribute. How do I use py2exe to do this? The python program consists of a py script that uses (imports) several other modules (py scripts) located in another directory. Heres what Ive tried so far: 1) Running "python setup.py py2exe" on the cmd line created the required exe file. Hoever, on running the exe file, it reports an error: File "log_all_msgs_spartacus.py", line 8, in ? ImportError: No module named listener 2) Running the command followed by comma seperated module names (all modules that are imported by the main script) python setup.py py2exe -i ..\lib\listener.py, ..\lib\ sender.py, ..\lib\gpsmsg.py, ..\lib\envmsg.py, ..\lib\cmds.py, ..\lib\logger.py, ..\lib\nmea.py Produced the foll error: invalid command name '..\lib\sender.py,' The contents of setup.py is as follows (got it off the py2exe website): from distutils.core import setup import py2exe setup( version = "0.0.1", description = "Log_all_msgs_from_Spartacus", name = "Spartacus_monitor", # targets to build console = ["log_all_msgs_spartacus.py"], ) Once I've created the exe file, can it be run on a PC which does not python setup in it? Note: - the program uses the standard pyserial module as well. Thanks, Hans From bgailer at alum.rpi.edu Wed Nov 23 00:46:38 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 22 Nov 2005 15:46:38 -0800 Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED In-Reply-To: References: Message-ID: <7.0.0.16.0.20051122154559.0357d8a0@alum.rpi.edu> At 02:41 PM 11/22/2005, mike donato wrote: >Greetings, I am new student to programming and am experimenting with PYTHON. > >From what I have read, seems to be a very versatile language. In the >following excercise I am getting an error > >class String(str, Object): try -> class String(str, object): > shift = 6 > > mask = ~0 << (31 - shift) > > def __hash__(self): > result = 0 > for c in self: > result = ((result & String.mask) ^ > result << String.shift ^ ord(c)) & sys.maxint > return result > > # ... > > > >Traceback (most recent call last): > File "", line 11, in -toplevel- > class String(str, Object): >NameError: name 'Object' is not defined > >>> > >_________________________________________________________________ >Express yourself instantly with MSN Messenger! Download today it's FREE! >http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Wed Nov 23 04:48:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 22 Nov 2005 22:48:14 -0500 Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED In-Reply-To: References: Message-ID: <4383E67E.4080306@tds.net> Danny Yoo wrote: > > On Tue, 22 Nov 2005, mike donato wrote: > > >>Greetings, I am new student to programming and am experimenting with >>PYTHON. From what I have read, seems to be a very versatile language. >>In the following excercise I am getting an error >> >>class String(str, Object): > > The error is true: Python doesn't know of any class named 'Object'. What > you may be looking for is the 'object' class (lowercase 'o'). Though inheriting from str and object is redundant as str already is a subclass of object. Kent -- http://www.kentsjohnson.com From kent37 at tds.net Wed Nov 23 14:05:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Nov 2005 08:05:34 -0500 Subject: [Tutor] Dynamic inheritance? In-Reply-To: References: Message-ID: <4384691E.8040405@tds.net> Jan Eden wrote: > Jan Eden wrote on 22.11.2005: >>Kent Johnson wrote on 20.11.2005: >> >>>Use getattr() to access attributes by name. SiteA is an attribute >>>of Templates and Page is an attribute of SiteA so you can get use >>>getattr() twice to get what you want: >>> >>>site = getattr(Templates, self.site_name) self.template = >>>getattr(site, self.template_type) >>> >> >>Unfortunately, this does not seem to work if Templates is a package, >>not a module. Python complains: >> >>AttributeError: 'module' object has no attribute 'SiteA' >> args = ("'module' object has no attribute 'SiteA'",) >> >>even though there is a module SiteA within package Templates. When >>manually importing SiteA from Templates, everything is good. >> > > Found a solution: > > import Templates > #... > def GetTemplates(self): > __import__('Templates.', globals(), locals(), [self.identifier]) > site = getattr(Templates, self.identifier) > self.template = getattr(site, self.template_type) > > works. Sorry about the bad advice. There is something about packages I don't fully understand - the modules in a package are not available as attributes in the package until the submodules have been imported. For example, using the standard email package as an example, if just email is imported then the submodules are not available as attributes: >>> import email >>> email.Charset Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'Charset' If I explicitly import the sub-module then it becomes available as an attribute: >>> from email import Charset >>> email.Charset Your __import__() statement is doing the same magic as the explicit 'from email import Charset'. The thing that confuses me about this is that for some modules the extra import is not needed. For example: >>> import os >>> getattr(os, 'path') OK looking at os.py, it is actually not a package, it is a module that imports other modules as attributes. It just looks like a package from the outside. So maybe os is the only strange one. Kent -- http://www.kentsjohnson.com From negroup at gmail.com Wed Nov 23 15:06:57 2005 From: negroup at gmail.com (Negroup -) Date: Wed, 23 Nov 2005 15:06:57 +0100 Subject: [Tutor] Introspection (modules and functions) Message-ID: <2fdabf190511230606h23af7bb9w@mail.gmail.com> Hi. My application hosts a module A that contains only a (variable) number of functions. In another part of this application I need to know which functions are defined inside module A. Initially I thought to use __dict__, but along with the functions of module A are listed all the builtins too. How is possible to obtain this information without defining return_all_functions() (see below)? Actually module A is something like: def f1(): pass def f2(): pass # def .... # def ... def return_all_functions(): t = (f1, f2, ....) return t Thanks From AKolinski at nriindustries.com Wed Nov 23 16:14:24 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Wed, 23 Nov 2005 10:14:24 -0500 Subject: [Tutor] files - strings - lists Message-ID: I want to create a program that uses data from text files, makes appropriate calculations and produces report. First I need to find out what is the right way to retrieve appropriate information from an input file. This is a typical format of the input file: 1 Polonijna Liga Mistrzow |from the heading portion 26 wrzesnia 2005 |only 6 12 6 4 1 |'6' and '4' will be needed 0 1 0 Bohossian - Kolinski |all names and 1 |all scores 1.000 9 13 19 |(3rd column - 2.000 2 4 16 |'13', '4', '8', '6' 1.000 10 8 17 |will be needed 0.000 8 6 17 | Szadkowska - Szczurek | 2 |same here 0.000 11 16 20 | 3.000 1 -4 14 | 3.500 3 -7 13 2.500 10 13 19 .................. 1 1 |skip the rest 1 1 1 |(at least for now) 6 4 5 10 8 3 9 1 11 2 12 7 -50 -7 7 0 0 0 400 0 0 -110 -2 2 -130 1 -1 100 -1 1 110 -4 4 150 4 -4 400 0 0 -90 -1 1 100 6 -6 100 -1 1 420 4 -4 110 5 -5 -480 -1 1 1310 15 -15 ............ Should I use string manipulations or convert a file to lists of lists to retrieve names and numbers? I have unsuccessfully tried to code using the latter but I couldn't overcome the fact that lists representing each raw of a text file have different lengths. How could I associate each name with a score (a sum of scores)? _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski office 416.652.4256 cell. 416.948.7767 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051123/e4dc2c5c/attachment.html From francis.moore at rawflow.com Wed Nov 23 16:20:46 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Wed, 23 Nov 2005 15:20:46 +0000 Subject: [Tutor] Introspection (modules and functions) In-Reply-To: <2fdabf190511230606h23af7bb9w@mail.gmail.com> References: <2fdabf190511230606h23af7bb9w@mail.gmail.com> Message-ID: <438488CE.9010409@rawflow.com> Negroup - wrote: >Hi. > >My application hosts a module A that contains only a (variable) number >of functions. In another part of this application I need to know which >functions are defined inside module A. Initially I thought to use >__dict__, but along with the functions of module A are listed all the >builtins too. > > Negroup, You might want to try this: custom_list = [x for x in A.__dict__ if not x.startswith('_')] This should remove the builtins. Hope this helps, Frank. From tubaranger at gmail.com Wed Nov 23 16:33:48 2005 From: tubaranger at gmail.com (Greg Lindstrom) Date: Wed, 23 Nov 2005 09:33:48 -0600 Subject: [Tutor] Pretty XML Message-ID: <57aa55060511230733m42f778bag41d692296e346d3@mail.gmail.com> Hello- I am in the process of creating an XML document from information stored in our database. One of my colleagues will use the record to format our information (health care claims) into all sorts of forms, reports, etc. He is partial to PHP5 but I like Python and would like to know if there is something that would read in my XML file and format it in a similar manner to "pretty print" so I can verify the correct information is being pulled. I have looked into the XML documentation and, to be honest, I am overwhelmed with the choices; SAX, DOM, XPath, 4Suite, and more. Though I've been coding full time for 25 years, I'm new to XML and could use some pointers. My immediate concern is to read in an XML stream from a file and format it with indentation so that I can read and verify the data against out database. My long term concern is what tool(s) do you think would give the biggest return against the effort required to learn them? The claim files I am generating will be less than a meg each, if that matters. Thanks! --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051123/2789dfc4/attachment.htm From ewald.ertl at hartter.com Wed Nov 23 16:39:57 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed, 23 Nov 2005 16:39:57 +0100 Subject: [Tutor] Introspection (modules and functions) In-Reply-To: <2fdabf190511230606h23af7bb9w@mail.gmail.com> References: <2fdabf190511230606h23af7bb9w@mail.gmail.com> Message-ID: <43848D4D.6010909@hartter.com> Hi! I quick solution for a name module could be: >>> import os >>> for d in os.__dict__: ... a="os." + d ... if callable( eval(a) ): ... print "Callable %s" % ( eval(a)) but there should also be a recipe on activestate for that problem. I think I've red something in the Python Cookbook HTH, Ewald Negroup - wrote: > Hi. > > My application hosts a module A that contains only a (variable) number > of functions. In another part of this application I need to know which > functions are defined inside module A. Initially I thought to use > __dict__, but along with the functions of module A are listed all the > builtins too. > > How is possible to obtain this information without defining > return_all_functions() (see below)? > > Actually module A is something like: > > def f1(): > pass > > def f2(): > pass > > # def .... > # def ... > > def return_all_functions(): > t = (f1, f2, ....) > return t > > Thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Wed Nov 23 17:03:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Nov 2005 11:03:50 -0500 Subject: [Tutor] files - strings - lists In-Reply-To: References: Message-ID: <438492E6.2080907@tds.net> Andrzej Kolinski wrote: > > I want to create a program that uses data from text files, makes > appropriate calculations and produces report. First I need to find out > what is the right way to retrieve appropriate information from an input > file. This is a typical format of the input file: > > 1 Polonijna Liga Mistrzow |from the heading portion > 26 wrzesnia 2005 |only > 6 12 *6* *4* 1 |'6' and '4' will be needed > 0 1 0 > *Bohossian* - *Kolinski* |all names and > 1 |all scores > 1.000 9 *13* 19 |(3rd column - > 2.000 2 *4* 16 |'13', '4', '8', '6' > 1.000 10 *8* 17 |will be needed > 0.000 8 *6* 17 | > *Szadkowska* - *Szczurek *| > 2 |same here > 0.000 11 *16* 20 | > 3.000 1 *-4* 14 | > 3.500 3 *-7* 13 > 2.500 10 *13* 19 > .................. > > 1 1 |skip the rest > 1 1 1 |(at least for now) It's pretty simple to make an ad-hoc reader for this data. A couple of things you need: - You can get individual lines from a file by treating it as an iterator. Instead of the usual f = open('data.txt') for line in f: you can call f.next() to get a single line. This makes it easy to skip lines or process lines differently. The call to f.next() will raise StopIteration when there are no more lines - You can use split() to break a line into fields, then subscripting to pull out the data you want: >>> line = ' 1.000 9 13 19' >>> line.split() ['1.000', '9', '13', '19'] >>> line.split()[2] '13' >>> int(line.split()[2]) 13 With these tools the solution is pretty simple. I pull the data from a string but it will work with a file as well. I save the results in a dictionary which maps name to a list of scores. data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 '''.split('\n') #lines = open('data.txt') # to get the data from a real file lines = iter(data) # getting data from a string, you don't need this when reading a file lines.next() # skip two headers lines.next() header = lines.next().split() six = int(header[2]) four = int(header[3]) print six, four lines.next() allScores = {} # accumulate scores into a dictionary whose key is the name # Now we can process the names and scores in a loop try: # you don't say how you know the end of the names, I just run to the end of data while True: name = lines.next().strip() lines.next() # skip line after name scores = [ int(lines.next().split()[2]) for i in range(4) ] allScores[name] = scores except StopIteration: # no more lines pass for name, scores in allScores.items(): print name, scores From francis.moore at rawflow.com Wed Nov 23 17:54:20 2005 From: francis.moore at rawflow.com (Frank Moore) Date: Wed, 23 Nov 2005 16:54:20 +0000 Subject: [Tutor] Pretty XML In-Reply-To: <57aa55060511230733m42f778bag41d692296e346d3@mail.gmail.com> References: <57aa55060511230733m42f778bag41d692296e346d3@mail.gmail.com> Message-ID: <43849EBC.3010907@rawflow.com> Greg Lindstrom wrote: > Hello- > I am in the process of creating an XML document from information > stored in our database. One of my colleagues will use the record to > format our information (health care claims) into all sorts of forms, > reports, etc. He is partial to PHP5 but I like Python and would like > to know if there is something that would read in my XML file and > format it in a similar manner to "pretty print" so I can verify the > correct information is being pulled. I have looked into the XML > documentation and, to be honest, I am overwhelmed with the choices; > SAX, DOM, XPath, 4Suite, and more. Though I've been coding full time > for 25 years, I'm new to XML and could use some pointers. > > My immediate concern is to read in an XML stream from a file and > format it with indentation so that I can read and verify the data > against out database. My long term concern is what tool(s) do you > think would give the biggest return against the effort required to > learn them? The claim files I am generating will be less than a meg > each, if that matters. > Greg, Googling found the following Python/SAX XML indenter: http://mail.python.org/pipermail/xml-sig/1999-January/000756.html It should do what you want or at least give you a head start. Cheers, F. From smiles at worksmail.net Wed Nov 23 18:19:50 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Wed, 23 Nov 2005 11:19:50 -0600 Subject: [Tutor] files - strings - lists References: Message-ID: <02b701c5f052$2e7d8650$062c4fca@csmith> | | With these tools the solution is pretty simple. I agree that handling this with Python is pretty straightforward, but I'm wondering if there exists some sort of mechanism for reading these types of well structured (though not XML format, etc...) files. Something like a reverse template, somewhat like the templates that are used to interpret dates and such in the time module (strftime, is it?). Something like this, where you put a command on each line telling what (if anything) to do: templ = ''' 1 Polonijna Liga Mistrzow #no command other than signifying a line is to be read 26 wrzesnia 2005 6 12 6 4 1 #here we need to do a split and keep 2 and 3, assigning them to a and b 0 1 0 Bohossian - Kolinski #c and d would have to be a list since there is a rpt command 1 1.000 9 13 19 #the x4 says to do this command 4 times 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 /rpt> I know you could write an regex to handle it, but I'm wondering if there is a kinder method around. Wondering, /c From lopoff at gmx.net Wed Nov 23 18:55:24 2005 From: lopoff at gmx.net (lmac) Date: Wed, 23 Nov 2005 18:55:24 +0100 Subject: [Tutor] sort list alphabetically Message-ID: <4384AD0C.2000206@gmx.net> Hallo, i have a list with the dirs/files from the current path. When i use sort() to sort the list alphabetically the list is still unsorted. How to use ? dirs_files = os.listdir(os.getcwd()) print dirs_files dirs_files.sort() print dirs_files Thank you. From doublesix at ureach.com Wed Nov 23 19:09:12 2005 From: doublesix at ureach.com (Double Six) Date: Wed, 23 Nov 2005 13:09:12 -0500 Subject: [Tutor] command in menu and button Message-ID: <200511231809.NAA00361@www23.ureach.com> Hi John and Alan, I got it! Thank you both for explaining this situation. Thanks, Joe ________________________________________________ Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag ---- On Tue, 22 Nov 2005, alan.gauld at freenet.co.uk (alan.gauld at freenet.co.uk) wrote: > >>I'm puzzled by the 'command' option in menu and Button of > >>Tkinter. With the following lines, > > The command value needs to be a *reference* to a function. > > That is not the function call itself but a reference to the function > that will be \called. > > Let me illustrate the difference: > > def f(): print 'Its me!' > > f() # prints the message > > g = f # this assigns a reference to f > > g() # this now calls that reference, > so calling g() is the same as calling f() > > > >>menu.add_command(label="Open Viewer", > command=os.system("Open my viewer &")) > > Here you assign the result of the os.system() > call to command, in fact you want to assign > a reference to a call of os.system which will > be executed when the menu/button is activated. > > The more straightforward way to do that is to > define a short function that calls os.system: > > def callSystem(): > os.system(Mycommand) > > And make the menu/button reference callSystem: > > >>menu.add_command(label="Open Viewer", > command=callSystem) > > Notice no parens, just the name of the function. > > Because we can wind up with loads of these little > wrapper functions there is a shortcut called lambda. > With lambda we can avoid defining a new mini function: > > >>menu.add_command(label="Open Viewer", > command=lambda : os.system("Open my viewer &")) > > the thing that follows the lambda is what gets > executed when the widget activates. > > Does that help? > > Alan G. > http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Wed Nov 23 19:31:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Nov 2005 10:31:51 -0800 (PST) Subject: [Tutor] sort list alphabetically In-Reply-To: <4384AD0C.2000206@gmx.net> Message-ID: On Wed, 23 Nov 2005, lmac wrote: > i have a list with the dirs/files from the current path. When i use > sort() to sort the list alphabetically the list is still unsorted. How > to use ? > > dirs_files = os.listdir(os.getcwd()) > print dirs_files > dirs_files.sort() > print dirs_files Hi lmac, I can't duplicate this. Can you show us the output that you see? Do any of the list elements permute at all? Here's what happens on my own system: ###### >>> files = os.listdir("/etc/init.d") >>> files ['README', 'acctadm', 'ldap.client', 'mkdtab', 'nscd', 'ufs_quota', 'devlinks', 'drvconfig', 'acct', 'dhcp', 'nfs.server', 'pcmcia', 'slpd', 'sendmail', 'Wnn6', 'sysetup', 'cachefs.daemon', 'PRESERVE', 'deallocate', 'autoinstall', 'dodatadm.udaplt', 'uucp', 'lu', 'ncakmod', 'appserv', 'audit', 'samba', 'apache', 'imq', 'volmgt', 'init.wbem', 'boot.server', 'llc2', 'dtlogin', 'webconsole', 'atsv', 'init.dmi', 'init.snmpdx', 'mipagent', 'ncalogd', 'IIim', 'pppd', 'loc.ja.cssd', 'init.sma', 'installupdates', 'cswopenldap', 'cswmysql', 'samba.old', 'mysql.server', 'patchserver', 'mysql.server~', 'init.wbem.119314-03'] >>> files.sort() >>> files ['IIim', 'PRESERVE', 'README', 'Wnn6', 'acct', 'acctadm', 'apache', 'appserv', 'atsv', 'audit', 'autoinstall', 'boot.server', 'cachefs.daemon', 'cswmysql', 'cswopenldap', 'deallocate', 'devlinks', 'dhcp', 'dodatadm.udaplt', 'drvconfig', 'dtlogin', 'imq', 'init.dmi', 'init.sma', 'init.snmpdx', 'init.wbem', 'init.wbem.119314-03', 'installupdates', 'ldap.client', 'llc2', 'loc.ja.cssd', 'lu', 'mipagent', 'mkdtab', 'mysql.server', 'mysql.server~', 'ncakmod', 'ncalogd', 'nfs.server', 'nscd', 'patchserver', 'pcmcia', 'pppd', 'samba', 'samba.old', 'sendmail', 'slpd', 'sysetup', 'ufs_quota', 'uucp', 'volmgt', 'webconsole'] ###### Everything appears to sort fine. The files that start with uppercase come first because of the way those strings compare to lowercase strings. If we want a case-insensitive sort, we can do something like this: ###### >>> def case_insensitive_cmp(a, b): ... return cmp(a.upper(), b.upper()) ... >>> files.sort(case_insensitive_cmp) >>> files ['acct', 'acctadm', 'apache', 'appserv', 'atsv', 'audit', 'autoinstall', 'boot.server', 'cachefs.daemon', 'cswmysql', 'cswopenldap', 'deallocate', 'devlinks', 'dhcp', 'dodatadm.udaplt', 'drvconfig', 'dtlogin', 'IIim', 'imq', 'init.dmi', 'init.sma', 'init.snmpdx', 'init.wbem', 'init.wbem.119314-03', 'installupdates', 'ldap.client', 'llc2', 'loc.ja.cssd', 'lu', 'mipagent', 'mkdtab', 'mysql.server', 'mysql.server~', 'ncakmod', 'ncalogd', 'nfs.server', 'nscd', 'patchserver', 'pcmcia', 'pppd', 'PRESERVE', 'README', 'samba', 'samba.old', 'sendmail', 'slpd', 'sysetup', 'ufs_quota', 'uucp', 'volmgt', 'webconsole', 'Wnn6'] ###### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Nov 23 19:39:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Nov 2005 10:39:51 -0800 (PST) Subject: [Tutor] files - strings - lists In-Reply-To: <02b701c5f052$2e7d8650$062c4fca@csmith> Message-ID: On Wed, 23 Nov 2005, Chris or Leslie Smith wrote: > I agree that handling this with Python is pretty straightforward, but > I'm wondering if there exists some sort of mechanism for reading these > types of well structured (though not XML format, etc...) files. Hi Chris, Yes, take a look at "parser" tools like pyparsing, mxTextTools, and Martel: http://pyparsing.sourceforge.net/ http://www.egenix.com/files/python/mxTextTools.html http://www.dalkescientific.com/Martel I have to admit that I don't use these tools much, since my data is already in some kind of predefined structure. If it's at all possible, I'd recommend sticking with pre-defined formats like XML: parsing can be a tedious job at times. From lobow at brturbo.com.br Thu Nov 24 03:31:52 2005 From: lobow at brturbo.com.br (Diego Galho Prestes) Date: Wed, 23 Nov 2005 16:31:52 -1000 Subject: [Tutor] How to discover which OS my python is running? Message-ID: <1132799512.1758.2.camel@rossum> Hi! I'm using a program that I want to know if I'm running the program in Linux or Windows. How can I do this? I want this because I created all my program in Linux but if someone runs it in Windows I have to do some things to make it work well, and I want to do this verification automatically. Thx, Diego From ismaelgf at adinet.com.uy Wed Nov 23 19:43:17 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed, 23 Nov 2005 16:43:17 -0200 Subject: [Tutor] Pretty XML In-Reply-To: <57aa55060511230733m42f778bag41d692296e346d3@mail.gmail.com> References: <57aa55060511230733m42f778bag41d692296e346d3@mail.gmail.com> Message-ID: <4384B845.7070909@adinet.com.uy> Greg Lindstrom wrote: > Hello- > I am in the process of creating an XML document from information > stored in our database. One of my colleagues will use the record to > format our information (health care claims) into all sorts of forms, > reports, etc. He is partial to PHP5 but I like Python and would like > to know if there is something that would read in my XML file and > format it in a similar manner to "pretty print" so I can verify the > correct information is being pulled. I have looked into the XML > documentation and, to be honest, I am overwhelmed with the choices; > SAX, DOM, XPath, 4Suite, and more. Though I've been coding full time > for 25 years, I'm new to XML and could use some pointers. > > My immediate concern is to read in an XML stream from a file and > format it with indentation so that I can read and verify the data > against out database. My long term concern is what tool(s) do you > think would give the biggest return against the effort required to > learn them? The claim files I am generating will be less than a meg > each, if that matters. > > Thanks! > --greg Try 4Suite / Amara: http://uche.ogbuji.net/uche.ogbuji.net/tech/4suite/amara/ (I downloaded the allinone package) >>> from Ft.Xml import Parse >>> from Ft.Xml.Domlette import PrettyPrint >>> xmlfile = open('c:/test.xml') >>> xml = "".join(xmlfile.readlines()) >>> xml 'some textlevel 3some other textHi!\n' >>> doc = Parse(xml) >>> PrettyPrint(doc) some textlevel 3 some other text Hi! It isn't a great representation... Perhaps my xml was malformed. Try it yourself to see if it works for you. HTH! Ismael From smiles at worksmail.net Wed Nov 23 20:03:49 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Wed, 23 Nov 2005 13:03:49 -0600 Subject: [Tutor] files - strings - lists References: Message-ID: <02d001c5f060$b24cc730$062c4fca@csmith> Danny Yoo wrote: | On Wed, 23 Nov 2005, Chris or Leslie Smith wrote: | || I agree that handling this with Python is pretty straightforward, but || I'm wondering if there exists some sort of mechanism for reading || these types of well structured (though not XML format, etc...) files. | | Hi Chris, | | Yes, take a look at "parser" tools like pyparsing, mxTextTools, and | Martel: | | http://pyparsing.sourceforge.net/ | | http://www.egenix.com/files/python/mxTextTools.html | | http://www.dalkescientific.com/Martel | Great links, Danny. Thanks. I had seen mxTextTools before but didn't search for the right thing before raising the question. The pyparsing seems very interesting. The code that I attach below is a very light-weight version of a formatted reader. It assumes that you just want to pluck white-space delimited values out of lines in a text file (something I've had to do from time to time and something others have asked about on tutor before). Perhaps this is the sort of simple approach that evolves into one of the tools above as more complex parsing rules are needed. Again, thank for the pointers. ---- OK, here's a first draft of a simple formatted reader that can be used to read and keep certain white-space delimited strings from lines in an input stream/file. The basic idea is to write the template using a representative chunk of the text file (so the codes that you write can be seen directly next to the data that you are going to read) or else you can separate the two. At the start of a line that you want processed, you put in angle brackets the number of items that (should) appear on the line when separated by white space and then a comma-delimited list of items that you want to keep. Here's a working example using the data submitted in this thread: ###### #a template can be done like this (w/ no visual reference to actual lines)...but don't forget to put the \ #after the triple quotes or else an extra line will be processed and don't put an extra return before the #last triple quote. The example below indicates that 4 lines will be processed. templ1 = '''\ _ _ <5x2,3> _''' # or like this, where a sample line is shown templ1 = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 <5x2,3> 6 12 6 4 1 0 1 0''' # here is another template that will be used to parse the lines templ2='''<3x0,2>Bohossian - Kolinski 1 <4x2> 1.000 9 13 19 <4x2> 2.000 2 4 16 <4x2> 1.000 10 8 17 <4x2> 0.000 8 6 17''' # -------------------here is the data--------------------------------- data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 and then here is single line '''.split('\n') lines = iter(data) # to get data from a string that has been split into lines #---------------------------------------------------------------------- def partition(s, t): # from python-dev list, I believe if not isinstance(t, basestring) or not t: raise ValueError('partititon argument must be a non-empty string') parts = s.split(t, 1) if len(parts) == 1: result = (s, '', '') else: result = (parts[0], t, parts[1]) return result def temp_read(templ, lines): ''' Use a template to extract strings from the given lines. Lines in the template that start with "<" are assumed to contain a parsing command that is in the format, , where N = number of white space separated items expected on the line x is the letter x L = a list of comma separated integers indicating which items to keep from the line e.g. <4x2,3> appearing at the start of a line in the template means that the corresponding line of data should have 4 items on it, and 2 and 3 should be returned If one or more lines of the data do not jive with the parsing instructions, a value of None will be returned. This may indicate the end of the data that can be interpreted with the template you gave. ''' rv = [] #all return values for the template will go here try: for ti in templ.splitlines(): #get a template line li = lines.next() #and a physical line of data if ti.startswith('<'): #check to see if there is a parse command on the line # get the command cmd = ti[1:].split('>')[0] things,_,keep = partition(cmd, 'x') things = int(things) keep = [int(x.strip()) for x in keep.split(',')] #split the physical line data = li.split() #check that the # of items matches the template specs assert len(data)==things #add the items to the return list for k in keep: rv.append(data[k]) else: pass #don't parse for data return rv except: return None print temp_read(templ1,lines) while True: vals = temp_read(templ2,lines) if vals == None: break print vals ###### /c From kent37 at tds.net Wed Nov 23 20:47:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Nov 2005 14:47:41 -0500 Subject: [Tutor] Introspection (modules and functions) In-Reply-To: <2fdabf190511230606h23af7bb9w@mail.gmail.com> References: <2fdabf190511230606h23af7bb9w@mail.gmail.com> Message-ID: <4384C75D.80301@tds.net> Negroup - wrote: > Hi. > > My application hosts a module A that contains only a (variable) number > of functions. In another part of this application I need to know which > functions are defined inside module A. Initially I thought to use > __dict__, but along with the functions of module A are listed all the > builtins too. > > How is possible to obtain this information without defining > return_all_functions() (see below)? How about a return_all_functions() that uses introspection? def return_all_functions(module): callables = [] for name in dir(module): value = getattr(module, name) if callable(value): callables.append(value) return callables Kent -- http://www.kentsjohnson.com From kent37 at tds.net Wed Nov 23 20:52:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 23 Nov 2005 14:52:05 -0500 Subject: [Tutor] How to discover which OS my python is running? In-Reply-To: <1132799512.1758.2.camel@rossum> References: <1132799512.1758.2.camel@rossum> Message-ID: <4384C865.5060307@tds.net> Diego Galho Prestes wrote: > Hi! I'm using a program that I want to know if I'm running the program > in Linux or Windows. How can I do this? I want this because I created > all my program in Linux but if someone runs it in Windows I have to do > some things to make it work well, and I want to do this verification > automatically. Try sys.platform or os.name. Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Wed Nov 23 21:47:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Nov 2005 12:47:03 -0800 (PST) Subject: [Tutor] How to discover which OS my python is running? In-Reply-To: <4384C865.5060307@tds.net> Message-ID: On Wed, 23 Nov 2005, Kent Johnson wrote: > Diego Galho Prestes wrote: > > Hi! I'm using a program that I want to know if I'm running the program > > in Linux or Windows. How can I do this? I want this because I created > > all my program in Linux but if someone runs it in Windows I have to do > > some things to make it work well, and I want to do this verification > > automatically. > > Try sys.platform or os.name. Hi Diego, Yes, even Distutils takes this approach. We can take a look at the function get_platform_lib(), where they use os.name to figure out what platform the program is running under. http://svn.python.org/projects/python/trunk/Lib/distutils/sysconfig.py (Hey, I didn't realize that python.org moved their source code repository from CVS to Subversion! When did this happen?! Oh, ok, I see the PEP now. http://www.python.org/peps/pep-0347.html. Cool!) Sorry, got off track. Anyway, Distutils appears to do a fairly simple case analysis: ###### if os.name == "posix": ## text cut elif os.name == "nt": ## text cut elif os.name == "mac": ## text cut elif os.name == "os2": ## text cut ###### So if it's good enough for Distutils, it may work out for you. *grin* You may want to isolate whatever platform-dependent parts of your application you have off to a separate module. That is, if you can, try writing modules that hide away the platform ugliness, so that the rest of your application can behave as if everything were platform-independent. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed Nov 23 22:09:59 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Nov 2005 13:09:59 -0800 (PST) Subject: [Tutor] files - strings - lists In-Reply-To: <02d001c5f060$b24cc730$062c4fca@csmith> Message-ID: > Great links, Danny. Thanks. I had seen mxTextTools before but didn't > search for the right thing before raising the question. The pyparsing > seems very interesting. The code that I attach below is a very > light-weight version of a formatted reader. It assumes that you just > want to pluck white-space delimited values out of lines in a text file > (something I've had to do from time to time and something others have > asked about on tutor before). Perhaps this is the sort of simple > approach that evolves into one of the tools above as more complex > parsing rules are needed. Hi Chris, Yes, I suspect that this happens a lot. I have my own little formatting reader that simulates some of the features of C's scanf, for example: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ so I think it's one of those little exercises that everyone ends up doing at least once. *grin* From AKolinski at nriindustries.com Wed Nov 23 22:26:09 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Wed, 23 Nov 2005 16:26:09 -0500 Subject: [Tutor] files - strings - lists In-Reply-To: <438492E6.2080907@tds.net> Message-ID: Thank you Kent, Chris, Danny, This is superb, let me work on my part for now and I promise get back to the group with more ... _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski wrote: > > I want to create a program that uses data from text files, makes > appropriate calculations and produces report. First I need to find out > what is the right way to retrieve appropriate information from an input > file. This is a typical format of the input file: > > 1 Polonijna Liga Mistrzow |from the heading portion > 26 wrzesnia 2005 |only > 6 12 *6* *4* 1 |'6' and '4' will be needed > 0 1 0 > *Bohossian* - *Kolinski* |all names and > 1 |all scores > 1.000 9 *13* 19 |(3rd column - > 2.000 2 *4* 16 |'13', '4', '8', '6' > 1.000 10 *8* 17 |will be needed > 0.000 8 *6* 17 | > *Szadkowska* - *Szczurek *| > 2 |same here > 0.000 11 *16* 20 | > 3.000 1 *-4* 14 | > 3.500 3 *-7* 13 > 2.500 10 *13* 19 > .................. > > 1 1 |skip the rest > 1 1 1 |(at least for now) It's pretty simple to make an ad-hoc reader for this data. A couple of things you need: - You can get individual lines from a file by treating it as an iterator. Instead of the usual f = open('data.txt') for line in f: you can call f.next() to get a single line. This makes it easy to skip lines or process lines differently. The call to f.next() will raise StopIteration when there are no more lines - You can use split() to break a line into fields, then subscripting to pull out the data you want: >>> line = ' 1.000 9 13 19' >>> line.split() ['1.000', '9', '13', '19'] >>> line.split()[2] '13' >>> int(line.split()[2]) 13 With these tools the solution is pretty simple. I pull the data from a string but it will work with a file as well. I save the results in a dictionary which maps name to a list of scores. data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 '''.split('\n') #lines = open('data.txt') # to get the data from a real file lines = iter(data) # getting data from a string, you don't need this when reading a file lines.next() # skip two headers lines.next() header = lines.next().split() six = int(header[2]) four = int(header[3]) print six, four lines.next() allScores = {} # accumulate scores into a dictionary whose key is the name # Now we can process the names and scores in a loop try: # you don't say how you know the end of the names, I just run to the end of data while True: name = lines.next().strip() lines.next() # skip line after name scores = [ int(lines.next().split()[2]) for i in range(4) ] allScores[name] = scores except StopIteration: # no more lines pass for name, scores in allScores.items(): print name, scores _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051123/a52991f9/attachment.html From bgailer at alum.rpi.edu Thu Nov 24 00:14:47 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 23 Nov 2005 15:14:47 -0800 Subject: [Tutor] sort list alphabetically In-Reply-To: <4384AD0C.2000206@gmx.net> References: <4384AD0C.2000206@gmx.net> Message-ID: <7.0.0.16.0.20051123150708.0337c290@alum.rpi.edu> At 09:55 AM 11/23/2005, lmac wrote: >i have a list with the dirs/files from the current path. When i use >sort() to sort the list alphabetically the list is still unsorted. When you say "unsorted" - are the list members in the same order as before the sort? >dirs_files = os.listdir(os.getcwd()) >print dirs_files >dirs_files.sort() >print dirs_files Works for me. On my computer: >>> dirs_files = os.listdir(os.getcwd()) >>> for x in dirs_files[:10]:x "'01GRTfiles" 'archive' 'backup' 'CU' 'data' 'documents' 'error_tbls_in' 'error_tbls_out' 'forms' 'GRTFiles' >>> dirs_files.sort() >>> for x in dirs_files[:10]:x "'01GRTfiles" 'CU' 'DIST_TEST.DBF' 'DUP_ATTR2.BAK' 'DUP_ATTR2.DBF' 'GRTFiles' 'GRT_CS_SA.DBF' 'GRT_ITEM_XREF.DBF' 'IMP_MC_CR.BAK' 'IMP_MC_CR.DBF' You may notice that sort is case sensitive. The names beginning with lower case letters follow all the names beginning with upper case letters. If you want case insensitivity, dirs_files = [x.lower() for x in dirs_files] before sorting. From john at fouhy.net Thu Nov 24 01:19:54 2005 From: john at fouhy.net (John Fouhy) Date: Thu, 24 Nov 2005 13:19:54 +1300 Subject: [Tutor] sort list alphabetically In-Reply-To: References: <4384AD0C.2000206@gmx.net> Message-ID: <5e58f2e40511231619u7c18abdex@mail.gmail.com> On 24/11/05, Danny Yoo wrote: > The files that start with uppercase come first because of the way those > strings compare to lowercase strings. If we want a case-insensitive sort, > we can do something like this: > > ###### > >>> def case_insensitive_cmp(a, b): > ... return cmp(a.upper(), b.upper()) > ... > >>> files.sort(case_insensitive_cmp) > >>> files [...] > ###### In python2.4, you can also use the key= keyword argument: ### def toUpper(s): return s.upper() files.sort(key=toUpper) ### This is more efficient, I believe, because the key function is only called once for each element, whereas cmp is called more than once. (we could use string.upper here instead of defining our own, but string.upper is deprecated these days...) -- John. From dyoo at hkn.eecs.berkeley.edu Thu Nov 24 01:47:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 23 Nov 2005 16:47:22 -0800 (PST) Subject: [Tutor] sort list alphabetically In-Reply-To: <5e58f2e40511231619u7c18abdex@mail.gmail.com> Message-ID: > In python2.4, you can also use the key= keyword argument: > > ### > def toUpper(s): > return s.upper() > files.sort(key=toUpper) > ### > > This is more efficient, I believe, because the key function is only > called once for each element, whereas cmp is called more than once. > > (we could use string.upper here instead of defining our own, but > string.upper is deprecated these days...) Hi John, The 'string' module might be deprecated, but the 'str' type should be fine: ###### >>> names = ['bill', 'Ted', 'Excellent'] >>> names.sort() >>> names ['Excellent', 'Ted', 'bill'] >>> names.sort(key=str.upper) >>> names ['bill', 'Excellent', 'Ted'] ###### Best of wishes! From bgailer at alum.rpi.edu Thu Nov 24 05:50:58 2005 From: bgailer at alum.rpi.edu (bob) Date: Wed, 23 Nov 2005 20:50:58 -0800 Subject: [Tutor] How to discover which OS my python is running? In-Reply-To: <1132799512.1758.2.camel@rossum> References: <1132799512.1758.2.camel@rossum> Message-ID: <7.0.0.16.0.20051123204943.03337008@alum.rpi.edu> At 06:31 PM 11/23/2005, Diego Galho Prestes wrote: >Hi! I'm using a program that I want to know if I'm running the program >in Linux or Windows. How can I do this? I want this because I created >all my program in Linux but if someone runs it in Windows I have to do >some things to make it work well, and I want to do this verification >automatically. import os print os.name # on my system I get nt # The following names have currently been registered: 'posix', 'nt', 'mac', 'os2', 'ce', 'java', 'riscos'. From smiles at worksmail.net Thu Nov 24 07:19:42 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Thu, 24 Nov 2005 00:19:42 -0600 Subject: [Tutor] files - strings - lists Message-ID: <004b01c5f0bf$70450b40$dc2c4fca@csmith> Danny wrote: | Hi Chris, | | Yes, I suspect that this happens a lot. I have my own little formatting | reader that simulates some of the features of C's scanf, for example: | | http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ | | so I think it's one of those little exercises that everyone ends up | doing at least once. *grin* I've always taken a personal pride in (eventually) following the in the footsteps of those that have gone before me. There is certainly a joy in rediscovery :-) (There is also a lot to learn from those whose stride is greater!) I was able to pretty easily take your sscanf facility and couple it with the template reader to read Andrzej Kolinski's data. FWIW, here it is: ##### data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 and then here is single line '''.split('\n') lines = iter(data) template1 = '''\ _ _ < %*s %*s %d %d %*s> #same sort of format as before, but now an explicit token identification occurs _''' template2 = '''\ <%s %*s %s>Bohossian - Kolinski _1 < %*s %*s %i %*s> 1.000 9 13 19 # I get around having to worry about the decimal by using %s < %*s %*s %i %*s> 2.000 2 4 16 < %*s %*s %i %*s> 1.000 10 8 17 < %*s %*s %i %*s> 0.000 8 6 17''' if __name__ == '__main__': def tread(template, lines): #reading lines using lines of the template to parse them if the #lines start with "<" rv = [] try: for i,li in enumerate(template.splitlines()): dat = lines.next() if li.startswith('<'): fmt = li.split('>')[0][1:] #take everything between the <> rv.extend(sscanf(dat, fmt)) return rv except: #print 'error at line',i #print 'in template:' #print template1 return None print tread(template1, lines) while True: vals = tread(template2, lines) if not vals: break print vals ###### Hey, Andrzej, it will be interesting to see what you come up with as a solution. This has been a helpful problem for me :-) /c From dyoo at hkn.eecs.berkeley.edu Thu Nov 24 09:51:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Nov 2005 00:51:54 -0800 (PST) Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED (fwd) Message-ID: ---------- Forwarded message ---------- Date: Wed, 23 Nov 2005 21:43:27 -0400 From: mike donato To: dyoo at hkn.eecs.berkeley.edu Subject: Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED Thank You Danny I changed - and didnt get an executable, not sure what is supposed to be the output. Mike >From: Danny Yoo >To: mike donato >CC: tutor at python.org >Subject: Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED >Date: Tue, 22 Nov 2005 14:46:14 -0800 (PST) > > > >On Tue, 22 Nov 2005, mike donato wrote: > > > Greetings, I am new student to programming and am experimenting with > > PYTHON. From what I have read, seems to be a very versatile language. > > In the following excercise I am getting an error > > > > class String(str, Object): > >[class definition cut] > > > > Traceback (most recent call last): > > File "", line 11, in -toplevel- > > class String(str, Object): > > NameError: name 'Object' is not defined > > >Hi Mike, > >The error is true: Python doesn't know of any class named 'Object'. What >you may be looking for is the 'object' class (lowercase 'o'). > >Good luck! > _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From ldapguru at yahoo.com Thu Nov 24 10:55:00 2005 From: ldapguru at yahoo.com (Alan) Date: Thu, 24 Nov 2005 03:55:00 -0600 Subject: [Tutor] Gurus of one liner- MOVe (blah) from one token to another and REnumber tokens In-Reply-To: Message-ID: <5DF1B5B2A4D64E06BFB5C36099C5AD8B@server01> Dear Gurus of python one liner innovator I have about 150 lines of python extracting text from large file, the problem I need a few lines to clean first to avoid the problem the script is facing Overview There is large text and I am trying to organize it for the python script to process, it is badly organized and I attempted to do it like this which the master script understand Keywords: ##### is number like 1 thru 99999 |H paragraphs |F reFerence |R Rating BEFORE I organized by text global and replace Each set of tokens was like this ##### paragraph F reference R rating Now (where master script understand) |H###### paragraph |F reference |R rating Notice no ##### in |F |R PROBLEMS Phase 1 PROBLEM 1 the |H paragraph (multi lines) has some words between () such as (xyz blah words) also maybe in multi lines ?.( blah blah blah blah) ? We need to move it to the end of |F reference (xyz blah words) Example BEFORE |H 00100 a friend in need is a friend indeed (author means both young \ and old) so select the best friend as soon as you can blah |F Old London book |R Cool AFTER your process |H 00100 "a friend in need is a friend indeed so select the best friend as soon as you can blah" |F Old London book |R Cool PROBLEM 2 I need to find out if the order is broken so I go and fix it by hand i.e. |H##### |F |R is any other order so it is outputted in ErrorOrderLogFile |H##### paragraph |H paragraph |R rating or any order like run new cleaning script and cat ErrorOrderLogFile |H00299 paragraph |F Reference |H Rating |H00300 paragraph |H paragraph |H rating cat ErrorOrderLogFile: bad set orders |H00300 paragraph Phase II PROBLEM 3 Once I fix by the order hand I need to renumber all from say 00001 to 99999 In this format |H00001 paragraph |F00001 reference |R00001 rating |H99999 paragraph |F99999 reference |R99999 rating --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From dyoo at hkn.eecs.berkeley.edu Thu Nov 24 11:35:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Nov 2005 02:35:24 -0800 (PST) Subject: [Tutor] lil help please - updated (fwd) Message-ID: [Slightly busy at the moment; can someone else help? Alan, in the future, don't send replies directly to me: send them to the Tutor list. It's an ad-hoc way to load-balance your questions across all the tutors.] ---------- Forwarded message ---------- Date: Thu, 24 Nov 2005 03:55:00 -0600 From: Alan To: ldapguru at yahoo.com, dyoo at hkn.eecs.berkeley.edu Subject: RE: lil help please - updated Sorry Lil better english I have about 150 lines of python extracting text from large file, the problem I need a few lines to clean first to avoid the problem the script is facing Overview There is large text and I am trying to organize it for the python script to process, it is badly organized and I attempted to do it like this which the master script understand Keywords: ##### is number like 1 thru 99999 |H paragraphs |F reFerence |R Rating BEFORE I organized by text global and replace Each set of tokens was like this ##### paragraph F reference R rating Now (where master script understand) |H###### paragraph |F reference |R rating Notice no ##### in |F |R PROBLEMS Phase 1 PROBLEM 1 the |H paragraph (multi lines) has some words between () such as (xyz blah words) also maybe in multi lines ….( blah blah blah blah) … We need to move it to the end of |F reference (xyz blah words) Example BEFORE |H 00100 a friend in need is a friend indeed (author means both young \ and old) so select the best friend as soon as you can blah |F Old London book |R Cool AFTER your process |H 00100 "a friend in need is a friend indeed so select the best friend as soon as you can blah" |F Old London book |R Cool PROBLEM 2 I need to find out if the order is broken so I go and fix it by hand i.e. |H##### |F |R is any other order so it is outputted in ErrorOrderLogFile |H##### paragraph |H paragraph |R rating or any order like run new cleaning script and cat ErrorOrderLogFile |H00299 paragraph |F Reference |H Rating |H00300 paragraph |H paragraph |H rating cat ErrorOrderLogFile: bad set orders |H00300 paragraph Phase II PROBLEM 3 Once I fix by the order hand I need to renumber all from say 00001 to 99999 In this format |H00001 paragraph |F00001 reference |R00001 rating |H99999 paragraph |F99999 reference |R99999 rating --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From negroup at gmail.com Thu Nov 24 12:00:27 2005 From: negroup at gmail.com (Negroup -) Date: Thu, 24 Nov 2005 12:00:27 +0100 Subject: [Tutor] getattr of functions Message-ID: <2fdabf190511240300n47cff1d5x@mail.gmail.com> Hi all! I'm here again with a question about introspection. My module stores a set of functions. I need to know, from another script, if a particular function of this module "is enabled" (it means, if it shall be executed by the caller script). I looked for some introspective builtin/function, but I didn't find anything useful (except func_globals, func_dict, func_code, etc, that don't help in my case). This is my solution: mymodule.py def f1(): pass def f2(): pass setattr(f1, 'enabled', True) setattr(f2, 'enabled', False) foo at bar:~/projects/erp/migra$ python Python 2.3.5 (#1, Sep 6 2005, 12:53:27) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from mymodule import * >>> f1.enabled False >>> f2.enabled True This seems to work.. I wonder for better solutions. Thanks you all! From ml.cyresse at gmail.com Thu Nov 24 12:07:39 2005 From: ml.cyresse at gmail.com (Liam Clarke) Date: Fri, 25 Nov 2005 00:07:39 +1300 Subject: [Tutor] getattr of functions In-Reply-To: <2fdabf190511240300n47cff1d5x@mail.gmail.com> References: <2fdabf190511240300n47cff1d5x@mail.gmail.com> Message-ID: What do you mean enabled? If it's imported into the namespace you can call it... Err, can you clarify on the enabling, what context are you using it in, and what are you trying to achieve? On 11/25/05, Negroup - wrote: > Hi all! I'm here again with a question about introspection. > > My module stores a set of functions. I need to know, from another > script, if a particular function of this module "is enabled" (it > means, if it shall be executed by the caller script). I looked for > some introspective builtin/function, but I didn't find anything useful > (except func_globals, func_dict, func_code, etc, that don't help in my > case). > > This is my solution: > > mymodule.py > def f1(): > pass > def f2(): > pass > > setattr(f1, 'enabled', True) > setattr(f2, 'enabled', False) > > foo at bar:~/projects/erp/migra$ python > Python 2.3.5 (#1, Sep 6 2005, 12:53:27) > [GCC 3.3.4] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> from mymodule import * > >>> f1.enabled > False > >>> f2.enabled > True > > This seems to work.. I wonder for better solutions. > > Thanks you all! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From negroup at gmail.com Thu Nov 24 12:28:03 2005 From: negroup at gmail.com (Negroup -) Date: Thu, 24 Nov 2005 12:28:03 +0100 Subject: [Tutor] getattr of functions In-Reply-To: References: <2fdabf190511240300n47cff1d5x@mail.gmail.com> Message-ID: <2fdabf190511240328x7f270133t@mail.gmail.com> 2005/11/24, Liam Clarke : > What do you mean enabled? > > If it's imported into the namespace you can call it... > > Err, can you clarify on the enabling, what context are you using it > in, and what are you trying to achieve? Hi, sorry. I'll try to present the actors omitting the details. table.txt: the first line is an header that lists all the table's fields. Following lines represent data; skel.py: it is script that get headers in table.txt and write the module mymodule.py; mymodule.py: it is a skeleton where are defined a number of functions. This number depends on the number of headers, and it may vary (different table.txt files have a different number of headers, which a different name too). Each function in the module has the name of an header. Finally there is another script, modifiers.py: it imports all the functions in mymodule and applies these functions to the corresponding fields. AS I don't want to apply all these functions indistinctly, I need a way to mark a function like enabled or disabled. If it is enabled, it will be invoked. It it results disabled, it won't be called (and thus, the corresponding field won't be modified). I don't know if it makes sense to you, I should explain better the whole flow.. However I don't think it is the right place. Anyway, I hope the scenario is a bit more free from clouds! Thanks From singletoned at gmail.com Thu Nov 24 13:02:44 2005 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 24 Nov 2005 12:02:44 +0000 Subject: [Tutor] Modifying Source Code while Program is Running Message-ID: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> Is it feasible to change a program's source code whilst it is running without having to restart the program? Is it feasible to get a program to change it's own source code while it is running? For example, if you have a web server such as CherryPy that will (hopefully) be running for months at a time and you want to be able to change classes without having to restart the server. Or if you want to allow users of the site to edit a class through the web and see the changes to the site immediately? Can a python program change a class, change all the objects already created by that class and save the modified class definition, so that if the program were restarted it would return to exactly the same state? (assuming all objects were saved to a database or somesuch). Does anyone have any good links to implementations of this? I assume someone's already done it before. Thanks Ed From kent37 at tds.net Thu Nov 24 14:27:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Nov 2005 08:27:18 -0500 Subject: [Tutor] getattr of functions In-Reply-To: <2fdabf190511240300n47cff1d5x@mail.gmail.com> References: <2fdabf190511240300n47cff1d5x@mail.gmail.com> Message-ID: <4385BFB6.5070602@tds.net> Negroup - wrote: > Hi all! I'm here again with a question about introspection. > > My module stores a set of functions. I need to know, from another > script, if a particular function of this module "is enabled" (it > means, if it shall be executed by the caller script). I looked for > some introspective builtin/function, but I didn't find anything useful > (except func_globals, func_dict, func_code, etc, that don't help in my > case). > > This is my solution: > > mymodule.py > def f1(): > pass > def f2(): > pass > > setattr(f1, 'enabled', True) > setattr(f2, 'enabled', False) This seems OK to me. You don't need setattr(), you can set the attribute directly: f1.enabled = True Adding attributes to functions is only supported in recent versions of Python so this is not a good solution if you need to work with older versions. >From your later description I see that you want to do this dynamically and the set of enabled functions is really a property of the client, not of the function itself. You have a list of headers and you want to apply all the functions that match the headers. I would look for a way to have the client figure out which functions to apply. Maybe keep a list of the headers and use it to filter the list of functions. For example if fns is the list of functions and headers is a list (or set) of header names matching the functions you could do for fn in fns: if fn.__name__ in headers: fn() This keeps the responsibility for executing the correct functions with the client which seems like the right place to me. Also if it matters, your solution is not thread-safe because it uses global state (the enabled flag in the function). If you have multiple threads doing this you will get errors. Kent -- http://www.kentsjohnson.com From kent37 at tds.net Thu Nov 24 14:32:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Nov 2005 08:32:41 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> Message-ID: <4385C0F9.1070201@tds.net> Ed Singleton wrote: > Is it feasible to change a program's source code whilst it is running > without having to restart the program? Is it feasible to get a > program to change it's own source code while it is running? > > For example, if you have a web server such as CherryPy that will > (hopefully) be running for months at a time and you want to be able to > change classes without having to restart the server. Or if you want > to allow users of the site to edit a class through the web and see the > changes to the site immediately? This is hard. IIRC CherryPy has a way to automatically restart the server when a module changes, which is not what you ask for but at least it is automatic. A couple of recent threads on comp.lang.python have talked about this: http://groups.google.com/group/comp.lang.python/browse_frm/thread/8bb4efbe726c4ab5/848860f76210be69 http://groups.google.com/group/comp.lang.python/browse_frm/thread/7b34c30c5833a9b0/4ed71bb7c5a97b57 Kent -- http://www.kentsjohnson.com From singletoned at gmail.com Thu Nov 24 15:26:06 2005 From: singletoned at gmail.com (Ed Singleton) Date: Thu, 24 Nov 2005 14:26:06 +0000 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <4385C0F9.1070201@tds.net> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385C0F9.1070201@tds.net> Message-ID: <34bb7f5b0511240626j62e5ebb7u@mail.gmail.com> On 24/11/05, Kent Johnson wrote: > Ed Singleton wrote: > > Is it feasible to change a program's source code whilst it is running > > without having to restart the program? Is it feasible to get a > > program to change it's own source code while it is running? > > > > For example, if you have a web server such as CherryPy that will > > (hopefully) be running for months at a time and you want to be able to > > change classes without having to restart the server. Or if you want > > to allow users of the site to edit a class through the web and see the > > changes to the site immediately? > > This is hard. IIRC CherryPy has a way to automatically restart the server when a module changes, which is not what you ask for but at least it is automatic. A couple of recent threads on comp.lang.python have talked about this: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/8bb4efbe726c4ab5/848860f76210be69 > http://groups.google.com/group/comp.lang.python/browse_frm/thread/7b34c30c5833a9b0/4ed71bb7c5a97b57 > > Kent Hmmm, that's discouraging. Do you know if it's feasible to just keep changes to code in memory synchronised with changes nto the source code? So rather than reload source code, make sure that the source code reflects what is running in memory? For example if your program is running, and you make a change to a class, is it possible to create the necessary class definition and save it to a file? Ed From lopoff at gmx.net Thu Nov 24 16:35:34 2005 From: lopoff at gmx.net (lmac) Date: Thu, 24 Nov 2005 16:35:34 +0100 Subject: [Tutor] sort list alphabetically In-Reply-To: <7.0.0.16.0.20051123150708.0337c290@alum.rpi.edu> References: <4384AD0C.2000206@gmx.net> <7.0.0.16.0.20051123150708.0337c290@alum.rpi.edu> Message-ID: <4385DDC6.7010804@gmx.net> Ok. That's the point. I think i meant case-sensitive. There are some ways described here that will me help out. Yes, the list is sorted when i print it out. It was my fault, sorry guys. Thank you a lot. mac From negroup at gmail.com Thu Nov 24 16:44:40 2005 From: negroup at gmail.com (Negroup -) Date: Thu, 24 Nov 2005 16:44:40 +0100 Subject: [Tutor] Pretty XML In-Reply-To: <57aa55060511230733m42f778bag41d692296e346d3@mail.gmail.com> References: <57aa55060511230733m42f778bag41d692296e346d3@mail.gmail.com> Message-ID: <2fdabf190511240744n369ed773o@mail.gmail.com> 2005/11/23, Greg Lindstrom : > something that would read in my XML file and format it in a similar manner > to "pretty print" so I can verify the correct information is being pulled. > My immediate concern is to read in an XML stream from a file and format it > with indentation so that I can read and verify the data against out > database. I had the same kind of request on September. Probably you will find useful the answers I got: http://mail.python.org/pipermail/tutor/2005-September/041759.html HTH From kent37 at tds.net Thu Nov 24 17:44:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Nov 2005 11:44:56 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511240626j62e5ebb7u@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385C0F9.1070201@tds.net> <34bb7f5b0511240626j62e5ebb7u@mail.gmail.com> Message-ID: <4385EE08.1020901@tds.net> Ed Singleton wrote: > Hmmm, that's discouraging. Do you know if it's feasible to just keep > changes to code in memory synchronised with changes nto the source > code? So rather than reload source code, make sure that the source > code reflects what is running in memory? > > For example if your program is running, and you make a change to a > class, is it possible to create the necessary class definition and > save it to a file? I think that would be hard too. How would you be making the changes to the class in the running program? I guess you could have a metaclass that looks for changes to a class, decompiles it and writes the result to a file. Of course there would be no comments in the result, and I don't think there is a good free Python decompiler available... Kent -- http://www.kentsjohnson.com From kent37 at tds.net Thu Nov 24 17:49:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Nov 2005 11:49:54 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> Message-ID: <4385EF32.8070606@tds.net> Ed Singleton wrote: > Is it feasible to change a program's source code whilst it is running > without having to restart the program? Is it feasible to get a > program to change it's own source code while it is running? You can change a class while it is running. > > For example, if you have a web server such as CherryPy that will > (hopefully) be running for months at a time and you want to be able to > change classes without having to restart the server. Or if you want > to allow users of the site to edit a class through the web and see the > changes to the site immediately? The auto-restart feature of CherryPy might do this for you. Also if the changes to the site are to a template such as Cheetah, those usually autoreload. > > Can a python program change a class, change all the objects already > created by that class and save the modified class definition, so that > if the program were restarted it would return to exactly the same > state? (assuming all objects were saved to a database or somesuch). You can have persistent objects using for example SQLObject or ZODB, > > Does anyone have any good links to implementations of this? I assume > someone's already done it before. It sounds like maybe you come from a background in Smalltalk, or maybe you should look at Smalltalk. In Smalltalk the whole environment is dynamic and can be saved and restored easily. For Python, I think you will do better if you narrow your requirements. Python is very dynamic - classes can be changed at runtime, or reloaded if you are careful - and there are several good ways to persist state. If you can be more specific about what you really need there may be a solution for you. Kent -- http://www.kentsjohnson.com From smiles at worksmail.net Thu Nov 24 18:52:15 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Thu, 24 Nov 2005 11:52:15 -0600 Subject: [Tutor] lil help please - updated (fwd) References: Message-ID: <00de01c5f11f$ed9a74d0$dc2c4fca@csmith> | I have about 150 lines of python extracting text from large file, the | problem I need a few lines to clean first to avoid the problem the | script is facing Hello, This seems like a well laid out task. If you post what you are trying and the problems you are encountering, that would be helpful. One suggestion that I have is that you switch problems 1 and 2. If the ordering is broken (e.g. HHFR instead of HFRH) then knowing where to put the parenthetical comment is going to be a problem. Also, you said that you wanted it put after the "F" reference did you mean that is should look like this: | AFTER your process || H 00100 "a friend in need is a friend indeed so select the best || friend | as soon as you can blah" || F Old London book (xyz blah words) <=== parenthetical here? || R Cool It's a little hard to tell from what you've said, but it looks like the "|" was an unnecessary addition. If your record markers were always a single character at the beginning of a line, those are easy enough to find--provided there is never an H, F, or R that is a NON-record marker at the beginning of a line as a single character. ###### >>> text='''H This is the start. ... F here is a reference. ... Right here is a non-reference R but it's not a single character starting the line ... so it won't be matched; and the single one in the middle isn't at the start. ... R cool''' >>> import re >>> text = '\n'+text #make the first one like all the others: preceded by newline character >>> re.findall(r'\n([HFR])\b', text) ['H', 'F', 'R'] >>> re.split(r'\n([HFR])\b', text) ['', 'H', ' This is the start.', 'F', " here is a reference. \nRight here is a non-reference R but it's not a single character starting the line\nso it won't be matched; and the single one in the middle isn't at the start.", 'R', ' cool'] ###### That last list has all the groups with the identifier preceding the corresponding data. Finally, I'm not sure how you are checking the correctness of the HFR sequence, but the findall used above suggests a way to do it: -do the findall -join the results together -replace 'HFR' with '.' -if the whole string isn't dots then there was a problem and the number of dots before the non-dot tell you how many correct records there were. ###### >>> bad=''' ... H ... F ... R ... R ... ''' >>> re.findall(r'\n([HFR])\b', bad) ['H', 'F', 'R', 'R'] >>> ''.join(_) # the _ refers to the last output 'HFRR' >>> _.replace('HFR', '.') '.R' >>> len(_),_.count('.') (2, 1) ###### Notice that since not all the HFRs were complete, there are not all the characters are periods (and so the count of periods is not the same as the length of the string). In this case there was one correct record (thus one leading dot) before the problem occurred. /c From dyoo at hkn.eecs.berkeley.edu Thu Nov 24 20:47:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 24 Nov 2005 11:47:09 -0800 (PST) Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED (fwd) In-Reply-To: Message-ID: > I changed - and didnt get an executable, not sure what is supposed to be > the output. Hi Mike, The main way to run a Python program is to run it through its interpreter. That is, there's no need to build a separate executable: the source is the distributable. If you really need to make an .EXE, there are tools like py2exe that help with this: http://py2exe.sourceforge.net but most people don't have to do this to play with Python. Are you going through a tutorial such as the ones below? http://wiki.python.org/moin/BeginnersGuide/NonProgrammers The tutorials there may help you get started. If you have more questions, please feel free to ask. From alberto.troiano at gmail.com Thu Nov 24 21:16:04 2005 From: alberto.troiano at gmail.com (Alberto Troiano) Date: Thu, 24 Nov 2005 16:16:04 -0400 Subject: [Tutor] Convert integer number to binary representation Message-ID: <43861F84.40207@gmail.com> Hey all I want to know how can I convert an integer number to a binary number. Like this example: +10 (decimal representation....integer) = 00001010 (binary representation) Thanks in advanced Alberto From alan.gauld at freenet.co.uk Tue Nov 22 05:33:06 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 22 Nov 2005 04:33:06 -0000 Subject: [Tutor] reduce with comprehension References: <5e58f2e40511211426h1396609dj@mail.gmail.com> Message-ID: <000001c5f137$99d510e0$0a01a8c0@xp> Hi John, > Everything is possible with list comprehensions! >>> [x for z in a for y in z for x in y] > [1, 2, 3, 31, 32, 4, 5, 6, 7, 71, 72, 8, 9] impressive! But in the general case can you do the same job as reduce in a list comprehension? ie apply an operation to the first two elements of a sequence and replace them with the result, then repeat until the list becomes a single value? I cannot think of a way to do that in the generaln case with a comprehension. I'd be interested to see if there is a recipe for that. Alan G From alan.gauld at freenet.co.uk Thu Nov 24 21:56:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 24 Nov 2005 20:56:17 -0000 Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED (fwd) References: Message-ID: <003401c5f139$83cedf90$0a01a8c0@xp> > I changed - and didnt get an executable, not sure what is supposed to be > the > output. I'm not sure what you expect to get, but an executable file is definitely not going to be it... >> > class String(str, Object): If you inherit from str you don't need to inherit from object since str already does. Other than that what does happen when you try to run it? Do you get an error message? If so, what? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Nov 24 22:08:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 24 Nov 2005 21:08:21 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> Message-ID: <005001c5f13b$3367eae0$0a01a8c0@xp> There are many ways of doing this, few of them very nice IMHO. > without having to restart the program? Is it feasible to get a > program to change it's own source code while it is running? Yes, you can overwrite an existing module then call reload from within the program. > For example, if you have a web server such as CherryPy that will > (hopefully) be running for months at a time and you want to be able to > change classes without having to restart the server. Yes that would be feasible., preferrably in response to an admin page where you could fill in a list of modules to be reloaded... But you neeed to be very careful not to break any of the interfaces, the Liskov Substitution Principle must be strictly observed. > to allow users of the site to edit a class through the web and > see the changes to the site immediately? Extremely dangerous but the same principle would apply, simply load the existing module into an editor pane then save the modified version and reload it. > Can a python program change a class, Yes as above. > change all the objects already created by that class Trickier and potentially involves some low level poking that should not be encouraged IMHO! :-) > and save the modified class definition, so that > if the program were restarted it would return to exactly the same > state? (assuming all objects were saved to a database or somesuch). If the LSP is adhered to its feasible but I don't intend to try any such thing! It would be full of pitfalls and an almosyt certain recipe for reliability problems that would be impossible to find. Self modifying code sounds like a good idea but there is a very good reason why its almost never used in production software! HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Nov 24 22:10:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 24 Nov 2005 21:10:48 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385C0F9.1070201@tds.net> <34bb7f5b0511240626j62e5ebb7u@mail.gmail.com> Message-ID: <005601c5f13b$8afd55b0$0a01a8c0@xp> > For example if your program is running, and you make a change to a > class, is it possible to create the necessary class definition and > save it to a file? You can do that but even if you do follow the LSP closely, you still can have problems, especially when you subtract functions or data rather than add them. Once they are gone you can't easily put them back if things go wrong! There is nearly always a better solution... Alan G. From john at fouhy.net Thu Nov 24 23:07:35 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 25 Nov 2005 11:07:35 +1300 Subject: [Tutor] reduce with comprehension In-Reply-To: <000001c5f137$99d510e0$0a01a8c0@xp> References: <5e58f2e40511211426h1396609dj@mail.gmail.com> <000001c5f137$99d510e0$0a01a8c0@xp> Message-ID: <5e58f2e40511241407j422bc3bfy@mail.gmail.com> On 22/11/05, Alan Gauld wrote: > But in the general case can you do the same job as > reduce in a list comprehension? ie apply an operation > to the first two elements of a sequence and replace > them with the result, then repeat until the list becomes > a single value? Well ... probably not. I may have been exaggerating ever-so-slightly in my praise of list comprehensions :-) Although you may be able to cheat: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 (but I'm pretty certain that this "feature" is on Guido's hitlist) Hmm... >>> def f(x, y): ... return x + y ... >>> arr = range(10) >>> sum(arr) # Our target 45 >>> tmp = [0] >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, y)) or True][-1] 45 Let's try some more... >>> def f(x, y): ... return x*y ... >>> arr = range(1, 10) # Don't want to include 0! >>> reduce(f, arr) # Our target 362880 >>> tmp = [1] >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, y)) or True][-1] 362880 >>> print 'Magic!' Magic! -- John. From AKolinski at nriindustries.com Thu Nov 24 23:15:35 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Thu, 24 Nov 2005 17:15:35 -0500 Subject: [Tutor] files - strings - lists In-Reply-To: <438492E6.2080907@tds.net> Message-ID: OK, I made some progress I think. I added a few lines to Kent's script to get closer what I really am after: ========================================== lines = open('liga050926.sbk') # to get the data from a real file #lines = iter(data) # getting data from a string, you don't need this when reading a file lines.next() # skip two headers lines.next() header = lines.next().split() hands = int(header[2]) rounds = int(header[3]) boards = hands*rounds lines.next() allScores = {} # accumulate scores into a dictionary whose key is the name # Now we can process the names and scores in a loop try: # you don't say how you know the end of the names, I just run to the end of data while True: names = lines.next().strip() player1 = names.split()[0] player2 = names.split()[2] lines.next() # skip line after name scores = [ int(lines.next().split()[2]) for i in range(rounds) ] tScores = 0 for i in scores: iScore = float(i) tScores = tScores + iScore allScores[player1] = tScores/boards allScores[player2] = tScores/boards except: # no more lines if lines.next() == '1,1': pass for player1, tScores in allScores.items(): print player1, tScores ============================================= 1. I singled out the players names. 2. I added the players scores and divided by the number of boards played. 3. The output contents is what I wanted: Chrabalowski 0.875 Kowalski -0.333333333333 Kolinski 1.29166666667 Bohossian 1.29166666667 Stankiewicz -1.16666666667 Cwir -0.708333333333 ... 4. The next step for me would be to read the data from more, similar files (from 2 to 10) representing different games and generate an average score for each participating player (a player does not necessary plays each game and I would eventually like to calculate averages of best six out of maximum ten games). Tough! How should I start this next step? (I would like to keep both options open: final ranking = (all tScores)/all boards), or final ranking = average(RScores/boards, RScores/boards, RScores/boards, ...) game1 game2 game3) Thanks Kent, Chris and Danny. After many, many months of using or modifying (and using) existing scripts, with your invaluable help I feel I can write script that is original and extremely useful to me! _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski Kent Johnson Sent by: tutor-bounces at python.org 23/11/2005 11:03 AM To cc tutor at python.org Subject Re: [Tutor] files - strings - lists Andrzej Kolinski wrote: > > I want to create a program that uses data from text files, makes > appropriate calculations and produces report. First I need to find out > what is the right way to retrieve appropriate information from an input > file. This is a typical format of the input file: > > 1 Polonijna Liga Mistrzow |from the heading portion > 26 wrzesnia 2005 |only > 6 12 *6* *4* 1 |'6' and '4' will be needed > 0 1 0 > *Bohossian* - *Kolinski* |all names and > 1 |all scores > 1.000 9 *13* 19 |(3rd column - > 2.000 2 *4* 16 |'13', '4', '8', '6' > 1.000 10 *8* 17 |will be needed > 0.000 8 *6* 17 | > *Szadkowska* - *Szczurek *| > 2 |same here > 0.000 11 *16* 20 | > 3.000 1 *-4* 14 | > 3.500 3 *-7* 13 > 2.500 10 *13* 19 > .................. > > 1 1 |skip the rest > 1 1 1 |(at least for now) It's pretty simple to make an ad-hoc reader for this data. A couple of things you need: - You can get individual lines from a file by treating it as an iterator. Instead of the usual f = open('data.txt') for line in f: you can call f.next() to get a single line. This makes it easy to skip lines or process lines differently. The call to f.next() will raise StopIteration when there are no more lines - You can use split() to break a line into fields, then subscripting to pull out the data you want: >>> line = ' 1.000 9 13 19' >>> line.split() ['1.000', '9', '13', '19'] >>> line.split()[2] '13' >>> int(line.split()[2]) 13 With these tools the solution is pretty simple. I pull the data from a string but it will work with a file as well. I save the results in a dictionary which maps name to a list of scores. data = '''1 Polonijna Liga Mistrzow 26 wrzesnia 2005 6 12 6 4 1 0 1 0 Bohossian - Kolinski 1 1.000 9 13 19 2.000 2 4 16 1.000 10 8 17 0.000 8 6 17 Szadkowska - Szczurek 2 0.000 11 16 20 3.000 1 -4 14 3.500 3 -7 13 2.500 10 13 19 '''.split('\n') #lines = open('data.txt') # to get the data from a real file lines = iter(data) # getting data from a string, you don't need this when reading a file lines.next() # skip two headers lines.next() header = lines.next().split() six = int(header[2]) four = int(header[3]) print six, four lines.next() allScores = {} # accumulate scores into a dictionary whose key is the name # Now we can process the names and scores in a loop try: # you don't say how you know the end of the names, I just run to the end of data while True: name = lines.next().strip() lines.next() # skip line after name scores = [ int(lines.next().split()[2]) for i in range(4) ] allScores[name] = scores except StopIteration: # no more lines pass for name, scores in allScores.items(): print name, scores _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051124/bbefa18d/attachment.htm From nick at javacat.f2s.com Thu Nov 24 23:15:26 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Thu, 24 Nov 2005 22:15:26 -0000 Subject: [Tutor] reduce with comprehension In-Reply-To: <5e58f2e40511241407j422bc3bfy@mail.gmail.com> Message-ID: > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On > >>> def f(x, y): > ... return x + y > ... > >>> arr = range(10) > >>> sum(arr) # Our target > 45 > >>> tmp = [0] > >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, > y)) or True][-1] > 45 > > Let's try some more... > > >>> def f(x, y): > ... return x*y > ... > >>> arr = range(1, 10) # Don't want to include 0! > >>> reduce(f, arr) # Our target > 362880 > >>> tmp = [1] > >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, > y)) or True][-1] > 362880 > >>> print 'Magic!' > Magic! LOL I feel like I've accidentally signed up for the perl-tutor list ;) From john at fouhy.net Thu Nov 24 23:28:33 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 25 Nov 2005 11:28:33 +1300 Subject: [Tutor] reduce with comprehension In-Reply-To: References: <5e58f2e40511241407j422bc3bfy@mail.gmail.com> Message-ID: <5e58f2e40511241428p6cd5f0eer@mail.gmail.com> On 25/11/05, Nick Lunt wrote: > > -----Original Message----- > > >>> def f(x, y): > > ... return x*y > > ... > > >>> arr = range(1, 10) # Don't want to include 0! > > >>> reduce(f, arr) # Our target > > 362880 > > >>> tmp = [1] > > >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, > > y)) or True][-1] > > 362880 > > >>> print 'Magic!' > > Magic! > > LOL I feel like I've accidentally signed up for the perl-tutor list ;) Oh no --- I have become that which I hate! I must quickly go and do twenty 'import this's as penance for my sins... -- John. From alan.gauld at freenet.co.uk Fri Nov 25 00:18:10 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu, 24 Nov 2005 23:18:10 -0000 Subject: [Tutor] reduce with comprehension References: <5e58f2e40511211426h1396609dj@mail.gmail.com><000001c5f137$99d510e0$0a01a8c0@xp> <5e58f2e40511241407j422bc3bfy@mail.gmail.com> Message-ID: <007f01c5f14d$55ef2940$0a01a8c0@xp> > But in the general case can you do the same job as > reduce in a list comprehension? >>> def f(x, y): ... return x + y ... >>> tmp = [0] >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, y)) or >>> True][-1] 45 Let's try some more... >>> def f(x, y): ... return x*y ... >>> tmp = [1] >>> [f(x, y) for x in arr for y in [tmp[-1]] if tmp.append(f(x, y)) or >>> True][-1] 362880 OK, you've nearly convinced me that its possible but I think I still prefer reduce()! :-) Alan G. From john at fouhy.net Fri Nov 25 01:46:07 2005 From: john at fouhy.net (John Fouhy) Date: Fri, 25 Nov 2005 13:46:07 +1300 Subject: [Tutor] Convert integer number to binary representation In-Reply-To: <43861F84.40207@gmail.com> References: <43861F84.40207@gmail.com> Message-ID: <5e58f2e40511241646y79582f38w@mail.gmail.com> On 25/11/05, Alberto Troiano wrote: > I want to know how can I convert an integer number to a binary number. > Like this example: Hi Alberto, There's no builtin function to do this (like there is for hex or oct). There are a few recipes in the Cookbook on ActiveState that will do base conversion --- here's a simple one for binary numbers that takes advantage of the correspondence between binary and hexidecimal representations of numbers: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528 -- John. From kent37 at tds.net Fri Nov 25 02:20:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Nov 2005 20:20:46 -0500 Subject: [Tutor] lil help please - updated (fwd) In-Reply-To: References: Message-ID: <438666EE.3050607@tds.net> > From: Alan > > I have about 150 lines of python extracting text from large file, the > problem I need a few lines to clean first to avoid the problem the > script is facing > > Overview > There is large text and I am trying to organize it for the python script > to process, it is badly organized and I attempted to do it like this > which the master script understand I think I would split this into three phases: - collect the data into groups of HFR - process each group by rearranging, renumbering, reporting errors - output the processed groups One potential problem is to resynchronize to the next group when there is a sequence error. If there is always a blank line between groups it is easy. Otherwise maybe just assume an H is the start of a group. hth, Kent > > Keywords: > ##### is number like 1 thru 99999 > |H paragraphs > |F reFerence > |R Rating > > BEFORE I organized by text global and replace > Each set of tokens was like this > > ##### paragraph > F reference > R rating > > Now (where master script understand) > > |H###### paragraph > |F reference > |R rating > > Notice no ##### in |F |R > > PROBLEMS > Phase 1 > PROBLEM 1 > the |H paragraph (multi lines) has some words between () such as (xyz > blah words) also maybe in multi lines > ?.( blah blah > blah blah) ? > > We need to move it to the end of |F reference (xyz blah words) > > > Example > BEFORE > > |H 00100 a friend in need is a friend indeed (author means both young \ > and old) so select the best friend as soon as you can blah > |F Old London book > |R Cool > > AFTER your process > |H 00100 "a friend in need is a friend indeed so select the best friend > as soon as you can blah" > |F Old London book > |R Cool > > PROBLEM 2 > I need to find out if the order is broken so I go and fix it by hand > i.e. |H##### |F |R is any other order so it is outputted in > ErrorOrderLogFile > > |H##### paragraph > |H paragraph > |R rating > > or any order like > > run new cleaning script and cat ErrorOrderLogFile > |H00299 paragraph > |F Reference > |H Rating > > |H00300 paragraph > |H paragraph > |H rating > > cat ErrorOrderLogFile: > bad set orders > |H00300 paragraph > > > Phase II > PROBLEM 3 > Once I fix by the order hand I need to renumber all from say 00001 to > 99999 > In this format > > |H00001 paragraph > |F00001 reference > |R00001 rating > > |H99999 paragraph > |F99999 reference > |R99999 rating > > > > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://www.kentsjohnson.com From ldapguru at yahoo.com Fri Nov 25 08:38:17 2005 From: ldapguru at yahoo.com (Alan) Date: Fri, 25 Nov 2005 01:38:17 -0600 Subject: [Tutor] lil help please - updated (|H|F|R) (Chris or Leslie Smith) TASK1 one relocate/move In-Reply-To: Message-ID: Smiles Thanks a thousands Let us do one task at a time= task 1 relocate/move any words in |H between (...) to the end of |R rating and before the next line of |H sorry the master python script wants one | before H and F and R in any place however some |H |F |R do not come in the beginning in error BEFORE any process |H 00100 "a friend in need is a friend indeed (xyz words) so select the best friend as soon as you can" |F Old London book |R Cool OR |H 00100 "a friend in need is a friend indeed (xyz words) so select the best friend as soon as you can" |F Old London book |R Cool RESULT AFTER task1 process |H 00100 "a friend in need is a friend indeed so select the best friend as soon as you can blah" |F Old London book (xyz blah words) <=== parenthetical here? |R Cool Hello, This seems like a well laid out task. If you post what you are trying and the problems you are encountering, that would be helpful. One suggestion that I have is that you switch problems 1 and 2. If the ordering is broken (e.g. HHFR instead of HFRH) then knowing where to put the parenthetical comment is going to be a problem. Also, you said that you wanted it put after the "F" reference did you mean that is should look like this: BEFORE any process |H 00100 "a friend in need is a friend indeed (xyz blah words) so select the best friend as soon as you can blah" |F Old London book |R Cool AFTER your process |H 00100 "a friend in need is a friend indeed so select the best friend as soon as you can blah" |F Old London book (xyz blah words) <=== parenthetical here? |R Cool It's a little hard to tell from what you've said, but it looks like the "|" was an unnecessary addition. If your record markers were always a single character at the beginning of a line, those are easy enough to find--provided there is never an H, F, or R that is a NON-record marker at the beginning of a line as a single character. ###### >>> text='''H This is the start. ... F here is a reference. ... Right here is a non-reference R but it's not a single character starting the line ... so it won't be matched; and the single one in the middle isn't at the start. ... R cool''' >>> import re >>> text = '\n'+text #make the first one like all the others: preceded by newline character >>> re.findall(r'\n([HFR])\b', text) ['H', 'F', 'R'] >>> re.split(r'\n([HFR])\b', text) ['', 'H', ' This is the start.', 'F', " here is a reference. \nRight here is a non-reference R but it's not a single character starting the line\nso it won't be matched; and the single one in the middle isn't at the start.", 'R', ' cool'] ###### That last list has all the groups with the identifier preceding the corresponding data. Finally, I'm not sure how you are checking the correctness of the HFR sequence, but the findall used above suggests a way to do it: -do the findall -join the results together -replace 'HFR' with '.' -if the whole string isn't dots then there was a problem and the number of dots before the non-dot tell you how many correct records there were. ###### >>> bad=''' ... H ... F ... R ... R ... ''' >>> re.findall(r'\n([HFR])\b', bad) ['H', 'F', 'R', 'R'] >>> ''.join(_) # the _ refers to the last output 'HFRR' >>> _.replace('HFR', '.') '.R' >>> len(_),_.count('.') (2, 1) ###### Notice that since not all the HFRs were complete, there are not all the characters are periods (and so the count of periods is not the same as the length of the string). In this case there was one correct record (thus one leading dot) before the problem occurred. /c --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From singletoned at gmail.com Fri Nov 25 12:11:58 2005 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 25 Nov 2005 11:11:58 +0000 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <4385EF32.8070606@tds.net> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> Message-ID: <34bb7f5b0511250311o2d85581dk@mail.gmail.com> On 24/11/05, Kent Johnson wrote: > Ed Singleton wrote: > > Is it feasible to change a program's source code whilst it is running > > without having to restart the program? Is it feasible to get a > > program to change it's own source code while it is running? > > You can change a class while it is running. > > > > For example, if you have a web server such as CherryPy that will > > (hopefully) be running for months at a time and you want to be able to > > change classes without having to restart the server. Or if you want > > to allow users of the site to edit a class through the web and see the > > changes to the site immediately? > > The auto-restart feature of CherryPy might do this for you. Also if the changes to the site are to a template such as Cheetah, those usually autoreload. > > > > Can a python program change a class, change all the objects already > > created by that class and save the modified class definition, so that > > if the program were restarted it would return to exactly the same > > state? (assuming all objects were saved to a database or somesuch). > > You can have persistent objects using for example SQLObject or ZODB, > > > > Does anyone have any good links to implementations of this? I assume > > someone's already done it before. > > It sounds like maybe you come from a background in Smalltalk, or maybe you should look at Smalltalk. In Smalltalk the whole environment is dynamic and can be saved and restored easily. Just had a quick look at Smalltalk, and at first glance the overview of the ideas behind it seems amazing, but the language seems quite ugly, and it seems to be very IDE led. > For Python, I think you will do better if you narrow your requirements. Python is very dynamic - classes can be changed at runtime, or reloaded if you are careful - and there are several good ways to persist state. If you can be more specific about what you really need there may be a solution for you. What I want to do seems quite simple to me in concept, but is seeming more and more as if it would be hard to implement. I want to create a small simple CMS for my website. Users will be able to add and edit basic pages. Pages can have sub-pages (no need for folders cause a folder and an index.html can be unified into one concept). Users will also be able to create new types of pages, maybe a PressReleasePage for example. PressReleases would be based on a normal page but might have extra attributes such as Author, Abstract or DateToBeReleased. This immediately seemed to me to be a case for classes. You provide a way for a user to create a new class by subclassing the page class (from their point of view probably through adding a few new fields to a form). Later if they change their mind they can edit the class by adding or removing attributes. However it doesn't really seem that Python is suited to this. Indeed it doesn't really seem that Python is suited to a persistent environment. Having a program running for a long time (months) is possible certainly, but it seems to be fighting against the language rather than working with it. Ed From singletoned at gmail.com Fri Nov 25 12:45:14 2005 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 25 Nov 2005 11:45:14 +0000 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <005001c5f13b$3367eae0$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <005001c5f13b$3367eae0$0a01a8c0@xp> Message-ID: <34bb7f5b0511250345r5250d826y@mail.gmail.com> On 24/11/05, Alan Gauld wrote: > There are many ways of doing this, few of them very nice IMHO. > > > without having to restart the program? Is it feasible to get a > > program to change it's own source code while it is running? > > Yes, you can overwrite an existing module then call reload > from within the program. > > > For example, if you have a web server such as CherryPy that will > > (hopefully) be running for months at a time and you want to be able to > > change classes without having to restart the server. > > Yes that would be feasible., preferrably in response to an admin > page where you could fill in a list of modules to be reloaded... > But you neeed to be very careful not to break any of the interfaces, > the Liskov Substitution Principle must be strictly observed. > > > to allow users of the site to edit a class through the web and > > see the changes to the site immediately? > > Extremely dangerous but the same principle would apply, > simply load the existing module into an editor pane then save > the modified version and reload it. > > > Can a python program change a class, > > Yes as above. > > > change all the objects already created by that class > > Trickier and potentially involves some low level poking that > should not be encouraged IMHO! :-) > > and save the modified class definition, so that > > if the program were restarted it would return to exactly the same > > state? (assuming all objects were saved to a database or somesuch). > > If the LSP is adhered to its feasible but I don't intend to try any > such thing! It would be full of pitfalls and an almosyt certain recipe > for reliability problems that would be impossible to find. > Self modifying code sounds like a good idea but there is a very > good reason why its almost never used in production software! Well, self-modifying isn't inherently necessary. What I guess I really need is persistent classes as well as persistent objects. I always tend to think of classes as templates for objects rather than factories. In my mind, object methods are just calls to the class which are evaluated every time they are called. Objects should be strict instances of classes that can't be modified except for the values of their attributes. I think I can actually achieve this to some degree by doing: Class Page(object): def print(self): printPage(self) And have all my methods call functions (passing on parameters as necessary). That way if I change a function, it will be changed for every instance of every object of that class. And couldn't I write a function that would add functions or attributes to classes and objects? def addAttribute(class, attribute, starting value): # add it to the class # iterate through all objects already created by the class # add attribute to object Am I trying to use the wrong language for this? I love Python but I seem to keep coming up against lots of practical issues with it and I really don't want to bother with practical issues. I just want to define the behaviours I want without having to bother with how the computer is actually going to handle them. I guess it's very much a "I don't care how it works!" attitude, which is probably a corollary to "premature optimisation is the root of all evil". Ignore all issues of memory and speed and create something highly abstract that allows you to define your solution. Then work down from there and start worrying about speed and memory and practical issues later (or hopefully never). Ed From kent37 at tds.net Fri Nov 25 14:31:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Nov 2005 08:31:28 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511250345r5250d826y@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <005001c5f13b$3367eae0$0a01a8c0@xp> <34bb7f5b0511250345r5250d826y@mail.gmail.com> Message-ID: <43871230.7090605@tds.net> Ed Singleton wrote: > I think I can actually achieve this to some degree by doing: > > Class Page(object): > def print(self): > printPage(self) > > And have all my methods call functions (passing on parameters as > necessary). That way if I change a function, it will be changed for > every instance of every object of that class. Yes, that will work. You can change the definition of a class method at runtime. > > And couldn't I write a function that would add functions or attributes > to classes and objects? > > def addAttribute(class, attribute, starting value): > # add it to the class > # iterate through all objects already created by the class > # add attribute to object Yes, you can add attributes to classes and objects. Did you look at this recipe? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 The MetaInstanceTracker metaclass gives an easy way for classes to keep track of their instances. The MetaAutoReloader metaclass uses MetaInstanceTracker to update class definitions when a module is reloaded. > > Am I trying to use the wrong language for this? I love Python but I > seem to keep coming up against lots of practical issues with it and I > really don't want to bother with practical issues. I just want to > define the behaviours I want without having to bother with how the > computer is actually going to handle them. That seems rather idealistic! > > I guess it's very much a "I don't care how it works!" attitude, which > is probably a corollary to "premature optimisation is the root of all > evil". Ignore all issues of memory and speed and create something > highly abstract that allows you to define your solution. Then work > down from there and start worrying about speed and memory and > practical issues later (or hopefully never). I still think you are shooting for too high a level of abstraction. Kent -- http://www.kentsjohnson.com From kent37 at tds.net Fri Nov 25 14:44:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Nov 2005 08:44:32 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511250311j3e204a0bh@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311j3e204a0bh@mail.gmail.com> Message-ID: <43871540.8040402@tds.net> Ed Singleton wrote: > On 24/11/05, Kent Johnson wrote: >> It sounds like maybe you come from a background in Smalltalk, or >> maybe you should look at Smalltalk. In Smalltalk the whole >> environment is dynamic and can be saved and restored easily.> > > Just had a quick look at Smalltalk, and at first glance the overview > of the ideas behind it seems amazing, but the language seems quite > ugly, and it seems to be very IDE led. I guess the language grows on you, it certainly has some strong supporters. It is very oriented to a single comprehensive environment. I think this is one reason it never became generally popular. But it also is what gives the language its extreme malleability. It does do what you want - it allows you to change objects and classes dynamically at run-time and save the state of the system at any time. The down side is that all interaction with the system is from within. >>For Python, I think you will do better if you narrow your requirements. Python is very dynamic - classes can be changed at runtime, or reloaded if you are careful - and there are several good ways to persist state. If you can be more specific about what you really need there may be a solution for you. > > > What I want to do seems quite simple to me in concept, but is seeming > more and more as if it would be hard to implement. > > I want to create a small simple CMS for my website. Users will be > able to add and edit basic pages. Pages can have sub-pages (no need > for folders cause a folder and an index.html can be unified into one > concept). Have you looked at Plone and PyLucid? http://plone.org/ http://www.pylucid.org/ > Indeed > it doesn't really seem that Python is suited to a persistent > environment. Having a program running for a long time (months) is > possible certainly, but it seems to be fighting against the language > rather than working with it. Python provides mechanisms for persistence but not a way to persist the entire environment. You have to design and build your program to support persistence. Long-running Python programs are certainly possible. PS Please reply on list. Kent -- http://www.kentsjohnson.com From ismaelgf at adinet.com.uy Fri Nov 25 15:50:29 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Fri, 25 Nov 2005 12:50:29 -0200 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511250311o2d85581dk@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> Message-ID: <438724B5.6070404@adinet.com.uy> Ed Singleton wrote: >I want to create a small simple CMS for my website. Users will be >able to add and edit basic pages. Pages can have sub-pages (no need >for folders cause a folder and an index.html can be unified into one >concept). > >Users will also be able to create new types of pages, maybe a >PressReleasePage for example. PressReleases would be based on a >normal page but might have extra attributes such as Author, Abstract >or DateToBeReleased. > > > Store the fields in a database, make a factory class that gets those fields and generates a page accordingly. I agree with Kent, what you're trying seems way too abstract. Ismael From singletoned at gmail.com Fri Nov 25 16:47:08 2005 From: singletoned at gmail.com (Ed Singleton) Date: Fri, 25 Nov 2005 15:47:08 +0000 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <438724B5.6070404@adinet.com.uy> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <438724B5.6070404@adinet.com.uy> Message-ID: <34bb7f5b0511250747t5de546a6r@mail.gmail.com> On 25/11/05, Ismael Garrido wrote: > Ed Singleton wrote: > > >I want to create a small simple CMS for my website. Users will be > >able to add and edit basic pages. Pages can have sub-pages (no need > >for folders cause a folder and an index.html can be unified into one > >concept). > > > >Users will also be able to create new types of pages, maybe a > >PressReleasePage for example. PressReleases would be based on a > >normal page but might have extra attributes such as Author, Abstract > >or DateToBeReleased. > > > > > > > Store the fields in a database, make a factory class that gets those > fields and generates a page accordingly. > > I agree with Kent, what you're trying seems way too abstract. Weirdly, I'd just realised that SQLObject does most of what I'm thinking about. It allows you to update a class and that will affect all the objects already instantiated. It has class persistence in that it will rebuild the class on startup from the columns in your table so your 'live' changes will be there after you restart the server. Though all that is only for the data in the class. Each method could just contain a call to a function (as I mentioned above) all the functions could be contained in a module, which would make it easy to update them as it appears to be easy enough to reload a module. The only thing you wouldn't really be able to do is add or remove methods, which I guess is fine for the moment. The only thing I'm not sure of is whether SQLObject can store properties (as in managed attributes) which I need to do for the 'inherit from parent' attribute that I mentioned is a previous thread: class Page(object): def __init__(self, parent): self.__header = None self.parent = parent def getheader(self): if not self._header and self.parent: return self.parent.header else: return self.__header def setheader(self, header): self.__header = header header = property(getheader, setheader) From smiles at worksmail.net Fri Nov 25 17:06:04 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 25 Nov 2005 10:06:04 -0600 Subject: [Tutor] lil help please - updated (fwd) References: Message-ID: <003601c5f1da$549b5e00$c82c4fca@csmith> | I think I would split this into three phases: | - collect the data into groups of HFR | - process each group by rearranging, renumbering, reporting errors | - output the processed groups | | One potential problem is to resynchronize to the next group when | there is a sequence error. If there is always a blank line between | groups it is easy. Otherwise maybe just assume an H is the start of a | group. | Hmm...so Alan could first split the data on the "|H" values. These *should* contain an |F and and |R, so the next step would be to break these HFR groups into pieces and check to see that all the pieces are there, and perhaps if not, printing those to an error file for review. Alan, regarding the extraction of the parentheticals, what have you tried? One suggestion for this aspect is to get rid of the line breaks in the |H chunk and then you won't have the problem of a broken parenthetical. For example, ###### >>> multiLines = '''This (as you ... can see) is multilined.''' >>> multiLines.splitlines() ['This (as you', 'can see) is multilined.'] >>> ' '.join(multiLines.splitlines()) 'This (as you can see) is multilined.' >>> # the above is one line and much easier to handle now. ###### How are you reading the data in from the file? /c From kent37 at tds.net Fri Nov 25 17:58:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Nov 2005 11:58:27 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511250747t5de546a6r@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <438724B5.6070404@adinet.com.uy> <34bb7f5b0511250747t5de546a6r@mail.gmail.com> Message-ID: <438742B3.3050901@tds.net> Ed Singleton wrote: > Weirdly, I'd just realised that SQLObject does most of what I'm > thinking about. Ahhh. (sigh of relief :-) Kent From ldapguru at yahoo.com Fri Nov 25 18:30:49 2005 From: ldapguru at yahoo.com (Alan) Date: Fri, 25 Nov 2005 11:30:49 -0600 Subject: [Tutor] lil help please - updated (fwd) (Chris or Leslie Smith) In-Reply-To: Message-ID: <9F8A4893BB7F47BEA57552EC198D07D5@server01> Smile and Kent The logic is so good so far. However, How do we move the (...) in |H to end of |R and before next |H Much respect AD Exceptional team: I like and I agree with your all logic (I have no choice! Smile you are more advanced than me) Kent said: I think I would split this into three phases: - collect the data into groups of HFR - process each group by rearranging, renumbering, reporting errors - output the processed groups One potential problem is to resynchronize to the next group when there is a sequence error. If there is always a blank line between groups it is easy. Otherwise maybe just assume an H is the start of a group. And Smile addressed Kent's concern by saying: Hmm...so Alan could first split the data on the "|H" values. These *should* contain an |F and and |R, so the next step would be to break these HFR groups into pieces and check to see that all the pieces are there, and perhaps if not, printing those to an error file for review. Alan, regarding the extraction of the parentheticals, what have you tried? One suggestion for this aspect is to get rid of the line breaks in the |H chunk and then you won't have the problem of a broken parenthetical. For example, ###### >>> multiLines = '''This (as you ... can see) is multilined.''' >>> multiLines.splitlines() ['This (as you', 'can see) is multilined.'] >>> ' '.join(multiLines.splitlines()) 'This (as you can see) is multilined.' >>> # the above is one line and much easier to handle now. ###### >How are you reading the data in from the file? I use the 150 line python I do not mind emailing it directly so I do not confuse these cleaning tasks - you just say yes Much respect AD --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From alan.gauld at freenet.co.uk Fri Nov 25 18:47:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 25 Nov 2005 17:47:53 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> Message-ID: <000f01c5f1e8$5ced00f0$0a01a8c0@xp> > Just had a quick look at Smalltalk, and at first glance the overview > of the ideas behind it seems amazing, but the language seems quite > ugly, and it seems to be very IDE led. Adherents will defend its simplicity but I confess I strugglred for a long time with SmallTalk before learning to love it :-) And yes it is IDE led although the IDE can be 'removed' when deploying applications. But much depends on the implementation, my favourite for PCs is Dolphin SmallTalk from ObjectArts. Its not a traditional SmallTalk (ala Xerox SmallTalk 80) but very much one for the '90's > This immediately seemed to me to be a case for classes. > You provide a way for a user to create a new class by > subclassing the page class (from their point of view > probably through adding a few new fields to > a form). That might be part of the problem, if you think of a class in terms of its data attributes then that is nearly always the wrong starting point. Classes express behaviour, the data is only there to support the behaviour. Thats why methods are polymorphic but not attributes. So you think of a class having an interface and users extending or modifying the behaviour, not the data. If you follow that route you might find you don't need to write self modifying code, you simply load new classes with a common interface into an existing hook structure. > However it doesn't really seem that Python is suited to this. Indeed > it doesn't really seem that Python is suited to a persistent > environment. What makes you think that? Most persistent environments (ie long running server processs) are written in C/C++ (or maybe Java nowadays) which are far less dynamic than Python. > Having a program running for a long time (months) is > possible certainly, but it seems to be fighting against the language Not at all, at least no more than in languages like C which require recoding, recompiling, stopping and then restarting the server to make changes. Thats why a simple framework with loadable modules it usally preferred to self modifying code! Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Nov 25 19:43:43 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri, 25 Nov 2005 18:43:43 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><005001c5f13b$3367eae0$0a01a8c0@xp> <34bb7f5b0511250345r5250d826y@mail.gmail.com> Message-ID: <001601c5f1f0$29b41540$0a01a8c0@xp> Hi Ed, This is a longish response because you are raising some very interesting (and deep) issues from a computer science point of view. > Well, self-modifying isn't inherently necessary. What I guess I > really need is persistent classes as well as persistent objects. Python classes can be persistent just like any other object, theres nothing intrinsically different between a class object and any other kind of object (except that classes as objects are kind of mind bending as a concept!) > I always tend to think of classes as templates for objects rather > than factories. They are both. > In my mind, object methods are just calls to the class which > are evaluated every time they are called. The methjods are function attributes of a class which are selected by the class dispatch mechanism in response to messages sent to instances. In Python that means the getattr() methods look up the right method in response to receipt of a message. > Objects should be strict instances of classes that can't be > modified except for the values of their attributes. Attributes in a pure OOP language include both the contained data and functions. In other workds methods can be added/removed and modified as well as the data. In fact many would argue that the internal data not only cannot be modified externally but should not even be seen - the Data Hiding school of thought. > Class Page(object): > def print(self): > printPage(self) What does that gain you? > And have all my methods call functions (passing on parameters as > necessary). That way if I change a function, it will be changed for > every instance of every object of that class. You mean like this: >>> class C: ... def m(self): print 'm' ... >>> def f(o): print 'other m' ... >>> c = C() >>> c.m() m >>> C.m = f >>> c.m() other m >>> > And couldn't I write a function that would add functions or attributes > to classes and objects? Of course, just like I did there. > Am I trying to use the wrong language for this? I love Python but I > seem to keep coming up against lots of practical issues with it Python is a pretty good language for this kind of thing, its just that this kind of thing is intrinsically difficult. The only lanuages I know of which are better than Python at it are Lisp and Smalltalk (and even Smalltalk has some limitations compared to Python). Do you have experience of a language which is more flexible in this regard? I'm curious because you seem to assume that its almost normal to be able to do these things, whereas in my experience its usually impossible rather than just difficult... > define the behaviours I want without having to bother with how the > computer is actually going to handle them. Believe it or not thats been the holy grail of language designers since the days of COBOL - The Common Business Oriented Language - which allowed business people to write theitr own programmes in "standard, everyday English", like: PROGRAM ID - HELLO PROCEDURE DIVISION MAIN-LINE-MODULE MOVE 0 TO COUNTER OPEN INPUT IN-FILE PERFORM READ IN-FILE UNTIL END-OF-FILE = "YES" ADD 1 TO COUNTER DISPLAY "LINE NUMBER ", COUNTER CLOSE IN-FILE STOP RUN. At the time it was considered revolutionary and programmers trembled at the prospect of instant redundancy. As it happened your average businessman found COBOL about as readable as pigin English! But that hasn't stopped us trying... One thing we have discovered is that the more natural the language seems to get the less flexible the language gets. Python is the closest I've seen yet to a general purpose language that is truly readable, but thats still a long way from being plain English! But I digress :-) Basically I just wonder what your background is that you seem to expect these kind of dynamic facilities? I'd certainly be interested in investigating it further. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051125/d841fa0b/attachment.html From ldapguru at yahoo.com Fri Nov 25 22:41:11 2005 From: ldapguru at yahoo.com (Alan) Date: Fri, 25 Nov 2005 15:41:11 -0600 Subject: [Tutor] lil help please - updated (fwd) (Chris or Leslie Smith) In-Reply-To: Message-ID: <775AD952041641D887F759D55D229693@server01> Thanks Getting Simpler I tested the below on python command line, it is very cool 1. So, how do we translate its re.compile into python? 2. them how to move it to at the end of |R and before next |H 3. I can almost remove all numbers (delete 0-9) and start new numbering ###### >>> multiLines = '''This (as you ... can see) is multilined.''' >>> multiLines.splitlines() ['This (as you', 'can see) is multilined.'] >>> ' '.join(multiLines.splitlines()) 'This (as you can see) is multilined.' >>> # the above is one line and much easier to handle now. ###### --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From dyoo at hkn.eecs.berkeley.edu Fri Nov 25 22:49:25 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Nov 2005 13:49:25 -0800 (PST) Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED (fwd) Message-ID: ---------- Forwarded message ---------- Date: Fri, 25 Nov 2005 08:59:30 -0400 From: mike donato To: dyoo at hkn.eecs.berkeley.edu Subject: Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED Dan, what I meant was that the program does not run. Why? Thanks >From: Danny Yoo >To: mike donato >CC: tutor at python.org >Subject: Re: [Tutor] TRULY NEWBIE - MENTOR NEEDED >Date: Tue, 22 Nov 2005 14:46:14 -0800 (PST) > > > >On Tue, 22 Nov 2005, mike donato wrote: > > > Greetings, I am new student to programming and am experimenting with > > PYTHON. From what I have read, seems to be a very versatile language. > > In the following excercise I am getting an error > > > > class String(str, Object): > >[class definition cut] > > > > Traceback (most recent call last): > > File "", line 11, in -toplevel- > > class String(str, Object): > > NameError: name 'Object' is not defined > > >Hi Mike, > >The error is true: Python doesn't know of any class named 'Object'. What >you may be looking for is the 'object' class (lowercase 'o'). > >Good luck! > _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: 4.5.py Url: http://mail.python.org/pipermail/tutor/attachments/20051125/cae87248/4.5-0001.asc From kent37 at tds.net Fri Nov 25 23:03:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Nov 2005 17:03:39 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> Message-ID: <43878A3B.8020707@tds.net> Ed Singleton wrote: > Can a python program change a class, change all the objects already > created by that class and save the modified class definition, so that > if the program were restarted it would return to exactly the same > state? (assuming all objects were saved to a database or somesuch). I asked on comp.lang.python about persisting classes. David Wahler posted an interesting solution. You can read the thread here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/10a03f094303a91c/7d65bd344d4e0063?hl=en#7d65bd344d4e0063 (David's reply hasn't appeared on Google as I post this but it should be there eventually...) Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Fri Nov 25 23:08:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Nov 2005 14:08:56 -0800 (PST) Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED (fwd) In-Reply-To: Message-ID: > Dan, what I meant was that the program does not run. Why? Hi Mike, We don't have enough information. I have to ask more questions to have a better idea what's going on. Also, please send your replies to the tutor list: don't send them to me directly. What do expect to see when your program runs? Are there other programs that you've run that do things? What do you mean when the program doesn't run? What are you doing to "run" the program? The class definition that you're showing us looks bizarre as a first program example. If you're really starting from scratch, I'd recommend starting with an easier tutorial. If you're starting from scratch, you may want to go through one of the tutorials in: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers I have no familiarity with the book you quote, but from the web site: http://www.brpreiss.com/books/opus7/ and from the statement in the foward here: http://www.brpreiss.com/books/opus7/ the author explicitely says that the book's audience is experienced programmers! It won't go out of it's way to talk about issues that affect beginner programmers, because that book expects you to already know basic Python programming. That is why I'm encouraging you to look at another tutorial from the Non Programmers section. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Fri Nov 25 23:10:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 25 Nov 2005 14:10:42 -0800 (PST) Subject: [Tutor] TRULY NEWBIE - MENTOR NEEDED (fwd) In-Reply-To: Message-ID: > I have no familiarity with the book you quote, but from the web site: > > http://www.brpreiss.com/books/opus7/ > > and from the statement in the foward here: > > http://www.brpreiss.com/books/opus7/ Gaaa, stupid HTML frames... *grin* Sorry, that second URL was supposed to be: http://www.brpreiss.com/books/opus7/html/page22.html#SECTION001400000000000000000 From enas_khalil at yahoo.com Fri Nov 25 23:58:28 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Fri, 25 Nov 2005 14:58:28 -0800 (PST) Subject: [Tutor] how to read a non english text file In-Reply-To: Message-ID: <20051125225828.74139.qmail@web30510.mail.mud.yahoo.com> hello everyone still my question about if i could read and process a non english language text file using python --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051125/4a164dc6/attachment.html From kent37 at tds.net Sat Nov 26 02:32:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Nov 2005 20:32:32 -0500 Subject: [Tutor] how to read a non english text file In-Reply-To: <20051125225828.74139.qmail@web30510.mail.mud.yahoo.com> References: <20051125225828.74139.qmail@web30510.mail.mud.yahoo.com> Message-ID: <4387BB30.7060108@tds.net> enas khalil wrote: > hello everyone > still my question about if i could read and process a non english > language text file using python To read the file use import codecs data = codecs.open('myfile.txt', 'r', 'cp1256').read() This will give you a Unicode string in data. I don't know how to use NLTK to tag this, I hope this will get you started. Kent -- http://www.kentsjohnson.com From kent37 at tds.net Sat Nov 26 03:16:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 25 Nov 2005 21:16:45 -0500 Subject: [Tutor] Trouble with classes - Pypeg again In-Reply-To: References: Message-ID: <4387C58D.9060509@tds.net> ->Terry<- wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > > Ok, I've got my peg game roughed out and I'm having > problems. > > The new code is at: > > > > I'm confused as to why. The whole OO picture > has my head reeling, but I thought I had some > grasp of the basics. Now I'm not so sure. d:^) Terry, I can see you're struggling with the OO parts of this program. I'll try to help... Classes group state (instance variables) and behaviour (methods). When designing the classes for a program, look for state and behaviour that belong together - groups of functions that act on common data. In your case, I think the fundamental object is a hole. A hole has a location and it may or may not contain a peg. Those are it's state. A hole has behaviour, in the OO sense, anyway - there are things you want to do with a hole. You can draw it, ask it if it has a peg in it, ask it if a mouse click falls inside it. So what would this look like? class Hole(object): # Load peg image. This is a class attribute, not an instance attribute pegImage = pygame.image.load('peg.png') def __init__(self, location): self.location = location self.hasPeg = False def draw(self, screen): ''' A hole knows how to draw itself. ''' if self.hasPeg: screen.blit(Hole.peg, self.location) # Blit it. def isClicked(self, click): return self.location[0] <= click[0] <= self.location[0] + 19 \ and self.location[1] <= click[1] <= self.location[1] + 19 OK, that looks like a pretty handy Hole. Notice that this Hole doesn't really correspond very well to what we call a hole in the real world. Real holes have locations and they may contain pegs, but they don't know how to do anything. That's OK. In the program, any functions that use the state of a hole belong in the Hole class. What else do we need? Well, we need some place to put a bunch of Holes and do stuff with the collection, like draw them all and hit test them all. This sounds like another class, let's call it Board. The state of a board is just the list of Holes it contains. The behaviours of a Board are to draw itself, to find which Hole a click falls on (if any), to check for valid moves and to perform the moves by changing the state of its Holes. That's a lot, I'll just start it: class Board(object): # Load board image boardImage = pygame.image.load('board.png').convert_alpha() def __init__(self): # create a list of Holes holeCoords = [[141, 41], [114, 91], [164, 91], [91, 141], [141, 141], [191, 141], [64, 191], [114, 191], [164, 191], [214, 191], [41, 241], [91, 241], [141, 241], [191, 241], [241,241]] holes = [ Hole(coords) for coord in holeCoords ] def draw(self, screen): screen.blit(Board.boardImage, (0, 0)) # Blit the board for hole in self.holes: hole.draw(screen) pygame.display.update() # Refresh display. See how Board lets the Holes take care of drawing themselves? The Hole is a useful abstraction - from the outside we don't have to worry about how it works, we can just use it. continuing with class Board... def getClick(self, click): ''' Find which Hole was clicked, if any ''' for hole in self.holes: if hole.isClicked(click): return hole return None Again, see the division of labor? The Board is just a container, it just works with Holes from the outside, it is the Hole that knows whether a click is in it or not. Notice how simple and self-contained each method is. This is another hallmark of good OO design. The methods that operate on data are in the same class as the data. Each class has a simple job to do; working together they get a complicated job done. I hope this helps; obviously there are many more methods to write in Board, and you will still have some kind of top-level driver that creates a board and runs a game; maybe you will discover that a Game class is useful for creating a Board, getting moves and running the game, or maybe a standalone function or two will do the job just fine. Kent PS I haven't tested any of this! From narm at go.com.jo Sat Nov 26 03:18:56 2005 From: narm at go.com.jo (Basem Narmok) Date: Sat, 26 Nov 2005 04:18:56 +0200 Subject: [Tutor] how to read a non english text file In-Reply-To: <20051125225828.74139.qmail@web30510.mail.mud.yahoo.com> References: <20051125225828.74139.qmail@web30510.mail.mud.yahoo.com> Message-ID: <4387C610.5020408@go.com.jo> enas khalil wrote: >hello everyone > still my question about if i could read and process a non english language text file using python > > Hi Enas, I think you mean Arabic language, yes of course you can, and I think you should see the Duali project: http://www.arabeyes.org/project.php?proj=Duali Duali is a simple Arabic spell checker written in Python, Duali will be a good start if you are interested in Arabic language, It will be hard if you are a newbie but try and see the code you will learn a lot. you can see a screenshot for Duali running at : http://art.arabeyes.org/duali/duali_0_1_1 What you need to learn is Unicode with Python, Duali is a very good example. Good Luck Basem Narmok From smiles at worksmail.net Sat Nov 26 04:53:28 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Fri, 25 Nov 2005 21:53:28 -0600 Subject: [Tutor] lil help please - updated (fwd) References: Message-ID: <001001c5f23f$9e742380$e62c4fca@csmith> | The logic is so good so far. However, How do we move the (...) in |H | to end of |R and before next |H Maybe you are thinking too literally about the moving of the parenthetical item from the |H to the end of the |R. Let's say you have the 3 chunks of information in variables h, f, and r: ### >>> h='This (you see) is the header.' >>> f='The Book' >>> r='cool' ### If you could break h apart into 3 pieces, the "This ", the "(you see)", and " is the header." and call them h1, h2, and h3 then you could add h1 and h3 back together (that's your new value of h) and add h2 to r as your new r: ### >>> h1='This ' >>> h2='(you see)' >>> h3=' is the header' >>> h=h1+h3 >>> r=r+'\n'+h2 #the \n puts the parenthetical on a new line >>> print h This is the header >>> print r cool (you see) ### (There's a double space left over at the place where the h1 and h3 were joined which is something you might want to fix before you add them back together. The string method ".strip() is nice for getting rid of leading and trailing space on a string. Here's an example: ### >>> print s space before and after is gone >>> print s.strip() space before and after is gone ### ) What would help maintain the spirit of the tutor list is if you would ask specific questions about problems that you are having getting the script to do what you you want or clarifications about how something is suppose to work. Right now you have a task that is defined but you are asking general questions about designing the program, not specific questions about the *python* related problems. Rather than sending or posting the script you have, why not just post the specific problems you are running into? Thanks, /c From singletoned at gmail.com Sat Nov 26 11:38:30 2005 From: singletoned at gmail.com (Ed Singleton) Date: Sat, 26 Nov 2005 11:38:30 +0100 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <000f01c5f1e8$5ced00f0$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <000f01c5f1e8$5ced00f0$0a01a8c0@xp> Message-ID: <34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com> On 25/11/05, Alan Gauld wrote: > > Just had a quick look at Smalltalk, and at first glance the overview > > of the ideas behind it seems amazing, but the language seems quite > > ugly, and it seems to be very IDE led. > > Adherents will defend its simplicity but I confess I strugglred for > a long time with SmallTalk before learning to love it :-) And yes > it is IDE led although the IDE can be 'removed' when deploying > applications. But much depends on the implementation, my favourite > for PCs is Dolphin SmallTalk from ObjectArts. Its not a traditional > SmallTalk (ala Xerox SmallTalk 80) but very much one for the '90's I'm definitely going to investigate it further, as it does seem interesting, but I remember the first time I looked into Python, I read the tutorial and was quite bemused as it didn't seem like I'd learned anything. It was all so obvious that I didn't feel there was anything to learn. As it was I was able to very quickly plunge much deeper and end up asking lots of difficult questions that in any other language you wouldn't approach for many years. > > This immediately seemed to me to be a case for classes. > > You provide a way for a user to create a new class by > > subclassing the page class (from their point of view > > probably through adding a few new fields to > > a form). > > That might be part of the problem, if you think of a class in terms > of its data attributes then that is nearly always the wrong starting > point. Classes express behaviour, the data is only there to support > the behaviour. Thats why methods are polymorphic but not attributes. If classes express behaviour, then what expresses the structure of the data? (ie what attributes there are going to be and what values they are likely to accept). You need (the option of) a data definition in order to generalise. Using my web server example from earlier, you need to be able to say that for any type of page, whatever it's attributes, you can create a web form to search for that type of page by iterating through it's attributes and creating a relevant form field for each type. > So you think of a class having an interface and users extending > or modifying the behaviour, not the data. If you follow that route > you might find you don't need to write self modifying code, > you simply load new classes with a common interface into an > existing hook structure. I definitely had the opposite in mind. The behaviours of all the classes would be the same (and would be fairly simple, a method for rendering the page with a template, a method to update the data based on a form submission). Users would basically be able to change the data structure (add and remove attributes). > > However it doesn't really seem that Python is suited to this. Indeed > > it doesn't really seem that Python is suited to a persistent > > environment. > > What makes you think that? Most persistent environments > (ie long running server processs) are written in C/C++ (or > maybe Java nowadays) which are far less dynamic than Python. I'm sure Python is quite possibly the least worst at this, but that doesn't make it good at it. > > Having a program running for a long time (months) is > > possible certainly, but it seems to be fighting against the language > > Not at all, at least no more than in languages like C which require > recoding, recompiling, stopping and then restarting the server to > make changes. Thats why a simple framework with loadable > modules it usally preferred to self modifying code! Again, I'm sure it is better than C, but I definitely have had the feeling that this is not something the language was designed for, and that not many other people seem to be trying it. Ed From kent37 at tds.net Sat Nov 26 12:56:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 26 Nov 2005 06:56:12 -0500 Subject: [Tutor] files - strings - lists In-Reply-To: References: Message-ID: <43884D5C.9040901@tds.net> Andrzej Kolinski wrote: > > OK, I made some progress I think. I added a few lines to Kent's script > to get closer what I really am after: Congratulations! See some notes below. > > ========================================== > lines = open('liga050926.sbk') # to get the data from a real file > > #lines = iter(data) # getting data from a string, you don't need this > when reading a file > > lines.next() # skip two headers > lines.next() > > header = lines.next().split() > hands = int(header[2]) > rounds = int(header[3]) > boards = hands*rounds > > lines.next() > > > allScores = {} # accumulate scores into a dictionary whose key is the name > > # Now we can process the names and scores in a loop > try: # you don't say how you know the end of the names, I just run to > the end of data > while True: > names = lines.next().strip() > player1 = names.split()[0] > player2 = names.split()[2] This could be names = lines.next().strip().split() player1 = names[0] player2 = names[2] or even player1, player2 = lines.next().strip().split(' - ') > > lines.next() # skip line after name > scores = [ int(lines.next().split()[2]) for i in range(rounds) ] > tScores = 0 > for i in scores: > iScore = float(i) > tScores = tScores + iScore This could be tScores = float(sum(scores)) > > allScores[player1] = tScores/boards > allScores[player2] = tScores/boards > > except: # no more lines > if lines.next() == '1,1': > pass I'm not sure what the two lines above are doing? It looks like you don't have a good way to detect the end of the data and you just catch some exception...you should figure out a clean way to exit the loop. Maybe when you read the names line you can look for '1,1' and break out of the loop, if that is what always follows the data you care about. > > for player1, tScores in allScores.items(): > print player1, tScores > ============================================= > 1. I singled out the players names. > 2. I added the players scores and divided by the number of boards > played. > 3. The output contents is what I wanted: > > Chrabalowski 0.875 > Kowalski -0.333333333333 > Kolinski 1.29166666667 > Bohossian 1.29166666667 > Stankiewicz -1.16666666667 > Cwir -0.708333333333 ... > > 4. The next step for me would be to read the data from more, > similar files (from 2 to 10) representing different games and generate > an average score for each participating player (a player does not > necessary plays each game and I would eventually like to calculate > averages of best six out of maximum ten games). Tough! How should I > start this next step? (I would like to keep both options open: > final ranking = (all tScores)/all boards), or > final ranking = average(RScores/boards, RScores/boards, > RScores/boards, ...) > game1 > game2 game3) I would save more data for each player. Instead of just keeping the average for the player, I would keep a list of pairs of (tScore, boards) for each game. Instead of allScores[player1] = tScores/boards you could say playerScores = allScores.get(player1, []) playerScores.append( (tScores, boards) ) allScores[player1] = playerScores all of which can be written more tersely (and obscurely) as allScores.setdefault(player1, []).append( (tScores, boards) ) Of course you need a loop to read all the files and you will initialize allScores before the loop. Then when you finish with the files you can retrieve the players' stats and process them either way you want. BTW what game is this? It seems odd that both players get the same score. > > Thanks Kent, Chris and Danny. After many, many months of using or > modifying (and using) existing scripts, with your invaluable help I feel > I can write script that is original and extremely useful to me! Glad to hear it! Kent From kent37 at tds.net Sat Nov 26 13:25:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 26 Nov 2005 07:25:04 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <000f01c5f1e8$5ced00f0$0a01a8c0@xp> <34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com> Message-ID: <43885420.6000800@tds.net> Ed Singleton wrote: >>>This immediately seemed to me to be a case for classes. >>>You provide a way for a user to create a new class by >>>subclassing the page class (from their point of view >>>probably through adding a few new fields to >>>a form). > > The behaviours of all the > classes would be the same (and would be fairly simple, a method for > rendering the page with a template, a method to update the data based > on a form submission). Users would basically be able to change the > data structure (add and remove attributes). It seems to me that rather than having a new class for each type of data, you need a class whose attributes are dynamic. I imagine you could have a list of page types, each of which has a list of attributes. A new page type is created not by defining a new class but by making a new entry in the types table. The data for a page might be as simple as just a dict, or maybe it makes sense to wrap it in a class, but the class would be the same for all pages. A page would be rendered by combining a template with the dict containing its data. Form submissions would be handled by referring to the list of attributes for the type and extracting the corresponding data. You might have a class to wrap the page data and another one to wrap the types table. These would provide operations on the contained data and be common to all types. For persistence you could take a couple of approaches. You could persist the lists and dicts directly using pickle or shelve or an object database. You could persist them in a relational database by using a generic table with one row for each data item - the columns would simply be object id, column name and data. SQLite might work very well for this as it allows multiple data types within a single column. The shift is from looking at the problem as one of dynamic classes, to one of dynamic data. Python is excellent for working with dynamic data! BTW have you looked at Django? I don't think it is quite as dynamic as you want on the model side but it has a lot of support for quickly generating a presentation of a changing model. http://www.djangoproject.com/ Kent From alan.gauld at freenet.co.uk Sat Nov 26 13:27:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 26 Nov 2005 12:27:15 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net><34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp> <34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com> Message-ID: <006d01c5f284$bc4ec190$0a01a8c0@xp> >> point. Classes express behaviour, the data is only there to support >> the behaviour. Thats why methods are polymorphic but not attributes. > >If classes express behaviour, then what expresses the structure of the > data? Why do you care? If the program behaves as you expect it what does it matter what data it uses or how. That should be hidden from you inside the classes. Worrying about data is a feature of traditional Information Modelling/Structured Analysis style programming, OOP is all about inter-communicating objects sending messages to each other, each requesting and providing services to the others. > (ie what attributes there are going to be and what values they > are likely to accept). You need to think about the objects that you pass around as part of the messages, but those obnjects are in turn accessed via messages so their structure is not important. What does matter is the relationships between the objects, and they are related by message paths not fixed data relationships. This switch in thinking is the fundamental difference between traditional and OOP design. > You need (the option of) a data definition in order to generalise. No, you need the ability to modify behaviour. Most traditional programmers think in terms of modifying behaviour in terms of big if/elif trees if obj.type == sometype doSomeTypeThing() elif obj.type == another doAnotherTypeTHing etc... Whereas in OOP you simply say obj.doThing() And the right kind of doThing will happen because obj knows how to respond to that message in the appropriate way. > Using my web server example from earlier, you need to be able to say > that for any type of page, whatever it's attributes, you can create a > web form to search for that type of page by iterating through it's > attributes and creating a relevant form field for each type. So you want, for a given page to create a Form and search. But that's behaviour of the Page, just let it create its own form and do its own searches, not your problem. Create the right kind of Page and it will do the work for you... > I definitely had the opposite in mind. The behaviours of all the > classes would be the same (and would be fairly simple, a method for > rendering the page with a template, a method to update the data based > on a form submission). Thats fair enough and the parent Page class would do just that, but the template class would have methods that the Page called, and you can subclass or data drive the templates to return the appropriate strings to the page. (Since web pages after all are just collections of strings - or evenone big string...) > Users would basically be able to change the > data structure (add and remove attributes). So maybe attributes are objects too? Maybe you page needs to know how to handle attributes and you can create pages by adding attributes from a pick list, each attribute knowing how to render itself and how to respond to searches? There are lots of ways to address this is we think of the world in terms of intercommunicating objects not static data structures with a few overeaching functions controlling it all. > I'm sure Python is quite possibly the least worst at this, but that > doesn't make it good at it. Which brings me back to my original question, what environment do you think is good at it? Are you aware of such an environment or merely wishing that such a thing could be invented? > Again, I'm sure it is better than C, but I definitely have had the > feeling that this is not something the language was designed for, > and that not many other people seem to be trying it. The language is a general purpose language like C and as such is designed to cover that type of operation, however the reason it's not generally used for long running server processes is the same reason that most of these are written in C: speed and resource usage. Server processes are usually required to run in the background, getting in the way as little as possible (think print spoolers), or to serve large numbers of clients requesting services(think databases) In the first case they need to consume as few resources as possible and in the latter they need to be low resource and very high speed. Because python is interpreted it tends to be a lot slower than C and because it needs the interpreter to be loaded in memory its also quite hih resource usage, so in that sense its not ideal for server or daemoin usage, but the language itself is as good as any other if speed/resources are not the key issues. Alan G From kent37 at tds.net Sat Nov 26 14:03:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 26 Nov 2005 08:03:43 -0500 Subject: [Tutor] Object-oriented design process In-Reply-To: <000f01c5f1e8$5ced00f0$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <000f01c5f1e8$5ced00f0$0a01a8c0@xp> Message-ID: <43885D2F.5060601@tds.net> Alan Gauld wrote: > That might be part of the problem, if you think of a class in terms > of its data attributes then that is nearly always the wrong starting > point. Classes express behaviour, the data is only there to support > the behaviour. Thats why methods are polymorphic but not attributes. > > So you think of a class having an interface and users extending > or modifying the behaviour, not the data. If you follow that route > you might find you don't need to write self modifying code, > you simply load new classes with a common interface into an > existing hook structure. I think of a class in terms of data attributes *and* behaviour. To me they are inseparable. To the client of the class, it is the behaviour that is important, but inside the class and when designing / discovering classes, I tend to look at what data I need to represent and solve a problem and what operations I need on that data and look for ways to group them together into cohesive classes. Alan, you and I have very different approaches to OO design and I don't mean to say my way is right, just an alternative! I tend to design from the bottom up - not exclusively, but in general I make small parts and combine them to make larger parts until I have something that does what I want. I refactor constantly as my understanding of a problem and the solution increase. This way I always have complete working code for some section of the problem. I rarely use stubs of any kind. To start I will take some small section of the problem and think about what kind of data and operations on the data I need to solve it. For a very simple problem I might just write some functions to operate on the data. As I expand into larger parts of the problem I might find that several functions are operating on the same data and decide that they belong in a class. Or it might be clear from the start that I want to create a class around the data. When one chunk is done to my satisfaction, I take on another, and another. I am creating building blocks, then using the building blocks to create larger blocks. Some of the blocks are classes, others are functions. I write unit tests as I go, sometimes test-first, sometimes test-after, but always alternating writing code with writing tests so I know the code works and I have a safety net when I need to refactor or make other major changes. At any time I may discover that I made a bad decision earlier, or realize that there is a better way to structure the code or data. Then I stop and rework until I am happy with what I have. The unit tests give me confidence that I haven's broken anything in the process. It's a very organic process, I sometimes think of it as growing a program. Kent From singletoned at gmail.com Sat Nov 26 21:44:34 2005 From: singletoned at gmail.com (Ed Singleton) Date: Sat, 26 Nov 2005 21:44:34 +0100 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <001601c5f1f0$29b41540$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <005001c5f13b$3367eae0$0a01a8c0@xp> <34bb7f5b0511250345r5250d826y@mail.gmail.com> <001601c5f1f0$29b41540$0a01a8c0@xp> Message-ID: <34bb7f5b0511261244t7807695ci@mail.gmail.com> On 25/11/05, Alan Gauld wrote: > > Hi Ed, > > This is a longish response because you are raising some > very interesting (and deep) issues from a computer science > point of view. > > > Well, self-modifying isn't inherently necessary. What I guess I > > really need is persistent classes as well as persistent objects. > > Python classes can be persistent just like any other object, > theres nothing intrinsically different between a class object > and any other kind of object (except that classes as objects > are kind of mind bending as a concept!) > > > I always tend to think of classes as templates for objects rather > > than factories. > > They are both. > > > In my mind, object methods are just calls to the class which > > are evaluated every time they are called. > > The methjods are function attributes of a class which are selected > by the class dispatch mechanism in response to messages sent to > instances. In Python that means the getattr() methods look up > the right method in response to receipt of a message. > > > Objects should be strict instances of classes that can't be > > modified except for the values of their attributes. > > Attributes in a pure OOP language include both the contained data > and functions. In other workds methods can be added/removed and > modified as well as the data. In fact many would argue that the > internal data not only cannot be modified externally but should not > even be seen - the Data Hiding school of thought. > > > Class Page(object): > > def print(self): > > printPage(self) > > What does that gain you? > > > And have all my methods call functions (passing on parameters as > > necessary). That way if I change a function, it will be changed for > > every instance of every object of that class. > > You mean like this: > > >>> class C: > ... def m(self): print 'm' > ... > >>> def f(o): print 'other m' > ... > >>> c = C() > >>> c.m() > m > >>> C.m = f > >>> c.m() > other m > >>> > > > And couldn't I write a function that would add functions or attributes > > to classes and objects? > > Of course, just like I did there. > > > Am I trying to use the wrong language for this? I love Python but I > > seem to keep coming up against lots of practical issues with it > > Python is a pretty good language for this kind of thing, > its just that this kind of thing is intrinsically difficult. > The only lanuages I know of which are better than Python > at it are Lisp and Smalltalk (and even Smalltalk > has some limitations compared to Python). Do you have > experience of a language which is more flexible in this regard? > I'm curious because you seem to assume that its almost > normal to be able to do these things, whereas in my > experience its usually impossible rather than just difficult... My background is in languages that are horrifically worse than python, but I'm overly demanding I guess. I think I have a good instinct for what computers should be doing for me. Everytime I'm doing something repetitious I get exasperated because I know the computer should be performing the repetitions rather than me. I had the misfortune a couple of days ago of having to knock up a couple of web pages in ASP. A very basic search form, results page and details page. I had to open up a connection to the database, open a recordset, concatenate a strings to make an SQL query, etc, etc. It was horrible. I copied and pasted a lot of the code, but even so it involved doing ridiculous amounts of unnecessary work. Maybe I'm just lazy, but then most progress has been made by people who were either curious or lazy. > > define the behaviours I want without having to bother with how the > > computer is actually going to handle them. > > Believe it or not thats been the holy grail of language > designers since the days of COBOL - The Common Business > Oriented Language - which allowed business people to > write theitr own programmes in "standard, everyday English", > like: > > PROGRAM ID - HELLO > > PROCEDURE DIVISION > MAIN-LINE-MODULE > MOVE 0 TO COUNTER > OPEN INPUT IN-FILE > PERFORM READ IN-FILE UNTIL END-OF-FILE = "YES" > ADD 1 TO COUNTER > DISPLAY "LINE NUMBER ", COUNTER > CLOSE IN-FILE > STOP RUN. > > At the time it was considered revolutionary and programmers > trembled at the prospect of instant redundancy. As it happened > your average businessman found COBOL about as readable as pigin > English! But that hasn't stopped us trying... > > One thing we have discovered is that the more natural the > language seems to get the less flexible the language gets. > Python is the closest I've seen yet to a general purpose > language that is truly readable, but thats still a long > way from being plain English! But I digress :-) I can quite imagine that natural language isn't the way forward, though I can also imagine that for business reasons readability won't be the way forward (however I do love readability). What's important is not natural language but eliminating unnecessary work and complexity. > Basically I just wonder what your background is that you > seem to expect these kind of dynamic facilities? I'd certainly > be interested in investigating it further. Maybe it's just knowing what'll be possible in 10 years time and being impatient for it. Ed From singletoned at gmail.com Sat Nov 26 23:04:22 2005 From: singletoned at gmail.com (Ed Singleton) Date: Sat, 26 Nov 2005 22:04:22 +0000 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <43885420.6000800@tds.net> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <000f01c5f1e8$5ced00f0$0a01a8c0@xp> <34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com> <43885420.6000800@tds.net> Message-ID: <34bb7f5b0511261404k38c061f8y@mail.gmail.com> On 26/11/05, Kent Johnson wrote: > Ed Singleton wrote: > >>>This immediately seemed to me to be a case for classes. > >>>You provide a way for a user to create a new class by > >>>subclassing the page class (from their point of view > >>>probably through adding a few new fields to > >>>a form). > > > > The behaviours of all the > > classes would be the same (and would be fairly simple, a method for > > rendering the page with a template, a method to update the data based > > on a form submission). Users would basically be able to change the > > data structure (add and remove attributes). > > It seems to me that rather than having a new class for each type of data, you need a class whose attributes are dynamic. I imagine you could have a list of page types, each of which has a list of attributes. A new page type is created not by defining a new class but by making a new entry in the types table. The data for a page might be as simple as just a dict, or maybe it makes sense to wrap it in a class, but the class would be the same for all pages. A page would be rendered by combining a template with the dict containing its data. Form submissions would be handled by referring to the list of attributes for the type and extracting the corresponding data. > > You might have a class to wrap the page data and another one to wrap the types table. These would provide operations on the contained data and be common to all types. > > For persistence you could take a couple of approaches. You could persist the lists and dicts directly using pickle or shelve or an object database. You could persist them in a relational database by using a generic table with one row for each data item - the columns would simply be object id, column name and data. SQLite might work very well for this as it allows multiple data types within a single column. > > The shift is from looking at the problem as one of dynamic classes, to one of dynamic data. Python is excellent for working with dynamic data! > > BTW have you looked at Django? I don't think it is quite as dynamic as you want on the model side but it has a lot of support for quickly generating a presentation of a changing model. > http://www.djangoproject.com/ >From this and what Alan said, I think I'm starting to get it. Each attribute could be an object or an entry in a list. Each type would be a collection or list of a particular set of attributes. The collection of types would be an object which is easily persisted. I could pass the type of the page as a parameter when I create it, and could have a method in the class that looks up the particular type and adds all the relevant attributes to the object with sensible default values. Adding new pagetypes would be easy enough cause they're just an entry in the types list. Can you create an object whose default action is to return a certain value? For example could I have a header object that where when you call page.header it returns a value but I can also have page.header.update(). Or (I think) I know that methods can have attributes, but can attributes have methods? I need a bit more time to sit down and think this through (I've gained a lot of information and at least a little enlightenment over the last few days), but I think this is really starting to come together. Ed From alan.gauld at freenet.co.uk Sat Nov 26 23:37:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 26 Nov 2005 22:37:57 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><005001c5f13b$3367eae0$0a01a8c0@xp><34bb7f5b0511250345r5250d826y@mail.gmail.com><001601c5f1f0$29b41540$0a01a8c0@xp> <34bb7f5b0511261244t7807695ci@mail.gmail.com> Message-ID: <001901c5f2da$0cb8d800$0a01a8c0@xp> Hi Ed, > Maybe it's just knowing what'll be possible in 10 years time and being > impatient for it. The problem is that over twenty years ago when I was at university the Japanese anounced that they would have launched a 5th generation computer language by 1990. They gave up and we are still waiting. Part of the problem is that we are familiar with how easily our brains can perform certain types of thought process so we asssume it must be easy to do on a computer. But our brains work very differently to computers and attempts to mimic the brain have so far been dismal failures. Sadly, I think 10 years will see less progress in software than you hope! Pessimistically, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From singletoned at gmail.com Sat Nov 26 23:42:15 2005 From: singletoned at gmail.com (Ed Singleton) Date: Sat, 26 Nov 2005 22:42:15 +0000 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <006d01c5f284$bc4ec190$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <000f01c5f1e8$5ced00f0$0a01a8c0@xp> <34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com> <006d01c5f284$bc4ec190$0a01a8c0@xp> Message-ID: <34bb7f5b0511261442y657ec43dp@mail.gmail.com> On 26/11/05, Alan Gauld wrote: > >> point. Classes express behaviour, the data is only there to support > >> the behaviour. Thats why methods are polymorphic but not attributes. > > > >If classes express behaviour, then what expresses the structure of the > > data? > > Why do you care? If the program behaves as you expect it what does > it matter what data it uses or how. That should be hidden from you > inside the classes. Worrying about data is a feature of traditional > Information Modelling/Structured Analysis style programming, > OOP is all about inter-communicating objects sending messages to > each other, each requesting and providing services to the others. I get this now. It goes back to what I said earlier about the "I don't care how it works" philosophy. Each object doesn't care how any other works. You could completely re-engineer the internals of an object and that would be fine as long as the interface is the same. As long as the methods and attributes keep returning sensible values then everything is fine. However, I'm still slightly uncomfortable with it. It smells to me a bit like the "as long as it works, its fine" school of thought. For my own sanity and peace of mind I like to have my data structures well defined, as at the end of the day it's the data that matters (I can rebuild functionality but data is given to me by other people and can rarely be gotten back). > > (ie what attributes there are going to be and what values they > > are likely to accept). > > You need to think about the objects that you pass around as part > of the messages, but those obnjects are in turn accessed via messages > so their structure is not important. What does matter is the > relationships between the objects, and they are related by message > paths not fixed data relationships. This switch in thinking is the > fundamental difference between traditional and OOP design. > > > You need (the option of) a data definition in order to generalise. > > No, you need the ability to modify behaviour. > Most traditional programmers think in terms of modifying > behaviour in terms of big if/elif trees > > if obj.type == sometype > doSomeTypeThing() > elif obj.type == another > doAnotherTypeTHing > etc... > > Whereas in OOP you simply say > > obj.doThing() > > And the right kind of doThing will happen because obj > knows how to respond to that message in the appropriate way. But writing a different doThing() for each object can be a huge waste of time. You want to be able to write one doThing() that is going to work on each object (of a particular type). This requires either knowing that all your objects are going to be similar in some respect, or writing a huge if..elseif as you mentioned. Even just saying every object has a doThing() is starting to create a data structure. > > Using my web server example from earlier, you need to be able to say > > that for any type of page, whatever it's attributes, you can create a > > web form to search for that type of page by iterating through it's > > attributes and creating a relevant form field for each type. > > So you want, for a given page to create a Form and search. > > But that's behaviour of the Page, just let it create its own form > and do its own searches, not your problem. Create the right > kind of Page and it will do the work for you... But then I've got to create lots of different behaviours instead of one simple generalised behaviour. > > I definitely had the opposite in mind. The behaviours of all the > > classes would be the same (and would be fairly simple, a method for > > rendering the page with a template, a method to update the data based > > on a form submission). > > Thats fair enough and the parent Page class would do just that, > but the template class would have methods that the Page called, > and you can subclass or data drive the templates to return the > appropriate strings to the page. (Since web pages after all are > just collections of strings - or evenone big string...) > > > Users would basically be able to change the > > data structure (add and remove attributes). > > So maybe attributes are objects too? Maybe you page needs > to know how to handle attributes and you can create pages by > adding attributes from a pick list, each attribute knowing how > to render itself and how to respond to searches? This combined with what Kent said, is what really solved the problem for me. > There are lots of ways to address this is we think of the world > in terms of intercommunicating objects not static data structures > with a few overeaching functions controlling it all. I've really gained a huge amount just from this one topic. Not least of which is that classes aren't necessarily a good answer to OOP problems. > > I'm sure Python is quite possibly the least worst at this, but that > > doesn't make it good at it. > > Which brings me back to my original question, what environment > do you think is good at it? Are you aware of such an environment > or merely wishing that such a thing could be invented? I know that such a thing could be invented. It's very straightforward, it's just a lot of work. If enough other people think that it would be useful then it will probably get done at some point (and I think the rise of web applications will bring it about as an inevitability). Ed From alan.gauld at freenet.co.uk Sun Nov 27 00:01:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 26 Nov 2005 23:01:05 -0000 Subject: [Tutor] Object-oriented design process References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp> <43885D2F.5060601@tds.net> Message-ID: <001d01c5f2dd$4809c060$0a01a8c0@xp> Hi Kent, >> point. Classes express behaviour, the data is only there to support >> the behaviour. Thats why methods are polymorphic but not attributes. >> >> So you think of a class having an interface and users extending >> or modifying the behaviour, not the data. > I think of a class in terms of data attributes *and* behaviour. To me > they are inseparable. To the client of the class, it is the behaviour > that is important, I was talking from the point of view of the client, although the client of one class is likely to be the internals of another! > but inside the class and when designing / discovering classes, > I tend to look at what data I need to represent and solve a > problem and what operations I need on that data I look at data when designing a class - or more specifically a method. I will naturally need some data to build a method, the data I need will be part of the class. And when I look at the totality of the methods I design the data attributes to maximise synergy between methods. But I always define the external behaviour before considering the internal data needevto provide that. > and look for ways to group them together into cohesive classes. I never use commonality of data to define a class. OK I lie, sometimes its just convenient to do it that way, but as a principle such classes are rarely extensible, they tend to be more like records in structured programming speak. > Alan, you and I have very different approaches to OO design > and I don't mean to say my way is right, just an alternative! I don;t think our results are different, (based on the code and ideas I've seen you present here), but our way of verbalising the approach is different. > I tend to design from the bottom up - not exclusively, I do top down design for the class strucure but design and build the classes from bottom up. In so doing I will of course discover new vclasses that must be slotted ito the structure. But my first cut is usually to build a framework of "abstract" classes that work together to solve the problem, then I go back filling in the methods from the bottom up, and testing each method as each slots into the abstract framework, gradually becoming more concrete as it builds. > but in general I make small parts and combine them to make > larger parts until I have something that does what I want. Me too, but in the context of a preconceived framework. > I refactor constantly as my understanding of a problem > and the solution increase. I occasionally refactor at the method level, I very occasionally refactor at the class level, but thats rare once I have the abstradt framework in place. > This way I always have complete working code for some > section of the problem. I rarely use stubs of any kind. And I have stubs for everything! So there we differ I rarely, if ever. write production methods without first testing the concept with a stub.:-) > To start I will take some small section of the problem > and think about what kind of data and operations on > the data I need to solve it. Inwill take the same approach but I will think about the objects, then I think about the responsibilities and collaborators (CRC Cards are my friends!). Then I write the abstract structure based on the CRCs and test it, if it works I go back and fill in the methods. In doing so I will discover what data I need. > For a very simple problem I might just write some functions > to operate on the data. For very simple problems I very rarely use OOP, I tend to find it most helpful when the problem gets beyond a certain size (depends on lamguage etc, but for Python around 50 -100 lines) > Some of the blocks are classes, others are functions. I've built hybrid programs occasionally but in general if a procedural approach starts to break I will tend to rework it into pure OOP rather than mix paradigms. > I write unit tests as I go, sometimes test-first, sometimes test-after, I like the idea of test first but for me it doesn't work well, but I do test on a method by method basis once past the initial framework. (The famework is tested class by class since they are only stubs). And individual classes get tested at the >>> prompt before veing tried in the framework - one of the great joys of Python is interactive testing at the >>>. > The unit tests give me confidence that I haven's broken anything > in the process. Me too, but at the method level. > It's a very organic process, I sometimes think of it as growing > a program. Yep, I agree. As I said I don;t think our end results are very far apart, we have some minor differences of approach but the focus is still on behaviour from an external point of view and data in the intenal view, I think. And so far as design goes its definitely healthy to compare and contrast approaches. Design is the truly creative bit of software engineering and its always good to know that there is more than one way to do it. And especially important to make that explicit in a tutor group like this! There are no absolutes in this game. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Nov 27 00:03:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 26 Nov 2005 23:03:34 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net><34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp><34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com><43885420.6000800@tds.net> <34bb7f5b0511261404k38c061f8y@mail.gmail.com> Message-ID: <002101c5f2dd$a0f0d880$0a01a8c0@xp> >From this and what Alan said, I think I'm starting to get it. Each > attribute could be an object or an entry in a list. Each type would > be a collection or list of a particular set of attributes. The > collection of types would be an object which is easily persisted. Absolutely! > Can you create an object whose default action is to return a certain > value? For example could I have a header object that where when you > call page.header it returns a value but I can also have > page.header.update(). Absolutely, in fact its quite normal. > Or (I think) I know that methods can have > attributes, but can attributes have methods? They can if the attributes are objects in their own right... HTH Alan G. From dyoo at hkn.eecs.berkeley.edu Sun Nov 27 00:24:07 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 26 Nov 2005 15:24:07 -0800 (PST) Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511261244t7807695ci@mail.gmail.com> Message-ID: > I had the misfortune a couple of days ago of having to knock up a couple > of web pages in ASP. A very basic search form, results page and details > page. I had to open up a connection to the database, open a recordset, > concatenate a strings to make an SQL query, etc, etc. > > It was horrible. I copied and pasted a lot of the code, but even so it > involved doing ridiculous amounts of unnecessary work. Hi Ed, I don't know how well ASP supports abstraction, but copying and pasting is usually the wrong solution: that's exactly where we should be thinking about writing functions and organizing those functions in libraries. If a block of code is being copied around, that unit of work captures some concept we have, and functions are a good way to formally capture that concept as an abstraction. We can --- and often must! --- lift ourselves up by using abstractions, or risk drowning in the tedious details. Guy Lewis Steele Jr. wrote a hilarious talk about this in "Growing a Language": http://www.brics.dk/~hosc/local/HOSC-12-3-pp221-236.pdf > > Basically I just wonder what your background is that you seem to > > expect these kind of dynamic facilities? I'd certainly be interested > > in investigating it further. > > Maybe it's just knowing what'll be possible in 10 years time and being > impatient for it. If we're chasing for a "silver bullet" in programming languages, we might wait for a very long time indeed. *grin* From photonquark at comcast.net Sun Nov 27 01:53:20 2005 From: photonquark at comcast.net (Hubert Fitch) Date: Sat, 26 Nov 2005 19:53:20 -0500 Subject: [Tutor] Scientific Notation + 18 digit precision Message-ID: <011001c5f2ed$1c5942f0$6401a8c0@hfsys3> I am using Python 2.3 under Windows XP Home edition I am too old to learn all the tricks of Python, and my main purpose is for Physics calculations I do have some questions, but perhaps my useage of Python as an Algebraic Calculator will be interesting to someone? Python is the best precision Algebraic Calculator solution that I have found so far. I like the large global space for variables. Using the Idle GUI to run .py modules, I can then use direct mode calculations in the Python shell, after I have defined a large list of variables by global assignment statements. For my purposes, this requires about 7 .py definition modules, which all accumulate these assignments as keys and data, within the scope of the calling Python script. The most important module is the first one which enters a lot of physical constants. I am not ready to begin any new module or calculation unless all the needed physical constants and derived variables are present within the scope of my calling program. Example of a Calling Script .py file ("NoPrintParameters.py"): The purpose of this file is to enter Physical data variables and values, and assignment formulas that define new variables, (without printing anything to the Shell Screen, unless I decide to do so in the following Display Section. To accomplish this, I have two similar function modules that I call: A Display Module Function, and a RunModule Function. (The Display Function was written for me by the head of our Physics Deparment, and I adapted it to create the Run Module Function) The display function operates on each line in the .py file and provides 4 formatted columns for: Variable Name, Data (18 digits ), Assignment Formula, and Comments. (After All this data is on screen I can "Save Copy As" to RTF file format, which prreserves the Shell window formatted data. (Saving in Word document files or Text files will not preserve the formatted data). The Run Module Function exectues all assignments, but no display is produced in the Shell screen. This is necessary to get all assignments within global memory. (As each new Python module was created, and ran for the first time, I always hoped to see only the Idle GUI blue screen characters, but usually I get some undefined variable errors. It is fun to finally get all of these errors resolved! There is so much going on, as the modules run, and I am always amazed that they really work!)) # # IMPORT DISPLAY FUNCTION from displayPyFile import DisplayPyFile # # IMPORT RUN MODULE FUNCTION (No Display) from runPyModule import RunModule # # --------------------------------------------------- # Load and Run Files (No Display) # ---------------------------------------------------# # RUN Main DEFINITION FILE (NO DISPLAY) RunModule ('pythondef.py',globals() ) # RUN Other DEFINITION FILEs (NO DISPLAY) RunModule ('R1Parameters.py',globals() ) RunModule ('R0Parameters.py',globals() ) RunModule ('R10Parameters.py',globals() ) RunModule ('R2Parameters.py',globals() ) RunModule ('R3Parameters.py',globals() ) RunModule ('deBroglieRelativistic.py',globals() ) # # ------------------------------------------------------ # DISPLAY LINES in: # ----------------------------------------------------- #DisplayPyFile ('pythondef.py',globals() ) #DisplayPyFile ('R1Parameters.py',globals() ) #DisplayPyFile ('R0Parameters.py',globals() ) #DisplayPyFile ('R10Parameters.py',globals() ) #DisplayPyFile ('R2Parameters.py',globals() ) #DisplayPyFile ('R3Parameters.py',globals() ) # #DisplayPyFile ('Section1.py',globals() ) #DisplayPyFile ('ClassicalSelfForces.py',globals() ) #DisplayPyFile ('Definitions.py',globals() ) # DisplayPyFile ('Topics.py',globals() ) #DisplayPyFile ('deBroglieRelativistic.py',globals() ) # # As you can see, I can display any (or all) modules by deleting the # comment character, however in this example, the only file that will produce screen output is "Topics.py" I could remove all the # characters, to display all .py file definitions, but that would be too much data to see at once. The main point of all the defintiion files is to be able to make direct mode calculations in the Python Shell, and to be able to write shorter scripts for a series of calculations which use these definitions. Many assignments are execution order sensitive. The next assignment formula depends on the previous assignments. Now for the questions: Most data and results are displayed properly formatted in scientific notation, but sometimes large numbers resulting from calculations are not converted to scientific notation. For example: mu0*I0/r0 = 1209755258303.6067 (should have been 1.2097552583036067e+012). I must then count about 7 or about 15 digits to detrmine how many places to the left to manuually move the decimal point, and manually add the e+012. Why does Python sometimes do this? Is there an easy way to convert these large numbers to the scientific notation format? Can we write a function call that I could use to convert the numbers to scientific notation whenever I need to do so from the Python shell in direct mode? Or called from a Python script file, when I already know in advance what Python will do? Another perhaps related thing is the way exact numbers like light speed = C (or C/2) are presented ( C = 299792458 ). And sometimes I get an incorrect result for integer calculations. This does not happen very often, but it worries me that it may happen when I don't know about it. A calculation involving integers will sometimes give an unexpected zero result. I wonder if this is caused by the GUI IDLE interpreter? Does the interpreter check all calculation results to see if they have been converted to scientific format? Thank you for any help. photonquark -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051126/d8cb789e/attachment.html From kent37 at tds.net Fri Nov 25 02:40:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 24 Nov 2005 20:40:41 -0500 Subject: [Tutor] files - strings - lists In-Reply-To: References: Message-ID: <43866B99.1030704@tds.net> Andrzej Kolinski wrote: > > OK, I made some progress I think. I added a few lines to Kent's script > to get closer what I really am after: Congratulations! See some notes below. > > ========================================== > lines = open('liga050926.sbk') # to get the data from a real file > > #lines = iter(data) # getting data from a string, you don't need this > when reading a file > > lines.next() # skip two headers > lines.next() > > header = lines.next().split() > hands = int(header[2]) > rounds = int(header[3]) > boards = hands*rounds > > lines.next() > > > allScores = {} # accumulate scores into a dictionary whose key is the name > > # Now we can process the names and scores in a loop > try: # you don't say how you know the end of the names, I just run to > the end of data > while True: > names = lines.next().strip() > player1 = names.split()[0] > player2 = names.split()[2] This could be names = lines.next().strip().split() player1 = names[0] player2 = names[2] or even player1, player2 = lines.next().strip().split(' - ') > > lines.next() # skip line after name > scores = [ int(lines.next().split()[2]) for i in range(rounds) ] > tScores = 0 > for i in scores: > iScore = float(i) > tScores = tScores + iScore This could be tScores = float(sum(scores)) > > allScores[player1] = tScores/boards > allScores[player2] = tScores/boards > > except: # no more lines > if lines.next() == '1,1': > pass I'm not sure what the two lines above are doing? It looks like you don't have a good way to detect the end of the data and you just catch some exception...you should figure out a clean way to exit the loop. Maybe when you read the names line you can look for '1,1' and break out of the loop, if that is what always follows the data you care about. > > for player1, tScores in allScores.items(): > print player1, tScores > ============================================= > 1. I singled out the players names. > 2. I added the players scores and divided by the number of boards > played. > 3. The output contents is what I wanted: > > Chrabalowski 0.875 > Kowalski -0.333333333333 > Kolinski 1.29166666667 > Bohossian 1.29166666667 > Stankiewicz -1.16666666667 > Cwir -0.708333333333 ... > > 4. The next step for me would be to read the data from more, > similar files (from 2 to 10) representing different games and generate > an average score for each participating player (a player does not > necessary plays each game and I would eventually like to calculate > averages of best six out of maximum ten games). Tough! How should I > start this next step? (I would like to keep both options open: > final ranking = (all tScores)/all boards), or > final ranking = average(RScores/boards, RScores/boards, > RScores/boards, ...) > game1 > game2 game3) I would save more data for each player. Instead of just keeping the average for the player, I would keep a list of pairs of (tScore, boards) for each game. Instead of allScores[player1] = tScores/boards you could say playerScores = allScores.get(player1, []) playerScores.append( (tScores, boards) ) allScores[player1] = playerScores all of which can be written more tersely (and obscurely) as allScores.setdefault(player1, []).append( (tScores, boards) ) Of course you need a loop to read all the files and you will initialize allScores before the loop. Then when you finish with the files you can retrieve the players' stats and process them either way you want. BTW what game is this? It seems odd that both players get the same score. > > Thanks Kent, Chris and Danny. After many, many months of using or > modifying (and using) existing scripts, with your invaluable help I feel > I can write script that is original and extremely useful to me! Glad to hear it! Kent From kent37 at tds.net Sun Nov 27 03:16:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 26 Nov 2005 21:16:16 -0500 Subject: [Tutor] Scientific Notation + 18 digit precision In-Reply-To: <011001c5f2ed$1c5942f0$6401a8c0@hfsys3> References: <011001c5f2ed$1c5942f0$6401a8c0@hfsys3> Message-ID: <438916F0.3020005@tds.net> Hubert Fitch wrote: > Now for the questions: > > Most data and results are displayed properly formatted in scientific > notation, but sometimes large numbers resulting from calculations are > not converted to scientific notation. > > For example: mu0*I0/r0 = 1209755258303.6067 (should have > been 1.2097552583036067e+012). > > Is there an easy way to convert these large numbers to the scientific > notation format? Can we write a function call that I could use > to convert the numbers to scientific notation whenever I need to do so > from the Python shell in direct mode? You can use string formatting to get closer control of the way numbers print. For example: >>> x= 1209755258303.6067 >>> x 1209755258303.6067 >>> '%e' % x '1.209755e+012' See the docs for details: http://docs.python.org/lib/typesseq-strings.html > And sometimes I get an incorrect result for integer calculations. This > does not happen very often, but it worries me that it may happen when I > don't know about it. A calculation involving integers will sometimes > give an unexpected zero result. Do you know that integer division is truncated? For example >>> 3/4 0 You can fix this by making sure one of the operands is a float: >>> 3.0 / 4 0.75 Future versions of Python will do this for you. You can enable it by this import: >>> from __future__ import division >>> 3/4 0.75 Kent -- http://www.kentsjohnson.com From kent37 at tds.net Sun Nov 27 04:21:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 26 Nov 2005 22:21:07 -0500 Subject: [Tutor] Object-oriented design process In-Reply-To: <001d01c5f2dd$4809c060$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp> <43885D2F.5060601@tds.net> <001d01c5f2dd$4809c060$0a01a8c0@xp> Message-ID: <43892623.8050807@tds.net> Alan Gauld wrote: > I never use commonality of data to define a class. OK I lie, sometimes > its just convenient to do it that way, but as a principle > such classes are rarely extensible, they tend to be more like records in > structured programming speak. Very few of my classes are ever extended with subclasses. I don't like to make classes that are just data containers, but I find that when I do make a class like that, I often find some behaviour to go with it. Usually pretty quickly :-) and then I have a real class that is pulling it's weight. > I do top down design for the class strucure but design and build the > classes from bottom up. In so doing I will of course discover new > vclasses that must be slotted ito the structure. But my first cut is > usually to build a framework of "abstract" classes that work together to > solve the problem, then I go back filling in the methods from the bottom > up, and testing each method as each slots into the abstract framework, > gradually becoming more concrete as it builds. I guess I have an idea of where I am going, what the eventual pieces will be, but I don't generally build any kind of framework in advance and I don't use many abstract classes. I think you work at a much larger scale (of program size) than I do, that may be one reason for the different approach. Most of my programs are small or medium size, I'm not sure I have ever worked on a project I would really call large. > I occasionally refactor at the method level, I very occasionally > refactor at the class level, but thats rare once I have the abstract > framework in place. I refactor constantly. I think of it as building the framework as I go, letting it emerge from the code. When I am done I often have a very highly tuned, application-specific framework, but I didn't imagine it from the start, I evolve it as I develop the overall solution. > Inwill take the same approach but I will think about the objects, then I > think about the responsibilities and collaborators (CRC Cards are my > friends!). Then I write the abstract structure based on the CRCs and > test it, if it works I go back and fill in the methods. In doing so I > will discover what data I need. I sometimes use something like CRC cards. How do you test the abstract structure? With stubs and mock objects? >> Some of the blocks are classes, others are functions. > > I've built hybrid programs occasionally but in general if a procedural > approach starts to break I will tend to rework it into pure OOP rather > than mix paradigms. I don't have any problem mixing. The procedural parts are usually low-level utility functions or high-level drivers. I just do what seems to work best for each part of the problem. > >> I write unit tests as I go, sometimes test-first, sometimes test-after, > > > I like the idea of test first but for me it doesn't work well, but I do > test on a method by method basis once past the initial framework. (The > famework is tested class by class since they are only stubs). And > individual classes get tested at the >>> prompt before veing tried in > the framework - one of the great joys of Python is interactive testing > at the >>>. I do very little of this. For me the problem with testing at the >>> prompt is that the tests aren't captured. By writing the tests as unit tests, they are run repeatedly. When I change the implementation of a class I can re-run the tests and be pretty confident I haven't broken anything. If my original tests were interactive I have to remember how I tested and run them again by hand. Kent -- http://www.kentsjohnson.com From smiles at worksmail.net Sun Nov 27 05:20:25 2005 From: smiles at worksmail.net (Chris or Leslie Smith) Date: Sat, 26 Nov 2005 22:20:25 -0600 Subject: [Tutor] Scientific Notation + 18 digit precision References: Message-ID: <002601c5f309$f9e9ee00$cd2c4fca@csmith> | The display function operates on each line in the .py file and | provides 4 formatted columns for: | Variable Name, Data (18 digits ), Assignment Formula, and Comments. | There are a couple of recipes at ASPN that might be useful with table generation: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302380 [x] | Now for the questions: | | Most data and results are displayed properly formatted in scientific | notation, but sometimes large numbers resulting from calculations are | not converted to scientific notation. | | For example: mu0*I0/r0 = 1209755258303.6067 (should have been | 1.2097552583036067e+012). | Apparently python doesn't agree ;-) Part of the answer has to do with how you show the result and part has to do with the size of the number. There are two representations of the number that are possible, str() and repr(). Here's a sample of both using your number: ###### >>> n=1209755258303.6067 >>> print n 1.2097552583e+012 >>> print str(n) 1.2097552583e+012 >>> print repr(n) 1209755258303.6067 >>> n 1209755258303.6067 >>> n=n*10**5 >>> n 1.2097552583036066e+017 ###### As you can see, even the repr() form of the number eventually is too large to display in non-exponential form.. How were you displaying the value to the screen? | I must then count about 7 or about 15 digits to detrmine how many | places to the left to manuually move the decimal point, and manually | add the e+012. Why does Python sometimes do this? | | Is there an easy way to convert these large numbers to the | scientific notation format? Can we write a function call that I could | use to convert the numbers to scientific notation whenever I need to | do so from the Python shell in direct mode? If you check the python language reference section on "String Formatting Operations" that will show you that you can use a format to create the desired number representation. If you want exponential, the %e is the format you want: ###### >>> for i in range(1,17,3): ... fmt='%%.%ie' % i ... print fmt,'\t', fmt % n ... %.1e 1.2e+012 %.4e 1.2098e+012 %.7e 1.2097553e+012 %.10e 1.2097552583e+012 %.13e 1.2097552583036e+012 %.16e 1.2097552583036067e+012 ###### So if you want 17 places after the decimal try print "%.17e" % n | Another perhaps related thing is the way exact numbers like light | speed = C (or C/2) are presented ( C = 299792458 ). | It's not clear what the problem is here. Can you clarify? | And sometimes I get an incorrect result for integer calculations. | This does not happen very often, but it worries me that it may happen | when I don't know about it. A calculation involving integers will | sometimes give an unexpected zero result. Watch out for the truncated division (presently the default for python). There's a nice write up at http://www.ferg.org/projects/python_gotchas.html (see section 3). Either convert one of the numbers to float or import the future behavior as described in the link above. ###### >>> 2/3 0 >>> float(2)/3 0.66666666666666663 >>> from __future__ import division >>> 2/3 0.66666666666666663 >>> 2//3 #with the future behavior in effect, the truncated division is obtained with // 0 ###### /c From alan.gauld at freenet.co.uk Sun Nov 27 10:03:08 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 27 Nov 2005 09:03:08 -0000 Subject: [Tutor] Modifying Source Code while Program is Running References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net><34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp><34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com><006d01c5f284$bc4ec190$0a01a8c0@xp> <34bb7f5b0511261442y657ec43dp@mail.gmail.com> Message-ID: <003701c5f331$63066e00$0a01a8c0@xp> > However, I'm still slightly uncomfortable with it. It smells to me a > bit like the "as long as it works, its fine" school of thought. FRom the client point of view thats true, but from the class designers point of view its very important that the internals be we well designed. And that includes how the internal objects and ultimately data are represented, but its a much smaller (and therefore easier) problem than trying to solve the total data picture. In this regard objects are an abstraction layer on top of the data, we focus on the entities and let the fields take care of themselves (or let the entity designers do it for us!)... > defined, as at the end of the day it's the data that matters Only at one level. You are right that the inputs and outputs of a program will be expressed in terms of data, but the program itself is an expression of behaviour. If I feed this in you transform it to that out. You can feed the data in as one big tuple ands feed it out in the same way, what happens to it in between is not important so long as the output is correctly matched to the input. > data is given to me by other people and can rarely be gotten back). The trick is not to change the inpuit data but to generate new output from the input. This is standard functional programming practice and good to apply in procedural, OOP or functional programming styles. >> Whereas in OOP you simply say > >> obj.doThing() >> > But writing a different doThing() for each object can be a huge waste > of time. You want to be able to write one doThing() that is going to > work on each object (of a particular type). This requires either > knowing that all your objects are going to be similar in some respect, > or writing a huge if..elseif as you mentioned. On the contrary its nearly alwys more efficient to write a separate function that gets called polymorphically than have long if/else chains. Not least because: a) you wind up with lots of if/else chains - one for every invocation of the polymorphic method b) the if/elif chains become a big maintenance headache requiring a revisit to each one every time you introduce a new type c) the invoking function becomes vulnerable to changes in the internals of the called objects, introducing high levels of coupling which is "a bad thing" Avoiding these kinds of chained if/else structures is one of the primary goals of good OO design, and one of the biggest improvements in reliability and readability brough about by OOP. But it does require a wee bit of faith initially to trust it! :-) However the many functions are not as bad as they sound because you don't have to write the whole function out again, only the differences. For example: class C: # some data bits here... def doit(self) # process the data bits pass class D(C): # some new data bits here def doit(self): C.doit(self) # get C to do its bits first # process my data bits pass class E(D): # data def doit(self): D.doit(self) # do my data bits pass So each subclass only has to process its own data and call the superclass method. The superclass call can be at the start, end or in the middle of the method - in Lisp terms this is called BEFORE, AFTER and AROUND methods... And if you think about it the data all has to be handled anyway so the extra lines of code is actually very few, much fewer than the accumulation of multiple if/else chains, and much easier to maintain because each object is responsible for its own data and nobody elses! > Even just saying every object has a doThing() is starting > to create a data structure. No its creating a behaviour structure, the two things are very different. Data structures are by definition static, behavour stuctures are dynamic. It is the difference between static data structures and dynamic behaviour structures that gives OOP its power. Every time you rely on a static data structure within an object you are limiting its ability to be reused. >> But that's behaviour of the Page, just let it create its own form >> and do its own searches, not your problem. Create the right >> kind of Page and it will do the work for you... > > But then I've got to create lots of different behaviours instead of > one simple generalised behaviour. Correct, thats what OOP is all about, lots of very short simple, (and thus reliable) methods. But you can parameterise them but often thats doine by passing other objects with their own behaviour. Thus class C: def meth(self, startObj, endObj) startObj.doit() doSomeOtherStuff() endObj.finish() So by passing in different objects we can completely change the behaviour of meth, but not by relying on data just passing in the objects we are working with andletting them do whatever it is they do... > > So maybe attributes are objects too? Maybe you page needs >> to know how to handle attributes and you can create pages by >This combined with what Kent said, is what really solved the problem for >me. Yes, you do have to keep stopping and asking "should this be an object?" Of course you can go too far and make everything an object until you wind up recreating the wheel (or the string, int etc). Part of the challenge of OOP is to know when you've hit the bottom of the tree! Picking up Kent's message about refactoring, my approach tends to mean I more often refactor by combining classes into a higher level one, or reverting a class to a native data type than I do by breaking a class into smaller pieces. Most folks tend to mean the opposite direction when they say refactor - breaking a class or method out into two. > I've really gained a huge amount just from this one topic. Not least > of which is that classes aren't necessarily a good answer to OOP > problems. Well classes are pretty essential! But thinking about the right granularity is important, and that classes should be as small as possible, but no smaller... > I know that such a thing could be invented. It's very > straightforward, it's just a lot of work. The problem is its not straightforward at all. People have been trying to build such dynamic environments for the last 50 years. Millions(BIllions?) of dollars have been spent and untold manhours but its very very difficult. As someone who once spent 5 years on a project trying to do something similar, working with some very clever people, I've come to the conclusion that it will take a radical change in the way we build computers before that kind of environment is truly available. But I'd love to be proved wrong! :-) Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Nov 27 10:13:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 27 Nov 2005 09:13:23 -0000 Subject: [Tutor] Scientific Notation + 18 digit precision References: <011001c5f2ed$1c5942f0$6401a8c0@hfsys3> Message-ID: <004301c5f332$d184c1a0$0a01a8c0@xp> > Is there an easy way to convert these large numbers to the scientific > notation format? The numbers are, of course, stored in binary so the real question is: can we *display* them in scientific format? The answer is yes using string format operators. Try playing with the %e and %g options: >>> val = 123456789453286432976.5309764 >>> print "%e" % val >>> print "%g" % val >>> print "%E" % val >>> print "%G" % val You can also control how many decimal places are displayed too >>> print "%.4" % val And the total number of digits, and the justification. Well worth browsing the documentation on string formatting. There are also ways of getting engineering notation (ie the powers are multiples of 3, but I've forgotten for now how that's done!) HTH Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Nov 27 11:13:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun, 27 Nov 2005 10:13:23 -0000 Subject: [Tutor] Object-oriented design process References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp><43885D2F.5060601@tds.net> <001d01c5f2dd$4809c060$0a01a8c0@xp> <43892623.8050807@tds.net> Message-ID: <005501c5f33b$331f8190$0a01a8c0@xp> > I think you work at a much larger scale (of program size) than I do That's probably true. My day job is as a systems architect/designer, most of the real coding is done by development teams scattered across the country. I use Python to prove the concepts of my design before converting it into Java speak for the real work An average project for me involves about 3 months of architecture/design generating maybe 5 or 6 workpackages given to different teams, each of which will comprise between 10 and 50 programmers, so total team size will be around 200-400 developers/testers and produce around 2 million line of Java code over a year or so. I used to think that was normal but I've discovered that in fact most folks are working on a much smaller scale. [My current project is the biggest yet - it will have around 2000 engineers working over 5 years and I've no idea how many millions of lines we will produce! Even the design team is over 50 people and the requirements team has over 30... The project office hasonlybeen set up but already has about a dozen planners etc It's a bit scary, but thankfully the senior archiects have worked on similar sized jobs in the past - and succeeded!...] > ave ever worked on a project I would really call large. The smallest real project I've ever worked on was 7 developers for 4 months - around 50,000 lines of C++ - it was my first C++ program and my first Unix project! >> individual classes get tested at the >>> prompt before veing tried in the >> framework - one of the great joys of Python is interactive testing at the >> >>>. > > I do very little of this. For me the problem with testing at the >>> > prompt is that the tests aren't captured. True, but I rely on my formal testing for that, but I do like being able to just instantiate a class and fire stuff into it to get instant feedback. [ Maybe it comes from being brought up in an environment wher we had to send our programmes down the wire and get printouts back 3 days later .... the joy of instant feedback is too much to ignore! :-) ] Alan G. From ldapguru at yahoo.com Sun Nov 27 11:54:55 2005 From: ldapguru at yahoo.com (Alan) Date: Sun, 27 Nov 2005 04:54:55 -0600 Subject: [Tutor] lil help Booky.py - updated (Chris or Leslie Smith) In-Reply-To: Message-ID: Smile Thanks #I am sorry I had bad cold #I am back I totally agree with you, I am sorry I was engrossed with the 150 lines of code Now I am attempting to address this booky.py script with your all help to clean the text Input Filename1.txt : 00001|H A quote this is a cool python coders (some of them know Java and c++) lucky them thereby they united the universe |F dollar sore book of the year |R nice 00007|H C qoute this is a cool Java group coders, they live San Jose at sun car parking lot all what they afraid of is the sun network (this is a dog outside |S Title I love the Canyon the door) in sun main building |F Santa Fe Flea Market book of the year |R very nice 00005|H B qoute this is a cool COBOL group of coders, they are loved by IBM some of them are trying to learn visual COBOL |F Good morning America book of the year |R bad Expected output Filename2.txt |H00001 A quote this is a cool python coders lucky them thereby they united the universe |F00001 dollar sore book of the year |R00001 nice (some of them know Java and c++) |H00002 C qoute this is a cool Java group coders, they live San Jose at sun car parking lot all what they afraid of is the sun network in sun main building |F00002 Santa Fe Flea Market book of the year |R00002 very nice (this is a dog outside the door) |H00003 B qoute this is a cool COBOL group of coders, they are loved by IBM some of them are trying to learn visual COBOL |F00003 Good morning America book of the year |R00003 bad #!c:\python42 # script Name: Booky # Date: 11/05 # Author: Python's good fellows # # requirements: # read Filename1.txt and produce filename2.txt and perhaps finemame3.txt as small test having accomplised the following: # 1. sorted by H statement # 2. numbereing |H |F |R # 3. () relocated from |H to after |R # 4. each statement united is only one line] # 5. disregard any "|" following by other than |H |F |R such as |S Title I love the Canyon # # # Abstract: # 1. consider remove all line feed, enter, etc from the whole file # 2. split by | to generate one line per | # 4. disregard (kill) any line having | which is not followed by H, F or R # 3. constuct regular expression to find between |H and next | any (words) # even if it is in multi line layout # 4. replace the (words) by one space and relocate (words) to the end of |R just before next |H # 5. sort each set (H F R) by |H statement # 6. renamber all sets (H F R) # done # match, search, findall or findliter import re import sys filename1 = "filename1.txt" filename2 = "filename2.txt" filename3 = "filetest1.txt" f1= open(filename1, "r") f2= open(filename2, "w") f3= open(filetest3, "w") # small test file to check the output f3= open(filename1, "r+w") reg1=re.compile('\(.*' , re.IGNORECASE) reg2=re.compile('.*\)' , re.IGNORECASE) #or: leftq=re.compile('\(\d+\s+\w+' , re.IGNORECASE) rightq=re.compile('\d+\s+\w+\)' , re.IGNORECASE) for searchstring in f1.readlines(): # which one is best match1 = reg1.match(searchstring) match2 = reg2.match(searchstring) search1 = reg1.search(searchstring) search2 = reg2.search(searchstring) findall1 = reg1.findall(searchstring) findall2 = reg2.findall(searchstring) finditer1=reg1.finditer(searchstring) finditer2=reg2.finditer(searchstring) if match1: print "Match 1 leftq:\t" , match1.group() if match2: print "Match 2 rightq:\t" , match2.group() else: print "No match" if search1: print "Match 3 leftq:\t" , search1.group() else: print "No match" if search2: print "Match 4 rightq:\t" , search2.group() else: print "No match" if findall1: print "Match 5 leftq:\t" , findall1.group() else: print "No match" if findall2: print "Match 6 rightq:\t" , findall2.group() else: print "No match" if finditer1: for i in finditer1: print i.group() else: print "no finditer match" if finditer2: for i in finditer1: print i.group() else: print "no finditer match" # use sub to remove () from |H # whole = (leftq + rightq) # whole = sub("whole", ' ') # Unlite () and relocate # Use Smile's multilines post tomake one line of whole # for searchstring in f1.readlines(): # line1 = reg1 # line2 = reg2 # multinines # sub (multilines, (reg1 + reg2) # use the test file to check the output # f3.writelines(searchstrings) # small test file to check the output # if the output is Ok then we write to f2 or f1 r+w # f2.writelines(searchstrings) # how do we write original file + changes # in progress Message: 8 Date: Fri, 25 Nov 2005 21:53:28 -0600 From: "Chris or Leslie Smith" Subject: Re: [Tutor] lil help please - updated (fwd) To: Message-ID: <001001c5f23f$9e742380$e62c4fca at csmith> Content-Type: text/plain; charset="iso-8859-1" | The logic is so good so far. However, How do we move the (...) in |H | to end of |R and before next |H Maybe you are thinking too literally about the moving of the parenthetical item from the |H to the end of the |R. Let's say you have the 3 chunks of information in variables h, f, and r: ### >>> h='This (you see) is the header.' >>> f='The Book' >>> r='cool' ### If you could break h apart into 3 pieces, the "This ", the "(you see)", and " is the header." and call them h1, h2, and h3 then you could add h1 and h3 back together (that's your new value of h) and add h2 to r as your new r: ### >>> h1='This ' >>> h2='(you see)' >>> h3=' is the header' >>> h=h1+h3 >>> r=r+'\n'+h2 #the \n puts the parenthetical on a new line print h This is the header >>> print r cool (you see) ### (There's a double space left over at the place where the h1 and h3 were joined which is something you might want to fix before you add them back together. The string method ".strip() is nice for getting rid of leading and trailing space on a string. Here's an example: ### >>> print s space before and after is gone >>> print s.strip() space before and after is gone ### ) What would help maintain the spirit of the tutor list is if you would ask specific questions about problems that you are having getting the script to do what you you want or clarifications about how something is suppose to work. Right now you have a task that is defined but you are asking general questions about designing the program, not specific questions about the *python* related problems. Rather than sending or posting the script you have, why not just post the specific problems you are running into? Thanks, /c --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.778 / Virus Database: 525 - Release Date: 10/15/2004 From photonquark at comcast.net Sun Nov 27 13:27:07 2005 From: photonquark at comcast.net (Hubert Fitch) Date: Sun, 27 Nov 2005 07:27:07 -0500 Subject: [Tutor] Scientific Notation + 18 Digit Precision Message-ID: <016601c5f34d$e427eba0$6401a8c0@hfsys3> Thanks to all of you (Alan, Chris, Kent) for your responses! Before I try to follow up on these suggestions, it might be good to examine the display function module, and provide a few lines from a .py module that needs display. Typical lines in a defintion module, that need a formatted display : (All referenced symbols in this module are previously defined in another module) # ------------------------------------------------------------------------------------------------------------------- # VARIABLE NAME, DATA , ASSIGNMENT FORMULA, COMMENT # ------------------------------------------------------------------------------------------------------------------- # # INDUCTANCE L0 = pi*mu0*r0 # Classical Inductance # CAPACITANCE c0 = 4*pi*ep0*r0 # Classical Cpacitance n = 2 # Quantum Number # RADIUS r3 = (r0*(n/a)**2 ) # Bohr radius # ORBIT VELOCITY v3 = Q0**2/(2*h*ep0*n) # Bohr Orbit Velocity v = a*C/n # Bohr Orbit Velocity v3 = v # Bohr Orbit Velocity g3 = (1-v3**2/C**2)**-0.5 # Gamma # FREQUENCY f3 = g3*m0*v3**2/h # Bohr Orbit deBroglie frequency --------------------------------------------------------------------------------------------- Most of the formatted results are already provided in the correct form. What should be changed in this display function module? ----------------------------------------------------------------------------------------------------------------- Display Function Module: (Written by Dr. Steve Spiklemire, Physics Dept Head Universtiy of indianapolis) ----------------------------------------------------------------------------------------------------------------- def DisplayPyFile(fname, context=None): if context is None: context = globals() f = open(fname) lines = f.readlines() f.close() for line in lines: line = line.strip() if not line: continue leftAndRight = line.split('#',2) comment = '' if len(leftAndRight)>1: comment = leftAndRight[1] assignment = leftAndRight[0] leftAndRight = assignment.split('=') if len(leftAndRight) == 2: name = leftAndRight[0].strip() exec(assignment, context) if context.get(name,None) is not None: value = context.get(name,'???') print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) else: print "%s not defined. %s" % (name, assignment) else: print line ----------------------------------------------------------------------------------------------------------------------------- Hubert -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051127/52fa26a6/attachment.htm From kent37 at tds.net Sun Nov 27 13:49:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 27 Nov 2005 07:49:04 -0500 Subject: [Tutor] Object-oriented design process In-Reply-To: <005501c5f33b$331f8190$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp><43885D2F.5060601@tds.net> <001d01c5f2dd$4809c060$0a01a8c0@xp> <43892623.8050807@tds.net> <005501c5f33b$331f8190$0a01a8c0@xp> Message-ID: <4389AB40.4000708@tds.net> Alan Gauld wrote: >> I think you work at a much larger scale (of program size) than I do > > That's probably true. > > An average project for me involves about 3 months of architecture/design > generating maybe 5 or 6 workpackages given to different teams, each of > which will comprise between 10 and 50 programmers, so total team size > will be around 200-400 developers/testers and produce around 2 million > line of Java code over a year or so. I used to think that was normal but > I've discovered that in fact most folks are working on a much smaller > scale. Yes, that's definitely larger than what I do! I can see why you need to think through the architecture more than I do. > The smallest real project I've ever worked on was 7 developers for 4 > months - around 50,000 lines of C++ - it was my first C++ program and my > first Unix project! Most of my projects are completed by 1-4 programmers in 3-6 months. The smallest real project I can think of took me about 2-4 weeks working by myself :-) Kent -- http://www.kentsjohnson.com From kent37 at tds.net Sun Nov 27 13:57:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 27 Nov 2005 07:57:00 -0500 Subject: [Tutor] Refactoring In-Reply-To: <003701c5f331$63066e00$0a01a8c0@xp> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com><4385EF32.8070606@tds.net><34bb7f5b0511250311o2d85581dk@mail.gmail.com><000f01c5f1e8$5ced00f0$0a01a8c0@xp><34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com><006d01c5f284$bc4ec190$0a01a8c0@xp> <34bb7f5b0511261442y657ec43dp@mail.gmail.com> <003701c5f331$63066e00$0a01a8c0@xp> Message-ID: <4389AD1C.4090308@tds.net> Alan Gauld wrote: > Picking up Kent's message about refactoring, my approach tends to > mean I more often refactor by combining classes into a higher level one, > or reverting a class to a native data type than I do by breaking a class > into smaller pieces. Most folks tend to mean the opposite direction > when they say refactor - breaking a class or method out into two. Hmm, refactoring is so much more than that. Common refactorings for me are extracting common code to a new function or method, moving an attribute or method from one class to another, changing a functional interface to an object-based one, changing the signature of a method, extracting a base class (OK, I do use base classes sometimes ;) There is a catalog of refactorings here: http://www.refactoring.com/catalog/index.html and I recommend Martin Fowler's book to anyone who hasn't read it: http://martinfowler.com/books.html#refactoring Kent From falcon3166 at hotmail.com Sun Nov 27 20:00:47 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 27 Nov 2005 12:00:47 -0700 Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? Message-ID: Hey all, Is it a good idea to use TKInter to change my password program into a GUI? I know it needs improvements, and I've noted them below: [code] #This is for a password protected program to store passwords. import getpass password = "hello" # This should instead load a file with the password in it. sitelist = {} def load_file(pw): import os filename = 'passcard.txt' # Weak, because any text file editor can read the usernames and passwords! if os.path.exists(filename): store = open(filename,'r') for line in store: site = line.strip() ID = store.next().strip() pw[site] = ID else: store = open(filename,'w') # create new empty file store.close() def save_file(pw): store = open('passcard.txt',"w") for site,ID in sitelist.items(): store.write(site + '\n') store.write(ID + '\n') store.close() def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "9) Save and Exit" def add_site(): print "Add a login info card" site = raw_input("Site: ") ID = raw_input("User ID and passcard, seperated by a space: ") # seperated should be spelt separated. sitelist[site] = ID def lookup_site(): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print site,sitelist[site] else: print site," was not found." def remove_site(): print "Remove a login info card" site = raw_input("Site: ") if sitelist.has_key(site): del sitelist[site] else: print site," was not found." def print_login_info(): print "Login Info" for site in sitelist.keys(): print "Site: ",site," \tID Passcard: ",sitelist[site]+"\n" # There should be a way to change the password, or add it for first time users. print "The Password Program" print "By Nathan Pinno" print load_file(sitelist) answer = getpass.getpass("What is the password? ") while password != answer: print "The password is incorrect." answer = getpass.getpass("What is the password? ") print "Welcome to the second half of the program." while 1: main_menu() menu_choice = int(raw_input("Choose an option (1-4, or 9: ")) if menu_choice == 1: add_site() elif menu_choice == 2: lookup_site() elif menu_choice == 3: remove_site() elif menu_choice == 4: print_login_info() elif menu_choice == 9: break else: print "That's not an option!" save_file(sitelist) print "Have a nice day!" [/code] Is it possible to salvage it? Give me your honest advice. Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051127/6e5a2a94/attachment.html From dyoo at hkn.eecs.berkeley.edu Sun Nov 27 22:42:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 27 Nov 2005 13:42:03 -0800 (PST) Subject: [Tutor] Scientific Notation + 18 Digit Precision In-Reply-To: <016601c5f34d$e427eba0$6401a8c0@hfsys3> Message-ID: On Sun, 27 Nov 2005, Hubert Fitch wrote: > Thanks to all of you (Alan, Chris, Kent) for your responses! > > Before I try to follow up on these suggestions, it might be good to > examine the display function module, and provide a few lines from a .py > module that needs display. [warning: long message. It's hard to show how to refactor code without actually doing it. *grin*] Hi Hubert, The code that you've shown is a bit unusual since the heart of it is 'exec'. I'll ignore that issue for the moment since it's so core to what the program intends. But instead, I'll concentrate on the overall structure of the program, and try to give some constructive criticism. (I'll try to condemn the use of exec at the end of this message. *grin*) The DisplayPyFile function feels too big: its inner workings obscures the main idea of the function: to execute every functional definition in the input file and display each result value. Let's see if we can refactor the program a bit to make that logic clearer. There's a whole block of code here that does the parsing of each definition: > line = line.strip() > if not line: > continue > leftAndRight = line.split('#',2) > comment = '' > if len(leftAndRight)>1: > comment = leftAndRight[1] > assignment = leftAndRight[0] > leftAndRight = assignment.split('=') > if len(leftAndRight) == 2: > name = leftAndRight[0].strip() Conceptually, the "input" into this block is a line from the file, and the "output" is either an equation or not. Let's informally say that an equation is a 3-tuple (name, assignment, comment). We can take the block above and turn it into a function: ########################################## def extractEquation(line): """Either returns a 3-tuple (name, assignment, comment) from the line, or None if we can't extract a definition from the line.""" line = line.strip() if not line: return None leftAndRight = line.split('#',2) comment = '' if len(leftAndRight) > 1: comment = leftAndRight[1] assignment = leftAndRight[0] leftAndRight = assignment.split('=') if len(leftAndRight) == 2: name = leftAndRight[0].strip() return (name, assignment, comment) return None ########################################## This function is a bit messy, but we can clean that up in a moment. But let's see how this might work: ###### >>> extractEquation("") >>> >>> extractEquation("x = 42") ('x', 'x = 42', '') >>> extractEquation("x = 42 # this is a test comment") ('x', 'x = 42 ', ' this is a test comment') ###### So this appears to work, although it's a bit rough. If we have this extractEquation, then the logic in the original DisplayPyFile() simplifies to: ################################################################## def DisplayPyFile(fname, context=None): if context is None: context = globals() f = open(fname) lines = f.readlines() f.close() for line in lines: equation = extractEquation(line) if equation: name, assignment, comment = equation exec(assignment, context) if context.get(name,None) is not None: value = context.get(name,'???') print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) else: print "%s not defined. %s" % (name, assignment) else: print line ################################################################## We can chip at DisplayPyFile() a bit more: there's a promising block here: ###################################### name, assignment, comment = equation exec(assignment, context) if context.get(name,None) is not None: value = context.get(name,'???') ###################################### This block tries to evaluate the equation and get its value. Actually, on further inspection, some of the logic is redundant: if we get into that 'if' block, context.get(name) has to work --- the default clause in "context.get(name, '???') is useless. We can simplify the block to: ###################################### name, assignment, comment = equation exec(assignment, context) if context.get(name,None) is not None: value = context.get(name) ###################################### Let's turn that equation-evaluating block into a real function: ################################################################## def evaluateEquation(equation, context): """Evaluates the equation in a given context. If we can't get a value, returns None.""" assert equation != None name, assignment, comment = equation exec(assignment, context) return context.get(name, None) ################################################################## Let's do a quick pass to see if this function works out: ###### >>> evaluateEquation(('x', 'x=42', ''), globals()) 42 ###### Ok, good; it's doing something. *grin* Once we have evaluateEquation(), we can use it to simplify DisplayPyFile some more: ################################################################## def DisplayPyFile(fname, context=None): if context is None: context = globals() f = open(fname) lines = f.readlines() f.close() for line in lines: equation = extractEquation(line) if equation: value = evaluateEquation(equation, context) if value: name, assignment, comment = equation print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) else: print "%s not defined. %s" % (name, assignment) else: print line ################################################################## Finaly, there's one more block that seems ripe, the part that prints out the value and the equation: ####################################################### if value: name, assignment, comment = equation print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) else: print "%s not defined. %s" % (name, assignment) ####################################################### And, of course, I'll push this into a function. *grin* ####################################################### def printEquationAndValue(equation, value): """Prints out the equation and its value.""" if value: name, assignment, comment = equation print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) else: print "%s not defined. %s" % (name, assignment) ####################################################### The refactored version of DisplayPyFile() now looks like: ################################################################# def DisplayPyFile(fname, context=None): if context is None: context = globals() f = open(fname) lines = f.readlines() f.close() for line in lines: equation = extractEquation(line) if equation: value = evaluateEquation(equation, context) printEquationAndValue(equation, value) else: print line ################################################################# Whew. *grin* I think I'll stop refactoring here for a moment and look back at your original question. Your original question was: > Most of the formatted results are already provided in the correct form. > What should be changed in this display function module? With all the refactoring, we can now point definitively at either evaluateEquation() or printEquationAndValue(). *grin* Seriously though, can you give us one of the definitions that's giving an incorrect result? With the revised program, we can now test if it's either evaluateEquation() that's messing up, or if it's the other function printEquationAndValue(). Actually, I know that there's something wrong with evaluateEquation(), because it's using Python's rules for doing arithmetic, and that includes its behavior on integer division. Here's an example: ###### >>> evaluateEquation(extractEquation('x = 1 / 2'), globals()) 0 >>> evaluateEquation(extractEquation('x = 1.0 / 2'), globals()) 0.5 ###### There are a few ways of fixing this. The easiest is to start Python up with the '-Qnew' command line option, which turns on true division globally: ###### mumak:~ dyoo$ python -Qnew Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 1 / 2 0.5 >>> eval('1 / 2') 0.5 ###### and since it looks like you're a beginner programmer, I'd recommend this approach: it means you won't have to change much. Unfortunately, this means that you'll have to remember to use '-Qnew' all the time, and that's bug-prone. An alternative way is to fix the bug is to modify extractEquation and evaluateEquation so that it doesn't depend on Python's evaluation functions. To an experienced programmer, I'd recommend that approach, to replace the call to 'exec' with a customized parser and evaluator: we have more control over the arithmetic. If you really need something like this, one of us can probably cook up such an evaluator for you. Best of wishes to you! From photonquark at comcast.net Mon Nov 28 04:19:29 2005 From: photonquark at comcast.net (Hubert Fitch) Date: Sun, 27 Nov 2005 22:19:29 -0500 Subject: [Tutor] Scientific Notation + 18 Digit Precision Message-ID: <01b301c5f3ca$8c3fec30$6401a8c0@hfsys3> Thank you Danny for your comments! I have now printed out four responses, and perhaps I might even learn some Python! It will take me some time to analyze all comments! I had never heard of Python until I audited two Physics classes. "Math Methods for Physics," and "Quantum Mechanics." (I am 73 years old, a retired Electronics Engineer). In my first definition module "pythondef.py" I enter physical constants and formulas that define these constants, but there can be many entirely different formulas that will calculate the same physical parameter. (I have quit trying to keep track of how many assignment formulas I have now, but it is over three hundred.) The main reason for all these different formulas is for checking my theories. If one or more formulas that calculate the same parameter do not give the correct precision data value or result, then I know that I have made a wrong assumption (misake). I need these defintions to be global, but changeable. That is, I want to be able to overwrite the parameter when the same assignment (or another assignment that calculates the same parameter) is executed again. This can be dangerous, so I must be careful. I may have 20 to 50 or more assignment satements in a .py module that must be in the correct computation order ( to be sure that all variables in each following assignment are all defined before execution). When these lines are processed by my run module, (or display module), they are not in a good order for including in a book. What is needed is to separate the equations into groups, and sometimes alphabetical order. This can be done after all definition modules have run once, to get all global variables defined. Then I rearrange the order of all of the 20 to 50 assignments, to make inspection of results easy, no longer needing to have a certain execution order to avoid an undefined variable error. So, typically I do the assignments twice. Once to get the variable entered globally, and the second time for presentation purposes. (This requires careful checking to be sure that all equations are in both lists, without any errors.) I have needed to frequently modify the defintition modules. And, they are not really suitable for compiled .pyc modules. However, my display function and run module function are compiled modules. ---------------------------------------------------------------------------------------------------------------------------------- I had thought not to introduce my theory into this discussion, but to help understand what the programs are supposed to do, I will tell you a little bit about it. My theory says that photons can be converted into electrons, to give the newly created electron intrinsic properties. The photon continues to exist, and to continue to travel at light speed! After the at-rest electron "structure" is understood, then we may extend this model to include electrons in motion. Physicists use Quantum Mechanics (QM) and Shrodinger's Equation to explain the in-motion electron, its momentum and energy states, using probabilities and wave functions, but ignore any electron intrinsic structure. Quantum Electro Dynamics (QED) and the Dirac Equation further explain electron properites, but likewise ignore any intrinsic electron structure. So, why is another electron model needed? ( At another time, perhaps we can say more. ) We need some notation, which could be explained more fully later, but here is a short description: Photon Parameters, Electron Classical Parameters, Electron Compton Parameters (2 sets), Atomic orbit Parameters, and Arbitrary Motion (not in any orbit) Parameters. Photon parameters use the subscript 1. Classical parameters use subscript 0. Compton Parameters use subscript 10, and 11. Orbiting Electron parameters use the subscripts 2, and 3, for the first two Hydrogen orbits. deBroglie Wave Parameters use a letter subscript (sometimes upper case, and somtimes lower case). For Example: (Seven Parameter groups) Photon Energy = E1, Electron Classical Energy = E0, Electron Compton Energy = E10, and E11. First Orbit Energy = E2, Second Orbit Energy = E3, deBroglie Energy = Ed And so on for: Current, Voltage, Period, Frequency, Inductance, Capacitance, Moments, Electric field, Magnetic Field, Flux Density, etc. etc. *********************************************************************************************************** So, we have seven groups of variable names, with precision data, assignment formulas, and comments arranged in four vertically aligned columns. (I use Landscape mode, legal size paper for printing .rtf files to maintain the 4 column formatting.) *********************************************************************************************************** So, if I displayed only 20 parameters for each of the seven groups, I would need additional room for the many redundant(?) calculations of each parameter using different equations which should calcuate the same result, but will somtime give different answers! This allows me to check my theory. I am tempted to assign many similar descriptive variable names for equations that calculate the same results, but this is unmanageable. So, I re-use unscripted variable names for calculating the redundant equations, like E, or simply use "x" To display a list of definitions without recalculating them, I sometimes enter statements like: f0 = f0, or E0 = E0. -------------------------------------------------------------------------------------------------------------------------------------- Unless someone asks me, I do not plan to further mix physics with Python. My QM instructor said that my electron model theory was "like a snake chasing its tail," so perhaps Python is the right language to use? Hubert -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051127/b5bfee50/attachment.htm From fire_fox_x_ at hotmail.com Mon Nov 28 02:47:16 2005 From: fire_fox_x_ at hotmail.com (Kevin Gall) Date: Sun, 27 Nov 2005 18:47:16 -0700 Subject: [Tutor] help Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051127/18b05ae5/attachment.html From dyoo at hkn.eecs.berkeley.edu Mon Nov 28 06:14:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 27 Nov 2005 21:14:47 -0800 (PST) Subject: [Tutor] help In-Reply-To: Message-ID: On Sun, 27 Nov 2005, Kevin Gall wrote: > how do i use python, do i download it? how do i use it . kevin. Hi Kevin, Out of curiosity, what do you know about Python or programming already? We want to avoid rehashing things that you already know, so if you can give any background on previous experience with computers and programming, that'll help us target our explanations to suit you better. There are resources on the web that should help you get started. For example: http://wiki.python.org/moin/BeginnersGuide The page there explains how to get started: how to download Python, what to expect, and how to find tutorials. I really can't get a sense of what you know already, so I'm defaulting to assuming that you're coming from a non-programmer background. In that case, I think you'll find the tutorials on: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers approachable. Pick a tutorial. When you have questions on something that doesn't make sense, send a question over to Tutor, and the tutors here will try to make sense of it. *grin* From rimbaudmiller at yahoo.com Mon Nov 28 07:55:40 2005 From: rimbaudmiller at yahoo.com (David Jimenez) Date: Sun, 27 Nov 2005 22:55:40 -0800 (PST) Subject: [Tutor] running a program Message-ID: <20051128065540.14917.qmail@web53707.mail.yahoo.com> Hello everybody, I have a very simple question: how can I run a script that uses module Tkinter without using IDLE? Thank you, David --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051127/75e3c6c9/attachment.html From ajikoe at gmail.com Mon Nov 28 09:58:53 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 28 Nov 2005 09:58:53 +0100 Subject: [Tutor] running a program In-Reply-To: <20051128065540.14917.qmail@web53707.mail.yahoo.com> References: <20051128065540.14917.qmail@web53707.mail.yahoo.com> Message-ID: this should be the same as running other python code. assuming you use windows, you can type from dos command : python namefile.py Cheers, pujo On 11/28/05, David Jimenez wrote: > > Hello everybody, > > I have a very simple question: how can I run a script that uses module > Tkinter without using IDLE? Thank you, > > David > > ------------------------------ > Yahoo! Music Unlimited - Access over 1 million songs. Try it free. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051128/a2474e30/attachment.html From kent37 at tds.net Mon Nov 28 11:53:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 28 Nov 2005 05:53:42 -0500 Subject: [Tutor] Modifying Source Code while Program is Running In-Reply-To: <34bb7f5b0511261442y657ec43dp@mail.gmail.com> References: <34bb7f5b0511240402v4f5bb0adv@mail.gmail.com> <4385EF32.8070606@tds.net> <34bb7f5b0511250311o2d85581dk@mail.gmail.com> <000f01c5f1e8$5ced00f0$0a01a8c0@xp> <34bb7f5b0511260238v1ff8d9e6q@mail.gmail.com> <006d01c5f284$bc4ec190$0a01a8c0@xp> <34bb7f5b0511261442y657ec43dp@mail.gmail.com> Message-ID: <438AE1B6.9020201@tds.net> Ed Singleton wrote: > On 26/11/05, Alan Gauld wrote: >>>I'm sure Python is quite possibly the least worst at this, but that >>>doesn't make it good at it. >> >>Which brings me back to my original question, what environment >>do you think is good at it? Are you aware of such an environment >>or merely wishing that such a thing could be invented? > > > I know that such a thing could be invented. It's very > straightforward, it's just a lot of work. If enough other people > think that it would be useful then it will probably get done at some > point (and I think the rise of web applications will bring it about as > an inevitability). You might be interested in this thread on the jython-dev list; Paul Fernhout is trying something similar to what you want: http://sourceforge.net/mailarchive/forum.php?forum_id=5587&max_rows=25&style=flat&viewmonth=200511&viewday=26 (read from the bottom up) Kent -- http://www.kentsjohnson.com From dyoo at hkn.eecs.berkeley.edu Mon Nov 28 18:19:01 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 28 Nov 2005 09:19:01 -0800 (PST) Subject: [Tutor] hey (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 28 Nov 2005 00:37:26 -0700 From: Kevin Gall To: dyoo at hkn.eecs.berkeley.edu Subject: hey hey, well i dont know how to program. i know how to use cmd a little bit. How to save open create new folders. Add new hardware, uninstall or install new programs. Just the basics, maybe a little more. Thats all. Python i just want to how to use it? ________________________________________________________________________________ Send junk mail straight into your Recycle Bin with MSN Premium: Join now and get the first two months FREE* From kent37 at tds.net Mon Nov 28 21:09:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 28 Nov 2005 15:09:35 -0500 Subject: [Tutor] Trouble with classes - Pypeg again In-Reply-To: References: <4387C58D.9060509@tds.net> Message-ID: <438B63FF.9040301@tds.net> (replying on-list) ->Terry<- wrote: > Thanks alot Kent. I really appreciate you taking > the time to respond. I'm taking your suggestions > and adding a bunch more reading to it. Hopefully > it will start to sink in. d:^) > > Any recommended reading? I recommend Robert Martin's "Agile Software Development: Principles, Patterns, and Practices" http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP This is the best book I know for learning object-oriented design the way I do it ;) - a very agile, pragmatic approach. It shows you the nitty-gritty details of how to create classes as you develop a solution. Also a good introduction to the agile development style. Much of the content of the book is available as essays on the ObjectMentor website: http://www.objectmentor.com/resources/listArticles?key=author&author=Robert%20C.%20Martin Before the Martin book came out my favorite was "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma, Richard Helm, Ralph Johnson and John M. Vlissides. This is the book that started the design pattern movement. The patterns are instructive in their own right and also serve as examples of good object-oriented design. http://www.aw-bc.com/catalog/academic/product/0,1144,0201633612,00.html Kent -- http://www.kentsjohnson.com From boyanpn at yahoo.com Mon Nov 28 15:07:36 2005 From: boyanpn at yahoo.com (Boyan R.) Date: Mon, 28 Nov 2005 15:07:36 +0100 Subject: [Tutor] using help Message-ID: <1vp4wxhd4quta$.hbl7xzahkply$.dlg@40tude.net> How can I see all error keywords for using Try..Except, like EOFError, ValueError etc by typing help('something') ? Also, what to type to see string handling commands ? like "int" [number = int(raw_input("Enter a number: "))] What's python equivalent for basic "val" command ? From jason.massey at gmail.com Mon Nov 28 21:56:38 2005 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 28 Nov 2005 14:56:38 -0600 Subject: [Tutor] using help In-Reply-To: <1vp4wxhd4quta$.hbl7xzahkply$.dlg@40tude.net> References: <1vp4wxhd4quta$.hbl7xzahkply$.dlg@40tude.net> Message-ID: <7e3eab2c0511281256m6dc56e50qf03ac5dda889e218@mail.gmail.com> Boyan, A listing of all the built-in exceptions can be found at: http://docs.python.org/lib/module-exceptions.html And is this what you're looking for? >>> a='123' >>> int(a) 123 >>> A description of this, and the other built-in functions, is at: http://docs.python.org/lib/built-in-funcs.html#built-in-funcs On 11/28/05, Boyan R. wrote: > > How can I see all error keywords for using Try..Except, > like EOFError, ValueError etc by typing help('something') ? > Also, what to type to see string handling commands ? > like "int" [number = int(raw_input("Enter a number: "))] > What's python equivalent for basic "val" command ? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051128/7896d8c7/attachment.htm From boyanpn at yahoo.com Mon Nov 28 22:15:12 2005 From: boyanpn at yahoo.com (Boyan R.) Date: Mon, 28 Nov 2005 22:15:12 +0100 Subject: [Tutor] using help References: <1vp4wxhd4quta$.hbl7xzahkply$.dlg@40tude.net> <7e3eab2c0511281256m6dc56e50qf03ac5dda889e218@mail.gmail.com> Message-ID: <9gf6e3wgrh2t.106ydc7cv2jdh$.dlg@40tude.net> On Mon, 28 Nov 2005 14:56:38 -0600, Jason Massey wrote: > Boyan, > > A listing of all the built-in exceptions can be found at: > > http://docs.python.org/lib/module-exceptions.html > > > A description of this, and the other built-in functions, is at: > > http://docs.python.org/lib/built-in-funcs.html#built-in-funcs Thanks, that will help. From dyoo at hkn.eecs.berkeley.edu Mon Nov 28 22:45:00 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 28 Nov 2005 13:45:00 -0800 (PST) Subject: [Tutor] hey (fwd) In-Reply-To: Message-ID: > hey, well i dont know how to program. i know how to use cmd a little > bit. How to save open create new folders. Add new hardware, uninstall or > install new programs. Just the basics, maybe a little more. Thats all. > Python i just want to how to use it? Hi Kevin, Ok, so in that case, I'd recommend starting off going through one of the tutorials in here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Download Python from: http://www.python.org/2.4.2/ and install it. Then start playing with Python along with a tutorial, and when you have questions, bring them up here on the Tutor mailing list. (By the way, you are not subscribed to the Tutor mailing list last time I checked; please subscribe yourself at http://mail.python.org/mailman/listinfo/tutor.) Since you're just starting off you might find the following tutorial helpful: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html (But just for full disclosure: I wrote it. *grin*) There is one bit that's outdated that I have to fix on it: the menu option for running scripts has moved to the "Run Module" command in the Module menu. Other than that, it should still be relevant. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Nov 28 22:57:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 28 Nov 2005 13:57:02 -0800 (PST) Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? In-Reply-To: Message-ID: On Sun, 27 Nov 2005, Nathan Pinno wrote: > Is it a good idea to use TKInter to change my password program into a > GUI? I know it needs improvements, and I've noted them below: Hi Nathan, Yes, some of it should be usable if it were in a GUI. The easy way to pick out what functions will and won't be useful is this: what functions use print and input statements? If you exclude those, then what's left will be useful for both your GUI and terminal programs. Actually, that's not quite accurate. For functions that do use print statements, it's possible to split off the console-driven stuff from the pure computation stuff, so there's actualy quite a bit you can reuse. Let's go into this. load_file() and safe_file() are directly reusable, since they don't interact with the user. Let's look at something that mixes computation with user interaction: > def add_site(): > print "Add a login info card" > site = raw_input("Site: ") > ID = raw_input("User ID and passcard, seperated by a space: ") > sitelist[site] = ID It's possible to break this down into two parts: the part that asks for login info: ###### def ask_for_login_info(): print "Add a login info card" site = raw_input("Site: ") ID = raw_input("User ID and passcard, seperated by a space: ") return (site, ID) ###### and the part that really does the gruntwork of entering into the site list: ###### def add_to_sitelist(site, ID): sitelist[site] = ID ###### Because this example is so small, doing the breakup this way is a bit silly, so maybe this is overkill for your program. But, in general, when we design a program to be used from both the console and the GUI, we'd break out the direct user interface stuff into a separate set of "user interface" functions, and have those interface functions reuse the common "model" functions that do the underlying work. In a GUI framework like Tkinter, the ask_for_login_info() function might use a "dialog box". http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm On a first pass to GUI-ify your program, each 'print' statement could be replaced with something like a printDialogMessage(): ###### import tkSimpleDialog import Tkinter def printDialogMessage(root, msg): """Uses a dialog window to display a message. If ok is pressed, returns True. If cancel is pressed, returns False. """ class Dialog(tkSimpleDialog.Dialog): def body(self, master): Tkinter.Label(master, text=msg).pack() def apply(self): self.result = True d = Dialog(root) if d.result: return True return False ###### Similarly, we can write something (let's call it readDialogInput) that simulates the console raw_input() function. And if you replace each use of 'print' with 'printDialogBox' and 'raw_input' with 'readDialogInput', we could argue that we have a GUI program. But if we take this route and just stop here, then this is no better than the console program. Getting GUIs right is more than just taking existing programs and putting nice shiny windows on them: it involves good user interface design that takes advantage of the things that GUIs get right. I don't know if there's a quick-and-dirty way to design such GUIs, though. You might find: http://www.manning.com/books/grayson helpful in getting started with Tkinter programming. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Nov 28 23:12:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 28 Nov 2005 14:12:29 -0800 (PST) Subject: [Tutor] Scientific Notation + 18 Digit Precision In-Reply-To: <01b301c5f3ca$8c3fec30$6401a8c0@hfsys3> Message-ID: > Unless someone asks me, I do not plan to further mix physics with > Python. My QM instructor said that my electron model theory was "like a > snake chasing its tail," so perhaps Python is the right language to use? Hi Hubert, I see, so it sounds like you're using Python as an extended calculation engine. By the way, from your descriptions, I think you might also find something like the Mathematica or Maxima systems useful. Mathematica's "workbook" interface, in particular, allows for similar kinds of experimental calculations. Both systems emphasize mathematical integrity, and this might make those system better well suited to your equations than Python. You can find out more here: http://maxima.sourceforge.net/ http://www.wolfram.com/ Best of wishes to you! From adam.jtm30 at gmail.com Mon Nov 28 23:43:40 2005 From: adam.jtm30 at gmail.com (Adam) Date: Mon, 28 Nov 2005 23:43:40 +0100 Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? In-Reply-To: References: Message-ID: Hello Nathan, glad to see you're still working on this. I don't think I can improve on Danny's info on the GUI but I'll add this. You might want to try the Python Cryptography Toolkit to encrypt the password files and maybe encrypting the file as a binary pickle will add a little bit more security too. One last thing, I think you might want to use "a" here def save_file(pw): store = open('passcard.txt',"w") so that new username/passwords are appended to the file rather than overwriting any previous ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051128/8b8fee17/attachment.htm From ukc802591034 at btconnect.com Tue Nov 29 00:49:07 2005 From: ukc802591034 at btconnect.com (Alan Gauld) Date: Mon, 28 Nov 2005 23:49:07 -0000 Subject: [Tutor] running a program References: <20051128065540.14917.qmail@web53707.mail.yahoo.com> Message-ID: > "Pujo Aji" wrote: > this should be the same as running other python code. > assuming you use windows, you can type from dos command : > > python namefile.py Or indeed just double click on the file in Windows explorer. Extra tip: If you rename it to namefile.pyc then it won't bring up the blank DOS console window. HTH, -- Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Nov 29 01:04:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 28 Nov 2005 19:04:00 -0500 Subject: [Tutor] running a program In-Reply-To: References: <20051128065540.14917.qmail@web53707.mail.yahoo.com> Message-ID: <438B9AF0.3080403@tds.net> Alan Gauld wrote: > Or indeed just double click on the file in Windows explorer. > > Extra tip: > If you rename it to namefile.pyc then it won't bring up the > blank DOS console window. mmm, that should be namefile.pyw Kent -- http://www.kentsjohnson.com From tanner at real-time.com Tue Nov 29 04:21:11 2005 From: tanner at real-time.com (Bob Tanner) Date: Mon, 28 Nov 2005 21:21:11 -0600 Subject: [Tutor] Beautiful Soup, inserting a node? Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Is there a way to insert a node with Beautiful Soup? I found away to append "things". But Blah

Foo!

I'd like to insert a
tag, like this: Blah - -- Bob Tanner | Phone : (952)943-8700 http://www.real-time.com, Minnesota, Linux | Fax : (952)943-8500 Key fingerprint = AB15 0BDF BCDE 4369 5B42 1973 7CF1 A709 2CC1 B288 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) iD8DBQFDi8kqfPGnCSzBsogRAtUrAKCptkOKxAYa4k1FQsQdBdT64sLoaQCfdo22 lHR84OMn37JOpzJ5x/lp+IA= =2AJE -----END PGP SIGNATURE----- From alan.gauld at freenet.co.uk Tue Nov 29 05:41:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue, 29 Nov 2005 04:41:22 -0000 Subject: [Tutor] Trouble with classes - Pypeg again References: <4387C58D.9060509@tds.net> <438B63FF.9040301@tds.net> Message-ID: <009301c5f49f$264bb3c0$0a01a8c0@xp> >> Any recommended reading? > > I recommend Robert Martin's "Agile Software Development: Principles, > Patterns, and Practices" > http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP > > This is the best book I know for learning object-oriented design the way I > do it ;) I really must get around to reading this one, I see so many recommendations for it. My personal favourites are: Object Oriented Design and Analysis by Grady Booch This is a very 'from the ground up' approach top OOP by one of the founding fathers based around C++ examples and using the authors own design notation. There are rumours of a new version based on Java and UML so borrow rather than buy is my recommendation for now! OO Software Construction by Bertrand Meyer Same basic approach but much more detailed. This is the most complete and scholarly coverage of OOP around. Unfortunately it uses Eiffel, a great language but hardly anyone uses it! Object Oriented Programming by Timothy Budd This one is for the hands-on types, teaches OO using several languages with lots opf comparitive examples. Its much shorter than the others with less talk about design and more about code level issues. > Before the Martin book came out my favorite was "Design Patterns: Elements > of Reusable Object-Oriented Software" by Erich Gamma, Richard Helm, Ralph > Johnson and John M. Vlissides. A good one, but not for the faint hearted. Its quite ponderous in style (IMHO!) and delves into some quite deep and subtly design concepts, but definitely one to keep with you long after you've finished with the others. Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From negroup at gmail.com Tue Nov 29 11:10:55 2005 From: negroup at gmail.com (Negroup -) Date: Tue, 29 Nov 2005 11:10:55 +0100 Subject: [Tutor] How to reuse code in Python Message-ID: <2fdabf190511290210p48a6677ck@mail.gmail.com> Hi. Suppose that I need to use in my project a module that belongs to another project, because - with some tuning - it can fit my needings. This is what I mean, with an example: module.py limit = 30 class A: def __init__(self): self.num = 20 def info(self): return limit def inc_num(self): self.num += 1 def check(self): return self.num > limit Now suppose that I'd like to have the same class A in my module, but also I want that the initial value of limit is set to 25. >>> limit = 25 >>> from module import A >>> a = A() >>> a.info() 30 Now I have a couple of questions. The most important: how to reuse the class A in my module? "class A" is not short and I think that copy/paste, then apply changes, wouldn't be a valid solution! This is the second question, more for curiosity than for real necessity, anyway: Considering that: >>> limit # Obvious 25 >>> print a.limit # Obvious Traceback (most recent call last): File "", line 1, in ? AttributeError: A instance has no attribute 'limit' >>> print A.limit # Obvious Traceback (most recent call last): File "", line 1, in ? AttributeError: class A has no attribute 'limit' where is the value 30 coming from? Thanks, dear tutors! From kent37 at tds.net Tue Nov 29 12:00:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 29 Nov 2005 06:00:59 -0500 Subject: [Tutor] How to reuse code in Python In-Reply-To: <2fdabf190511290210p48a6677ck@mail.gmail.com> References: <2fdabf190511290210p48a6677ck@mail.gmail.com> Message-ID: <438C34EB.8080105@tds.net> Negroup - wrote: > Hi. > Suppose that I need to use in my project a module that belongs to > another project, because - with some tuning - it can fit my needings. > > module.py > limit = 30 > > class A: > def __init__(self): > self.num = 20 > def info(self): > return limit > def inc_num(self): > self.num += 1 > def check(self): > return self.num > limit > > Now suppose that I'd like to have the same class A in my module, but > also I want that the initial value of limit is set to 25. > > >>>>limit = 25 >>>>from module import A >>>>a = A() >>>>a.info() > > 30 Obviously this doesn't do what you want. The problem is that class A is seeing the limit defined in it's module. 'global' variables in Python actually have module scope, there is no truly global scope in Python (OK, there's the __builtin__ scope, but this is a beginner's list!) IMO the best solution is to pass limit as a parameter to A's constructor and save it as an instance attribute: class A: def __init__(self, limit): self.limit = limit self.num = 20 def info(self): return self.limit def inc_num(self): self.num += 1 def check(self): return self.num > self.limit Now you can create whatever kind of A's you want: from module import A a = A(30) etc. Another way to do this is to make limit a class attribute. Then you can change it in subclasses: class A: limit = 25 def __init__(self): self.num = 20 def info(self): return self.limit def inc_num(self): self.num += 1 def check(self): return self.num > self.limit class B(A): limit = 30 a = A() a.info() --> 25 b = B() b.info() --> 30 Kent Note you still refer to self.limit so the value of limit in the current class will be found. > where is the value 30 coming from? from module.limit. Kent -- http://www.kentsjohnson.com From negroup at gmail.com Tue Nov 29 13:20:16 2005 From: negroup at gmail.com (Negroup -) Date: Tue, 29 Nov 2005 13:20:16 +0100 Subject: [Tutor] How to reuse code in Python In-Reply-To: <438C34EB.8080105@tds.net> References: <2fdabf190511290210p48a6677ck@mail.gmail.com> <438C34EB.8080105@tds.net> Message-ID: <2fdabf190511290420o5c64bcf2o@mail.gmail.com> 2005/11/29, Kent Johnson : > Negroup - wrote: [cut] > Obviously this doesn't do what you want. The problem is that class A is seeing the limit defined in it's module. 'global' variables in Python actually have module scope, there is no truly global scope in Python (OK, there's the __builtin__ scope, but this is a beginner's list!) > IMO the best solution is to pass limit as a parameter to A's constructor and save it as an instance attribute: > > class A: > def __init__(self, limit): > self.limit = limit > self.num = 20 > def info(self): > return self.limit > def inc_num(self): > self.num += 1 > def check(self): > return self.num > self.limit > > Now you can create whatever kind of A's you want: > from module import A > a = A(30) > etc. This is true. However following this approach I have touched the code in module.py (the original), and I'd avoid to do that. > > Another way to do this is to make limit a class attribute. Then you can change it in subclasses: Idem [cut] A way I found is to import module directly and then simply assign to it the property limit: >>> import module >>> module.limit = 25 >>> a = module.A() >>> b = module.A() (25, 25) This however has a side effect (that luckily is not a big problem, because I don't need to change limit after the first time): >>> module.limit = 26 >>> a.info(), b.info() (26, 26) > > where is the value 30 coming from? > > from module.limit. I have some difficulties understanding this. In my previous post the syntax is: from module import A and so 'module' is not imported. Thanks for your attention From kent37 at tds.net Tue Nov 29 13:57:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 29 Nov 2005 07:57:17 -0500 Subject: [Tutor] How to reuse code in Python In-Reply-To: <2fdabf190511290420o5c64bcf2o@mail.gmail.com> References: <2fdabf190511290210p48a6677ck@mail.gmail.com> <438C34EB.8080105@tds.net> <2fdabf190511290420o5c64bcf2o@mail.gmail.com> Message-ID: <438C502D.2070905@tds.net> Negroup - wrote: > 2005/11/29, Kent Johnson : >>class A: >> def __init__(self, limit): >> self.limit = limit >> self.num = 20 >> def info(self): >> return self.limit >> def inc_num(self): >> self.num += 1 >> def check(self): >> return self.num > self.limit >> >>Now you can create whatever kind of A's you want: >>from module import A >>a = A(30) >>etc. > > > This is true. However following this approach I have touched the code > in module.py (the original), and I'd avoid to do that. Why? It was not written to be reusable, now you are trying to reuse it. A minor rewrite now will save you trouble later. If you want to be backwards compatible you can give a default value for limit: class A: def __init__(self, limit=25): # etc then you can say a = A() a.info() --> 25 b = A(30) b.info() --> 30 a.info() --> still 25 > A way I found is to import module directly and then simply assign to > it the property limit: > >>>>import module >>>>module.limit = 25 >>>>a = module.A() >>>>b = module.A() > > (25, 25) > > This however has a side effect (that luckily is not a big problem, > because I don't need to change limit after the first time): > >>>>module.limit = 26 >>>>a.info(), b.info() > > (26, 26) Yes, you can do that but it's ugly and fragile. It will cause obscure bugs the first time you write a program that uses module twice with two different limits. Maybe you will never do that. I prefer not to put time bombs in my code. > > >>>where is the value 30 coming from? >> >>from module.limit. > > > I have some difficulties understanding this. In my previous post the > syntax is: from module import A and so 'module' is not imported. Right, but all access to limit is from inside module. Names are looked up first in the local namespace (the current function), then in any enclosing name space (if you have nested functions), then in the namespace of the *containing* module (*not* the module where the function is used, rather the module where it is defined) and finally in the built-in namespace. Again, 'global' scope is the scope of the textually containing module, not the scope of the calling module. This is called static or lexical scoping. See the tutorial and WikiPedia for more: http://docs.python.org/tut/node11.html#SECTION0011200000000000000000 http://en.wikipedia.org/wiki/Static_scoping Kent -- http://www.kentsjohnson.com From din22 at earthlink.net Tue Nov 29 14:40:18 2005 From: din22 at earthlink.net (david) Date: Tue, 29 Nov 2005 07:40:18 -0600 Subject: [Tutor] my text adventure Message-ID: <000601c5f4ea$70bdaad0$0201a8c0@d71bh5mhis9p7o> hello again python tutors! my latest attempt to learn python. any comments or suggestions most greatly appreciated. import sys import string ncoords = [0,0] class Room: def __init__(self,name): self.exits = {} self.contents = [] self.name = name self.coords = () room1 = Room('room1') room2 = Room('room2') room3 = Room('room3') room1.coords = (0,0) room2.coords = (0,1) room3.coords = (0,-1) room1.exits = {'n':room2,'s':room3} room2.exits = {'s':room1} room3.exits = {'n':room1} world = { (0,0):room1, (0,1):room2, (0,-1):room3} class Object: def __init__(self,name): self.name = name def getname(self): return self.name class Player: def __init__(self,name): self.name = name self.location = None self.inventory = [] self.wielded = None def look(self): print self.location.name def move(self,direction): if self.location.exits.has_key(direction): self.location = self.location.exits[direction] print self.location.name else: print 'alas, you cannot go that way' def dig(self,direction): lcoords = list(self.location.coords) if self.location.exits.has_key(direction): print 'there is already an exit there' elif direction == 'n': ncoords[1] == lcoords[1] + 1 elif direction == 's': ncoords[1] == lcoords[1] - 1 elif direction == 'e': ncoords[0] == lcoords[0] + 1 elif direction == 'w': ncoords[0] == lcoords[0] - 1 elif world.has_key(tuple(ncoords)): print "there is a room there" #so add exits else: #make a room and add exits to and from pass def wield(self,what): self.wielded = what def wear(self,what): pass def take(self,what): pass def drop(self,what): pass def do(self): cmd = raw_input('>') if cmd == 'l': self.look() elif cmd in ['n','s','e','w']: self.move(cmd) elif cmd == 'quit': sys.exit() elif cmd == 'i': for a in self.inventory: print a.getname() else: print 'what?' p = Player('david') sword = Object('sword') hat = Object('hat') p.location = world[(0,0)] p.inventory.append(sword) p.inventory.append(hat) while 1: p.do() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051129/d5e8b23c/attachment.html From noahbedford at gmail.com Tue Nov 29 20:26:03 2005 From: noahbedford at gmail.com (Noah Bedford) Date: Tue, 29 Nov 2005 14:26:03 -0500 Subject: [Tutor] my text adventure In-Reply-To: <000601c5f4ea$70bdaad0$0201a8c0@d71bh5mhis9p7o> References: <000601c5f4ea$70bdaad0$0201a8c0@d71bh5mhis9p7o> Message-ID: <20051129142603.0bbb1d47@localhost.localdomain> On Tue, 29 Nov 2005 07:40:18 -0600 "david" wrote: >hello again python tutors! my latest attempt to learn python. >any comments or suggestions most greatly appreciated. I like it! add in some scenery, and you have a game there! I like the inventory, that is nice to have, but I can not see anything to do with the sword and the hat... -\n From srini_iyyer_bio at yahoo.com Tue Nov 29 18:15:30 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue, 29 Nov 2005 09:15:30 -0800 (PST) Subject: [Tutor] Weird situation in using .split() function In-Reply-To: <000601c5f4ea$70bdaad0$0201a8c0@d71bh5mhis9p7o> Message-ID: <20051129171530.36743.qmail@web31613.mail.mud.yahoo.com> Hello group: I have a list t and the elements are tab limited. there are 2 columns: >>>t ['STAG2\tmiR-101', 'SMARCA1\tmiR-101', 'RAP2C\tmiR-101', 'DDX3Y\tmiR-101', 'AGRN\tmiR-101\tmiR-144', 'EPB41\tmiR-101\tmiR-144', 'PUM1\tmiR-101\tmiR-144', 'KIAA1573\tmiR-101\tmiR-144', 'ST6GALNAC3\tmiR-101\tmiR-144', 'CAPZA1\tmiR-101\tmiR-144'] >>> for i in t: i = i.strip('') cols = i.split('\t') print cols[0] STAG2 SMARCA1 RAP2C DDX3Y AGRN EPB41 PUM1 KIAA1573 ST6GALNAC3 CAPZA1 >>> for i in t: i = i.strip('') cols = i.split('\t') print cols[1] miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 >>> for i in t: i = i.strip('') cols = i.split('\t') print cols[2] Traceback (most recent call last): File "", line 4, in -toplevel- print cols[2] IndexError: list index out of range >>> for i in t: i = i.strip('') cols = i.split('\t') print cols ['STAG2', 'miR-101'] ['SMARCA1', 'miR-101'] ['RAP2C', 'miR-101'] ['DDX3Y', 'miR-101'] ['AGRN', 'miR-101', 'miR-144'] ['EPB41', 'miR-101', 'miR-144'] ['PUM1', 'miR-101', 'miR-144'] ['KIAA1573', 'miR-101', 'miR-144'] ['ST6GALNAC3', 'miR-101', 'miR-144'] ['CAPZA1', 'miR-101', 'miR-144'] When I try to Print column 2 (0,1,2 which is miR-144) elements why is it saying index out of range whern miR-144 is already there. Can any one please help me. thanks Srini __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com From sli1que at yahoo.com Tue Nov 29 18:26:02 2005 From: sli1que at yahoo.com (Eric Walker) Date: Tue, 29 Nov 2005 09:26:02 -0800 (PST) Subject: [Tutor] Weird situation in using .split() function In-Reply-To: <20051129171530.36743.qmail@web31613.mail.mud.yahoo.com> Message-ID: <20051129172602.20297.qmail@web60114.mail.yahoo.com> The first few are out of range. Only have one \t so you only get col[0] and col[1] ['STAG2\tmiR-101', 'SMARCA1\tmiR-101', 'RAP2C\tmiR-101', 'DDX3Y\tmiR-101', Srinivas Iyyer wrote: Hello group: I have a list t and the elements are tab limited. there are 2 columns: >>>t ['STAG2\tmiR-101', 'SMARCA1\tmiR-101', 'RAP2C\tmiR-101', 'DDX3Y\tmiR-101', 'AGRN\tmiR-101\tmiR-144', 'EPB41\tmiR-101\tmiR-144', 'PUM1\tmiR-101\tmiR-144', 'KIAA1573\tmiR-101\tmiR-144', 'ST6GALNAC3\tmiR-101\tmiR-144', 'CAPZA1\tmiR-101\tmiR-144'] >>> for i in t: i = i.strip('') cols = i.split('\t') print cols[0] STAG2 SMARCA1 RAP2C DDX3Y AGRN EPB41 PUM1 KIAA1573 ST6GALNAC3 CAPZA1 >>> for i in t: i = i.strip('') cols = i.split('\t') print cols[1] miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 miR-101 >>> for i in t: i = i.strip('') cols = i.split('\t') print cols[2] Traceback (most recent call last): File " ", line 4, in -toplevel- print cols[2] IndexError: list index out of range >>> for i in t: i = i.strip('') cols = i.split('\t') print cols ['STAG2', 'miR-101'] ['SMARCA1', 'miR-101'] ['RAP2C', 'miR-101'] ['DDX3Y', 'miR-101'] ['AGRN', 'miR-101', 'miR-144'] ['EPB41', 'miR-101', 'miR-144'] ['PUM1', 'miR-101', 'miR-144'] ['KIAA1573', 'miR-101', 'miR-144'] ['ST6GALNAC3', 'miR-101', 'miR-144'] ['CAPZA1', 'miR-101', 'miR-144'] When I try to Print column 2 (0,1,2 which is miR-144) elements why is it saying index out of range whern miR-144 is already there. Can any one please help me. thanks Srini __________________________________ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Yahoo! Music Unlimited - Access over 1 million songs. Try it free. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051129/25018750/attachment-0001.htm From kent37 at tds.net Tue Nov 29 18:32:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 29 Nov 2005 12:32:01 -0500 Subject: [Tutor] Weird situation in using .split() function In-Reply-To: <20051129171530.36743.qmail@web31613.mail.mud.yahoo.com> References: <20051129171530.36743.qmail@web31613.mail.mud.yahoo.com> Message-ID: <438C9091.9020900@tds.net> Srinivas Iyyer wrote: > Hello group: > > I have a list t and the elements are tab limited. > there are 2 columns: > >>>>t > > ['STAG2\tmiR-101', 'SMARCA1\tmiR-101', > 'RAP2C\tmiR-101', 'DDX3Y\tmiR-101', > 'AGRN\tmiR-101\tmiR-144', 'EPB41\tmiR-101\tmiR-144', > 'PUM1\tmiR-101\tmiR-144', > 'KIAA1573\tmiR-101\tmiR-144', > 'ST6GALNAC3\tmiR-101\tmiR-144', > 'CAPZA1\tmiR-101\tmiR-144'] > >>>>for i in t: > > i = i.strip('') > cols = i.split('\t') > print cols[2] > > Traceback (most recent call last): > File "", line 4, in -toplevel- > print cols[2] > IndexError: list index out of range > When I try to Print column 2 (0,1,2 which is miR-144) > elements why is it saying index out of range whern > miR-144 is already there. Because not every row has three columns, some just have two. Since the first row only has two columns it gets an error and nothing is printed. You can test for this: cols = i.split('\t') if len(cols) > 2: print cols[2] Kent -- http://www.kentsjohnson.com From wkranec at gmail.com Tue Nov 29 20:58:57 2005 From: wkranec at gmail.com (wkranec@gmail.com) Date: Tue, 29 Nov 2005 14:58:57 -0500 Subject: [Tutor] Read Excel file without COM Message-ID: <32b77d5a0511291158u7f7c0067h37226f5dc7bae6c2@mail.gmail.com> Hi, I have written a script which reads a Microsoft Excel file and moves the data inside onto a database. The script uses the PyWin32 module written by Mark Hammond, but I was wondering if anyone knew of a way to extract the data without using COM. A Python module would be best, but I suppose any conversion program that could be called from Python would be satisfactory. Saving the file as .csv isn't really an option since there are multiple pages in the sheet, and the people sending the files have been somewhat "standardized" to send an Excel sheet. I have thought briefly about using xml, but this would require me to rewrite a lot of my code, and I would like to avoid this unless there are some other good reasons to do so. I think I found a good resource at http://chicago.sourceforge.net/devel/docs/excel/, but it doesn't include any Python code. Does anyone know of something similar for Python? Thanks, Bill From Liam.Clarke-Hutchinson at business.govt.nz Tue Nov 29 21:13:09 2005 From: Liam.Clarke-Hutchinson at business.govt.nz (Liam Clarke-Hutchinson) Date: Wed, 30 Nov 2005 09:13:09 +1300 Subject: [Tutor] Read Excel file without COM Message-ID: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B14B2@chbnt01.alpha.wd.govt.nz> Actually, and I'm surprising myself here, but COM would be the easiest way to go about this if you're not able to convert to CSV. If you want to avoid COM, why don't you use it to save each page of the spreadsheet as a CSV file and then go from there? The close tie-in between Excel and COM is designed for your problem... Alternatively check PyPI, I'm sure there's something that will do what you want, but most of what you find will probably just use the Win32 package instead of reinventing the wheel. Regards, Liam Clarke -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of wkranec at gmail.com Sent: Wednesday, 30 November 2005 8:59 a.m. To: tutor at python.org Subject: [Tutor] Read Excel file without COM Hi, I have written a script which reads a Microsoft Excel file and moves the data inside onto a database. The script uses the PyWin32 module written by Mark Hammond, but I was wondering if anyone knew of a way to extract the data without using COM. A Python module would be best, but I suppose any conversion program that could be called from Python would be satisfactory. Saving the file as .csv isn't really an option since there are multiple pages in the sheet, and the people sending the files have been somewhat "standardized" to send an Excel sheet. I have thought briefly about using xml, but this would require me to rewrite a lot of my code, and I would like to avoid this unless there are some other good reasons to do so. I think I found a good resource at http://chicago.sourceforge.net/devel/docs/excel/, but it doesn't include any Python code. Does anyone know of something similar for Python? Thanks, Bill _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. From bgailer at alum.rpi.edu Tue Nov 29 21:17:48 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 29 Nov 2005 12:17:48 -0800 Subject: [Tutor] Read Excel file without COM In-Reply-To: <32b77d5a0511291158u7f7c0067h37226f5dc7bae6c2@mail.gmail.co m> References: <32b77d5a0511291158u7f7c0067h37226f5dc7bae6c2@mail.gmail.com> Message-ID: <7.0.0.16.0.20051129121313.021d2850@alum.rpi.edu> At 11:58 AM 11/29/2005, wkranec at gmail.com wrote: >Hi, > >I have written a script which reads a Microsoft Excel file and moves >the data inside onto a database. The script uses the PyWin32 module >written by Mark Hammond, but I was wondering if anyone knew of a way >to extract the data without using COM. A Python module would be best, >but I suppose any conversion program that could be called from Python >would be satisfactory. Interesting you ask at the same time I'm researching this question. I found http://sourceforge.net/projects/pyexcelerator Somewhere I thought I saw a reference to its ability to read Excel files, but I'm having a hard time getting to that. It does a great job writing Excel files. >Saving the file as .csv isn't really an option since there are >multiple pages in the sheet, and the people sending the files have >been somewhat "standardized" to send an Excel sheet. I have thought >briefly about using xml, but this would require me to rewrite a lot of >my code, and I would like to avoid this unless there are some other >good reasons to do so. > >I think I found a good resource at >http://chicago.sourceforge.net/devel/docs/excel/, but it doesn't >include any Python code. Does anyone know of something similar for >Python? > >Thanks, > >Bill >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From ewalker at micron.com Tue Nov 29 21:26:01 2005 From: ewalker at micron.com (Eric Walker) Date: Tue, 29 Nov 2005 13:26:01 -0700 Subject: [Tutor] Read Excel file without COM In-Reply-To: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B14B2@chbnt01.alpha.wd.govt.nz> References: <98EB0AAEFDF1824CB936AEC4E6DB5CBC025B14B2@chbnt01.alpha.wd.govt.nz> Message-ID: <200511291326.01794.ewalker@micron.com> yes, I found some stuff when I was playing around with win32. It does allow you to read from excell sheets... Eric ... On Tuesday 29 November 2005 01:13 pm, Liam Clarke-Hutchinson wrote: > Actually, and I'm surprising myself here, but COM would be the easiest way > to go about this if you're not able to convert to CSV. If you want to avoid > COM, why don't you use it to save each page of the spreadsheet as a CSV > file and then go from there? > > The close tie-in between Excel and COM is designed for your problem... > Alternatively check PyPI, I'm sure there's something that will do what you > want, but most of what you find will probably just use the Win32 package > instead of reinventing the wheel. > > Regards, > > Liam Clarke > > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of wkranec at gmail.com > Sent: Wednesday, 30 November 2005 8:59 a.m. > To: tutor at python.org > Subject: [Tutor] Read Excel file without COM > > > Hi, > > I have written a script which reads a Microsoft Excel file and moves the > data inside onto a database. The script uses the PyWin32 module written by > Mark Hammond, but I was wondering if anyone knew of a way to extract the > data without using COM. A Python module would be best, but I suppose any > conversion program that could be called from Python would be satisfactory. > > Saving the file as .csv isn't really an option since there are multiple > pages in the sheet, and the people sending the files have been somewhat > "standardized" to send an Excel sheet. I have thought briefly about using > xml, but this would require me to rewrite a lot of my code, and I would > like to avoid this unless there are some other good reasons to do so. > > I think I found a good resource at > http://chicago.sourceforge.net/devel/docs/excel/, but it doesn't include > any Python code. Does anyone know of something similar for Python? > > Thanks, > > Bill > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > A new monthly electronic newsletter covering all aspects of MED's work is > now available. Subscribers can choose to receive news from any or all of > seven categories, free of charge: Growth and Innovation, Strategic > Directions, Energy and Resources, Business News, ICT, Consumer Issues and > Tourism. See http://news.business.govt.nz for more details. > > > > > http://www.govt.nz - connecting you to New Zealand central & local > government services > > Any opinions expressed in this message are not necessarily those of the > Ministry of Economic Development. This message and any files transmitted > with it are confidential and solely for the use of the intended recipient. > If you are not the intended recipient or the person responsible for > delivery to the intended recipient, be advised that you have received this > message in error and that any use is strictly prohibited. Please contact > the sender and delete the message and any attachment from your computer. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From falcon3166 at hotmail.com Tue Nov 29 21:48:21 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 29 Nov 2005 13:48:21 -0700 Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? In-Reply-To: Message-ID: Hey Danny and all, Alberto told me that there was a password entry box in TKInter. Can anyone tell me about that, please? Thanks, Nathan Pinno, Owner/operator of The Web Surfer's Store. http://www.the-web-surfers-store.com/ MSN Messenger: falcon3166 at hotmail.com Yahoo! Messenger: spam_swatter31 AIM: f3mighty ICQ: 199020705 -----Original Message----- From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] Sent: November 28, 2005 2:57 PM To: Nathan Pinno Cc: Albertito Troiano; Tutor Mailing List Subject: Re: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? On Sun, 27 Nov 2005, Nathan Pinno wrote: > Is it a good idea to use TKInter to change my password program into a > GUI? I know it needs improvements, and I've noted them below: Hi Nathan, Yes, some of it should be usable if it were in a GUI. The easy way to pick out what functions will and won't be useful is this: what functions use print and input statements? If you exclude those, then what's left will be useful for both your GUI and terminal programs. Actually, that's not quite accurate. For functions that do use print statements, it's possible to split off the console-driven stuff from the pure computation stuff, so there's actualy quite a bit you can reuse. Let's go into this. load_file() and safe_file() are directly reusable, since they don't interact with the user. Let's look at something that mixes computation with user interaction: > def add_site(): > print "Add a login info card" > site = raw_input("Site: ") > ID = raw_input("User ID and passcard, seperated by a space: ") > sitelist[site] = ID It's possible to break this down into two parts: the part that asks for login info: ###### def ask_for_login_info(): print "Add a login info card" site = raw_input("Site: ") ID = raw_input("User ID and passcard, seperated by a space: ") return (site, ID) ###### and the part that really does the gruntwork of entering into the site list: ###### def add_to_sitelist(site, ID): sitelist[site] = ID ###### Because this example is so small, doing the breakup this way is a bit silly, so maybe this is overkill for your program. But, in general, when we design a program to be used from both the console and the GUI, we'd break out the direct user interface stuff into a separate set of "user interface" functions, and have those interface functions reuse the common "model" functions that do the underlying work. In a GUI framework like Tkinter, the ask_for_login_info() function might use a "dialog box". http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm On a first pass to GUI-ify your program, each 'print' statement could be replaced with something like a printDialogMessage(): ###### import tkSimpleDialog import Tkinter def printDialogMessage(root, msg): """Uses a dialog window to display a message. If ok is pressed, returns True. If cancel is pressed, returns False. """ class Dialog(tkSimpleDialog.Dialog): def body(self, master): Tkinter.Label(master, text=msg).pack() def apply(self): self.result = True d = Dialog(root) if d.result: return True return False ###### Similarly, we can write something (let's call it readDialogInput) that simulates the console raw_input() function. And if you replace each use of 'print' with 'printDialogBox' and 'raw_input' with 'readDialogInput', we could argue that we have a GUI program. But if we take this route and just stop here, then this is no better than the console program. Getting GUIs right is more than just taking existing programs and putting nice shiny windows on them: it involves good user interface design that takes advantage of the things that GUIs get right. I don't know if there's a quick-and-dirty way to design such GUIs, though. You might find: http://www.manning.com/books/grayson helpful in getting started with Tkinter programming. Hope this helps! From jason.massey at gmail.com Tue Nov 29 21:52:21 2005 From: jason.massey at gmail.com (Jason Massey) Date: Tue, 29 Nov 2005 14:52:21 -0600 Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? In-Reply-To: References: Message-ID: <7e3eab2c0511291252n2c1ce57dj16c2a8ea39b43a2b@mail.gmail.com> Nathan, Look here: http://effbot.org/tkinterbook/entry.htm Apparently you can change the default setting for the entry box so that it will show whatever character you like rather than what the user is typing. On 11/29/05, Nathan Pinno wrote: > > Hey Danny and all, > > Alberto told me that there was a password entry box in TKInter. Can anyone > tell me about that, please? > > Thanks, > Nathan Pinno, > Owner/operator of The Web Surfer's Store. > http://www.the-web-surfers-store.com/ > MSN Messenger: falcon3166 at hotmail.com > Yahoo! Messenger: spam_swatter31 > AIM: f3mighty > ICQ: 199020705 > > -----Original Message----- > From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu] > Sent: November 28, 2005 2:57 PM > To: Nathan Pinno > Cc: Albertito Troiano; Tutor Mailing List > Subject: Re: [Tutor] Is it a good idea to use TKInter to change my > password > program into a GUI? > > > > On Sun, 27 Nov 2005, Nathan Pinno wrote: > > > Is it a good idea to use TKInter to change my password program into a > > GUI? I know it needs improvements, and I've noted them below: > > Hi Nathan, > > Yes, some of it should be usable if it were in a GUI. The easy way to > pick > out what functions will and won't be useful is this: what functions use > print and input statements? If you exclude those, then what's left will > be > useful for both your GUI and terminal programs. > > Actually, that's not quite accurate. For functions that do use print > statements, it's possible to split off the console-driven stuff from the > pure computation stuff, so there's actualy quite a bit you can reuse. > Let's go into this. > > > load_file() and safe_file() are directly reusable, since they don't > interact > with the user. Let's look at something that mixes computation with user > interaction: > > > def add_site(): > > print "Add a login info card" > > site = raw_input("Site: ") > > ID = raw_input("User ID and passcard, seperated by a space: ") > > sitelist[site] = ID > > It's possible to break this down into two parts: the part that asks for > login info: > > ###### > def ask_for_login_info(): > print "Add a login info card" > site = raw_input("Site: ") > ID = raw_input("User ID and passcard, seperated by a space: ") > return (site, ID) > ###### > > and the part that really does the gruntwork of entering into the site > list: > > ###### > def add_to_sitelist(site, ID): > sitelist[site] = ID > ###### > > > Because this example is so small, doing the breakup this way is a bit > silly, > so maybe this is overkill for your program. But, in general, when we > design > a program to be used from both the console and the GUI, we'd break out the > direct user interface stuff into a separate set of "user interface" > functions, and have those interface functions reuse the common "model" > functions that do the underlying work. > > > > In a GUI framework like Tkinter, the ask_for_login_info() function might > use > a "dialog box". > > > http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm > > On a first pass to GUI-ify your program, each 'print' statement could be > replaced with something like a printDialogMessage(): > > ###### > import tkSimpleDialog > import Tkinter > > def printDialogMessage(root, msg): > """Uses a dialog window to display a message. If ok is pressed, > returns True. If cancel is pressed, returns False. > """ > class Dialog(tkSimpleDialog.Dialog): > def body(self, master): > Tkinter.Label(master, text=msg).pack() > def apply(self): > self.result = True > d = Dialog(root) > if d.result: > return True > return False > ###### > > Similarly, we can write something (let's call it readDialogInput) that > simulates the console raw_input() function. And if you replace each use > of > 'print' with 'printDialogBox' and 'raw_input' with 'readDialogInput', we > could argue that we have a GUI program. > > > But if we take this route and just stop here, then this is no better than > the console program. Getting GUIs right is more than just taking existing > programs and putting nice shiny windows on them: it involves good user > interface design that takes advantage of the things that GUIs get right. > I don't know if there's a quick-and-dirty way to design such GUIs, though. > > You might find: > > http://www.manning.com/books/grayson > > helpful in getting started with Tkinter programming. > > > Hope this helps! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051129/8413525b/attachment-0001.htm From klappnase at freenet.de Tue Nov 29 22:35:07 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 29 Nov 2005 22:35:07 +0100 Subject: [Tutor] Is it a good idea to use TKInter to change my password program into a GUI? In-Reply-To: References: Message-ID: <20051129223507.165dd9e0.klappnase@freenet.de> On Tue, 29 Nov 2005 13:48:21 -0700 "Nathan Pinno" wrote: > Hey Danny and all, > > Alberto told me that there was a password entry box in TKInter. Can anyone > tell me about that, please? > Hi Nathan, maybe he meant the Pmw.PromptDialog () ? Regards Michael From EDouglass at gaylordhotels.com Tue Nov 29 22:23:26 2005 From: EDouglass at gaylordhotels.com (Douglass, Erik) Date: Tue, 29 Nov 2005 15:23:26 -0600 Subject: [Tutor] Question Message-ID: <566E54419328A642A3A6E91376E885B1048EA086@txex.tx.get> I am a bit new to the *nix environment, as well as brand new to Python (perhaps I am biting of a bit much, I know). I was wondering if someone could point me in a direction to get started in this environment. What apps to code in, is there an interactive mode? Specifically FreeBSD 6.0 running KDE. If anyone has any pointers I would be much appreciated. Thanks! Erik -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051129/174cc51f/attachment.html From john at fouhy.net Tue Nov 29 22:45:56 2005 From: john at fouhy.net (John Fouhy) Date: Wed, 30 Nov 2005 10:45:56 +1300 Subject: [Tutor] Read Excel file without COM In-Reply-To: <7.0.0.16.0.20051129121313.021d2850@alum.rpi.edu> References: <32b77d5a0511291158u7f7c0067h37226f5dc7bae6c2@mail.gmail.com> <7.0.0.16.0.20051129121313.021d2850@alum.rpi.edu> Message-ID: <5e58f2e40511291345m37955961x@mail.gmail.com> On 30/11/05, bob wrote: > Interesting you ask at the same time I'm researching this question. I found > http://sourceforge.net/projects/pyexcelerator > Somewhere I thought I saw a reference to its ability to read Excel > files, but I'm having a hard time getting to that. It does a great > job writing Excel files. Yeah, I like pyExcelerator, but the documentation lacks in places :-) Just call pyExcelerator.parse_xls() on the filename you wish to parse. -- John. From john at fouhy.net Tue Nov 29 22:53:40 2005 From: john at fouhy.net (John Fouhy) Date: Wed, 30 Nov 2005 10:53:40 +1300 Subject: [Tutor] Question In-Reply-To: <566E54419328A642A3A6E91376E885B1048EA086@txex.tx.get> References: <566E54419328A642A3A6E91376E885B1048EA086@txex.tx.get> Message-ID: <5e58f2e40511291353g55af647x@mail.gmail.com> On 30/11/05, Douglass, Erik wrote: > I am a bit new to the *nix environment, as well as brand new to Python > (perhaps I am biting of a bit much, I know). I was wondering if someone > could point me in a direction to get started in this environment. What apps > to code in, is there an interactive mode? Specifically FreeBSD 6.0 running > KDE. If anyone has any pointers I would be much appreciated. Hi Erik, Do you know what a shell is? I think KDE calls it "Konsole". If you start up a shell and then type "python", you will start up the python interpreter and be able to interact with it. This is quite handy! If you haven't already done so, check out the tutorial on python.org. It talks about this (amongst other things). As to what app to code in ... that's a can of worms :-) I am a fan of emacs and vi. You could also try IDLE, which comes with python. -- John. From dyoo at hkn.eecs.berkeley.edu Tue Nov 29 23:06:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 29 Nov 2005 14:06:42 -0800 (PST) Subject: [Tutor] Question In-Reply-To: <5e58f2e40511291353g55af647x@mail.gmail.com> Message-ID: > > I am a bit new to the *nix environment, as well as brand new to Python > > (perhaps I am biting of a bit much, I know). I was wondering if > > someone could point me in a direction to get started in this > > environment. Hi Erik, I agree; I'd recommend getting used to operating your new Unix environment first. After you feel more comfortable with your environment, then go for Python. Trying to learn both at the same time might be counterproductive, especially in the presense of mistakes. If things go wrong, you'll want to know if you're looking at a Unix error or a Python one. You can find KDE user documentation here: http://docs.kde.org/ http://docs.kde.org/development/en/kdebase/userguide/index.html When you feel comfortable enough with your environment, then you can find good starting points for learning Python here: http://wiki.python.org/moin/BeginnersGuide > > What apps to code in, is there an interactive mode? Yes, Python has an interactive prompt. If you do have a console handy, type 'python' and see if something comes up. Best of wishes to you! From K.Weinert at gmx.net Tue Nov 29 23:52:29 2005 From: K.Weinert at gmx.net (K.Weinert@gmx.net) Date: Tue, 29 Nov 2005 23:52:29 +0100 (MET) Subject: [Tutor] Read Excel file without COM Message-ID: <28152.1133304749@www88.gmx.net> Hello, you could try to access the excel file via ODBC if the only thing you need to do is reading. It worked for me when I was working with Excel 95 (no COM) and wanted to read in worksheets in python. Here are some infos on excel datasources: http://www.idude.net/excel/articles/using_excel_file_datasources.asp I could not access password-protected excel files, the fetchall() method did not work, create/drop index, alter table did not work, table names are like "[sheet1$]" (note the brackets and the dollar sign). Just my 2Cents, Karsten. -- Highspeed-Freiheit. Bei GMX supergünstig, z.B. GMX DSL_Cityflat, DSL-Flatrate für nur 4,99 Euro/Monat* http://www.gmx.net/de/go/dsl From kent37 at tds.net Wed Nov 30 00:20:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 29 Nov 2005 18:20:13 -0500 Subject: [Tutor] my text adventure In-Reply-To: <000601c5f4ea$70bdaad0$0201a8c0@d71bh5mhis9p7o> References: <000601c5f4ea$70bdaad0$0201a8c0@d71bh5mhis9p7o> Message-ID: <438CE22D.7090001@tds.net> david wrote: > hello again python tutors! my latest attempt to learn python. > any comments or suggestions most greatly appreciated. > > import sys > import string > ncoords = [0,0] > class Room: > def __init__(self,name): > self.exits = {} > self.contents = [] > self.name = name > self.coords = () > room1 = Room('room1') > room2 = Room('room2') > room3 = Room('room3') > room1.coords = (0,0) > room2.coords = (0,1) > room3.coords = (0,-1) > room1.exits = {'n':room2,'s':room3} > room2.exits = {'s':room1} > room3.exits = {'n':room1} > world = { (0,0):room1, (0,1):room2, (0,-1):room3} You might want to make coords an init parameter for Room, rather than assigning it separately. You could also have Rooms register themselves with world as part of their initialization, that would be better than having to repeat yourself in the definition of world. > > class Object: > def __init__(self,name): > self.name = name > > def getname(self): > return self.name Object is not such a great name, it is too easily confused with object, the base class of new-style classes. Maybe Item? Right now this class isn't pulling its weight, it could be replaced by a simple string. Presumably you will add more functionality to it; if so it's worth keeping it around, otherwise get rid of it. Common Python practice is *not* to define setters and getters, just access the attribute directly - so get maybe you don't need getname(). > > class Player: > def __init__(self,name): > self.name = name > self.location = None > self.inventory = [] > self.wielded = None Maybe location should be an init param? > def look(self): > print self.location.name > > def move(self,direction): > if self.location.exits.has_key(direction): > self.location = self.location.exits[direction] > print self.location.name > else: print 'alas, you cannot go that way' > def dig(self,direction): > lcoords = list(self.location.coords) Why do you convert to a list? You can access tuple elements by index. > if self.location.exits.has_key(direction): > print 'there is already an exit there' > > > elif direction == 'n': > ncoords[1] == lcoords[1] + 1 You probably mean ncoords[1] = lcoords[1] + 1 but I think I would make ncoords a local variable and just say ncoords = (0, lcoords[1] + 1) With ncoords as a global you have a bug, you only set one element here, the other one will be left over from the last time through. Kent > elif direction == 's': > ncoords[1] == lcoords[1] - 1 > elif direction == 'e': > ncoords[0] == lcoords[0] + 1 > elif direction == 'w': > ncoords[0] == lcoords[0] - 1 > elif world.has_key(tuple(ncoords)): > print "there is a room there" > #so add exits > else: > #make a room and add exits to and from > pass > def wield(self,what): > self.wielded = what > def wear(self,what): > pass > def take(self,what): > pass > def drop(self,what): > pass > def do(self): > cmd = raw_input('>') > if cmd == 'l': > self.look() > elif cmd in ['n','s','e','w']: > self.move(cmd) > elif cmd == 'quit': > sys.exit() > elif cmd == 'i': > for a in self.inventory: > print a.getname() > else: > print 'what?' > > p = Player('david') > sword = Object('sword') > hat = Object('hat') > > p.location = world[(0,0)] > p.inventory.append(sword) > p.inventory.append(hat) > while 1: > p.do() > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- http://www.kentsjohnson.com From bgailer at alum.rpi.edu Wed Nov 30 01:13:51 2005 From: bgailer at alum.rpi.edu (bob) Date: Tue, 29 Nov 2005 16:13:51 -0800 Subject: [Tutor] Read Excel file without COM In-Reply-To: <5e58f2e40511291345m37955961x@mail.gmail.com> References: <32b77d5a0511291158u7f7c0067h37226f5dc7bae6c2@mail.gmail.com> <7.0.0.16.0.20051129121313.021d2850@alum.rpi.edu> <5e58f2e40511291345m37955961x@mail.gmail.com> Message-ID: <7.0.0.16.0.20051129161230.01d102f0@alum.rpi.edu> At 01:45 PM 11/29/2005, John Fouhy wrote: >On 30/11/05, bob wrote: > > Interesting you ask at the same time I'm researching this question. I found > > http://sourceforge.net/projects/pyexcelerator > > Somewhere I thought I saw a reference to its ability to read Excel > > files, but I'm having a hard time getting to that. It does a great > > job writing Excel files. > >Yeah, I like pyExcelerator, but the documentation lacks in places :-) > >Just call pyExcelerator.parse_xls() on the filename you wish to parse. Great. That works. But I seem to just get the data. For now that suffices. Is there a way to retrieve formatting and other properties? >-- >John. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From mosinu at gmail.com Wed Nov 30 01:40:10 2005 From: mosinu at gmail.com (Will Harris) Date: Tue, 29 Nov 2005 19:40:10 -0500 Subject: [Tutor] log parsing Message-ID: <5faf36700511291640o21160de7p5e2b22fa7bb14284@mail.gmail.com> I am trying to work out doing a bit of log parsing in python. Below is the code I have gotten so far, It works in an earlier version of this one but this one doesn't print out the lines in my log files. Does anyone see anything that I am missing here or can just point me in the direction to look? This iteration I am just trying to get it to let me specify the logs I want to parse from the command line (later I want to sort all this out and put it into a postgres database) #!/usr/bin/python ### import sys import re ### USAGE = (sys.argv[0]) + ''' logfile logfile logfile ''' ### def hasAccept(s): return s.find('accept-n-log') != -1 def hasDrop(s): return s.find('drop-n-log') != -1 def main(): if len(sys.argv) <= 1: print USAGE return 1 for logs in sys.argv[1:]: open(logs) for line in logs: if hasAccept(line): print(line) if __name__ == '__main__': main() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051129/6016ce88/attachment.htm From kent37 at tds.net Wed Nov 30 04:36:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 29 Nov 2005 22:36:26 -0500 Subject: [Tutor] log parsing In-Reply-To: <5faf36700511291640o21160de7p5e2b22fa7bb14284@mail.gmail.com> References: <5faf36700511291640o21160de7p5e2b22fa7bb14284@mail.gmail.com> Message-ID: <438D1E3A.8010807@tds.net> Will Harris wrote: > I am trying to work out doing a bit of log parsing in python. Below is > the code I have gotten so far, It works in an earlier version of this > one but this one doesn't print out the lines in my log files. Does > anyone see anything that I am missing here or can just point me in the > direction to look? > > for logs in sys.argv[1:]: > open(logs) > for line in logs: This should be something like f = open(logs) for line in f: You are opening the file and throwing it away, then iterating over the command line argument. Kent -- http://www.kentsjohnson.com From din22 at earthlink.net Wed Nov 30 13:33:47 2005 From: din22 at earthlink.net (david) Date: Wed, 30 Nov 2005 06:33:47 -0600 Subject: [Tutor] my text adventure References: Message-ID: <000701c5f5aa$4ff10c50$0201a8c0@d71bh5mhis9p7o> > You might want to make coords an init parameter for Room, rather than > assigning it separately. You could also have Rooms register themselves > with world as part of their initialization, that would be better than > having to repeat yourself in the definition of world. brilliant! i'll do that. >> >> class Object: >> def __init__(self,name): >> self.name = name >> >> def getname(self): >> return self.name > > Object is not such a great name, it is too easily confused with object, > the base class of new-style classes. Maybe Item? > > Right now this class isn't pulling its weight, it could be replaced by a > simple string. Presumably you will add more functionality to it; if so > it's worth keeping it around, otherwise get rid of it. > > Common Python practice is *not* to define setters and getters, just access > the attribute directly - so get maybe you don't need getname> i just now learned what setter and getter is. i did this to make my inventory function work properly. i'll try to remove my getter. didn't know we had new-style classes. >> def look(self): >> print self.location.name >> >> def move(self,direction): >> if self.location.exits.has_key(direction): >> self.location = self.location.exits[direction] >> print self.location.name >> else: print 'alas, you cannot go that way' >> def dig(self,direction): >> lcoords = list(self.location.coords) > > Why do you convert to a list? You can access tuple elements by index. i need to change the coordinates of the current room to the room i'm digging into so i can check world to see if that room exists. there is probably a better way to do all that. > >> if self.location.exits.has_key(direction): >> print 'there is already an exit there' >> >> >> elif direction == 'n': >> ncoords[1] == lcoords[1] + 1 > > You probably mean > ncoords[1] = lcoords[1] + 1 > but I think I would make ncoords a local variable and just say > ncoords = (0, lcoords[1] + 1) > > With ncoords as a global you have a bug, you only set one element here, > the other one will be left over from the last time through. > > Kent i stuck that global up there to make something work. i forget what now. maybe i should take notes or something :) i'm thinking i should write some separate convert directions to coordinates function. thanks for the thought food and thanks for taking time to look at my code. version 2 will be along shortly but don't hold your breath :) (because thats bad for you) From kent37 at tds.net Wed Nov 30 14:17:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Nov 2005 08:17:48 -0500 Subject: [Tutor] my text adventure In-Reply-To: <000701c5f5aa$4ff10c50$0201a8c0@d71bh5mhis9p7o> References: <000701c5f5aa$4ff10c50$0201a8c0@d71bh5mhis9p7o> Message-ID: <438DA67C.2020700@tds.net> david wrote: > i just now learned what setter and getter is. > i did this to make my inventory function work properly. > i'll try to remove my getter. The inventory list can be just for a in self.inventory: print a.name You can access object attributes from outside the object, they are public. > didn't know we had new-style classes. Yes, modern practice is to have your classes inherit from object, e.g. class Room(object): >>> def move(self,direction): >>> if self.location.exits.has_key(direction): >>> self.location = self.location.exits[direction] >>> print self.location.name >>> else: print 'alas, you cannot go that way' >>> def dig(self,direction): >>> lcoords = list(self.location.coords) >> >>Why do you convert to a list? You can access tuple elements by index. > > i need to change the coordinates of the current room to the room i'm > digging into so i can check world to see if that room exists. Yes, I understand the intent, but I think you can use self.location.coords everywhere you are now using lcoords - the conversion to list is not needed. >>but I think I would make ncoords a local variable and just say >> ncoords = (0, lcoords[1] + 1) >> >>With ncoords as a global you have a bug, you only set one element here, >>the other one will be left over from the last time through. > > i stuck that global up there to make something work. i forget what now. > maybe i should take notes or something :) i'm thinking i should write some > separate convert directions to coordinates function. That sounds like a good idea. But still you can create ncoords directly as shown above. Kent -- http://www.kentsjohnson.com From python at kapitalisten.no Wed Nov 30 14:54:28 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Wed, 30 Nov 2005 14:54:28 +0100 (CET) Subject: [Tutor] Unicode trouble Message-ID: <32724.193.71.38.142.1133358868.squirrel@mail.sporck.net> Hello. I am writing a program that reads in a text file, extracts each of the words and replaces a different document with the words. It works great until it encounter a non-english letter. I have tried the following: self.f = codecs.open(ordliste, 'r', 'utf-8') where I open the first file. And en = unicode(en) en = en.encode('utf-8') as well as en = en.decode('iso-8859-1') where each word is entered from the document. But, still, I get this error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 17: ordinal not in range(128) As well as this: UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: invalid data if I skips the second part. What is wrong? How can I fix this? I am using ActiveState Python 2.3 and WinXp. Thanks in advance... This is the whole source: from win32com.client import Dispatch import time import codecs class oversett: def __init__(self, ordliste, dokument): objWord = Dispatch("Word.Application") self.f = codecs.open(ordliste, 'r', 'utf-8') #self.f = open(ordliste) objDoc = objWord.Documents.Open(dokument) self.objSelection = objWord.Selection def kjor(self): s = time.clock() wdReplaceAll = 2 wdFindContinue = 1 t = 1 for i in self.f.readlines(): en = i.split('\t')[0] #en = str(en).decode('iso-8859-1') #en = en.decode('iso-8859-1') en = unicode(en) en = en.encode('utf-8') print en to = i.split('\t')[1] #to = str(to).decode('iso-8859-1') #to = to.decode('iso-8859-1') to = unicode(to) to = to.encode('utf-8') t = t + 1 if t % 1000 == 0: print t try: self.objSelection.Find.Execute(en, False, True, False, False, True, True, wdFindContinue, True, to, wdReplaceAll, False, False, False, False) except UnicodeEncodeError: print 'pokker' except: pass print time.clock() - s if __name__ == '__main__': n = oversett('c:/ordliste.txt','c:/foo.doc') n.kjor() -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Wed Nov 30 15:15:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Nov 2005 09:15:33 -0500 Subject: [Tutor] Unicode trouble In-Reply-To: <32724.193.71.38.142.1133358868.squirrel@mail.sporck.net> References: <32724.193.71.38.142.1133358868.squirrel@mail.sporck.net> Message-ID: <438DB405.1090405@tds.net> ?yvind wrote: > Hello. > > I am writing a program that reads in a text file, extracts each of the > words and replaces a different document with the words. It works great > until it encounter a non-english letter. > > I have tried the following: > > self.f = codecs.open(ordliste, 'r', 'utf-8') > where I open the first file. > > And > en = unicode(en) > en = en.encode('utf-8') > > as well as > en = en.decode('iso-8859-1') > > where > each word is entered from the document. > > But, still, I get this error: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 17: > ordinal not in range(128) > > As well as this: > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: > invalid data > if I skips the second part. Where are you getting these errors (what line of the program)? Do you know what kind of strings objSelection.Find.Execute() is expecting? Kent > > What is wrong? How can I fix this? I am using ActiveState Python 2.3 and > WinXp. > > Thanks in advance... > > > This is the whole source: > > from win32com.client import Dispatch > import time > import codecs > > class oversett: > def __init__(self, ordliste, dokument): > objWord = Dispatch("Word.Application") > self.f = codecs.open(ordliste, 'r', 'utf-8') > #self.f = open(ordliste) > objDoc = objWord.Documents.Open(dokument) > self.objSelection = objWord.Selection > > def kjor(self): > s = time.clock() > wdReplaceAll = 2 > wdFindContinue = 1 > t = 1 > for i in self.f.readlines(): > en = i.split('\t')[0] > #en = str(en).decode('iso-8859-1') > #en = en.decode('iso-8859-1') > en = unicode(en) > en = en.encode('utf-8') > print en > to = i.split('\t')[1] > #to = str(to).decode('iso-8859-1') > #to = to.decode('iso-8859-1') > to = unicode(to) > to = to.encode('utf-8') > t = t + 1 > if t % 1000 == 0: > print t > try: > self.objSelection.Find.Execute(en, False, True, False, > False, True, True, wdFindContinue, True, to, wdReplaceAll, > False, False, False, False) > except UnicodeEncodeError: > print 'pokker' > except: > pass > > print time.clock() - s > > if __name__ == '__main__': > n = oversett('c:/ordliste.txt','c:/foo.doc') > n.kjor() > > -- http://www.kentsjohnson.com From python at kapitalisten.no Wed Nov 30 15:37:48 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Wed, 30 Nov 2005 15:37:48 +0100 (CET) Subject: [Tutor] Unicode trouble Message-ID: <49598.193.71.38.142.1133361468.squirrel@mail.sporck.net> >Where are you getting these errors (what line of the program)? Do you know >what kind of strings objSelection.Find.Execute() is expecting? > >Kent The program stops working and gives me these errors when I try to run it when it encounters a non-english letter. This is the full error: 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 "C:\Python\BA\Oversett.py", line 47, in ? File "C:\Python\BA\Oversett.py", line 23, in kjor en = i.split('\t')[0] File "C:\Python23\lib\codecs.py", line 388, in readlines return self.reader.readlines(sizehint) File "C:\Python23\lib\codecs.py", line 314, in readlines return self.decode(data, self.errors)[0].splitlines(1) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: invalid data and 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 "C:\Python\BA\Oversett.py", line 49, in ? File "C:\Python\BA\Oversett.py", line 33, in kjor if t % 1000 == 0: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 17: ordinal not in range(128) objSelection.Find.Execute() is supposed to accept any kind of string. (It is the function Search & Replace in MS Word). -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From janos.juhasz at VELUX.com Wed Nov 30 16:18:04 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 30 Nov 2005 16:18:04 +0100 Subject: [Tutor] rare matrix In-Reply-To: Message-ID: Dear All, do you know any python solution to handle big big rare matrices effectively with python. I would make matrix multiplications with 3000x3000 matrices, but with 1-2% data in them. Could you recommend any starting point for that ? Yours sincerely, ______________________________ J?nos Juh?sz From mosinu at gmail.com Wed Nov 30 16:20:35 2005 From: mosinu at gmail.com (Will Harris) Date: Wed, 30 Nov 2005 10:20:35 -0500 Subject: [Tutor] log parsing In-Reply-To: <438D1E3A.8010807@tds.net> References: <5faf36700511291640o21160de7p5e2b22fa7bb14284@mail.gmail.com> <438D1E3A.8010807@tds.net> Message-ID: <5faf36700511300720s121f25a2n6bd6485afa44bab3@mail.gmail.com> Cool, thanks Kent. On 11/29/05, Kent Johnson wrote: > > Will Harris wrote: > > I am trying to work out doing a bit of log parsing in python. Below is > > the code I have gotten so far, It works in an earlier version of this > > one but this one doesn't print out the lines in my log files. Does > > anyone see anything that I am missing here or can just point me in the > > direction to look? > > > > for logs in sys.argv[1:]: > > open(logs) > > for line in logs: > > This should be something like > f = open(logs) > for line in f: > > You are opening the file and throwing it away, then iterating over the > command line argument. > > Kent > > -- > http://www.kentsjohnson.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051130/45ca631b/attachment.html From ajikoe at gmail.com Wed Nov 30 16:21:12 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 30 Nov 2005 16:21:12 +0100 Subject: [Tutor] rare matrix In-Reply-To: References: Message-ID: try numeric or numpy in : http://www.numpy.org/ Cheers, pujo On 11/30/05, J?nos Juh?sz wrote: > > Dear All, > > do you know any python solution to handle big big rare matrices > effectively > with python. > I would make matrix multiplications with 3000x3000 matrices, but with 1-2% > data in them. > Could you recommend any starting point for that ? > > > > Yours sincerely, > ______________________________ > J?nos Juh?sz > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051130/5846729c/attachment.htm From kent37 at tds.net Wed Nov 30 16:23:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Nov 2005 10:23:17 -0500 Subject: [Tutor] rare matrix In-Reply-To: References: Message-ID: <438DC3E5.10200@tds.net> J?nos Juh?sz wrote: > Dear All, > > do you know any python solution to handle big big rare matrices effectively > with python. > I would make matrix multiplications with 3000x3000 matrices, but with 1-2% > data in them. > Could you recommend any starting point for that ? Googling "python sparse matrix" yields several hits that look promising. Kent -- http://www.kentsjohnson.com From kent37 at tds.net Wed Nov 30 16:29:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Nov 2005 10:29:44 -0500 Subject: [Tutor] Unicode trouble In-Reply-To: <49598.193.71.38.142.1133361468.squirrel@mail.sporck.net> References: <49598.193.71.38.142.1133361468.squirrel@mail.sporck.net> Message-ID: <438DC568.6070306@tds.net> ?yvind wrote: > >>Where are you getting these errors (what line of the program)? Do you > > know >what kind of strings objSelection.Find.Execute() is expecting? > >>Kent > > > The program stops working and gives me these errors when I try to run it > when it encounters a non-english letter. > > This is the full error: > 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 "C:\Python\BA\Oversett.py", line 47, in ? > File "C:\Python\BA\Oversett.py", line 23, in kjor > en = i.split('\t')[0] > File "C:\Python23\lib\codecs.py", line 388, in readlines > return self.reader.readlines(sizehint) > File "C:\Python23\lib\codecs.py", line 314, in readlines > return self.decode(data, self.errors)[0].splitlines(1) > UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: > invalid data This is fairly strange as the line en = i.split('\t')[0] should not call any method in codecs. I don't know how you can get such a stack trace. Maybe try deleting all the .pyc files to make sure they are in sync with the source and try again? The actual error indicates that the input data is not valid utf-8. Are you sure that is the correct encoding for the input file? If the file is utf-8 and has bad characters you could pass error='ignore' or error='replace' as a parameter to codecs.open() to change the error handling style to something more forgiving. > > and > > 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 "C:\Python\BA\Oversett.py", line 49, in ? > File "C:\Python\BA\Oversett.py", line 33, in kjor > if t % 1000 == 0: > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 17: > ordinal not in range(128) Again this stack trace doesn't make sense, the indicated line doesn't do any string operation. This error message normally occurs when a non-ascii string is converted to unicode using the default encoding (which is 'ascii'). Often the conversion is implicit in some other operation but I don't see any such operation here. > > objSelection.Find.Execute() is supposed to accept any kind of string. (It > is the function Search & Replace in MS Word). It has to make some assumption about the type of the string. Does it want unicode or encoded bytes? If encoded bytes, what encoding does it expect? Kent -- http://www.kentsjohnson.com From photonquark at comcast.net Wed Nov 30 17:22:34 2005 From: photonquark at comcast.net (Hubert Fitch) Date: Wed, 30 Nov 2005 11:22:34 -0500 Subject: [Tutor] Scientific Notation + 18 Digit Pecision Message-ID: <000d01c5f5ca$48167f40$6401a8c0@hfsys3> Hi Danny! (Python 2.3 IDLE GUI in WindowsXP Home edition) Thank you and the others who have sent replies! Attached to this file is a Rich Text File using "Save Copy As" from the Python Shell display. This will give an example of the desired formatted output. Some displayed lines are long, so I use legal size paper and landscape mode for printing this RTF file. Methods for turning on true division? A. Install the new Python, when it is available. When will this be available? B. from__future__import division This will work properly in an IDLE Python Shell, if I type it in, but not when it is present in .py modules. I see that it was read from the .py file by the python shell, but the behaviour in the shell still is not changed from integer division to normal division. (I put the statement at the beginning of my .py modules.) C. -Qnew I did not understand how to get and install Qnew, so I searched on the information below, and got a lot of results (1100), that confused me further. D. customized parser and evaluator This approach might be the best, but before I consider it, I must get the two affected fuunctions working. I saved the function modules that you refactored for me, into separate files, but should probably put them all into one file later. 1. Extract Equation 2. EvaluateEquation 3. PrintEquationAndValue 4. DisplayPyFile and my 5. Calling Program Module When I ran the caling module, (and got the indentation right in the function modues) all modules appeared to work except for the PrintEquationAnd Value Function which gives a syntax error for "if value:" with an arrow pointing to value. Reproduced below are the four function modules. and the calling module, and included is the original display module. # printEquation.py ############################################ def PrintEquationAndValue(equation, value): """Prints out the equation and its value.""" if value: name, assignment, comment = equation print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) else: print "%s not defined. %s" % (name, assignment) ############################################ # extractEquaiton.py def ExtractEquation(line): """Either returns a 3-tuple (name, assignment, comment) from the line, or None if we can't extract a definition from the line.""" line = line.strip() if not line: return None leftAndRight = line.split('#',2) comment = '' if len(leftAndRight) > 1: comment = leftAndRight[1] assignment = leftAndRight[0] leftAndRight = assignment.split('=') if len(leftAndRight) == 2: name = leftAndRight[0].strip() return (name, assignment, comment) return None # evaluateEquation.py # ############################################## def EvaluateEquation(equation, context): """Evaluates the equation in a given context. If we can't get a value, returns None.""" assert equation != None name, assignment, comment = equation exec(assignment, context) return context.get(name, None) ############################################## # new2DisplayPyFile.py # ############################################# def NewDisplayPyFile(fname, context=None): if context is None: context = globals() f = open(fname) lines = f.readlines() f.close() for line in lines: equation = ExtractEquation(line) if equation: value = EvaluateEquation(equation, context) printEquationAndValue(equation, value) else: print line ############################################## Original display function module. (Notice that I added the from future statement) from __future__ import division def DisplayPyFile(fname, context=None): if context is None: context = globals() f = open(fname) lines = f.readlines() f.close() for line in lines: line = line.strip() if not line: continue leftAndRight = line.split('#',2) comment = '' if len(leftAndRight)>1: comment = leftAndRight[1] assignment = leftAndRight[0] leftAndRight = assignment.split('=') if len(leftAndRight) == 2: name = leftAndRight[0].strip() exec(assignment, context) if context.get(name,None) is not None: value = context.get(name,'???') print "%10s = %18.15e (%s)\t[%s]" % (name, value, assignment, comment) else: print "%s not defined. %s" % (name, assignment) else: print line -------------------------------------------------------------------------------------------- >There are a few ways of fixing this. The easiest is to start Python up with the '-Qnew' command line option, which turns on true division globally: mumak:~ dyoo$ python -Qnew Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information > I'd recommend this approach: it means you won't have to change much. Unfortunately, this means that you'll have to remember to use '-Qnew' all the time, and that's bug-prone. An alternative way is to fix the bug is to modify extractEquation and evaluateEquation so that it doesn't depend on Python's evaluation functions. To an experienced programmer, I'd recommend that approach, to replace the call to 'exec' with a customized parser and evaluator: we have more control over the arithmetic. If you really need something like this, one of us can probably cook up such an evaluator for you. --------------------------------------------------------------------------------------------------- Thank you for your help! Hubert -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20051130/bcc8f456/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: R1SaveCopyAs.rtf Type: application/msword Size: 7721 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20051130/bcc8f456/R1SaveCopyAs-0001.dot From python at kapitalisten.no Wed Nov 30 19:14:14 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Wed, 30 Nov 2005 19:14:14 +0100 (CET) Subject: [Tutor] Unicode trouble Message-ID: <1789.193.71.156.231.1133374454.squirrel@mail.sporck.net> ?yvind wrote: > >>Where are you getting these errors (what line of the program)? Do you > > know >what kind of strings objSelection.Find.Execute() is expecting? > >>Kent > > >> The program stops working and gives me these errors when I try to run it >> when it encounters a non-english letter. > >> This is the full error: >> 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 "C:\Python\BA\Oversett.py", line 47, in ? >> File "C:\Python\BA\Oversett.py", line 23, in kjor >> en = i.split('\t')[0] >> File "C:\Python23\lib\codecs.py", line 388, in readlines >> return self.reader.readlines(sizehint) >> File "C:\Python23\lib\codecs.py", line 314, in readlines >> return self.decode(data, self.errors)[0].splitlines(1) >> UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: >> invalid data >This is fairly strange as the line > en = i.split('\t')[0] >should not call any method in codecs. I don't know how you can get such a >stack trace. The file f where en comes from does contain lots of lines with one english word followed by a tab and a norwegian one. (Approximately 25000 lines) It can look like this: core\tkj?rne So en is supposed to be the english word that the program need to find in MS Word, and to is the replacement word. So wouldn't that be a string that should be handeled by codecs? for i in self.f.readlines(): en = i.split('\t')[0] >Maybe try deleting all the .pyc files to make sure they are in sync with >the source and try again? This didn't seem to help. >The actual error indicates that the input data is not valid utf-8. Are you >sure that is the correct encoding for the input file? If the file is utf-8 >and has bad characters you could pass error='ignore' or error='replace' as >a parameter to codecs.open() to change the error handling style to >something more forgiving. Is not valid utf-8? I have tried with latin-1 as well. No avail. The letters that are the problem is ???. They shouldn't be that exotic? >> 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 "C:\Python\BA\Oversett.py", line 49, in ? >> File "C:\Python\BA\Oversett.py", line 33, in kjor >> if t % 1000 == 0: >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 17: >> ordinal not in range(128) >Again this stack trace doesn't make sense, the indicated line doesn't do >any string operation. >This error message normally occurs when a non-ascii string is converted to >unicode using the default encoding (which is 'ascii'). Often the >conversion is implicit in some other operation but I don't see any such >operation here. But regardless, shouldn't 'ascii' be excluded here? Since I tell the program to change to utf-8, not only once but twice? >> objSelection.Find.Execute() is supposed to accept any kind of string. (It >> is the function Search & Replace in MS Word). >It has to make some assumption about the type of the string. Does it want >unicode or encoded bytes? If encoded bytes, what encoding does it expect? I think the letters should be accepted. The pythonscript here is written to replace abot 25000 MS Word-macros, so all the letters have been accepted by MS Word when feeded by Visual Basic. All I have done now is to extract the words from the macros and put them in a file. -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Wed Nov 30 19:41:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Nov 2005 13:41:54 -0500 Subject: [Tutor] Unicode trouble In-Reply-To: <1789.193.71.156.231.1133374454.squirrel@mail.sporck.net> References: <1789.193.71.156.231.1133374454.squirrel@mail.sporck.net> Message-ID: <438DF272.2060400@tds.net> ?yvind wrote: > ?yvind wrote: > >>>Where are you getting these errors (what line of the program)? Do you >> >>know >what kind of strings objSelection.Find.Execute() is expecting? >> >> >>>Kent >> >> >>>The program stops working and gives me these errors when I try to run it >>>when it encounters a non-english letter. >> >>>This is the full error: >>>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 "C:\Python\BA\Oversett.py", line 47, in ? >>> File "C:\Python\BA\Oversett.py", line 23, in kjor >>> en = i.split('\t')[0] >>> File "C:\Python23\lib\codecs.py", line 388, in readlines >>> return self.reader.readlines(sizehint) >>> File "C:\Python23\lib\codecs.py", line 314, in readlines >>> return self.decode(data, self.errors)[0].splitlines(1) >>>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: >>>invalid data > > >>This is fairly strange as the line >> en = i.split('\t')[0] >>should not call any method in codecs. I don't know how you can get such a >>stack trace. > > The file f where en comes from does contain lots of lines with one english > word followed by a tab and a norwegian one. (Approximately 25000 lines) It > can look like this: core\tkj?rne Yes, I understand that. > So en is supposed to be the english word that the program need to find in > MS Word, and to is the replacement word. So wouldn't that be a string that > should be handeled by codecs? > > for i in self.f.readlines(): > en = i.split('\t')[0] The thing is, it's the line for i in self.f.readlines(): that is calling the codecs module, not the line en = i.split('\t')[0] but it is the latter line that is in the stack trace. Can any of the other tutors make any sense of this stack trace? > >>The actual error indicates that the input data is not valid utf-8. Are > > you >sure that is the correct encoding for the input file? If the file is > utf-8 >and has bad characters you could pass error='ignore' or > error='replace' as >a parameter to codecs.open() to change the error > handling style to >something more forgiving. > > Is not valid utf-8? I have tried with latin-1 as well. No avail. The > letters that are the problem is ???. They shouldn't be that exotic? Not that exotic, no, but they have different representations in latin-1 and utf-8, and maybe other latin-x as well. If you don't know the encoding of your input file, you need to figure it out before you do anything else. > > >>>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 "C:\Python\BA\Oversett.py", line 49, in ? >>> File "C:\Python\BA\Oversett.py", line 33, in kjor >>> if t % 1000 == 0: >>>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 17: >>>ordinal not in range(128) > > >>Again this stack trace doesn't make sense, the indicated line doesn't do >>any string operation. > > >>This error message normally occurs when a non-ascii string is converted > > to >unicode using the default encoding (which is 'ascii'). Often the > >>conversion is implicit in some other operation but I don't see any such >>operation here. > > > But regardless, shouldn't 'ascii' be excluded here? Since I tell the > program to change to utf-8, not only once but twice? if the stack trace made sense I would have a better answer for you. >>>objSelection.Find.Execute() is supposed to accept any kind of string. (It >>>is the function Search & Replace in MS Word). I doubt it. This function has no way to distinguish utf-8 from latin-1 or latin-2 or ebcdic or whatever. If you are giving it encoded strings, it has to make some assumption about the encoding. Or else it is expecting unicode strings. If this is the first time you have had to deal with different encodings you might want to read http://www.joelonsoftware.com/articles/Unicode.html or any of the other articles referenced at the end of this essay: http://www.pycs.net/users/0000323/stories/14.html Kent -- http://www.kentsjohnson.com From klappnase at freenet.de Wed Nov 30 20:46:30 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed, 30 Nov 2005 20:46:30 +0100 Subject: [Tutor] Unicode trouble In-Reply-To: <438DF272.2060400@tds.net> References: <1789.193.71.156.231.1133374454.squirrel@mail.sporck.net> <438DF272.2060400@tds.net> Message-ID: <20051130204630.2ca9aba8.klappnase@freenet.de> On Wed, 30 Nov 2005 13:41:54 -0500 Kent Johnson wrote: > >>>This is the full error: > >>>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 "C:\Python\BA\Oversett.py", line 47, in ? > >>> File "C:\Python\BA\Oversett.py", line 23, in kjor > >>> en = i.split('\t')[0] > >>> File "C:\Python23\lib\codecs.py", line 388, in readlines > >>> return self.reader.readlines(sizehint) > >>> File "C:\Python23\lib\codecs.py", line 314, in readlines > >>> return self.decode(data, self.errors)[0].splitlines(1) > >>>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: > >>>invalid data > > > > > >>This is fairly strange as the line > >> en = i.split('\t')[0] > >>should not call any method in codecs. I don't know how you can get such a > >>stack trace. > > > > The file f where en comes from does contain lots of lines with one english > > word followed by a tab and a norwegian one. (Approximately 25000 lines) It > > can look like this: core\tkj?rne > > Yes, I understand that. > > > So en is supposed to be the english word that the program need to find in > > MS Word, and to is the replacement word. So wouldn't that be a string that > > should be handeled by codecs? > > > > for i in self.f.readlines(): > > en = i.split('\t')[0] > > The thing is, it's the line > for i in self.f.readlines(): > that is calling the codecs module, not the line > en = i.split('\t')[0] > but it is the latter line that is in the stack trace. > > Can any of the other tutors make any sense of this stack trace? As far as I see here, isn't the line return self.decode(data, self.errors)[0].splitlines(1) causing the traceback? I haven't read all of this thread, but maybe you are trying to pass a non-utf8 string to the utf8 codec? Michael From kent37 at tds.net Wed Nov 30 23:05:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 30 Nov 2005 17:05:46 -0500 Subject: [Tutor] Unicode trouble In-Reply-To: <20051130204630.2ca9aba8.klappnase@freenet.de> References: <1789.193.71.156.231.1133374454.squirrel@mail.sporck.net> <438DF272.2060400@tds.net> <20051130204630.2ca9aba8.klappnase@freenet.de> Message-ID: <438E223A.7040707@tds.net> Michael Lange wrote: > On Wed, 30 Nov 2005 13:41:54 -0500 > Kent Johnson wrote: >>>>>This is the full error: >>>>>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 "C:\Python\BA\Oversett.py", line 47, in ? >>>>> File "C:\Python\BA\Oversett.py", line 23, in kjor >>>>> en = i.split('\t')[0] >>>>> File "C:\Python23\lib\codecs.py", line 388, in readlines >>>>> return self.reader.readlines(sizehint) >>>>> File "C:\Python23\lib\codecs.py", line 314, in readlines >>>>> return self.decode(data, self.errors)[0].splitlines(1) >>>>>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 168-170: >>>>>invalid data >>> >>> >>>>This is fairly strange as the line >>>>en = i.split('\t')[0] >>>>should not call any method in codecs. I don't know how you can get such a >>>>stack trace. >>> >>Can any of the other tutors make any sense of this stack trace? > > > As far as I see here, isn't the line > > return self.decode(data, self.errors)[0].splitlines(1) > > causing the traceback? > > I haven't read all of this thread, but maybe you are trying to pass a > non-utf8 string to the utf8 codec? Yes, I guess that much is pretty clear - there is some data in the source file that is not valid utf-8. Kent From keridee at jayco.net Wed Nov 30 23:00:09 2005 From: keridee at jayco.net (Jacob S.) Date: Wed, 30 Nov 2005 17:00:09 -0500 Subject: [Tutor] Need help with wxListCtrl Message-ID: <001c01c5f5f9$84c67e70$6501a8c0@JSLAPTOP> Hi, long time no see. For you Spanish speakers: Yo ten?a que aprender a poco espa?ol mientras no estaba aqu?. Si ustedes son aburrido y me desean ayudar aprender m?s, mandan una -- ?Qu? desea decir "email"? Y no mandan el (email) en el (mailing list), por favor. (It would be much, much appreciated.) Okay, now that that is done, I would appreciate help with the wxListCtrl. The documentation is supposed to be portable between languages, but it confuses me. Using boa-constructor, I have placed a wxListCtrl on my form, but am unable to figure out how to add items to it. Diagram below. +-----------+---------------------+--------------------+------------------+----------------+---------+ | Date | Description | Points | Points Possible | Percentage | Grade | +-----------+---------------------+--------------------+------------------+----------------+---------+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | +-----------+---------------------+--------------------+------------------+----------------+---------+ I noticed there is a simplified form of wxListCtrl, but both seem to want to add wxListItem s which include images, etc. Does anyone know a straight forward way to add lines to this control implicitly -- programmatically? I figure if I don't get responses here, I will try at the wxPython list. (I hesitate to do that yet, I know you better here) Sincerely, Jacob From keridee at jayco.net Wed Nov 30 23:29:43 2005 From: keridee at jayco.net (Jacob S.) Date: Wed, 30 Nov 2005 17:29:43 -0500 Subject: [Tutor] Need help with wxListCtrl Message-ID: <005901c5f5fd$a458ef30$6501a8c0@JSLAPTOP> Resending due to change in subject line -- adding [Tutor] Also, I wish to point out now that I've noticed, the spacing on the diagram hasn't persisted.... If anyone wants a jpg or something, let me know. > Hi, long time no see. > > For you Spanish speakers: > > Yo ten?a que aprender a poco espa?ol mientras no estaba aqu?. Si ustedes > son aburrido y me desean ayudar aprender m?s, mandan una -- ?Qu? desea > decir "email"? Y no mandan el (email) en el (mailing list), por favor. > (It would be much, much appreciated.) > > > > Okay, now that that is done, I would appreciate help with the wxListCtrl. > The documentation is supposed to be portable between languages, but it > confuses me. Using boa-constructor, I have placed a wxListCtrl on my > form, but am unable to figure out how to add items to it. Diagram below. > > > > +-----------+---------------------+--------------------+------------------+----------------+---------+ > > | Date | Description | Points | > Points Possible | Percentage | Grade | > > +-----------+---------------------+--------------------+------------------+----------------+---------+ > > | | | | > | | | > > | | | | > | | | > > | | | | > | | | > > | | | | > | | | > > | | | | > | | | > > | | | | > | | | > > | | | | > | | | > > +-----------+---------------------+--------------------+------------------+----------------+---------+ > > > I noticed there is a simplified form of wxListCtrl, but both seem to want > to add wxListItem s which include images, etc. > Does anyone know a straight forward way to add lines to this control > implicitly -- programmatically? > I figure if I don't get responses here, I will try at the wxPython list. > (I hesitate to do that yet, I know you better here) > > Sincerely, > Jacob