From alan.gauld@bt.com Sat Jun 1 00:00:58 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sat, 1 Jun 2002 00:00:58 +0100 Subject: [Tutor] Catching the exit Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C631@mbtlipnt02.btlabs.bt.co.uk> > def catchexit(event): > query = askyesno(title='Warning', message='Did you save > your work') > print query > if query == 'Yes': > sys.exit() > else: > return I think this return will now take you into the default handler which will exit anyway. You need to use return "break" to turn off the default behaviour. Alan G From mpeters@mac.com Sat Jun 1 10:31:12 2002 From: mpeters@mac.com (Michael A. Peters) Date: Sat, 1 Jun 2002 02:31:12 -0700 Subject: [Tutor] Python and PHP config files Message-ID: <20020601023112.7fec147b.mpeters@mac.com> Hi all- I'm trying to have python run as a cron in the background to assist in a php web application. I need to have the python script be able to get values from a php config file. Here's the relative parts of my script so far- ------------------------------- #!/usr/local/bin/python PathToConfig = "/var/www/folding_stats/folding.config.php" import os, sys, urllib try: import MySQLdb except ImportError, e: print "It seems you do not have the python MySQLdb module installed." sys.exit(1) if os.path.isfile(PathToConfig): # here is where I read the data I need datafile = open(PathToConfig) config = datafile.readlines() datafile.close() else: print "I can not find your config file." print "Please specify its location at" print "line 2 of this file." sys.exit(1) ------------------------------- config is now an array containing the php file- but I need to extract info out of that, and I can't seem to figure out how :( For example, the lines in the file i need are- $db_name="foldingathome"; $db_host="localhost"; $db_port="3306"; $db_user="samwise"; $db_password="xyzzy"; I need to find where the php variable for db_name is defined and assign a python variable for that- such as db_name = somefunction(config, db_name) where somefunction(config, db_name) would find $db_name= in the config list and then return what's in their. Anyone know how to do it? in bourne with shell tools I would do db_name=`grep "^\$db_name=" filename |cut -d"\"" -f2` but I'm using python, not bourne :D Thanks for any help From kalle@lysator.liu.se Sat Jun 1 14:44:37 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Sat, 1 Jun 2002 15:44:37 +0200 Subject: [Tutor] Python and PHP config files In-Reply-To: <20020601023112.7fec147b.mpeters@mac.com> References: <20020601023112.7fec147b.mpeters@mac.com> Message-ID: <20020601134437.GA1640@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Michael A. Peters] > For example, the lines in the file i need are- > > $db_name="foldingathome"; > $db_host="localhost"; > $db_port="3306"; > $db_user="samwise"; > $db_password="xyzzy"; > > I need to find where the php variable for db_name is defined and assign a > python variable for that- such as > > db_name = somefunction(config, db_name) > where > somefunction(config, db_name) > would find $db_name= in the config list and then return what's in their. A rough beginning might look something like this: def find_parameter(config_lines, parameter): for line in config_lines: if line.find(parameter) >= 0: return line.split("=")[1] It can be used like this: >>> config = ['foo\n', '$db_host="host";\n', '$db_user="user";\n'] >>> find_parameter(config, "$db_user") '"user";\n' See http://python.org/doc/current/lib/string-methods.html for more information about string methods like find and split. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE8+M+odNeA1787sd0RAhNBAKC0WIDuM8Utz7UtDKAytDc/8z6+HgCeKeDL UgwMzmTkaqyIkbrspapR4Hs= =7UWR -----END PGP SIGNATURE----- From lkvam@venix.com Sat Jun 1 23:43:55 2002 From: lkvam@venix.com (Lloyd Kvam) Date: Sat, 01 Jun 2002 18:43:55 -0400 Subject: [Tutor] Python and PHP config files References: <20020601023112.7fec147b.mpeters@mac.com> <20020601134437.GA1640@i92.ryd.student.liu.se> Message-ID: <3CF94E2B.2020604@venix.com> An alternative approach would be to put the config information into a dictionary. Picking up from your code: ... config = datafile.readlines() config_dict = {} for con in config: #line by line name,value = con.split('=') #split as Kalle did config_dict[name] = value ... now db = config_dict["db_name"] When I can, I like to save my config info directly in a dictionary that I simply import. Kalle Svensson wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [Michael A. Peters] > >>For example, the lines in the file i need are- >> >>$db_name="foldingathome"; >>$db_host="localhost"; >>$db_port="3306"; >>$db_user="samwise"; >>$db_password="xyzzy"; >> >>I need to find where the php variable for db_name is defined and assign a >>python variable for that- such as >> >>db_name = somefunction(config, db_name) >>where >>somefunction(config, db_name) >>would find $db_name= in the config list and then return what's in their. >> > > A rough beginning might look something like this: > > def find_parameter(config_lines, parameter): > for line in config_lines: > if line.find(parameter) >= 0: > return line.split("=")[1] > > It can be used like this: > > >>>>config = ['foo\n', '$db_host="host";\n', '$db_user="user";\n'] >>>>find_parameter(config, "$db_user") >>>> > '"user";\n' > > See http://python.org/doc/current/lib/string-methods.html for more > information about string methods like find and split. > > Peace, > Kalle > - -- > Kalle Svensson, http://www.juckapan.org/~kalle/ > Student, root and saint in the Church of Emacs. > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.0.7 (GNU/Linux) > Comment: Processed by Mailcrypt 3.5.6 > > iD8DBQE8+M+odNeA1787sd0RAhNBAKC0WIDuM8Utz7UtDKAytDc/8z6+HgCeKeDL > UgwMzmTkaqyIkbrspapR4Hs= > =7UWR > -----END PGP SIGNATURE----- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo@hkn.eecs.berkeley.edu Sun Jun 2 02:07:29 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 1 Jun 2002 18:07:29 -0700 (PDT) Subject: [Tutor] Why NOT to Use Python? [A Perl apologist] In-Reply-To: <20020529224330.C6147@localhost.localdomain> Message-ID: > I learned perl first, and switched to python because I wanted a language > with better object oriented support. I also wanted to parse xml data, > and I was told python was much better for this task than perl. I may need to get myself in a mean frame of mind before I defend Perl. *grin* Cheekiness aside, I think Perl does have excellent XML support; Michel Rodriguez's XML::Twig module is very nice: http://www.xmltwig.com/ and I think it would be great if there were a Python equivalent to XML::Twig, but perhaps I haven't looked hard enough yet. > So far, I think python is *much* better than perl. In fact, I would tell > anybody learning perl this: "Don't bother. Python can do everything perl > can, but the code is much more readable and easier to maintain. At the same time, it's still a good thing to peek at the other side of the fence every now and then, just to see what's out there. There is something... seductive about tricky programming. I can understand how Perl can appeal to certain minds. I guess I'm trying to say that it might be counterproductive to discourage people from looking at the other languages. I feel that most people are intelligent enough to look at the choices out there, weigh the pros and cons, and decide for themselves that Python is a superb language. *grin* Hope this helps! From shalehperry@attbi.com Sun Jun 2 05:27:29 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat, 01 Jun 2002 21:27:29 -0700 (PDT) Subject: [Tutor] Why NOT to Use Python? [A Perl apologist] In-Reply-To: Message-ID: > >> So far, I think python is *much* better than perl. In fact, I would tell >> anybody learning perl this: "Don't bother. Python can do everything perl >> can, but the code is much more readable and easier to maintain. > > At the same time, it's still a good thing to peek at the other side of the > fence every now and then, just to see what's out there. There is > something... seductive about tricky programming. I can understand how > Perl can appeal to certain minds. > > > I guess I'm trying to say that it might be counterproductive to discourage > people from looking at the other languages. I feel that most people are > intelligent enough to look at the choices out there, weigh the pros and > cons, and decide for themselves that Python is a superb language. *grin* > I do not remember where the quote it from but it goes something like "A man willing to test his convictions is better than one who blindly believes". I too am a recovering perl user who can't imaging going back. However 80% of the last group I worked with were rabid perl hackers. I know why too -- it matched how they thought. Quick hacks, their own personal (and often weird) approach to coding, etc. Python's "bland" and "homogenizing" approach would not fit them. Coding is a personal thing, people need to use what works for them. From dyoo@hkn.eecs.berkeley.edu Sun Jun 2 07:47:59 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 1 Jun 2002 23:47:59 -0700 (PDT) Subject: [Tutor] Dots-And-Boxes Message-ID: Hi everyone, [Warning; somewhat long message. Sorry!] For fun, I picked up Elwyn Berlekamp's "The Dots and Boxes Game", which is a book about a deceptively simple game. Here's Berlekamp's paragraph describing the game: """Dots-and-Boxes is a familiar paper an pencil game for two players; it has other names in various parts of the world. Two players start from a rectangular array of dots and take turns to join two horizonally or vertically adjacent dots. If a player completes the fourth side of a square (box) he initials that box and must then draw another line. When all the boxes have een completed the game ends and whoever has initialed more boxes is declared the winner. A player who can complete a box is not obligated to do so if he has something else he prefers to do.""" To make the game clearer, I'll run through a sample game. Let's say that two players, A and B, are playing Dots-And-Boxes on a 3x3 board: + + + + + + + + + Here's one run through the game: +--+ + + + + + + + Player A chooses to join the first two dots. +--+ + | + + + + + + Player B chooses to join the mid-top and middle. The game can proceed like this: +--+ + | + + + A moves a bit more down. | + + + +--+ + | + + + B makes it snake around a bit. | + +--+ +--+ + | + + + A connects the lower left and mid left points. | | + +--+ +--+ + | + + + A connects the lower left and mid left points. | | + +--+ +--+ + | + + + B forgets that the game is not Hangman. | | +--+--+ +--+ + | +--+ + A completes a square. Because of this, it's A's turn | A| again. +--+--+ +--+ + | A| +--+ + A completes the upper left square. Another free turn. | A| +--+--+ +--+--+ | A| +--+ + A plays the upper right square, finally giving a turn | A| to B. But it's too late. +--+--+ +--+--+ | A| +--+ + B places a futile line. | A| | +--+--+ +--+--+ | A| +--+--+ And A promptly trounces. | A| A| +--+--+ +--+--+ | A| A| +--+--+ A dominates the game. | A| A| +--+--+ So it's sorta like Tic-Tac-Toe, but a little more interesting. Yahoo Games actually has this as one of their Java applets, I think... but wouldn't it be fun to write a Python program to play this game? *grin* (We could even hold a Tutor Dots-And-Boxes competition, where our program battle each other! Hmmm!) Fantasies aside, I'm written some toy code and thought perhaps someone here might be interested too. My code for the game is here: http://hkn.eecs.berkeley.edu/~dyoo/python/dots-and-boxes/board.py I need to start working on the GUI for it since entering coordinates can be a bit non-user-friendly; I'll start on this tomorrow. From urnerk@qwest.net Sun Jun 2 08:09:21 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 02 Jun 2002 00:09:21 -0700 Subject: [Tutor] Why NOT to Use Python? [A Perl apologist] In-Reply-To: References: Message-ID: <4.2.0.58.20020601234955.01bfef00@pop3.norton.antivirus> > >I too am a recovering perl user who can't imaging going back. However 80% of >the last group I worked with were rabid perl hackers. I know why too -- it >matched how they thought. Quick hacks, their own personal (and often weird) >approach to coding, etc. Python's "bland" and "homogenizing" approach would >not fit them. > >Coding is a personal thing, people need to use what works for them. I'm currently a Python coder (coming from APL, PL/1, Fortran, some Java, dBase -> VFP7 (mainly this last, as a career even)). However, I have fun learning Perl in my spare time. I'm currently perusing the print version (O'Reilly, 1999) of Eric S. Raymond's 'The Cathedral & the Bazaar' (a key text in the open source syllabus, which I tend to link to 'design science revolution' -- another story (see Stutz, Linux Cookbook)) suggests Python -> Java -> C/C++ as a good sequence, and I agree that this is a fine way to go. He also throws LISP into the bag, which I might approach via Scheme (the PLT flavor by Matthias & Co. and Rice Univ., to be specific). It's somewhat ironic, ain't it?, that Java was designed with C/C++ programmers in mind (aimed to capitalize on this huge skillbase by adopting similar syntax) and yet now we have a next generation of hacker using the similarities to go _from_ Java _to_ C, instead of coming the other way. Likewise, Python can be an onramp into programming in general, and from there one branch out into whatever -- Perl included (continuing literacy in this language most definitely a plus, especially given the trajectory of Unix/GNU/Linux in century 0x15). I think the most healthful attitude is to become a connoisseur of many languages, vs. a partisan/fanatic/religious-warrior who gets sucked in to thinking that what's best is to behave as a proselytizer/missionary on behalf of one in particular. Likewise when it comes to operating systems -- provided none are backed against the wall in danger of complete extinction (Linux is in no such danger, so I don't do bared fangs thing -- Windows is more the dinosaur in this evolutionary picture, which doesn't mean we should hasten its extinction (we need to buy some time here, as a lot of the best apps/games are written to that massively popular platform))). BeOS is also worth adding to a multi-boot system. So yes, Python is exceedingly great, a fantastic language, but that doesn't move me to diss Perl, which I also appreciate, and love spending some free time tackling (was reading about package-level symbol tables vs. my() variables earlier tonight). I'm also revisiting C/C++ and have plenty of respect for Scheme and LISP. And I'll always be nostalgic for my first love: APL. Vive le Difference! Kirby From urnerk@qwest.net Sun Jun 2 08:14:46 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 02 Jun 2002 00:14:46 -0700 Subject: [Tutor] Dots-And-Boxes In-Reply-To: Message-ID: <4.2.0.58.20020602001027.01bfebc0@pop3.norton.antivirus> >\ >"""Dots-and-Boxes is a familiar paper an pencil game for two players; Thanks for bringing this up Danny. In earlier lives (as a younger guy), I played this game quite a bit on paper, with my sister Julie, peer group. Taught it to a few people. Then I forgot about it completely -- until now. I always called it "Square Off" and played it on graphing paper (grid paper). Yes, having a GUI version w/ Python guts would be mucho fun and a challenging project. I salute you for initiating this bold proposal, backed with original code. Kirby From shalehperry@attbi.com Sun Jun 2 08:21:48 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun, 02 Jun 2002 00:21:48 -0700 (PDT) Subject: [Tutor] Dots-And-Boxes In-Reply-To: <4.2.0.58.20020602001027.01bfebc0@pop3.norton.antivirus> Message-ID: On 02-Jun-2002 Kirby Urner wrote: > >>\ >>"""Dots-and-Boxes is a familiar paper an pencil game for two players; > > > Thanks for bringing this up Danny. In earlier lives (as a > younger guy), I played this game quite a bit on paper, with > my sister Julie, peer group. Taught it to a few people. > Then I forgot about it completely -- until now. I always > called it "Square Off" and played it on graphing paper > (grid paper). > > Yes, having a GUI version w/ Python guts would be mucho fun > and a challenging project. I salute you for initiating this > bold proposal, backed with original code. > yeah, great one from childhood. For the competition the design can be much simpler. Have the player program read state from stdin and output moves to stdout. A mediator program can init to players and control the game. Much like the various net programming contests. a sample session from the mediator's perspective would be: (>> is output, <1 is player1 input, <2 is player2 input) player 1 always goes first. >1 init player1 as 1, grid 5x5 >2 init player2 as 2, grid 5x5 <1 move (0,0) (0,1) >2 connect (0,), (0,1) <2 move (5,0), (5,1) 1> connect (5,0), (5,1) ... <1 move (3,2), (3,3) # this move makes a box and wins >2 connect (3,2), (3,3) >2 conceed >> Player 1 wins, total .. out of .. From cpepperrell@hotmail.com Sun Jun 2 08:43:53 2002 From: cpepperrell@hotmail.com (christopher pepperrell) Date: Sun, 02 Jun 2002 07:43:53 +0000 Subject: [Tutor] Im just starting Message-ID: Hi All! I am new to this and have just downloaded "Python" can anyone give me advice as to the best online Tutor to start with. Regards Chris _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From dyoo@hkn.eecs.berkeley.edu Sun Jun 2 08:51:03 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 2 Jun 2002 00:51:03 -0700 (PDT) Subject: [Tutor] Im just starting In-Reply-To: Message-ID: On Sun, 2 Jun 2002, christopher pepperrell wrote: > I am new to this and have just downloaded "Python" can anyone > give me advice as to the best online Tutor to start with. Hi Chris, welcome aboard! Check out the "Python for Beginners" page --- it has a bunch of links to online tutorials: http://www.python.org/doc/Newbies.html I'm partial to "Learn to Program Using Python", but that's just because I'm trying to make Alan Gauld blush (he's one of the Tutors here too). But all of the tutorials there are really good. And if you're looking for online Tutors of the human kind, you've come to the right place. Feel free to ask questions here on tutor@python.org, and we'll be happy to talk with you. From virketis@post.harvard.edu Sun Jun 2 16:24:20 2002 From: virketis@post.harvard.edu (Pijus Virketis) Date: Sun, 2 Jun 2002 11:24:20 -0400 Subject: [Tutor] Dots-And-Boxes In-Reply-To: Message-ID: <200206021524.g52FOM532726@smtp3.fas.harvard.edu>
Reading through Danny's code, I found a frequently used= keyword "assert", like so:
 
assert 2 <=3D self.width and 2 <=3D= self.height,\
          =      "Game can't be played on this= board's dimension."
 
I've never seen if before, so I checked the Reference, and= found a description here: http://= www.python.org/doc/current/ref/assert.html. However, the= syntax given there is different:
 
if __debug__:
   if not expression: raise= AssertionError

Also, the keyword itself is not really mentioned. So, my question= is this: what does "assert" do, and where can I find= out more about its use the way Danny employs it?
 
Cheers,
 
Pijus

--
"Anyone attempting to generate random numbers by= deterministic means is, of course, living in a state of= sin." -- John Von Neumann
From wolf_binary@hotmail.com Sun Jun 2 16:58:07 2002 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Sun, 2 Jun 2002 10:58:07 -0500 Subject: [Tutor] inherince and dependancy Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0009_01C20A24.60D70580 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, I have a few questions listed here: 1.) If your have classes inherit from mulitple other classes doesn't = that build dependency in your program? =20 2.) Doesn't it also make reusability of code more difficult? =20 3.) If you have multiple inheritance doesn't it make changeability in = the code easier? You don't have to make changes in multiple places then = right? Thanks for your help, Cameron Stoner ------=_NextPart_000_0009_01C20A24.60D70580 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi all,
 
I have a few questions listed = here:
 
1.)  If your have classes inherit = from=20 mulitple other classes doesn't that build dependency in your = program? =20
 
2.)  Doesn't it also make = reusability of code=20 more difficult? 
 
3.)  If you have multiple = inheritance doesn't=20 it make changeability in the code easier?  You don't have to make = changes=20 in multiple places then right?
 
Thanks for your help,
Cameron Stoner
 
 
------=_NextPart_000_0009_01C20A24.60D70580-- From kalle@lysator.liu.se Sun Jun 2 17:27:59 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Sun, 2 Jun 2002 18:27:59 +0200 Subject: [Tutor] Dots-And-Boxes In-Reply-To: <200206021524.g52FOM532726@smtp3.fas.harvard.edu> References: <200206021524.g52FOM532726@smtp3.fas.harvard.edu> Message-ID: <20020602162759.GA972@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Pijus Virketis] > Reading through Danny's code, I found a frequently used keyword > "assert", like so: > > assert 2 <= self.width and 2 <= self.height,\ > "Game can't be played on this board's dimension." > > I've never seen if before, so I checked the Reference, and found a > description here: > http://www.python.org/doc/current/ref/assert.html. However, the > syntax given there is different: > > if __debug__: > if not expression: raise AssertionError This is the eqivalent replacement syntax for assert expression > Also, the keyword itself is not really mentioned. So, my question is > this: what does "assert" do, and where can I find out more about its > use the way Danny employs it? The assert statement evaluates an expression, and if the result is false (0, None, [], () or "", for example) raises an AssertionError. This only happens if the built-in variable __debug__ is true. Thus: assert a == b and if __debug__: if not a == b: raise AssertionError do the same thing. __debug__ is always true if you haven't started python with the -O option. For example: : kalle@chloe [~]$ ; python -O -c "assert 0; print 'Hi'" Hi : kalle@chloe [~]$ ; python -c "assert 0; print 'Hi'" Traceback (most recent call last): File "", line 1, in ? AssertionError Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE8+keJdNeA1787sd0RApPXAKDIMTMxwawwq/nmnxS5kQikVcy97ACgqJrh +e8UgNtFiAQwG9K99dw3nWc= =kybv -----END PGP SIGNATURE----- From kalle@lysator.liu.se Sun Jun 2 17:45:42 2002 From: kalle@lysator.liu.se (Kalle Svensson) Date: Sun, 2 Jun 2002 18:45:42 +0200 Subject: [Tutor] Dots-And-Boxes In-Reply-To: <20020602162759.GA972@i92.ryd.student.liu.se> References: <200206021524.g52FOM532726@smtp3.fas.harvard.edu> <20020602162759.GA972@i92.ryd.student.liu.se> Message-ID: <20020602164542.GB972@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [I wrote about assert statements] > __debug__ is always true if you haven't started python with the -O > option. For example: > > : kalle@chloe [~]$ ; python -O -c "assert 0; print 'Hi'" > Hi > : kalle@chloe [~]$ ; python -c "assert 0; print 'Hi'" > Traceback (most recent call last): > File "", line 1, in ? > AssertionError Note, though: : kalle@chloe [~]$ ; python -c "__debug__ = 0; assert 0; print 'Hi'" :0: SyntaxWarning: can not assign to __debug__ Hi : kalle@chloe [~]$ ; python -V Python 2.1.3 That is, __debug__ can be assigned to in Python 2.1.3 (and earlier), but it will raise a SyntaxWarning (in 2.1.x). : kalle@chloe [~]$ ; python2.2 -c "__debug__ = 0; assert 0; print 'Hi'" File "", line 1 SyntaxError: can not assign to __debug__ : kalle@chloe [~]$ ; python2.2 -V Python 2.2.1 In Python 2.2 it is no longer possible to assign to __debug__. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE8+kuzdNeA1787sd0RAmpoAJ9dm8Ig+rNHkSisVxcBaIlAqAwkFQCfd/01 Q/jm/jAdVPccrw4+Eq1EdNc= =WxjD -----END PGP SIGNATURE----- From alex@gabuzomeu.net Sun Jun 2 18:05:54 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Sun, 02 Jun 2002 19:05:54 +0200 Subject: assert (was "[Tutor] Dots-And-Boxes") In-Reply-To: <20020602160004.8543.12057.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020602185246.00b78b70@pop3.norton.antivirus> Hi Pijus, At 12:00 02/06/2002 -0400, you wrote: >From: Pijus Virketis >Date: Sun, 2 Jun 2002 11:24:20 -0400 >Subject: Re: [Tutor] Dots-And-Boxes >Reading through Danny's code, I found a frequently used keyword "assert" >Also, the keyword itself is not really mentioned. So, my question is this: >what does "assert" do, and where can I find out more about its use the way >Danny employs it? Here is a short description: """There is now an assert statement: ``assert '' or ``assert , ''. It raises AssertionError if the condition evaluates to false. The default error message is empty; the source text of the assertion statement is printed as part of the traceback.""" Source: http://www.python.org/1.5/whatsnew.html You can use "assert" to test a condition in a program. With "assert", you don't need to include "if" tests when debugging. Example: >>> toto = 2 >>> assert toto > 1, "Wrong value" Nothing happens, i.e. assertion is true. >>> assert toto < 1, "Wrong value" Traceback (most recent call last): File "", line 1, in ? AssertionError: Wrong value Here the test failed, so you get a traceback. I remember dimly assertion testing can be switched off for speed (with a command line flag, I think). Cheers. Alexandre From phinsxiii@knology.net Sun Jun 2 18:10:13 2002 From: phinsxiii@knology.net (SA) Date: Sun, 02 Jun 2002 12:10:13 -0500 Subject: [Tutor] Text to HTML question. Message-ID: Hi Everyone- I have a couple of questions for ya. Remember I'm new to Python and am still learning: 1. I have a bunch of text files. I have a python script to generate html. I would like to substitute the body of the text files in between of the html file. I think I can get this part. The trouble I'm having is formatting the text body into html. For instance for every "\n" in the text body I need to substitute
before placing it into the html file body section. And for every "\n\n" I wish to substitute

. I suppose I nead to use regexp, but how do you call the re module and search/sub these patterns? 2. I'm sure this is probably a problem that has been solved before, so does anyone know of a module to do this and how do I use it to accomplish the goal? Thanks in advance for your help. I'm just now starting to get the whole class thing in Python. SA From haroldmerrill@yahoo.com Mon Jun 3 00:02:15 2002 From: haroldmerrill@yahoo.com (Harold Merrill) Date: Sun, 2 Jun 2002 16:02:15 -0700 (PDT) Subject: [Tutor] Extension Message-ID: <20020602230215.11217.qmail@web20002.mail.yahoo.com> Can you write Python in WordPad? What is the extension (ex. HTML is *.htm or *.html)? Thanks, Harold __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From dyoo@hkn.eecs.berkeley.edu Mon Jun 3 00:53:46 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 2 Jun 2002 16:53:46 -0700 (PDT) Subject: [Tutor] Extension In-Reply-To: <20020602230215.11217.qmail@web20002.mail.yahoo.com> Message-ID: On Sun, 2 Jun 2002, Harold Merrill wrote: > Can you write Python in WordPad? Hi Harold, It would be technically possible, but not too fun, since WordPad will try to treat the Python source as if it were a document for humans --- it would get in the way a lot. Notepad would be a better program to edit Python, since it wouldn't interfere as much, but there are actually better text editors you can use. If you install Python, it automatically comes with a text editor called IDLE, and IDLE's pretty good. I have a small tutorial on how to start playing with it here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro > What is the extension (ex. HTML is *.htm or *.html)? Python programs often have the extension '.py'. If you have more questions, please feel free to ask. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Jun 3 01:02:00 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 2 Jun 2002 17:02:00 -0700 (PDT) Subject: [Tutor] Text to HTML question. [string.replace()] In-Reply-To: Message-ID: On Sun, 2 Jun 2002, SA wrote: > I have a couple of questions for ya. Remember I'm new to Python and > am still learning: No problem! Let's take a look at your question. > 1. I have a bunch of text files. I have a python script to generate > html. I would like to substitute the body of the text files in between > of the html file. I think I can get this part. The trouble > I'm having is formatting the text body into html. For instance for every > "\n" in the text body I need to substitute
before placing it into > the html file body section. And for every "\n\n" I wish to substitute >

. I suppose I nead to use regexp, but how do you call the re module > and search/sub these patterns? For text substitution like this, we might be able to get away with just using the 'replace()' method of strings. Here's an example of what I mean: ### >>> story = """Gully Foyle is my name ... And Terra is my nation ... Deep space is my dwelling place ... And death's my destination.""" >>> new_story = story.replace("And death's", "The stars") >>> print story Gully Foyle is my name And Terra is my nation Deep space is my dwelling place And death's my destination. >>> print new_story Gully Foyle is my name And Terra is my nation Deep space is my dwelling place The stars my destination. ### What comes out of replace() is a new string, where all instances of the thing we want to replace will be substituted. This leaves the old string alone though. If we want to make it look as if the string were being transformed, in-place, we can do something like this: ### >>> story = story.replace("And death's", "The stars") >>> print story Gully Foyle is my name And Terra is my nation Deep space is my dwelling place The stars my destination. ### and now 'story' contains the modified story. You can use string.replace() to solve your text->HTML problem. Just make sure to convert all the "\n\n" substrings first --- if you convert all single '\n' characters first, that wipes out the empty lines! *grin* So be careful about the order. Good luck! From glingl@aon.at Mon Jun 3 01:50:06 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 3 Jun 2002 02:50:06 +0200 Subject: [Tutor] Dots-And-Boxes References: Message-ID: <001901c20a98$9abfc100$1615a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0016_01C20AA9.5E03E6E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hi! Until now I didn't know "The Dots and Boxes" Game, but Dannies program made me interested in it. So I wrote the beginning of a gui version. I tried hard to use Dannies code as is - so the gui code is (nearly) completely separated from the game machinery. I consider this a proof for the exceptionally good design of Dannies program (imho). O.k., maybe my extension of the program still needs some more buttons or textfields or so, but perhaps it could be a starting point. Critical remarks are strongly welcome. I'm especially interested in a comparison with an implementation using Pygame - this is what Danny has in mind to do? Making the computer play the game is still another point ... Gregor P.S.: There is one point, which is not completely clear to me: Danny's algorithm always assigns only one square to the player who did the last move, even if his draw completes two squares, So in the end the sum of the points may be less than (w-1)*(h-1). Is this according to the rules of the game? -------------- here follows the code, which is also attached: """Graphic user interface to Danny Yoo's 'dots and boxes' -program. I tried to avoid changes to this program as far as possible. So there remain the following changes: Line 222: Return statement in play() now returns the square_corner instead of 1 (this was the only necessary one (in m opinion) Line 255/256: head of for-loop --- this was the easiest way to accomodate text-output to graphical one. ( Bad design decision for the graphics display, may be reverted if there is time ...) Lines 305-318, 332, 333: A somewhat safer input method for more convenient testing Lines 354ff: Incorporate graphics mode into __main__() """ from Tkinter import * from Canvas import Rectangle def cartesian( v1, v2 ): """ Helper function returns cartesian product of the two 'sets' v1, v2""" return tuple([(x,y) for x in v1 for y in v2]) def right(x): """Helper function: argument x must be a dot. Returns dot right of x.""" return (x[0]+1,x[1]) def upper(x): """Helper function: argument x must be a dot. Returns dot above (actually below) x.""" return (x[0], x[1]+1) class GameGUI: def __init__(self, board): """Initializes graphic display of a rectangular gameboard.""" # Properties of gameboard dw = self.dotwidth = 6 sw = self.squarewidth = 60 sk = self.skip = 4 fw = self.fieldwidth = dw + sw + 2*sk ins = self.inset = sw/2 self.barcolors = ['red','blue'] self.squarecolors = ['orange', 'lightblue'] # Construct Canvas self.board = board width, height = board.width, board.height # compute size of canvas: w = width * fw h = height * fw self.root = Tk() cv = self.cv = Canvas(self.root, width=w, height=h, bg='white') cv.bind('', self._callback) cv.pack() # Put geometrical objects - dots, bars and squares - on canvas self.bars = {} self.squares = {} for dot in cartesian(range(width), range(height)): # dots. Never used again Rectangle( cv, ins+dot[0]*fw, ins+dot[1]*fw, ins+dot[0]*fw + dw, ins+dot[1]*fw + dw, fill='black', outline='' ) # horizontal bars if dot[0] < width - 1: x0 = ins+dot[0]*fw+dw+sk y0 = ins+dot[1]*fw self.bars[(dot,right(dot))] =\ Rectangle(cv,x0,y0,x0+sw,y0+dw,fill='lightgray',outline='') # vertical bars if dot[1] < height - 1: x0 = ins+dot[0]*fw y0 = ins+dot[1]*fw + dw + sk self.bars[(dot,upper(dot))] =\ Rectangle(cv,x0,y0,x0+dw,y0+sw,fill='lightgray',outline='') # squares if (dot[0] < width - 1) and (dot[1] < height - 1): x0 =ins+dot[0]*fw + dw + sk y0 =ins+dot[1]*fw + dw + sk self.squares[dot] =\ Rectangle(cv,x0,y0,x0+sw,y0+sw,fill='lightyellow',outline='') cv.update() self.root.mainloop() def _coord(self,x): """returns pixel-coordinate corresponding to a dot-coordinate x""" return self.inset + self.dotwidth/2 + self.fieldwidth*x def _find_bar(self,event): """returns bar next to mouse-position when clicked, if applicable, otherwise None""" ex, ey = event.x, event.y for bar in self.bars: ((x1,y1),(x2,y2))=bar mx, my = (self._coord(x1)+self._coord(x2))/2, (self._coord(y1)+self._coord(y2))/2 if abs(ex-mx)+abs(ey-my) < self.squarewidth/2: return bar def _callback(self, event): """Action following a mouse-click""" hit = self._find_bar(event) board = self.board print "Hit:", hit if not hit or board.isGameOver() or board.board.has_key(hit): return # Do a move player = board.getPlayer() print "Turn %d (Player %s)" % (board.turn, player) self.bars[hit]['fill']=self.barcolors[player] target = board.play(hit) print "Target:", target if target: print "Square completed.", board.squares[target] self.squares[target]['fill'] = self.squarecolors[player] board.scores[player] += 1 board.turn = board.turn + 1 print "\n" if board.isGameOver(): print "Game over!" print "Final board position:" print board print print "Final score:\n\tPlayer 0: %s\n\tPlayer 1: %s" % \ tuple(board.scores) def _gtest(width, height): """A small driver to make sure that the board works. It's not safe to use this test function in production, because it uses input().""" print "Running _gtest... " board = GameBoard(width, height) board.turn = 1 board.scores = [0, 0] gui = GameGUI(board) ##### Danny Yoo's board.py ######################################### import types class GameBoard: def __init__(self, width=5, height=5): """Initializes a rectangular gameboard.""" self.width, self.height = width, height assert 2 <= self.width and 2 <= self.height,\ "Game can't be played on this board's dimension." self.board = {} self.squares = {} self.player = 0 def isGameOver(self): """Returns true if no more moves can be made. The maximum number of moves is equal to the number of possible lines between adjacent dots. I'm calculating this to be $2*w*h - h - w$; I think that's right. *grin* """ w, h = self.width, self.height return len(self.board.keys()) == 2*w*h - h - w def _isSquareMove(self, move): """Returns a true value if a particular move will create a square. In particular, returns the lower left corner of the created square.""" b = self.board mmove = self._makeMove ## just to make typing easier ((x1, y1), (x2, y2)) = move if self._isHorizontal(move): for j in [-1, 1]: if (b.has_key(mmove((x1, y1), (x1, y1-j))) and b.has_key(mmove((x1, y1-j), (x1+1, y1-j))) and b.has_key(mmove((x1+1, y1-j), (x2, y2)))): return min([(x1, y1), (x1, y1-j), (x1+1, y1-j), (x2, y2)]) else: for j in [-1, 1]: if (b.has_key(mmove((x1, y1), (x1-j, y1))) and b.has_key(mmove((x1-j, y1), (x1-j, y1+1))) and b.has_key(mmove((x1-j, y1+1), (x2, y2)))): return min([(x1, y1), (x1-j, y1), (x1-j, y1+1), (x2, y2)]) return None def _isHorizontal(self, move): "Return true if the move is in horizontal orientation." return abs(move[0][0] - move[1][0]) == 1 def _isVertical(self, move): "Return true if the move is in vertical orientation." return not self.isHorizontal(self, move) def play(self, move): """Place a particular move on the board. If any wackiness occurs, raise an AssertionError.""" assert (self._isGoodCoord(move[0]) and self._isGoodCoord(move[1])),\ "Bad coordinates, out of bounds of the board." move = self._makeMove(move[0], move[1]) assert(not self.board.has_key(move)),\ "Bad move, line already occupied." self.board[move] = self.player ## Check if a square is completed. square_corner = self._isSquareMove(move) if square_corner: self.squares[square_corner] = self.player # return 1 return square_corner # CHANGED to get information which # square to colour else: self._switchPlayer() return 0 def _switchPlayer(self): self.player = (self.player + 1) % 2 def getPlayer(self): return self.player def getSquares(self): """Returns a dictionary of squares captured. Returns a dict of lower left corner keys marked with the player who captured them.""" return self.squares def __str__(self): """Return a nice string representation of the board.""" buffer = [] ## do the top line for i in range(self.width-1): if self.board.has_key(((i, self.height-1), (i+1, self.height-1))): buffer.append("+--") else: buffer.append("+ ") buffer.append("+\n") ## and now do alternating vertical/horizontal passes # for j in range(self.height-2, -1, -1): # CHANGED for corresponence for j in range(self.height-1): # with graphical display ## vertical: for i in range(self.width): if self.board.has_key(((i, j), (i, j+1))): buffer.append("|") else: buffer.append(" ") if self.squares.has_key((i, j)): buffer.append("%s " % self.squares[i,j]) else: buffer.append(" ") buffer.append("\n") ## horizontal for i in range(self.width-1): if self.board.has_key(((i, j), (i+1, j))): buffer.append("+--") else: buffer.append("+ ") buffer.append("+\n") return ''.join(buffer) def _makeMove(self, coord1, coord2): """Return a new "move", and ensure it's in canonical form. (That is, force it so that it's an ordered tuple of tuples.) """ ## TODO: do the Flyweight thing here to reduce object creation xdelta, ydelta = coord2[0] - coord1[0], coord2[1] - coord1[1] assert ((abs(xdelta) == 1 and abs(ydelta) == 0) or (abs(xdelta) == 0 and abs(ydelta) == 1)),\ "Bad coordinates, not adjacent points." if coord1 < coord2: return (coord1, coord2) else: return (tuple(coord2), tuple(coord1)) def _isGoodCoord(self, coord): """Returns true if the given coordinate is good. A coordinate is "good" if it's within the boundaries of the game board, and if the coordinates are integers.""" return (0 <= coord[0] < self.width and 0 <= coord[1] < self.height and isinstance(coord[0], types.IntType) and isinstance(coord[1], types.IntType)) def getMove(self): # <=== NEW NEW NEW """Found this little bit of error-checking useful for testing, because I tend to mistype everything rather often. Moreover now it's more safe""" done = 0 while not done: try: x1, y1, sep, x2, y2 = raw_input("Move?").split() move = ((int(x1),int(y1)),(int(x2),int(y2))) done = 1 except: pass return move def _test(width, height): """A small driver to make sure that the board works. It's not safe to use this test function in production, because it uses input().""" board = GameBoard(width, height) turn = 1 scores = [0, 0] while not board.isGameOver(): player = board.getPlayer() print "Turn %d (Player %s)" % (turn, player) print board # move = input("Move? ") move = board.getMove() # <== CHANGED !!! if board.play(move): print "Square completed." scores[player] += 1 turn = turn + 1 print "\n" print "Game over!" print "Final board position:" print board print print "Final score:\n\tPlayer 0: %s\n\tPlayer 1: %s" % \ (scores[0], scores[1]) if __name__ == "__main__": """If we're provided arguments, look if first one equals 't', in which case textmode only is invoked. try using rest of the arguments as the width/height of the game board.""" import sys if len(sys.argv[1:]) > 0 and sys.argv[1] == 't': # textmode if len(sys.argv[1:]) == 3: _test(int(sys.argv[2]), int(sys.argv[3])) elif len(sys.argv[1:]) == 2: _test(int(sys.argv[2]), int(sys.argv[2])) else: _test(5, 5) else: # grachics mode if len(sys.argv[1:]) == 2: _gtest(int(sys.argv[1]), int(sys.argv[2])) elif len(sys.argv[1:]) == 1: _gtest(int(sys.argv[1]), int(sys.argv[1])) else: _gtest(5, 5) ------=_NextPart_000_0016_01C20AA9.5E03E6E0 Content-Type: text/plain; name="gboard.py" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="gboard.py" """Graphic user interface to Danny Yoo's 'dots and boxes' -program. I tried to avoid changes to this program as far as possible. So there remain the following changes: Line 222: Return statement in play() now returns the square_corner instead of 1 (this was the only necessary one (in m opinion) Line 255/256: head of for-loop --- this was the easiest way to accomodate text-output to graphical one. ( Bad design decision for the graphics display, may be reverted if there is time ...) Lines 305-318, 332, 333: A somewhat safer input method for more convenient testing Lines 354ff: Incorporate graphics mode into __main__() """ from Tkinter import * from Canvas import Rectangle def cartesian( v1, v2 ): """ Helper function returns cartesian product of the two 'sets' v1, v2""" return tuple([(x,y) for x in v1 for y in v2]) def right(x): """Helper function: argument x must be a dot. Returns dot right of x.""" return (x[0]+1,x[1]) def upper(x): """Helper function: argument x must be a dot. Returns dot above (actually below) x.""" return (x[0], x[1]+1) class GameGUI: def __init__(self, board): """Initializes graphic display of a rectangular gameboard.""" # Properties of gameboard dw =3D self.dotwidth =3D 6 sw =3D self.squarewidth =3D 60 sk =3D self.skip =3D 4 fw =3D self.fieldwidth =3D dw + sw + 2*sk ins =3D self.inset =3D sw/2 self.barcolors =3D ['red','blue'] self.squarecolors =3D ['orange', 'lightblue'] # Construct Canvas =20 self.board =3D board width, height =3D board.width, board.height # compute size of canvas: w =3D width * fw=20 h =3D height * fw=20 self.root =3D Tk() cv =3D self.cv =3D Canvas(self.root, width=3Dw, height=3Dh, = bg=3D'white') cv.bind('', self._callback) cv.pack() # Put geometrical objects - dots, bars and squares - on canvas self.bars =3D {} self.squares =3D {} for dot in cartesian(range(width), range(height)): # dots. Never used again Rectangle( cv, ins+dot[0]*fw, ins+dot[1]*fw, ins+dot[0]*fw + dw, ins+dot[1]*fw + dw, fill=3D'black', outline=3D'' ) # horizontal bars if dot[0] < width - 1: x0 =3D ins+dot[0]*fw+dw+sk y0 =3D ins+dot[1]*fw self.bars[(dot,right(dot))] =3D\ = Rectangle(cv,x0,y0,x0+sw,y0+dw,fill=3D'lightgray',outline=3D'') # vertical bars if dot[1] < height - 1: x0 =3D ins+dot[0]*fw y0 =3D ins+dot[1]*fw + dw + sk self.bars[(dot,upper(dot))] =3D\ = Rectangle(cv,x0,y0,x0+dw,y0+sw,fill=3D'lightgray',outline=3D'') # squares if (dot[0] < width - 1) and (dot[1] < height - 1): x0 =3Dins+dot[0]*fw + dw + sk y0 =3Dins+dot[1]*fw + dw + sk=20 self.squares[dot] =3D\ = Rectangle(cv,x0,y0,x0+sw,y0+sw,fill=3D'lightyellow',outline=3D'') cv.update() self.root.mainloop() =20 def _coord(self,x): """returns pixel-coordinate corresponding to a dot-coordinate x""" return self.inset + self.dotwidth/2 + self.fieldwidth*x def _find_bar(self,event): """returns bar next to mouse-position when clicked, if applicable, otherwise None""" ex, ey =3D event.x, event.y for bar in self.bars: ((x1,y1),(x2,y2))=3Dbar mx, my =3D (self._coord(x1)+self._coord(x2))/2, = (self._coord(y1)+self._coord(y2))/2 if abs(ex-mx)+abs(ey-my) < self.squarewidth/2: return bar =20 def _callback(self, event): """Action following a mouse-click""" hit =3D self._find_bar(event) board =3D self.board print "Hit:", hit if not hit or board.isGameOver() or board.board.has_key(hit): return # Do a move player =3D board.getPlayer() print "Turn %d (Player %s)" % (board.turn, player) self.bars[hit]['fill']=3Dself.barcolors[player] target =3D board.play(hit) print "Target:", target if target: print "Square completed.", board.squares[target] self.squares[target]['fill'] =3D self.squarecolors[player] board.scores[player] +=3D 1 board.turn =3D board.turn + 1 print "\n" if board.isGameOver(): print "Game over!" print "Final board position:" print board print print "Final score:\n\tPlayer 0: %s\n\tPlayer 1: %s" % \ tuple(board.scores) def _gtest(width, height):=0A= """A small driver to make sure that the board works. It's not=0A= safe to use this test function in production, because it uses=0A= input().""" print "Running _gtest... "=0A= board =3D GameBoard(width, height)=0A= board.turn =3D 1=0A= board.scores =3D [0, 0] gui =3D GameGUI(board) ##### Danny Yoo's board.py ######################################### import types=0A= =0A= class GameBoard:=0A= def __init__(self, width=3D5, height=3D5):=0A= """Initializes a rectangular gameboard."""=0A= self.width, self.height =3D width, height=0A= assert 2 <=3D self.width and 2 <=3D self.height,\=0A= "Game can't be played on this board's dimension."=0A= self.board =3D {}=0A= self.squares =3D {}=0A= self.player =3D 0=0A= =0A= =0A= def isGameOver(self):=0A= """Returns true if no more moves can be made.=0A= =0A= The maximum number of moves is equal to the number of possible=0A= lines between adjacent dots. I'm calculating this to be=0A= $2*w*h - h - w$; I think that's right. *grin*=0A= """=0A= w, h =3D self.width, self.height=0A= return len(self.board.keys()) =3D=3D 2*w*h - h - w=0A= =0A= =0A= =0A= def _isSquareMove(self, move):=0A= """Returns a true value if a particular move will create a=0A= square. In particular, returns the lower left corner of the=0A= created square."""=0A= b =3D self.board=0A= mmove =3D self._makeMove ## just to make typing easier=0A= ((x1, y1), (x2, y2)) =3D move=0A= if self._isHorizontal(move):=0A= for j in [-1, 1]:=0A= if (b.has_key(mmove((x1, y1), (x1, y1-j)))=0A= and b.has_key(mmove((x1, y1-j), (x1+1, y1-j)))=0A= and b.has_key(mmove((x1+1, y1-j), (x2, y2)))):=0A= return min([(x1, y1), (x1, y1-j),=0A= (x1+1, y1-j), (x2, y2)])=0A= else:=0A= for j in [-1, 1]:=0A= if (b.has_key(mmove((x1, y1), (x1-j, y1)))=0A= and b.has_key(mmove((x1-j, y1), (x1-j, y1+1)))=0A= and b.has_key(mmove((x1-j, y1+1), (x2, y2)))):=0A= return min([(x1, y1), (x1-j, y1),=0A= (x1-j, y1+1), (x2, y2)])=0A= return None=0A= =0A= =0A= =0A= def _isHorizontal(self, move):=0A= "Return true if the move is in horizontal orientation."=0A= return abs(move[0][0] - move[1][0]) =3D=3D 1=0A= =0A= =0A= def _isVertical(self, move):=0A= "Return true if the move is in vertical orientation."=0A= return not self.isHorizontal(self, move)=0A= =0A= =0A= def play(self, move):=0A= """Place a particular move on the board. If any wackiness=0A= occurs, raise an AssertionError."""=0A= assert (self._isGoodCoord(move[0]) and=0A= self._isGoodCoord(move[1])),\=0A= "Bad coordinates, out of bounds of the board."=0A= move =3D self._makeMove(move[0], move[1])=0A= assert(not self.board.has_key(move)),\=0A= "Bad move, line already occupied."=0A= self.board[move] =3D self.player=0A= ## Check if a square is completed.=0A= square_corner =3D self._isSquareMove(move)=0A= if square_corner:=0A= self.squares[square_corner] =3D self.player=0A= # return 1 return square_corner # CHANGED to get information which # square to colour=0A= else:=0A= self._switchPlayer()=0A= return 0=0A= =0A= =0A= def _switchPlayer(self):=0A= self.player =3D (self.player + 1) % 2=0A= =0A= =0A= def getPlayer(self): return self.player=0A= =0A= =0A= def getSquares(self):=0A= """Returns a dictionary of squares captured. Returns=0A= a dict of lower left corner keys marked with the=0A= player who captured them."""=0A= return self.squares=0A= =0A= =0A= def __str__(self):=0A= """Return a nice string representation of the board."""=0A= buffer =3D []=0A= =0A= ## do the top line=0A= for i in range(self.width-1):=0A= if self.board.has_key(((i, self.height-1), (i+1, = self.height-1))):=0A= buffer.append("+--")=0A= else: buffer.append("+ ")=0A= buffer.append("+\n")=0A= =0A= ## and now do alternating vertical/horizontal passes=0A= # for j in range(self.height-2, -1, -1): # CHANGED for = corresponence =0A= for j in range(self.height-1): # with graphical display=0A= ## vertical:=0A= for i in range(self.width):=0A= if self.board.has_key(((i, j), (i, j+1))):=0A= buffer.append("|")=0A= else:=0A= buffer.append(" ")=0A= if self.squares.has_key((i, j)):=0A= buffer.append("%s " % self.squares[i,j])=0A= else:=0A= buffer.append(" ")=0A= buffer.append("\n")=0A= =0A= ## horizontal=0A= for i in range(self.width-1):=0A= if self.board.has_key(((i, j), (i+1, j))):=0A= buffer.append("+--")=0A= else: buffer.append("+ ")=0A= buffer.append("+\n")=0A= =0A= return ''.join(buffer)=0A= =0A= =0A= =0A= def _makeMove(self, coord1, coord2):=0A= """Return a new "move", and ensure it's in canonical form.=0A= (That is, force it so that it's an ordered tuple of tuples.)=0A= """=0A= ## TODO: do the Flyweight thing here to reduce object creation=0A= xdelta, ydelta =3D coord2[0] - coord1[0], coord2[1] - coord1[1]=0A= assert ((abs(xdelta) =3D=3D 1 and abs(ydelta) =3D=3D 0) or=0A= (abs(xdelta) =3D=3D 0 and abs(ydelta) =3D=3D 1)),\=0A= "Bad coordinates, not adjacent points."=0A= if coord1 < coord2:=0A= return (coord1, coord2)=0A= else:=0A= return (tuple(coord2), tuple(coord1))=0A= =0A= =0A= def _isGoodCoord(self, coord):=0A= """Returns true if the given coordinate is good.=0A= =0A= A coordinate is "good" if it's within the boundaries of the=0A= game board, and if the coordinates are integers."""=0A= return (0 <=3D coord[0] < self.width=0A= and 0 <=3D coord[1] < self.height=0A= and isinstance(coord[0], types.IntType)=0A= and isinstance(coord[1], types.IntType))=0A= def getMove(self): # <=3D=3D=3D NEW NEW NEW """Found this little bit of error-checking useful for testing, because I tend to mistype everything rather often. Moreover now it's more safe""" done =3D 0 while not done: try: x1, y1, sep, x2, y2 =3D raw_input("Move?").split() move =3D ((int(x1),int(y1)),(int(x2),int(y2))) done =3D 1 except: pass return move =0A= =0A= def _test(width, height):=0A= """A small driver to make sure that the board works. It's not=0A= safe to use this test function in production, because it uses=0A= input()."""=0A= board =3D GameBoard(width, height)=0A= turn =3D 1=0A= scores =3D [0, 0]=0A= while not board.isGameOver():=0A= player =3D board.getPlayer()=0A= print "Turn %d (Player %s)" % (turn, player)=0A= print board=0A= # move =3D input("Move? ") move =3D board.getMove() # <=3D=3D CHANGED !!!=0A= if board.play(move):=0A= print "Square completed."=0A= scores[player] +=3D 1=0A= turn =3D turn + 1=0A= print "\n"=0A= print "Game over!"=0A= print "Final board position:"=0A= print board=0A= print=0A= print "Final score:\n\tPlayer 0: %s\n\tPlayer 1: %s" % \=0A= (scores[0], scores[1])=0A= =0A= if __name__ =3D=3D "__main__": """If we're provided arguments, look if first one equals 't', in which case textmode only is invoked. try using rest of the arguments as the width/height of the game board.""" import sys if len(sys.argv[1:]) > 0 and sys.argv[1] =3D=3D 't': # textmode if len(sys.argv[1:]) =3D=3D 3: _test(int(sys.argv[2]), int(sys.argv[3])) elif len(sys.argv[1:]) =3D=3D 2: _test(int(sys.argv[2]), int(sys.argv[2])) else: _test(5, 5) else: # grachics mode if len(sys.argv[1:]) =3D=3D 2: _gtest(int(sys.argv[1]), int(sys.argv[2])) elif len(sys.argv[1:]) =3D=3D 1: _gtest(int(sys.argv[1]), int(sys.argv[1])) else: _gtest(5, 5) ------=_NextPart_000_0016_01C20AA9.5E03E6E0-- From shalehperry@attbi.com Mon Jun 3 02:17:20 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun, 02 Jun 2002 18:17:20 -0700 (PDT) Subject: [Tutor] Dots-And-Boxes In-Reply-To: <001901c20a98$9abfc100$1615a8c0@mega> Message-ID: > > P.S.: There is one point, which is not completely clear to me: > Danny's algorithm always assigns only one square to the player > who did the last move, even if his draw completes two squares, > So in the end the sum of the points may be less than (w-1)*(h-1). > Is this according to the rules of the game? > no. If your move boxes in any number of squares you get all of them. From glingl@aon.at Mon Jun 3 02:28:52 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 3 Jun 2002 03:28:52 +0200 Subject: [Tutor] Dots-And-Boxes References: Message-ID: <003b01c20a9e$054b59d0$1615a8c0@mega> So the method play() (and perhaps already the method _isSquareMove() should better return a list of the corners of all the affected squares? Can 'any number' be greater than 2? Under which circumstances? Gregor ----- Original Message ----- From: "Sean 'Shaleh' Perry" To: "Gregor Lingl" Cc: Sent: Monday, June 03, 2002 3:17 AM Subject: Re: [Tutor] Dots-And-Boxes > > P.S.: There is one point, which is not completely clear to me: > Danny's algorithm always assigns only one square to the player > who did the last move, even if his draw completes two squares, > So in the end the sum of the points may be less than (w-1)*(h-1). > Is this according to the rules of the game? > no. If your move boxes in any number of squares you get all of them. From dyoo@hkn.eecs.berkeley.edu Mon Jun 3 02:42:09 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 2 Jun 2002 18:42:09 -0700 (PDT) Subject: [Tutor] Dots-And-Boxes In-Reply-To: Message-ID: On Sun, 2 Jun 2002, Sean 'Shaleh' Perry wrote: > > P.S.: There is one point, which is not completely clear to me: > > Danny's algorithm always assigns only one square to the player who did > > the last move, even if his draw completes two squares, So in the end > > the sum of the points may be less than (w-1)*(h-1). Is this according > > to the rules of the game? > > > > no. If your move boxes in any number of squares you get all of them. Yikes, that's a bug in my program then! I completely forgot about double-cross moves. I'll try to fix this tonight; thanks for reminding me about this! From dyoo@hkn.eecs.berkeley.edu Mon Jun 3 02:53:52 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 2 Jun 2002 18:53:52 -0700 (PDT) Subject: [Tutor] Dots-And-Boxes In-Reply-To: Message-ID: > > > P.S.: There is one point, which is not completely clear to me: > > > Danny's algorithm always assigns only one square to the player who > > > did the last move, even if his draw completes two squares, So in the > > > end the sum of the points may be less than (w-1)*(h-1). Is this > > > according to the rules of the game? > > > > > > > no. If your move boxes in any number of squares you get all of them. > > Yikes, that's a bug in my program then! I completely forgot about > double-cross moves. I'll try to fix this tonight; thanks for reminding me > about this! Ok, fixed, I think. I took Gregor's suggestions, and now my _isSquareMove() returns a list of squares instead of just one potential square. At most 2 squares can be created by a move, via a "double-crossed" move. The following play shows how this can be done: ### dyoo@coffeetable:~/dots-and-boxes$ python board.py Turn 1 (Player 0) + + + + + + + + + + + + + + + + + + + + + + + + + Move? (0, 0), (0, 1) Turn 2 (Player 1) + + + + + + + + + + + + + + + + + + + + | + + + + + Move? (0, 1), (1, 1) Turn 3 (Player 0) + + + + + + + + + + + + + + + +--+ + + + | + + + + + Move? (1, 1), (2, 1) Turn 4 (Player 1) + + + + + + + + + + + + + + + +--+--+ + + | + + + + + Move? (2, 1), (2, 0) Turn 5 (Player 0) + + + + + + + + + + + + + + + +--+--+ + + | | + + + + + Move? (2, 0), (1, 0) Turn 6 (Player 1) + + + + + + + + + + + + + + + +--+--+ + + | | + +--+ + + Move? (1, 0), (0, 0) Turn 7 (Player 0) + + + + + + + + + + + + + + + +--+--+ + + | | +--+--+ + + Move? (1, 1), (1, 0) Square completed. Turn 8 (Player 0) + + + + + + + + + + + + + + + +--+--+ + + |0 |0 | +--+--+ + + ### So this should fix things properly now. I've updated my source code, so you can download it again: http://hkn.eecs.berkeley.edu/~dyoo/python/dots-and-boxes/board.py Thanks again! From glingl@aon.at Mon Jun 3 03:14:19 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 3 Jun 2002 04:14:19 +0200 Subject: [Tutor] Dots-And-Boxes References: Message-ID: <006301c20aa4$5e8f0220$1615a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0060_01C20AB5.21C0B170 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit ----- Original Message ----- From: "Danny Yoo" Ok, fixed, I think. I took Gregor's suggestions, and now my _isSquareMove() returns a list of squares instead of just one potential square. At most 2 squares can be created by a move, via a "double-crossed" move. The following play shows how this can be done: ---------------- gui version accordingly fixed. see attachment Gregor ------=_NextPart_000_0060_01C20AB5.21C0B170 Content-Type: text/plain; name="gboard2.py" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="gboard2.py" """Graphic user interface to Danny Yoo's 'dots and boxes' -program. I tried to avoid changes to this program as far as possible. So there remain the following changes: Line 229: Return statement in play() now returns the square_corners instead of 1 (this was the only necessary one (in m opinion) Line 258/259: head of for-loop --- this was the easiest way to accomodate text-output to graphical one. ( Bad design decision for the graphics display, may be reverted if there is time ...) Lines 308-321, 335, 336: A somewhat safer input method for more convenient testing Lines 357ff: Incorporate graphics mode into __main__() """ from Tkinter import * from Canvas import Rectangle def cartesian( v1, v2 ): """ Helper function returns cartesian product of the two 'sets' v1, v2""" return tuple([(x,y) for x in v1 for y in v2]) def right(x): """Helper function: argument x must be a dot. Returns dot right of x.""" return (x[0]+1,x[1]) def upper(x): """Helper function: argument x must be a dot. Returns dot above (actually below) x.""" return (x[0], x[1]+1) class GameGUI: def __init__(self, board): """Initializes graphic display of a rectangular gameboard.""" # Properties of gameboard dw =3D self.dotwidth =3D 6 sw =3D self.squarewidth =3D 60 sk =3D self.skip =3D 4 fw =3D self.fieldwidth =3D dw + sw + 2*sk ins =3D self.inset =3D sw/2 self.barcolors =3D ['red','blue'] self.squarecolors =3D ['orange', 'lightblue'] # Construct Canvas =20 self.board =3D board width, height =3D board.width, board.height # compute size of canvas: w =3D width * fw=20 h =3D height * fw=20 self.root =3D Tk() cv =3D self.cv =3D Canvas(self.root, width=3Dw, height=3Dh, = bg=3D'white') cv.bind('', self._callback) cv.pack() # Put geometrical objects - dots, bars and squares - on canvas self.bars =3D {} self.squares =3D {} for dot in cartesian(range(width), range(height)): # dots. Never used again Rectangle( cv, ins+dot[0]*fw, ins+dot[1]*fw, ins+dot[0]*fw + dw, ins+dot[1]*fw + dw, fill=3D'black', outline=3D'' ) # horizontal bars if dot[0] < width - 1: x0 =3D ins+dot[0]*fw+dw+sk y0 =3D ins+dot[1]*fw self.bars[(dot,right(dot))] =3D\ = Rectangle(cv,x0,y0,x0+sw,y0+dw,fill=3D'lightgray',outline=3D'') # vertical bars if dot[1] < height - 1: x0 =3D ins+dot[0]*fw y0 =3D ins+dot[1]*fw + dw + sk self.bars[(dot,upper(dot))] =3D\ = Rectangle(cv,x0,y0,x0+dw,y0+sw,fill=3D'lightgray',outline=3D'') # squares if (dot[0] < width - 1) and (dot[1] < height - 1): x0 =3Dins+dot[0]*fw + dw + sk y0 =3Dins+dot[1]*fw + dw + sk=20 self.squares[dot] =3D\ = Rectangle(cv,x0,y0,x0+sw,y0+sw,fill=3D'lightyellow',outline=3D'') cv.update() self.root.mainloop() =20 def _coord(self,x): """returns pixel-coordinate corresponding to a dot-coordinate x""" return self.inset + self.dotwidth/2 + self.fieldwidth*x def _find_bar(self,event): """returns bar next to mouse-position when clicked, if applicable, otherwise None""" ex, ey =3D event.x, event.y for bar in self.bars: ((x1,y1),(x2,y2))=3Dbar mx, my =3D (self._coord(x1)+self._coord(x2))/2, = (self._coord(y1)+self._coord(y2))/2 if abs(ex-mx)+abs(ey-my) < self.squarewidth/2: return bar =20 def _callback(self, event): """Action following a mouse-click""" hit =3D self._find_bar(event) board =3D self.board print "Hit:", hit if not hit or board.isGameOver() or board.board.has_key(hit): return # Do a move player =3D board.getPlayer() print "Turn %d (Player %s)" % (board.turn, player) self.bars[hit]['fill']=3Dself.barcolors[player] # Here following Danny's bug fix targets =3D board.play(hit) print "Targets:", targets for target in targets: print "Square completed.", board.squares[target] self.squares[target]['fill'] =3D self.squarecolors[player] board.scores[player] +=3D 1 board.turn =3D board.turn + 1 print "\n" if board.isGameOver(): print "Game over!" print "Final board position:" print board print print "Final score:\n\tPlayer 0: %s\n\tPlayer 1: %s" % \ tuple(board.scores) def _gtest(width, height):=0A= """A small driver to make sure that the board works. It's not=0A= safe to use this test function in production, because it uses=0A= input().""" print "Running _gtest... "=0A= board =3D GameBoard(width, height)=0A= board.turn =3D 1=0A= board.scores =3D [0, 0] gui =3D GameGUI(board) ##### Danny Yoo's board.py ######################################### import types=0A= =0A= class GameBoard:=0A= def __init__(self, width=3D5, height=3D5):=0A= """Initializes a rectangular gameboard."""=0A= self.width, self.height =3D width, height=0A= assert 2 <=3D self.width and 2 <=3D self.height,\=0A= "Game can't be played on this board's dimension."=0A= self.board =3D {}=0A= self.squares =3D {}=0A= self.player =3D 0=0A= =0A= =0A= def isGameOver(self):=0A= """Returns true if no more moves can be made.=0A= =0A= The maximum number of moves is equal to the number of possible=0A= lines between adjacent dots. I'm calculating this to be=0A= $2*w*h - h - w$; I think that's right. *grin*=0A= """=0A= w, h =3D self.width, self.height=0A= return len(self.board.keys()) =3D=3D 2*w*h - h - w=0A= =0A= =0A= =0A= def _isSquareMove(self, move):=0A= """Returns a true value if a particular move will create a=0A= square. In particular, returns a list of the the lower left=0A= corners of the squares captured by a move.=0A= =0A= (Note: I had forgotten about double crossed moves. Gregor=0A= Lingl reported the bug; I'd better fix it now! *grin*) """=0A= b =3D self.board=0A= mmove =3D self._makeMove ## just to make typing easier=0A= ((x1, y1), (x2, y2)) =3D move=0A= captured_squares =3D []=0A= if self._isHorizontal(move):=0A= for j in [-1, 1]:=0A= if (b.has_key(mmove((x1, y1), (x1, y1-j)))=0A= and b.has_key(mmove((x1, y1-j), (x1+1, y1-j)))=0A= and b.has_key(mmove((x1+1, y1-j), (x2, y2)))):=0A= captured_squares.append(min([(x1, y1), (x1, y1-j),=0A= (x1+1, y1-j), (x2, = y2)]))=0A= else:=0A= for j in [-1, 1]:=0A= if (b.has_key(mmove((x1, y1), (x1-j, y1)))=0A= and b.has_key(mmove((x1-j, y1), (x1-j, y1+1)))=0A= and b.has_key(mmove((x1-j, y1+1), (x2, y2)))):=0A= captured_squares.append(min([(x1, y1), (x1-j, y1),=0A= (x1-j, y1+1), (x2, = y2)]))=0A= return captured_squares=0A= =0A= =0A= =0A= def _isHorizontal(self, move):=0A= "Return true if the move is in horizontal orientation."=0A= return abs(move[0][0] - move[1][0]) =3D=3D 1=0A= =0A= =0A= def _isVertical(self, move):=0A= "Return true if the move is in vertical orientation."=0A= return not self.isHorizontal(self, move)=0A= =0A= =0A= def play(self, move):=0A= """Place a particular move on the board. If any wackiness=0A= occurs, raise an AssertionError."""=0A= assert (self._isGoodCoord(move[0]) and=0A= self._isGoodCoord(move[1])),\=0A= "Bad coordinates, out of bounds of the board."=0A= move =3D self._makeMove(move[0], move[1])=0A= assert(not self.board.has_key(move)),\=0A= "Bad move, line already occupied."=0A= self.board[move] =3D self.player=0A= ## Check if a square is completed.=0A= square_corners =3D self._isSquareMove(move)=0A= if square_corners:=0A= for corner in square_corners:=0A= self.squares[corner] =3D self.player=0A= else:=0A= self._switchPlayer()=0A= return square_corners # <=3D=3D here also change = necessary!!=0A= =0A= =0A= def _switchPlayer(self):=0A= self.player =3D (self.player + 1) % 2=0A= =0A= =0A= def getPlayer(self): return self.player=0A= =0A= =0A= def getSquares(self):=0A= """Returns a dictionary of squares captured. Returns=0A= a dict of lower left corner keys marked with the=0A= player who captured them."""=0A= return self.squares=0A= =0A= =0A= def __str__(self):=0A= """Return a nice string representation of the board."""=0A= buffer =3D []=0A= =0A= ## do the top line=0A= for i in range(self.width-1):=0A= if self.board.has_key(((i, self.height-1), (i+1, = self.height-1))):=0A= buffer.append("+--")=0A= else: buffer.append("+ ")=0A= buffer.append("+\n")=0A= =0A= ## and now do alternating vertical/horizontal passes=0A= # for j in range(self.height-2, -1, -1): # CHANGED for = corresponence =0A= for j in range(self.height-1): # with graphical display=0A= ## vertical:=0A= for i in range(self.width):=0A= if self.board.has_key(((i, j), (i, j+1))):=0A= buffer.append("|")=0A= else:=0A= buffer.append(" ")=0A= if self.squares.has_key((i, j)):=0A= buffer.append("%s " % self.squares[i,j])=0A= else:=0A= buffer.append(" ")=0A= buffer.append("\n")=0A= =0A= ## horizontal=0A= for i in range(self.width-1):=0A= if self.board.has_key(((i, j), (i+1, j))):=0A= buffer.append("+--")=0A= else: buffer.append("+ ")=0A= buffer.append("+\n")=0A= =0A= return ''.join(buffer)=0A= =0A= =0A= =0A= def _makeMove(self, coord1, coord2):=0A= """Return a new "move", and ensure it's in canonical form.=0A= (That is, force it so that it's an ordered tuple of tuples.)=0A= """=0A= ## TODO: do the Flyweight thing here to reduce object creation=0A= xdelta, ydelta =3D coord2[0] - coord1[0], coord2[1] - coord1[1]=0A= assert ((abs(xdelta) =3D=3D 1 and abs(ydelta) =3D=3D 0) or=0A= (abs(xdelta) =3D=3D 0 and abs(ydelta) =3D=3D 1)),\=0A= "Bad coordinates, not adjacent points."=0A= if coord1 < coord2:=0A= return (coord1, coord2)=0A= else:=0A= return (tuple(coord2), tuple(coord1))=0A= =0A= =0A= def _isGoodCoord(self, coord):=0A= """Returns true if the given coordinate is good.=0A= =0A= A coordinate is "good" if it's within the boundaries of the=0A= game board, and if the coordinates are integers."""=0A= return (0 <=3D coord[0] < self.width=0A= and 0 <=3D coord[1] < self.height=0A= and isinstance(coord[0], types.IntType)=0A= and isinstance(coord[1], types.IntType))=0A= def getMove(self): # <=3D=3D=3D NEW NEW NEW """Found this little bit of error-checking useful for testing, because I tend to mistype everything rather often. Moreover now it's more safe""" done =3D 0 while not done: try: x1, y1, sep, x2, y2 =3D raw_input("Move?").split() move =3D ((int(x1),int(y1)),(int(x2),int(y2))) done =3D 1 except: pass return move =0A= =0A= def _test(width, height):=0A= """A small driver to make sure that the board works. It's not=0A= safe to use this test function in production, because it uses=0A= input()."""=0A= board =3D GameBoard(width, height)=0A= turn =3D 1=0A= scores =3D [0, 0]=0A= while not board.isGameOver():=0A= player =3D board.getPlayer()=0A= print "Turn %d (Player %s)" % (turn, player)=0A= print board=0A= # move =3D input("Move? ") move =3D board.getMove() # <=3D=3D CHANGED !!!=0A= if board.play(move):=0A= print "Square completed."=0A= scores[player] +=3D 1=0A= turn =3D turn + 1=0A= print "\n"=0A= print "Game over!"=0A= print "Final board position:"=0A= print board=0A= print=0A= print "Final score:\n\tPlayer 0: %s\n\tPlayer 1: %s" % \=0A= (scores[0], scores[1])=0A= =0A= if __name__ =3D=3D "__main__": """If we're provided arguments, look if first one equals 't', in which case textmode only is invoked. try using rest of the arguments as the width/height of the game board.""" import sys if len(sys.argv[1:]) > 0 and sys.argv[1] =3D=3D 't': # textmode if len(sys.argv[1:]) =3D=3D 3: _test(int(sys.argv[2]), int(sys.argv[3])) elif len(sys.argv[1:]) =3D=3D 2: _test(int(sys.argv[2]), int(sys.argv[2])) else: _test(5, 5) else: # grachics mode if len(sys.argv[1:]) =3D=3D 2: _gtest(int(sys.argv[1]), int(sys.argv[2])) elif len(sys.argv[1:]) =3D=3D 1: _gtest(int(sys.argv[1]), int(sys.argv[1])) else: _gtest(5, 5) ------=_NextPart_000_0060_01C20AB5.21C0B170-- From dyoo@hkn.eecs.berkeley.edu Mon Jun 3 03:21:57 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 2 Jun 2002 19:21:57 -0700 (PDT) Subject: [Tutor] Dots-And-Boxes In-Reply-To: <001901c20a98$9abfc100$1615a8c0@mega> Message-ID: > """Graphic user interface to Danny Yoo's 'dots and boxes' -program. > I tried to avoid changes to this program as far as possible. > So there remain the following changes: > > Line 222: Return statement in play() now returns the > square_corner instead of 1 (this was the only > necessary one (in m opinion) Ok, that makes perfect sense. I'll reflect this in my code too. > Line 255/256: head of for-loop --- this was the easiest way > to accomodate text-output to graphical one. > ( Bad design decision for the graphics display, > may be reverted if there is time ...) > > Lines 305-318, 332, 333: A somewhat safer input method for > more convenient testing > > Lines 354ff: Incorporate graphics mode into __main__() Very cool! I'll play around with this tonight. Thank you! A muse is murmuring to me that we should put this code up on a source code repository like Sourceforge. *grin* Should I do this? From sarmstrong13@mac.com Mon Jun 3 05:09:55 2002 From: sarmstrong13@mac.com (SA) Date: Sun, 02 Jun 2002 23:09:55 -0500 Subject: [Tutor] Input variable help please. Message-ID: Hi everyone - I'm trying to get the user to input the directory of their choosing into a variable: x = input("Please enter directory name: ") But when I enter something like: /Users/username I get the following error: Traceback (most recent call last): File "", line 1, in ? File "", line 1 /Users/username ^ SyntaxError: invalid syntax Please point out my error and how I can fix this so that it accepts UNIX style directory listings. Thanks. SA From paulsid@shaw.ca Mon Jun 3 05:56:03 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Sun, 02 Jun 2002 22:56:03 -0600 Subject: [Tutor] Dots-And-Boxes References: Message-ID: <3CFAF6E3.5ECFED58@shaw.ca> Danny Yoo wrote: > For fun, I picked up Elwyn Berlekamp's "The Dots and Boxes Game", which is > a book about a deceptively simple game. Here's Berlekamp's paragraph > describing the game: [snip] Damn, why is it I'm always doing something when you bring up the cool topics? :-) I remember this game very well, only as a solitaire version. It came in books with invisible ink that you had to rub a special pen over to reveal. Each line you picked was either broken or solid, and you had to complete a box with a particular type of line (I believe it was solid) to be allowed to claim the box. It was loads of fun; I think I went through 2 or 3 of those books. IIRC there was also some kind of guarantee so you could deduce something about the location of the solid lines. It might have been that every square had a solid line touching it somewhere, not sure. Anyhow, I took a look at Danny's code and Gregor's GUI front-end, looks good! I'll be following developments of this closely. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From glingl@aon.at Mon Jun 3 07:15:26 2002 From: glingl@aon.at (Gregor Lingl) Date: Mon, 3 Jun 2002 08:15:26 +0200 Subject: [Tutor] Input variable help please. References: Message-ID: <002901c20ac6$0d571b50$1615a8c0@mega> ----- Original Message ----- From: "SA" To: "tutor" I'm trying to get the user to input the directory of their choosing into a variable: x = input("Please enter directory name: ") But when I enter something like: /Users/username I get the following error: Traceback (most recent call last): File "", line 1, in ? File "", line 1 /Users/username ^ SyntaxError: invalid syntax ------------------´reply: You have to use the function raw_input() instead of input to enter arbitrary strings: >>> x = raw_input("Please enter directory name: ") Please enter directory name: /Users/username >>> x '/Users/username' >>> input() only accepts leagal Python expression, which are immediately evaluated before assignment, e.g.: >>> x = input("Gimme an expression: ") Gimme an expression: 6 # legal Python >>> x 6 >>> x = input("Gimme an expression: ") Gimme an expression: 6 + 6 >>> x 12 >>> x = input("Gimme an expression: ") Gimme an expression: '/Users/username' >>> x '/Users/username' >>> You see, you have to put your directory name between ' ' s (quotation marks (?)). That doesn't make sense in your case. So stick with raw_input() Best wishes Gregor From dyoo@hkn.eecs.berkeley.edu Mon Jun 3 08:39:14 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Jun 2002 00:39:14 -0700 (PDT) Subject: [Tutor] Dots-And-Boxes [on sourceforge now!] In-Reply-To: <3CFAF6E3.5ECFED58@shaw.ca> Message-ID: On Sun, 2 Jun 2002, Paul Sidorsky wrote: > Danny Yoo wrote: > > > For fun, I picked up Elwyn Berlekamp's "The Dots and Boxes Game", > > which is a book about a deceptively simple game. Here's Berlekamp's > > paragraph describing the game: > [snip] > > Damn, why is it I'm always doing something when you bring up the cool > topics? :-) Please feel free to contribute! I didn't expect so many people to be interested, but I'm very glad that people are. I've set things up on Sourceforge, so anyone's welcome to take a look at how the code mutates. http://sourceforge.net/projects/tutorbot/ The code is under the 'dots-and-boxes' directory, under the main cvs root diretory. If you have an account on Sourceforge already, and you'd like to fiddle with the code, just email me, and I'll be happy to add you as a developer! > Anyhow, I took a look at Danny's code and Gregor's GUI front-end, looks > good! I'll be following developments of this closely. I just played with Gregor's GUI; I'm floored. It looks really nice. From lumbricus@gmx.net Mon Jun 3 13:06:47 2002 From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=) Date: Mon, 3 Jun 2002 14:06:47 +0200 (MEST) Subject: [Tutor] Text to HTML question. References: Message-ID: <25218.1023106007@www40.gmx.net> > Hi Everyone- Hello > I have a couple of questions for ya. Remember I'm new to Python and am > still learning: > > 1. I have a bunch of text files. I have a python script to generate html. > I > would like to substitute the body of the text files in between > > of the html file. I think I can get this part. The trouble I'm having is > formatting the text body into html. For instance for every "\n" in the > text > body I need to substitute
before placing it into the html file body > section. Don't do this. It's the Browsers job to do the linebreaking. If you want to enforce a linebreak for every "\n" in the HTML source, use the

 tag.

> And for every "\n\n" I wish to substitute 

. I suppose I nead > to > use regexp, but how do you call the re module and search/sub these > patterns? > > 2. I'm sure this is probably a problem that has been solved before, so > does > anyone know of a module to do this and how do I use it to accomplish the > goal? > > Thanks in advance for your help. I'm just now starting to get the whole > class thing in Python. > > SA HTH, HAND and Greetings, J"o! -- sigfault -- GMX - Die Kommunikationsplattform im Internet. http://www.gmx.net From purplebo@babylonia.flatirons.org Mon Jun 3 17:29:09 2002 From: purplebo@babylonia.flatirons.org (Chris Avery) Date: Mon, 3 Jun 2002 10:29:09 -0600 Subject: [Tutor] formatting strings In-Reply-To: <20020603160004.30168.6044.Mailman@mail.python.org>; from tutor-request@python.org on Mon, Jun 03, 2002 at 12:00:04PM -0400 References: <20020603160004.30168.6044.Mailman@mail.python.org> Message-ID: <20020603102909.A9561@babylonia.flatirons.org> Hi. I need to format a string so that the newline is indented. For example, it would need to look like this: * this is a line that is really long and should change to a newline abou t here and it is the same line still and I am a turkey etc. etc. and not like this: * this is a line that is really long and should change to a newline about here and it is the same line still and I am a turkey etc. etc. Thanks for your help -- +++++++++++++++++++ Chris Avery, KC0KTH +++++++++++++++++++ From shalehperry@attbi.com Mon Jun 3 17:42:44 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 03 Jun 2002 09:42:44 -0700 (PDT) Subject: [Tutor] formatting strings In-Reply-To: <20020603102909.A9561@babylonia.flatirons.org> Message-ID: On 03-Jun-2002 Chris Avery wrote: > Hi. I need to format a string so that the newline is indented. For example, > it would need to look like this: > > * this is a line that is really long and should change to a newline abou t > here and it is the same line still and I am a turkey etc. etc. > > and not like this: > * this is a line that is really long and should change to a newline about > here and it is the same line still and I am a turkey etc. etc. > > Thanks for your help > so let's stop and think about this one for a moment. How does say your text editor handle line wrapping? It keeps a maximum line width variable and checks the line against it. When the length is reached it inserts a newline and the rest of the line becomes a new line. Indentation is simply extra whitespace (a tab, 4 chars, something). So it would go something like this: .... handle line things .... if (len(line) > max_line_length): line = (line before max_line_length) + '\n' next_line = (indent) + (remainder) .... .... From wolf_binary@hotmail.com Mon Jun 3 20:26:40 2002 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Mon, 3 Jun 2002 14:26:40 -0500 Subject: [Tutor] computers Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_000A_01C20B0A.AD981940 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, I have an opportunity to get a dual processored computer that would = replace my old one. My question is can Windows 98 be used on it and can = I use all my other programs on it? I don't wanted to loose the ability = to do all the old things with this one. Thanks, Cameron Stoner ------=_NextPart_000_000A_01C20B0A.AD981940 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi all,
 
I have an opportunity to get a dual = processored=20 computer that would replace my old one.  My question is can Windows = 98 be=20 used on it and can I use all my other programs on it?  I don't = wanted to=20 loose the ability to do all the old things with this one.
 
Thanks,
 
Cameron = Stoner
------=_NextPart_000_000A_01C20B0A.AD981940-- From sarmstrong13@mac.com Mon Jun 3 21:05:06 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 03 Jun 2002 15:05:06 -0500 Subject: [Tutor] computers In-Reply-To: Message-ID: > This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. --B_3105961508_885558 Content-type: text/plain; charset="US-ASCII" Content-transfer-encoding: 7bit Yes you should be able to run win98. However, since Win98 is a piece of junk (IMHO), Win98 will not be able to access both processors. If I remember correctly, the only windoze capable of taking full advantage of multiprocessor systems are NT, 2000, and XP. Win 98 will only reecognize one processor, so there is no advantage. Good Luck. SA On 6/3/02 2:26 PM, "Cameron Stoner" wrote: > Hi all, > > I have an opportunity to get a dual processored computer that would replace my > old one. My question is can Windows 98 be used on it and can I use all my > other programs on it? I don't wanted to loose the ability to do all the old > things with this one. > > Thanks, > > Cameron Stoner > --B_3105961508_885558 Content-type: text/html; charset="US-ASCII" Content-transfer-encoding: quoted-printable Re: [Tutor] computers Yes you should be able to run win98. However, since Wi= n98 is a piece of junk (IMHO), Win98 will not be able to access both process= ors. If I remember correctly, the only windoze capable of taking full advant= age of multiprocessor systems are NT, 2000, and XP.
Win 98 will only reecognize one processor, so there is no advantage.

Good Luck.
SA
On 6/3/02 2:26 PM, "Cameron Stoner" <wolf_binary@hotmail.com&g= t; wrote:

Hi all,

I have an opportunity to get a dua= l processored computer that would replace my old one.  My question is c= an Windows 98 be used on it and can I use all my other programs on it?  = ;I don't wanted to loose the ability to do all the old things with this one.=

Thanks,

Cameron Stoner


--B_3105961508_885558-- From ATrautman@perryjudds.com Mon Jun 3 21:18:02 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Mon, 3 Jun 2002 15:18:02 -0500 Subject: [Tutor] computers Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A2BF@CORP_EXCHANGE> You need more information on the motherboard many have an ability to turn of the second processor unit (it would work more than likely). The approach to the bios is very different and I would look to the bios maker to see if it can disable the two processor part or if they state it can be used. My experience is that the motherboard needs to be matched to operating system in multi-processor system even some that work with NT 4.0 (the ones I had to convert) will not work with 2000 and (IMHO I wouldn't even try 98 or XP Home). 2000, BSD and Linux have good reputations with multi-processor use. Good Luck, Alan -----Original Message----- From: Cameron Stoner [mailto:wolf_binary@hotmail.com] Sent: Monday, June 03, 2002 2:27 PM To: python tutor Subject: [Tutor] computers Hi all, I have an opportunity to get a dual processored computer that would replace my old one. My question is can Windows 98 be used on it and can I use all my other programs on it? I don't wanted to loose the ability to do all the old things with this one. Thanks, Cameron Stoner From phthenry@earthlink.net Tue Jun 4 03:13:55 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon, 3 Jun 2002 22:13:55 -0400 Subject: [Tutor] remove 2.2 install 2.1 Message-ID: <20020603221354.C20733@localhost.localdomain> I need to go back to version 2.1 of python because of a conflict. I would like to use the 4xslt suite, but the stable of version of 4xslt conflicts with python 2.2. I use linux, specifically Mandrake 8.1 I have already downloaded the source for python 2.1. Should I remove the library in the /usr/local/lib folder? And should I remove the exectubale from my /bin folder? When I installed python 2.2, I simply did: make make install This worked like a charm, so I'm not anticipating any problems with the actual installation. But I would like to make sure I get rid of any conflicts in my library! Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From kojo@hal-pc.org Tue Jun 4 04:29:50 2002 From: kojo@hal-pc.org (Kojo Idrissa) Date: Mon, 03 Jun 2002 22:29:50 -0500 Subject: [Tutor] computers Message-ID: <5.1.0.14.0.20020603222933.02398a30@mail.hal-pc.org> --=====================_658883584==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Here's my question: Does the new computer have to replace the old one? Will you have to give up the old one to get the new one? If not, try to keep both. If you can't keep both, you might want to consider dual-booting Win98 with Linux/BSD or even Win2K. It might be fun to practice some multi threaded Python programming with to procs. Like everyone else has already said, Windows based on a 9x kernel won't do Multi-Proc. You need an NT kernel (NT/2k/XP...not sure about XP Home). At 02:26 PM 6/3/2002 -0500, you wrote: >Hi all, > >I have an opportunity to get a dual processored computer that would >replace my old one. My question is can Windows 98 be used on it and can I >use all my other programs on it? I don't wanted to loose the ability to >do all the old things with this one. > >Thanks, > >Cameron Stoner **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** --=====================_658883584==_.ALT Content-Type: text/html; charset="us-ascii" Here's my question:  Does the new computer have to replace the old one?  Will you have to give up the old one to get the new one?  If not, try to keep both.  If you can't keep both, you might want to consider dual-booting Win98 with Linux/BSD or even Win2K.  It might be fun to practice some multi threaded Python programming with to procs.

Like everyone else has already said, Windows based on a 9x kernel won't do Multi-Proc.  You need an NT kernel (NT/2k/XP...not sure about XP Home).

At 02:26 PM 6/3/2002 -0500, you wrote:
Hi all,
 
I have an opportunity to get a dual processored computer that would replace my old one.  My question is can Windows 98 be used on it and can I use all my other programs on it?  I don't wanted to loose the ability to do all the old things with this one.
 
Thanks,
 
Cameron Stoner

****************************
Kojo Idrissa
 
kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
**************************** --=====================_658883584==_.ALT-- From canterol@wharton.upenn.edu Tue Jun 4 05:19:57 2002 From: canterol@wharton.upenn.edu (Laura Cantero) Date: Tue, 4 Jun 2002 00:19:57 -0400 Subject: [Tutor] Python and Excel Message-ID: <000a01c20b7f$17aa8b00$23ecc797@vaio> This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C20B5D.8EFE74E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable How can I export data strings from a .txt file, and display them on = Excel (individually)??? I need the CODE! Thanks, Laura ------=_NextPart_000_0007_01C20B5D.8EFE74E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

How can I export data strings from = a .txt=20 file, and display them on Excel (individually)???
I need the=20 CODE!
Thanks,
Laura
------=_NextPart_000_0007_01C20B5D.8EFE74E0-- From dyoo@hkn.eecs.berkeley.edu Tue Jun 4 07:08:44 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Jun 2002 23:08:44 -0700 (PDT) Subject: [Tutor] Python and Excel In-Reply-To: <000a01c20b7f$17aa8b00$23ecc797@vaio> Message-ID: On Tue, 4 Jun 2002, Laura Cantero wrote: > How can I export data strings from a .txt file, Hi Laura, This depends on how your data is formatted. Python strings support several utility functions you can use to parse out the data. If it's in tab-delimited format, you'll find the 'split()' string method pretty useful. Here's an example of how it might work: ### >>> sample_line = 'hello world, this is a test' >>> words = sample_line.split(' ') >>> words ['hello', 'world,', 'this', 'is', 'a', 'test'] ### This example shows that we can split a line along space boundaries, and we can do similar stuff with tabs if that's how your file is organized. But Excel already has the ability to load tab-delimited data, so perhaps your information has some structure to it. Tell us more information about the file format, and we'll try giving suggestions. > and display them on Excel (individually)??? I need the CODE! Thanks, It sounds like you're planning to do win32 stuff. I'd recommend taking a look at "Python Programming on Win32": http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html I'm almost positive there's a chapter in there about driving Excel, so looking through that book will be helpful. Also, try contacting the python-win32 list; there are Windows experts there who might be able to cook up a nice example for you. Their mailing list is here: http://mail.python.org/mailman/listinfo/python-win32 Do you have experience in Python already? If you tell us more about what you've tried already, we can tailor our responses better. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Jun 4 07:20:27 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Jun 2002 23:20:27 -0700 (PDT) Subject: [Tutor] Python and Excel In-Reply-To: Message-ID: > It sounds like you're planning to do win32 stuff. I'd recommend taking a > look at "Python Programming on Win32": > > http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html > > I'm almost positive there's a chapter in there about driving Excel, so > looking through that book will be helpful. I'm still hunting through the web; here are a few other things I'm dredging up: http://starship.python.net/crew/pirx/spam7/ http://www.msdnaa.net/interchange/preview.asp?PeerID=1285 http://www.faqts.com/knowledge_base/view.phtml/aid/3093/fid/591 Google is beautiful. *grin* The last link has example code; play around with it and tell us if it works for you. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Jun 4 07:13:41 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 3 Jun 2002 23:13:41 -0700 (PDT) Subject: [Tutor] remove 2.2 install 2.1 In-Reply-To: <20020603221354.C20733@localhost.localdomain> Message-ID: On Mon, 3 Jun 2002, Paul Tremblay wrote: > I need to go back to version 2.1 of python because of a conflict. > I would like to use the 4xslt suite, but the stable of version of > 4xslt conflicts with python 2.2. Hi Paul, One thing to make sure is that '/usr/local/bin/python' is linked to '/usr/local/bin/python2.1'; I think that the upgrade to 2.2 might have overridden '/usr/local/bin/python'. Otherwise, I haven't had any problems myself, but then, testimonials are always a little unreliable... *grin* By the way, if you want to experiment with compiled versions of Python, you can use the '--prefix=/some/temporary/directory' flag during the './configure' step; by doing this, you can compile Python in the relative safety of your own directories. I've often done something like: './configure --prefix=/home/dyoo/local/python-2.2' which makes it fairly easy to uninstall it later. Good luck to you! From rab121@york.ac.uk Tue Jun 4 12:45:12 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Tue, 04 Jun 2002 12:45:12 +0100 Subject: [Tutor] Connection/Analyis Order Message-ID: <3CFCA848.9B65E2C8@york.ac.uk> Hello, I am about to embark on a little project and was wondering if you wonderful ppeeps could offer me some advice. I am setting up a series of web pages to display certain data based upon the input to a form (ratings for levels in a game to be precise). Unfortunately, I currently have no access to proper cgi type stuff so I am having to use a 'normal' email post from the services that my host does provide. So, emails arrive at my server with the form data in, I want to analyse each, store the data and publish some of it to web pages. All of the coding I think I can handle (never done mail stuff before, but this is Python, how hard can it be :o), my problem is more how I organise the steps. I currently have three ideas: 1. Connect to server blah. Check each mail (will not be just postings). If mail has correct subject: Get body of mail and analyse etc. Check next mail etc. 2. Connect. Check each mail. If correct mail: Get body of mail, stick in variable. Check next mail. Analyse all data in variable (ie do all mails at once). 3. Connect. Check each mail. If correct mail: Analyse mail in seperate thread whilst... Continuting to check mail... Now, I think my exact connection circumstances may effect this... At present I have access to a permanent, fast connection to an IMAP server. However, in the future I will probably have to connect over normal dial-up, possible to IMAP, possibly to POP3. Given my current status, I tend to favour 1, but over dial up would 2 or 3 make more sense? I have never done any thread programming before (though Prog. Python makes it look easy enough), but I am concerned about different threads accessing the storage of the data at incompatible times and mucking it up and similar problems connecting to the mail server (I want to delete successfully analysed mails.) Your advice is very welcome... Russell -- http://www.bigmaddrongo.com President of York University Trampolining Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From shalehperry@attbi.com Tue Jun 4 15:51:31 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 04 Jun 2002 07:51:31 -0700 (PDT) Subject: [Tutor] Connection/Analyis Order In-Reply-To: <3CFCA848.9B65E2C8@york.ac.uk> Message-ID: > > I have never done any thread programming before (though Prog. Python > makes it look easy enough), but I am concerned about different threads > accessing the storage of the data at incompatible times and mucking it > up and similar problems connecting to the mail server (I want to delete > successfully analysed mails.) > > Your advice is very welcome... > The only reason to play with threads would be if you wanted to have a mail parser thread and a mail retriever thread. Reasonable, but not a requirement. If you look at any of the comp sci books on threads one of the models discussed is "producer/consumer" which is exactly what you describe. The way it works is the producer thread does some work to produce data which is stored in a common area. The consumer eats one piece of data at a time. This could easily be done with python via a list accessible by both threads. Have the consumer eat from the front of the list and the producer add to the end. From python@rcn.com Tue Jun 4 16:10:30 2002 From: python@rcn.com (Raymond Hettinger) Date: Tue, 4 Jun 2002 11:10:30 -0400 Subject: [Tutor] Python and Excel References: <000a01c20b7f$17aa8b00$23ecc797@vaio> Message-ID: <005801c20bd9$f8701920$12f8a4d8@othello> This is a multi-part message in MIME format. ------=_NextPart_000_0055_01C20BB8.706BDBC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Laura, from win32com.client.dynamic import Dispatch xl =3D Dispatch( 'Excel.Application' ) xl.Range('a1:a100').Value =3D [[line] for line in open('file.txt')] Raymond Hettinger ----- Original Message -----=20 From: Laura Cantero=20 To: tutor@python.org=20 Sent: Tuesday, June 04, 2002 12:19 AM Subject: [Tutor] Python and Excel How can I export data strings from a .txt file, and display them on = Excel (individually)??? I need the CODE! Thanks, Laura ------=_NextPart_000_0055_01C20BB8.706BDBC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Laura,
 
from win32com.client.dynamic import = Dispatch
xl=20 =3D Dispatch( 'Excel.Application' )
xl.Range('a1:a100').Value =3D [[line] = for line in=20 open('file.txt')]
 
Raymond Hettinger
----- Original Message -----
From:=20 Laura Cantero
Sent: Tuesday, June 04, 2002 = 12:19=20 AM
Subject: [Tutor] Python and = Excel

How can I export data = strings from a .txt=20 file, and display them on Excel (individually)???
I need the=20 CODE!
Thanks,
Laura
------=_NextPart_000_0055_01C20BB8.706BDBC0-- From kojo@hal-pc.org Tue Jun 4 16:17:20 2002 From: kojo@hal-pc.org (Kojo Idrissa) Date: Tue, 04 Jun 2002 10:17:20 -0500 Subject: [Tutor] Connection/Analyis Order In-Reply-To: <3CFCA848.9B65E2C8@york.ac.uk> Message-ID: <5.1.0.14.0.20020604101315.0237ed28@mail.hal-pc.org> --=====================_701528454==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed And now, for something completely different... This is about you not having access to CGI type stuff. Have you considered Freezope.org? You can set up a free account and have access to Zope and a lot of other Zope/Python related stuff. Free for non-commercial use. I just set up an account yesterday and plan to use it to practice some Python and WebDev stuff. My ISP doesn't offer CGI through Python, only Perl. Of course, there' s the added learning curve of Zope, but hey, it's all done in Python, how hard could it be? :-) Seriously, given what you seem to want to do, Zope has all the functionality you need. Ok, it's overkill, but hey, it's free! Just an "out of the box" suggestion, not so much a direct response to your query. At 12:45 PM 6/4/2002 +0100, Russell Bungay wrote: >Hello, >I am setting up a series of web pages to display certain data based upon >the input to a form (ratings for levels in a game to be precise). > >Unfortunately, I currently have no access to proper cgi type stuff so I >am having to use a 'normal' email post from the services that my host >does provide. > >So, emails arrive at my server with the form data in, I want to analyse >each, store the data and publish some of it to web pages. All of the >coding I think I can handle (never done mail stuff before, but this is >Python, how hard can it be :o), my problem is more how I organise the >steps. I currently have three ideas: > >1. >Connect to server blah. >Check each mail (will not be just postings). >If mail has correct subject: > Get body of mail and analyse etc. >Check next mail etc. > >2. >Connect. >Check each mail. >If correct mail: > Get body of mail, stick in variable. >Check next mail. >Analyse all data in variable (ie do all mails at once). > >3. >Connect. >Check each mail. >If correct mail: > Analyse mail in seperate thread whilst... >Continuting to check mail... > >Now, I think my exact connection circumstances may effect this... > >At present I have access to a permanent, fast connection to an IMAP >server. However, in the future I will probably have to connect over >normal dial-up, possible to IMAP, possibly to POP3. > >Given my current status, I tend to favour 1, but over dial up would 2 or >3 make more sense? > >I have never done any thread programming before (though Prog. Python >makes it look easy enough), but I am concerned about different threads >accessing the storage of the data at incompatible times and mucking it >up and similar problems connecting to the mail server (I want to delete >successfully analysed mails.) > >Your advice is very welcome... > >Russell >-- **************************** Kojo Idrissa kojo@hal-pc.org http://www.hal-pc.org/~kojo/ **************************** --=====================_701528454==_.ALT Content-Type: text/html; charset="us-ascii" And now, for something completely different...

This is about you not having access to CGI type stuff.  Have you considered Freezope.org? <http://www.freezope.org/>
You can set up a free account and have access to Zope and a lot of other Zope/Python related stuff.  Free for non-commercial use.  I just set up an account yesterday and plan to use it to practice some Python and WebDev stuff.  My ISP doesn't offer CGI through Python, only Perl.

Of course, there' s the added learning curve of Zope, but hey, it's all done in Python, how hard could it be?
:-)
Seriously, given what you seem to want to do, Zope has all the functionality you need.  Ok, it's overkill, but hey, it's free!

Just an "out of the box" suggestion, not so much a direct response to your query.

At 12:45 PM 6/4/2002 +0100, Russell Bungay wrote:
Hello,
I am setting up a series of web pages to display certain data based upon
the input to a form (ratings for levels in a game to be precise).

Unfortunately, I currently have no access to proper cgi type stuff so I
am having to use a 'normal' email post from the services that my host
does provide.

So, emails arrive at my server with the form data in, I want to analyse
each, store the data and publish some of it to web pages.  All of the
coding I think I can handle (never done mail stuff before, but this is
Python, how hard can it be :o), my problem is more how I organise the
steps.  I currently have three ideas:

1.
Connect to server blah.
Check each mail (will not be just postings).
If mail has correct subject:
        Get body of mail and analyse etc.
Check next mail etc.
        
2.
Connect.
Check each mail.
If correct mail:
        Get body of mail, stick in variable.
Check next mail.
Analyse all data in variable (ie do all mails at once).

3.
Connect.
Check each mail.
If correct mail:
        Analyse mail in seperate thread whilst...
Continuting to check mail...

Now, I think my exact connection circumstances may effect this...

At present I have access to a permanent, fast connection to an IMAP
server.  However, in the future I will probably have to connect over
normal dial-up, possible to IMAP, possibly to POP3.

Given my current status, I tend to favour 1, but over dial up would 2 or
3 make more sense?

I have never done any thread programming before (though Prog. Python
makes it look easy enough), but I am concerned about different threads
accessing the storage of the data at incompatible times and mucking it
up and similar problems connecting to the mail server (I want to delete
successfully analysed mails.)

Your advice is very welcome...

Russell
--

****************************
Kojo Idrissa
 
kojo@hal-pc.org
http://www.hal-pc.org/~kojo/
**************************** --=====================_701528454==_.ALT-- From rab121@york.ac.uk Tue Jun 4 16:25:39 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Tue, 04 Jun 2002 16:25:39 +0100 Subject: [Tutor] Connection/Analyis Order References: Message-ID: <3CFCDBF3.4D637C35@york.ac.uk> Sean 'Shaleh' Perry wrote: >>I have never done any thread programming before (though Prog. Python >>makes it look easy enough), but I am concerned about different threads >>accessing the storage of the data at incompatible times and mucking it >>up and similar problems connecting to the mail server (I want to >>delete successfully analysed mails.) >The only reason to play with threads would be if you wanted to have a >mail parser thread and a mail retriever thread. Reasonable, but not a >requirement. Thats what I was thinking. So I would only run one parser at a time? I can see the advantages to this and really should of thought of it myself :o) My current implementation (half written) runs unthreaded, but when I have to go dial up again, I think I will rewrite it. Thankyou, Russell -- http://www.bigmaddrongo.com President of York University Trampolining Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From rab121@york.ac.uk Tue Jun 4 16:27:23 2002 From: rab121@york.ac.uk (Russell Bungay) Date: Tue, 04 Jun 2002 16:27:23 +0100 Subject: [Tutor] Connection/Analyis Order References: <5.1.0.14.0.20020604101315.0237ed28@mail.hal-pc.org> Message-ID: <3CFCDC5B.58733AC9@york.ac.uk> >Have you considered Freezope.org? Yes, but not for this project :o) Like you say, I would have the learning curve of Zope, and at the moment I an interest in a quick fix, I can tidy it up later. I am probably going to go Zope for a future project I am planning though... Thankyou, Russell -- http://www.bigmaddrongo.com President of York University Trampolining Club: http://york.trampolining.net Chair of The York Glee Singers: http://www.gleesingers.co.uk From shalehperry@attbi.com Tue Jun 4 16:33:27 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 04 Jun 2002 08:33:27 -0700 (PDT) Subject: [Tutor] Connection/Analyis Order In-Reply-To: <3CFCDBF3.4D637C35@york.ac.uk> Message-ID: On 04-Jun-2002 Russell Bungay wrote: > Sean 'Shaleh' Perry wrote: >>>I have never done any thread programming before (though Prog. Python >>>makes it look easy enough), but I am concerned about different threads >>>accessing the storage of the data at incompatible times and mucking it >>>up and similar problems connecting to the mail server (I want to >>delete >>>successfully analysed mails.) >>The only reason to play with threads would be if you wanted to have a >mail >>parser thread and a mail retriever thread. Reasonable, but not a >>>requirement. > > Thats what I was thinking. So I would only run one parser at a time? I > can see the advantages to this and really should of thought of it myself >:o) > yeah the parser thread would do: while (not blocked): mail = eatMailFromQueue() output = parse(mail) use output From jeff@ccvcorp.com Tue Jun 4 17:14:36 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 04 Jun 2002 09:14:36 -0700 Subject: [Tutor] Connection/Analyis Order References: <3CFCA848.9B65E2C8@york.ac.uk> Message-ID: <3CFCE76C.6C247F83@ccvcorp.com> Russell Bungay wrote: > Given my current status, I tend to favour 1, but over dial up would 2 or > 3 make more sense? Personally, I'd be inclined to use #2 in any case. It depends not only on your connection to your mailserver, but also to the connection to the webserver that you're publishing your data on. I'd think that you will probably want to update the web page only once for each run of your script. To my mind, the simplest way to do this is stepwise -- first grab all data, then analyze all data, then publish the results. If you *do* decide to use option #3 and go with threads, you will *definately* want to look into the Queue module. Queue does exactly what you'd need for passing chunks of data from one thread to another, safely. Your producer thread(s) add data to the Queue, your consumer thread(s) pull data from the Queue, and the Queue itself will make sure that nobody steps on each other's toes. You could also have a separate "publisher" thread -- once your data has been analyzed by your parser thread, the results can be put in another Queue to be pulled out by the publisher thread. That thread could accumulate results from multiple messages, and when the Queue is empty, update your web page. Or perhaps the publisher should wait for the Queue to be empty for longer than some time limit, such as half a second, to allow for some slight delays in the reading/parsing. > I have never done any thread programming before (though Prog. Python > makes it look easy enough), but I am concerned about different threads > accessing the storage of the data at incompatible times and mucking it > up and similar problems connecting to the mail server (I want to delete > successfully analysed mails.) Thread programming isn't *too* complicated if you're careful... ;) If you use a Queue to manage any data passed between threads, you'll probably be in good shape. Just be sure to think about all the possible conditions of "if *this* thread does X before or after *that* thread does Y, what will the effect be?" It's easy to assume a particular order of occurrences, but with threading those assumptions are dangerous -- if the order is important, then you *must* enforce it with thread synchronization techniques (of which Queues are perhaps the easiest...) And, while I haven't done anything with IMAP mailservers, using poplib to access POP3 accounts *is* indeed dead easy. :) (I sometimes check my home email while I'm at work, by firing up the Python interpreter and interactively poking through it with poplib...) Jeff Shannon Technician/Programmer Credit International From stuart_clemons@us.ibm.com Tue Jun 4 19:59:47 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Tue, 4 Jun 2002 14:59:47 -0400 Subject: [Tutor] Use of dictionary or DBM instead of spreadsheet Message-ID: --0__=0ABBE15DDFFBBF288f9e8a93df938690918c0ABBE15DDFFBBF28 Content-type: text/plain; charset=US-ASCII Hi all: I have an WinNT application I run that consists of three phases, 1) Python, 2) spreadsheet, and 3) Python. I would like to eliminate the spreadsheet and make this an all Python application. Here's the details. 1) I run a python program that "pings" a list of IP addresses and determines if the IP addresses are being used. I run this daily. The result is collected daily in a text file called ipresult.txt, which looks like this: 9.99.99.1 noreply 9.99.99.2 reply 9.99.99.3 reply 9.99.99.4 noreply, etc. 2) I then import this file daily into a spreadsheet which is acting as a collection repository. The spreadsheet file looks like this, with column entries for each day's results. 6/1 6/2 6/3 6/4 9.99.9.1 noreply reply reply reply 9.99.9.2 reply reply reply reply 9.99.9.3 reply noreply reply reply 9.99.9.4 noreply noreply noreply noreply 3) I then export this file into a text file that looks like the above, only it's a text file. I then run another Python program that will print out only those IP address that have only no reply's. In the above example, the IP address 9.99.9.4 is the only IP address that has not had a reply. I would like to eliminate using the spreadsheet as the data repository and make this all python. I was thinking I could use either a dictionary or the anydbm module to act as the collection repository instead of the spreadsheet, but I don't know how to do it. My Python reference books only touch on dictionaries and the anydbm module. I ruled out appending to a file, since it would not allow for columns of data. I guess I need to know how to add data to the repository and then how to check the entries for each IP address in the repository. Any guidance would be greatly appreciated. - Stuart --0__=0ABBE15DDFFBBF288f9e8a93df938690918c0ABBE15DDFFBBF28 Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi all:

I have an WinNT application I run that consists of three phases, 1) Python, 2) spreadsheet, and 3) Python. I would like to eliminate the spreadsheet and make this an all Python application.

Here's the details.

1) I run a python program that "pings" a list of IP addresses and determines if the IP addresses are being used. I run this daily. The result is collected daily in a text file called ipresult.txt, which looks like this:

9.99.99.1 noreply
9.99.99.2 reply
9.99.99.3 reply
9.99.99.4 noreply, etc.

2) I then import this file daily into a spreadsheet which is acting as a collection repository. The spreadsheet file looks like this, with column entries for each day's results.

6/1 6/2 6/3 6/4
9.99.9.1 noreply reply reply reply
9.99.9.2 reply reply reply reply
9.99.9.3 reply noreply reply reply
9.99.9.4 noreply noreply noreply noreply

3) I then export this file into a text file that looks like the above, only it's a text file. I then run another Python program that will print out only those IP address that have only no reply's. In the above example, the IP address 9.99.9.4 is the only IP address that has not had a reply.

I would like to eliminate using the spreadsheet as the data repository and make this all python. I was thinking I could use either a dictionary or the anydbm module to act as the collection repository instead of the spreadsheet, but I don't know how to do it. My Python reference books only touch on dictionaries and the anydbm module. I ruled out appending to a file, since it would not allow for columns of data.

I guess I need to know how to add data to the repository and then how to check the entries for each IP address in the repository.

Any guidance would be greatly appreciated.

- Stuart

--0__=0ABBE15DDFFBBF288f9e8a93df938690918c0ABBE15DDFFBBF28-- From stuart_clemons@us.ibm.com Tue Jun 4 20:20:51 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Tue, 4 Jun 2002 15:20:51 -0400 Subject: [Tutor] re: computers Message-ID: --0__=0ABBE15DDFFADAC38f9e8a93df938690918c0ABBE15DDFFADAC3 Content-type: text/plain; charset=US-ASCII FYI. Even if your OS, such as NT, is capable of running on a multi- processor system, it does not mean that your programs or compilers will run any faster than when run on a single processor system. Most programs and compilers do not take advantage of multi-processor systems, which is something most people don't seem to realise. In fact, in some cases a single processor system will complete tasks faster than a multi-processor system. So, for most people, having a multiprocessor system is a waste time, money, and resources. --0__=0ABBE15DDFFADAC38f9e8a93df938690918c0ABBE15DDFFADAC3 Content-type: text/html; charset=US-ASCII Content-Disposition: inline

FYI. Even if your OS, such as NT, is capable of running on a multi-processor system, it does not mean that your programs or compilers will run any faster than when run on a single processor system. Most programs and compilers do not take advantage of multi-processor systems, which is something most people don't seem to realise. In fact, in some cases a single processor system will complete tasks faster than a multi-processor system. So, for most people, having a multiprocessor system is a waste time, money, and resources. --0__=0ABBE15DDFFADAC38f9e8a93df938690918c0ABBE15DDFFADAC3-- From wolf_binary@hotmail.com Tue Jun 4 21:30:44 2002 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Tue, 4 Jun 2002 15:30:44 -0500 Subject: [Tutor] re: computers References: Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_000A_01C20BDC.CAEC7540 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Thanks Stuart, That's what I was thinking. I wondered if programs would run faster. I = was looking into it to make my graphics work, ie: 3D modeling, take less = time to use. When doing animation it currently takes me like a = half-hour to save my work. This is not a gross overestamation either. = It then turns out to be less than 30 sec of animation when I play it. = Would having multiple processors make it more efficient? Thanks, Cameron Stoner ----- Original Message -----=20 From: stuart_clemons@us.ibm.com=20 To: tutor@python.org=20 Sent: Tuesday, June 04, 2002 2:20 PM Subject: [Tutor] re: computers FYI. Even if your OS, such as NT, is capable of running on a = multi-processor system, it does not mean that your programs or compilers = will run any faster than when run on a single processor system. Most = programs and compilers do not take advantage of multi-processor systems, = which is something most people don't seem to realise. In fact, in some = cases a single processor system will complete tasks faster than a = multi-processor system. So, for most people, having a multiprocessor = system is a waste time, money, and resources. ------=_NextPart_000_000A_01C20BDC.CAEC7540 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Thanks Stuart,
 
That's what I was thinking.  I = wondered if=20 programs would run faster.  I was looking into it to make my = graphics work,=20 ie: 3D modeling, take less time to use.  When doing animation it = currently=20 takes me like a half-hour to save my work.  This is not a gross=20 overestamation either.  It then turns out to be less than 30 sec of = animation when I play it.  Would having multiple processors make it = more=20 efficient?
 
Thanks,
Cameron Stoner
----- Original Message -----
From:=20 stuart_clemons@us.ibm.com =
Sent: Tuesday, June 04, 2002 = 2:20=20 PM
Subject: [Tutor] re: = computers

FYI. Even if your OS, such as NT, is capable of running on a=20 multi-processor system, it does not mean that your programs or = compilers will=20 run any faster than when run on a single processor system. Most = programs and=20 compilers do not take advantage of multi-processor systems, which is = something=20 most people don't seem to realise. In fact, in some cases a single = processor=20 system will complete tasks faster than a multi-processor system. So, = for most=20 people, having a multiprocessor system is a waste time, money, and=20 resources.

------=_NextPart_000_000A_01C20BDC.CAEC7540-- From ATrautman@perryjudds.com Tue Jun 4 22:01:04 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Tue, 4 Jun 2002 16:01:04 -0500 Subject: [Tutor] re: computers Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A2C6@CORP_EXCHANGE> Cameron, This depends a huge amount upon your software and the type of animation. Is this vector based animation or pixel resolution? In addition based on the amount of time it takes to save what amount of RAM is free during your save edit? Unless you increase you free RAM the two processor unit will use more RAM to support the second unit so it could be even slower. If the program supports two processors and most high end programs do it separates the file and IO function from the vector math functions which will give you a lot more speed. See the high end MAC workstations as that is what they are routinely used for. IMHO If you don't have this type of software an upgrade to a single processor, high end vector video card, high sped hard drive, and lots of RAM are probably the best answer. Peace Alan -----Original Message----- From: Cameron Stoner [mailto:wolf_binary@hotmail.com] Sent: Tuesday, June 04, 2002 3:31 PM To: tutor@python.org; stuart_clemons@us.ibm.com Subject: Re: [Tutor] re: computers Thanks Stuart, That's what I was thinking. I wondered if programs would run faster. I was looking into it to make my graphics work, ie: 3D modeling, take less time to use. When doing animation it currently takes me like a half-hour to save my work. This is not a gross overestamation either. It then turns out to be less than 30 sec of animation when I play it. Would having multiple processors make it more efficient? Thanks, Cameron Stoner ----- Original Message ----- From: stuart_clemons@us.ibm.com To: tutor@python.org Sent: Tuesday, June 04, 2002 2:20 PM Subject: [Tutor] re: computers FYI. Even if your OS, such as NT, is capable of running on a multi-processor system, it does not mean that your programs or compilers will run any faster than when run on a single processor system. Most programs and compilers do not take advantage of multi-processor systems, which is something most people don't seem to realise. In fact, in some cases a single processor system will complete tasks faster than a multi-processor system. So, for most people, having a multiprocessor system is a waste time, money, and resources. From marcolinux@linuxbr.com.br Tue Jun 4 22:16:24 2002 From: marcolinux@linuxbr.com.br (Marc) Date: Tue, 4 Jun 2002 18:16:24 -0300 Subject: [Tutor] re: computers In-Reply-To: References: Message-ID: <20020604181624.A7870@marcolab.proconet> stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) wrote: > > FYI. Even if your OS, such as NT, is capable of running on a multi- > processor system, it does not mean that your programs or compilers will > run any faster than when run on a single processor system. Most programs > and compilers do not take advantage of multi-processor systems, which is > something most people don't seem to realise. In fact, in some cases a > single processor system will complete tasks faster than a multi-processor > system. So, for most people, having a multiprocessor system is a waste > time, money, and resources. Supose two programs (A,B) not multi-processor aware. So you are saying that if I run a program A on a multi-processor system, and call another program B, it will wait for the processor that is working with A even if I have another processor sitting there doing nothing? Shouldnt the OS take care of that? Or am I missing something? From stuart_clemons@us.ibm.com Tue Jun 4 23:24:45 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Tue, 4 Jun 2002 18:24:45 -0400 Subject: [Tutor] re: computers Message-ID: --0__=0ABBE15DDFE9DD2A8f9e8a93df938690918c0ABBE15DDFE9DD2A Content-type: text/plain; charset=US-ASCII Hi Cameron: I would highly doubt that a two processor system would even minimally speed up your graphic work. I would speak with the makers of the 3D modeling software and get their suggestions on improving performance. My guess is that they will suggest a high-end graphics card, more RAM and a faster disk subsystem (highend SCSI controller and harddrive) and then possibly a better single processor in that order. I would not think that they would even mention adding a second processor, but then, I don't really know all the details. Just my guess. Also, I would guess that Win2000 would run your software more efficiently than Win98. Let us know what they say. - Stuart ---------------------- Forwarded by Stuart Clemons/Westford/IBM on 06/04/2002 06:30 PM --------------------------- "Cameron Stoner" on 06/04/2002 04:30:44 PM To: , cc: Subject: Re: [Tutor] re: computers Thanks Stuart, That's what I was thinking. I wondered if programs would run faster. I was looking into it to make my graphics work, ie: 3D modeling, take less time to use. When doing animation it currently takes me like a half-hour to save my work. This is not a gross overestamation either. It then turns out to be less than 30 sec of animation when I play it. Would having multiple processors make it more efficient? Thanks, Cameron Stoner ----- Original Message ----- From: stuart_clemons@us.ibm.com To: tutor@python.org Sent: Tuesday, June 04, 2002 2:20 PM Subject: [Tutor] re: computers FYI. Even if your OS, such as NT, is capable of running on a multi- processor system, it does not mean that your programs or compilers will run any faster than when run on a single processor system. Most programs and compilers do not take advantage of multi-processor systems, which is something most people don't seem to realise. In fact, in some cases a single processor system will complete tasks faster than a multi-processor system. So, for most people, having a multiprocessor system is a waste time, money, and resources. --0__=0ABBE15DDFE9DD2A8f9e8a93df938690918c0ABBE15DDFE9DD2A Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi Cameron:

I would highly doubt that a two processor system would even minimally speed up your graphic work. I would speak with the makers of the 3D modeling software and get their suggestions on improving performance. My guess is that they will suggest a high-end graphics card, more RAM and a faster disk subsystem (highend SCSI controller and harddrive) and then possibly a better single processor in that order. I would not think that they would even mention adding a second processor, but then, I don't really know all the details. Just my guess. Also, I would guess that Win2000 would run your software more efficiently than Win98. Let us know what they say.

- Stuart

---------------------- Forwarded by Stuart Clemons/Westford/IBM on 06/04/2002 06:30 PM ---------------------------

To: <tutor@python.org>, <stuart_clemons@us.ibm.com>
cc:
Subject: Re: [Tutor] re: computers

Thanks Stuart,

That's what I was thinking. I wondered if programs would run faster. I was looking into it to make my graphics work, ie: 3D modeling, take less time to use. When doing animation it currently takes me like a half-hour to save my work. This is not a gross overestamation either. It then turns out to be less than 30 sec of animation when I play it. Would having multiple processors make it more efficient?

Thanks,
Cameron Stoner
----- Original Message -----
From: stuart_clemons@us.ibm.com
To: tutor@python.org
Sent: Tuesday, June 04, 2002 2:20 PM
Subject: [Tutor] re: computers

FYI. Even if your OS, such as NT, is capable of running on a multi-processor system, it does not mean that your programs or compilers will run any faster than when run on a single processor system. Most programs and compilers do not take advantage of multi-processor systems, which is something most people don't seem to realise. In fact, in some cases a single processor system will complete tasks faster than a multi-processor system. So, for most people, having a multiprocessor system is a waste time, money, and resources.


--0__=0ABBE15DDFE9DD2A8f9e8a93df938690918c0ABBE15DDFE9DD2A-- From stuart_clemons@us.ibm.com Wed Jun 5 18:11:11 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed, 5 Jun 2002 13:11:11 -0400 Subject: [Tutor] re: computers Message-ID: --0__=0ABBE15CDFCBD1E08f9e8a93df938690918c0ABBE15CDFCBD1E0 Content-type: text/plain; charset=US-ASCII Hi Marc: In my experience with NT and multiprocessor systems, running the two "not multi-processor aware" programs you mentioned would be handled one of two ways in a two processor system: 1) Believe it or not, one processor would handle the full load of running both programs. The second processor would be virtually idle. (In most cases, this is actually irrelevant to overall performance times) 2) The two processors would each split the load. In either case, the total time to accomplish whatever task you were asking the two programs to accomplish would be nearly identical. There are a number of reasons for this, but in general terms, one significant reason related to processors is that the vast majority of programs are not written to run parallel tasks or threads using multiple processors. However, more importantly, in the vast majority of program useage, the processor is not the bottleneck in regards to performance. RAM, bus speed, disk subsystem, caching, net access, etc all usually have a more significant impact on program performance than the processor (which is usually underutilized). In most cases, the number of processors being used is usually irrelevant to performance. They can't make disk I/O go faster or move data across the bus faster, for example. I've never delved into how NT decides to split its tasks with multiple processors, mainly because it wasn't that important to me in terms of overall performance, which is important to me. Most of my experience is with general use applications and compilers. I don't have experience with compute intensive applications which are designed for multiprocessors. I'm sure in those cases, load-balanced multiprocessors (and RAM) would be important factors in performance. Marc wrote: Supose two programs (A,B) not multi-processor aware. So you are saying that if I run a program A on a multi-processor system, and call another program B, it will wait for the processor that is working with A even if I have another processor sitting there doing nothing? Shouldnt the OS take care of that? Or am I missing something? Message: 6 Date: Tue, 4 Jun 2002 18:16:24 -0300 From: Marc To: tutor@python.org Subject: Re: [Tutor] re: computers Organization: "Doo Bee Doo Inc" stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) wrote: > > FYI. Even if your OS, such as NT, is capable of running on a multi- > processor system, it does not mean that your programs or compilers will > run any faster than when run on a single processor system. Most programs > and compilers do not take advantage of multi-processor systems, which is > something most people don't seem to realise. In fact, in some cases a > single processor system will complete tasks faster than a multi-processor > system. So, for most people, having a multiprocessor system is a waste > time, money, and resources. --0__=0ABBE15CDFCBD1E08f9e8a93df938690918c0ABBE15CDFCBD1E0 Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi Marc:

In my experience with NT and multiprocessor systems, running the two "not multi-processor aware" programs you mentioned would be handled one of two ways in a two processor system:

1) Believe it or not, one processor would handle the full load of running both programs. The second processor would be virtually idle. (In most cases, this is actually irrelevant to overall performance times)

2) The two processors would each split the load.

In either case, the total time to accomplish whatever task you were asking the two programs to accomplish would be nearly identical. There are a number of reasons for this, but in general terms, one significant reason related to processors is that the vast majority of programs are not written to run parallel tasks or threads using multiple processors.

However, more importantly, in the vast majority of program useage, the processor is not the bottleneck in regards to performance. RAM, bus speed, disk subsystem, caching, net access, etc all usually have a more significant impact on program performance than the processor (which is usually underutilized). In most cases, the number of processors being used is usually irrelevant to performance. They can't make disk I/O go faster or move data across the bus faster, for example.

I've never delved into how NT decides to split its tasks with multiple processors, mainly because it wasn't that important to me in terms of overall performance, which is important to me.

Most of my experience is with general use applications and compilers. I don't have experience with compute intensive applications which are designed for multiprocessors. I'm sure in those cases, load-balanced multiprocessors (and RAM) would be important factors in performance.

Marc wrote:
Supose two programs (A,B) not multi-processor aware.
So you are saying that if I run a program A on a multi-processor system,
and call another program B, it will wait for the processor that is
working with A even if I have another processor sitting there
doing nothing?
Shouldnt the OS take care of that? Or am I missing something?



Message: 6
Date: Tue, 4 Jun 2002 18:16:24 -0300
From: Marc <marcolinux@linuxbr.com.br>
To: tutor@python.org
Subject: Re: [Tutor] re: computers
Organization: "Doo Bee Doo Inc"

stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) wrote:

>
> FYI. Even if your OS, such as NT, is capable of running on a multi-
> processor system, it does not mean that your programs or compilers will
> run any faster than when run on a single processor system. Most programs
> and compilers do not take advantage of multi-processor systems, which is
> something most people don't seem to realise. In fact, in some cases a
> single processor system will complete tasks faster than a multi-processor
> system. So, for most people, having a multiprocessor system is a waste
> time, money, and resources.

--0__=0ABBE15CDFCBD1E08f9e8a93df938690918c0ABBE15CDFCBD1E0-- From terjeja@hotmail.com Wed Jun 5 18:36:12 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 05 Jun 2002 17:36:12 +0000 Subject: [Tutor] xor Message-ID: What does really xor do? I tried an example, >>> 30^76 82 ^ means xor if I am completely wrong. I don't see any connection between the numbers. Can anyone explain? Thanks, Terje _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From paulsid@shaw.ca Wed Jun 5 18:43:41 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 05 Jun 2002 11:43:41 -0600 Subject: [Tutor] xor References: Message-ID: <3CFE4DCD.EBACB2C3@shaw.ca> Terje Johan Abrahamsen wrote: > What does really xor do? I tried an example, > >>> 30^76 > 82 > > ^ means xor if I am completely wrong. I don't see any connection between the > numbers. Can anyone explain? XOR works on the binary level. x XOR y is true if and only if x != y, where x and y are binary digits (bits). So if we convert your example to binary, it makes sense: 0011110 = 30 ^ 1001100 = 76 -------------- 1010010 = 82 -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From terjeja@hotmail.com Wed Jun 5 21:37:09 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Wed, 05 Jun 2002 20:37:09 +0000 Subject: [Tutor] PythonWin Message-ID: I use Pythonwin instead of the normal IDLE. THe version is 146 which should contain Python 2.2. I am currently trying a few of the modules that are included, but it seems like quite a few is missing. For example, os.getsize as an example. However, others like os.rename exists. It is described in the Python book I currently read (Core Python Programming), but is not accessible in Pythonwin. The same was the case with a number of modules I read about in the newest Python library reference. Am I just not finding them, or does the Pythonwin have an amputated number of modules? _________________________________________________________________ Join the world’s largest e-mail service with MSN Hotmail. http://www.hotmail.com From dyoo@hkn.eecs.berkeley.edu Wed Jun 5 21:41:45 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 5 Jun 2002 13:41:45 -0700 (PDT) Subject: [Tutor] xor In-Reply-To: <3CFE4DCD.EBACB2C3@shaw.ca> Message-ID: On Wed, 5 Jun 2002, Paul Sidorsky wrote: > Terje Johan Abrahamsen wrote: > > > What does really xor do? I tried an example, > > >>> 30^76 > > 82 > > > > ^ means xor if I am completely wrong. I don't see any connection > > between the numbers. Can anyone explain? > > XOR works on the binary level. x XOR y is true if and only if x != y, > where x and y are binary digits (bits). So if we convert your example > to binary, it makes sense: > > 0011110 = 30 > ^ 1001100 = 76 > -------------- > 1010010 = 82 XOR stands for "exclusive or", so you can think of it as the "one, or the other, but not both" bit operation. On a tangent note, there's a cute trick that assembly and C programmers could use with XOR to swap two values around without using a temporary variable. Here's an interpreter session that shows how it works: ### >>> a 42 >>> b 24 >>> a = a ^ b >>> b = a ^ b >>> a = a ^ b >>> a 24 >>> b 42 ### (Danny Hillis mentions this trick in his talk with game developers on Dr. Dobb's Technetcast: http://technetcast.ddj.com/tnc_play_stream.html?stream_id=220) But in Python, to swap two values, it's probably just easier to write: ### >>> a, b = b, a ### anyway, so the XOR swap trick is much less useful in Python. In other languages, with unusual constraints, it might be a useful thing to know... *grin* From wolf_binary@hotmail.com Thu Jun 6 00:42:49 2002 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Wed, 5 Jun 2002 18:42:49 -0500 Subject: [Tutor] special class methods Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0021_01C20CC0.CA858F80 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, Why would you want to use the __add__ special class method in a class? = I know what it is soposed to do, but can't you just add two objects = together. I read somewhere that in Python everything is an object. So = having a special class method used to add objects seem to be redundant = to me. Is this true? Thanks, Cameron ------=_NextPart_000_0021_01C20CC0.CA858F80 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi all,
 
Why would you want to use the=20 __add__ special class method in a class?  I know = what it=20 is soposed to do, but can't you just add two objects together.  I = read=20 somewhere that in Python everything is an object.  So having a = special=20 class method used to add objects seem to be redundant to me.  Is = this=20 true?
 
Thanks,
Cameron
 
 
------=_NextPart_000_0021_01C20CC0.CA858F80-- From paulsid@shaw.ca Thu Jun 6 01:13:42 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Wed, 05 Jun 2002 18:13:42 -0600 Subject: [Tutor] xor References: Message-ID: <3CFEA936.C6AE36D5@shaw.ca> Danny Yoo wrote: > On a tangent note, there's a cute trick that assembly and C programmers > could use with XOR to swap two values around without using a temporary > variable. Here's an interpreter session that shows how it works: > >>> a = a ^ b > >>> b = a ^ b > >>> a = a ^ b In C this is usually condensed to the ugly but very efficient a^=b^=a^=b, which I first saw in Abrash's Zen of Graphics Programming. Aside from saving space, it's significantly faster. Of course, this won't work in Python because a ^= b is an assignment and assignments don't have values in Python. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From shalehperry@attbi.com Thu Jun 6 01:51:58 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed, 05 Jun 2002 17:51:58 -0700 (PDT) Subject: [Tutor] special class methods In-Reply-To: Message-ID: On 05-Jun-2002 Cameron Stoner wrote: > Hi all, > > Why would you want to use the __add__ special class method in a class? I > know what it is soposed to do, but can't you just add two objects together. > I read somewhere that in Python everything is an object. So having a special > class method used to add objects seem to be redundant to me. Is this true? > when you define __add__ (or its brothers) the interpreter calls them when you use the respective symbols. so: >>> class Foo: ... def __init__(self, v = 5): ... self.value = v ... def __add__(self, other): ... return self.value * other.value ... >>> a = Foo(3) >>> b = Foo(7) >>> a + b 21 # not 10 yes, this is a silly example. But you define how the class acts with the math ops by defining the equivalent function. A more useful example would be something like: class Rational: def __init__(self, top, bottom): self.numerator = top self.denominator = bottom def __add__(self, other): # do common denominator math then add the two numbers and reduce then you could do: a = Rational(1,2) # 1/2 b = Rational(2,3) # 2/3 c = a + b # 3/6 + 4/6 => 7/6 or a = Rational(1,3) b = Rational(1,6) c = a + b # 2/6 + 1/6 => 3/6 => 1/2 From syrinx@simplecom.net Thu Jun 6 04:07:38 2002 From: syrinx@simplecom.net (Scott) Date: Wed, 5 Jun 2002 22:07:38 -0500 Subject: [Tutor] dialup Message-ID: <20020605220738.42676167.syrinx@simplecom.net> Hello. I'm setting up a "Linux From Scratch" system, and thought I would take a stab at writing my ppp-on script in Python (just for the heck of it). Which module should I look at to use to talk to my modem? From dyoo@hkn.eecs.berkeley.edu Thu Jun 6 07:13:54 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 5 Jun 2002 23:13:54 -0700 (PDT) Subject: [Tutor] PythonWin In-Reply-To: Message-ID: > contain Python 2.2. I am currently trying a few of the modules that are > included, but it seems like quite a few is missing. For example, > os.getsize as an example. Hi Terje, You're probably thinking of 'os.path.getsize()': The getsize() function is within the 'os.path' module. > However, others like os.rename exists. It is described in the Python > book I currently read (Core Python Programming), but is not accessible > in Pythonwin. Hmmm! This is most likely a typo then; do you have the page number where it talks about this? According to Wesley's Core Python Programming Errata page: http://starship.python.net/crew/wesc/cpp/errata.htm there's no reference to a bug with 'os.getsize', so it sounds like you found something new. Maybe you could convince Wes to send a check for $2.56. *grin* > The same was the case with a number of modules I read about in the > newest Python library reference. Am I just not finding them, or does the > Pythonwin have an amputated number of modules? Hmmm! Not sure about this one. I'm assuming that the Activestate distribution of Python has, at least, the Standard Library. For the official documentation on the modules that come with Python, you can look at: http://www.python.org/doc/lib/ If you have more questions, please feel free to ask! From scot@possum.in-berlin.de Thu Jun 6 05:46:35 2002 From: scot@possum.in-berlin.de (Scot W. Stevenson) Date: Thu, 6 Jun 2002 06:46:35 +0200 Subject: [Tutor] computers In-Reply-To: <5.1.0.14.0.20020603222933.02398a30@mail.hal-pc.org> References: <5.1.0.14.0.20020603222933.02398a30@mail.hal-pc.org> Message-ID: <200206060646.35212.scot@possum.in-berlin.de> Hi -=20 > It might be fun to > practice some multi threaded Python programming with to procs. Wait a moment. I thought that Python threads weren't really run in parall= el=20 because of something called the Great Interpreter Lock. Wouldn't this mea= n=20 that you can have all the processors you want, it will not make Python=20 faster? (And, concerning another list thread here, wouldn't this be another reaso= n=20 to use Java instead of Python?) Y, Scot From lumbricus@gmx.net Thu Jun 6 11:18:43 2002 From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=) Date: Thu, 6 Jun 2002 12:18:43 +0200 (MEST) Subject: [Tutor] dialup References: <20020605220738.42676167.syrinx@simplecom.net> Message-ID: <19355.1023358723@www42.gmx.net> > Hello. I'm setting up a "Linux From Scratch" system, and thought I > would take a stab at writing my ppp-on script in Python (just for the > heck of it). Which module should I look at to use to talk to my modem? __builtins__ ;-) man 2 open man 2 read man 2 write HTH, HAND and Greetings, J"o! -- sigfault -- GMX - Die Kommunikationsplattform im Internet. http://www.gmx.net From ericblack69@yahoo.com Thu Jun 6 15:14:48 2002 From: ericblack69@yahoo.com (Eric Black) Date: Thu, 6 Jun 2002 07:14:48 -0700 (PDT) Subject: [Tutor] tuple sorting Message-ID: <20020606141448.35195.qmail@web13201.mail.yahoo.com> Hello all, I am a newbie who's been lurking here for a couple of months now and I just love this list. While considering the May 20 post of Raymond Hettinger: Convert the outer tuple to a list so that it can be sorted: >>> a = ((4,1,8), (9,2,5),(3,6,9)) >>> b = list(a) >>> b.sort() >>> a = tuple(b) >>> print a ((3, 6, 9), (4, 1, 8), (9, 2, 5)) I guess I found a very trivial typo in the distribution. Is this worth reporting? >>> tuple( # the popup says: --> list, not tuple. >>> tuple.__doc__() ## has the same typo. 'tuple(sequence) -> list\n\nReturn a tuple whose items are the same as those of the argument sequence.\nIf the argument is a tuple, the return value is the same object.' >>> This gave me the ambition to rummage in the innards of python. I know there is a doc string somewhere in the source but after using windows find tool looking in C:\Python21 for the text I couldn't find the physical file where it's located. I am running the windows executable version of Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32 The entries in 7.3.4 Tuple Objects of the Python/C API Reference Manual imply C code is involved. If someone could explain where the doc string is and how to rummage in the innards I would appreciate it. TIA, Eric Black __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From dyoo@hkn.eecs.berkeley.edu Thu Jun 6 15:33:29 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Jun 2002 07:33:29 -0700 (PDT) Subject: [Tutor] tuple sorting In-Reply-To: <20020606141448.35195.qmail@web13201.mail.yahoo.com> Message-ID: > >>> a = ((4,1,8), (9,2,5),(3,6,9)) > >>> b = list(a) > >>> b.sort() > >>> a = tuple(b) > >>> print a > ((3, 6, 9), (4, 1, 8), (9, 2, 5)) > > I guess I found a very trivial typo in the distribution. Is this worth > reporting? Yes. Good eyes. *grin* The docstring was buggy, but this has been fixed in Python 2.2: ### Python 2.2.1 (#1, Apr 13 2002, 13:15:33) [GCC 2.95.4 20011002 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print tuple.__doc__ tuple() -> an empty tuple tuple(sequence) -> tuple initialized from sequence's items If the argument is a tuple, the return value is the same object. ### > This gave me the ambition to rummage in the innards of python. I know > there is a doc string somewhere in the source but after using windows > find tool looking in C:\Python21 for the text I couldn't find the > physical file where it's located. In Python 2.2, it should be located in the Objects/tupleobject.c file; the docstring is held in a variable called 'tuple_doc'. I don't have a copy of the Python 2.1 sources handy at the moment, but looking at Sourceforge, I think I've found it in 'Python/bltinmodule.c': http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/*checkout*/python/python/dist/src/Python/bltinmodule.c?rev=2.197.2.1&only_with_tag=r213 The tuple() function moved between 2.1 to 2.2 as a side effect of the unification between types and classes: http://www.python.org/2.2/descrintro.html so that explains why it moved from 'bltinmodule.c' to 'tupleobject.c'. Hope this helps! From jeff@ccvcorp.com Thu Jun 6 17:47:32 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jun 2002 09:47:32 -0700 Subject: [Tutor] computers References: <5.1.0.14.0.20020603222933.02398a30@mail.hal-pc.org> <200206060646.35212.scot@possum.in-berlin.de> Message-ID: <3CFF9224.4C5939AB@ccvcorp.com> "Scot W. Stevenson" wrote: > Hi - > > > It might be fun to > > practice some multi threaded Python programming with to procs. > > Wait a moment. I thought that Python threads weren't really run in parallel > because of something called the Great Interpreter Lock. Wouldn't this mean > that you can have all the processors you want, it will not make Python > faster? Actually, it's the Global (not great) Interpreter Lock, but this is largely true. The Python interpreter itself has been made "threadsafe" in a rather crude (but effective) way -- by only allowing a single Python thread to run at a time. This means that the only possible way that multithreading can speed up a Python program is if it spends a fair amount of time either waiting for I/O, or in C extensions (which release the GIL). Of course, considering how few people use multiproc systems, and that few of *those* will distribute threads from a single process across different processors, the GIL is much less of a bottleneck than it sounds like. Especially when you consider that the majority of real-world programs are I/O bound (or memory bound), not CPU bound -- the processor spends a fair amount of time sitting idle anyhow, so squeezing CPU efficiency any further tends to not have much practical effect. The real advantage to multithreading is that it separates your program into distinct, logical tasks, making it easier to understand what's going on (if you're separating tasks right ;) ). Only in very special cases does multithreading really help with program speed. > (And, concerning another list thread here, wouldn't this be another reason > to use Java instead of Python?) In a word, no. ;) First of all, on many platforms Java (IIRC) emulates threads in a nonthreaded environment ("green" threads), with semantics that are similar to Python's GIL (but weaker, because the GIL is typically released in extensions). Second, and more importantly, efficient use of multiple processors (even if Java offered that) is typically a poor reason to choose a language to develop in -- as mentioned above, it's probably not going to result in a faster program. And if you really needed that efficiency, then you should be coding in C, not Java. The point of using Python is that it's easier/faster to develop software with it. The (hypothetical) advantages that Java offers for SMP environments are rarely going to be enough of a benefit to override the extra costs of developing in Java. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu Jun 6 17:56:50 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jun 2002 09:56:50 -0700 Subject: [Tutor] PythonWin References: Message-ID: <3CFF9452.7B471D58@ccvcorp.com> Danny Yoo wrote: > > contain Python 2.2. I am currently trying a few of the modules that are > > included, but it seems like quite a few is missing. [...] > > > The same was the case with a number of modules I read about in the > > newest Python library reference. Am I just not finding them, or does the > > Pythonwin have an amputated number of modules? > > Hmmm! Not sure about this one. I'm assuming that the Activestate > distribution of Python has, at least, the Standard Library. I have been using the ActiveState ActivePython distribution (and the Windows-only IDE included with it, PythonWin) for versions 2.0, 2.1, and 2.2 now. I have not yet found a single module available in the PythonLabs Windows distribution that is not available in ActiveState's distribution. However, you may be reading, in that library reference, about a number of OS-specific modules. There's a fair amount of stuff that's included on Unix-ish distributions that isn't there in Windows distributions, simply because the OS can't support it (or doesn't need it). For example, the curses module doesn't exist on Windows because there's no underlying curses library for it to interface to -- Windows uses a different method to control terminal screens. Conversely, there's modules that are available for Windows that have no Unix equivalents -- most notably Mark Hammond's Win32 extensions, which are packaged with ActivePython. I'd suggest checking the library reference a little more closely for the OS availability. I'm guessing that you'll see that those "missing" modules are Unix-only. (Or, like os.path.getsize(), you may be mistakenly looking for them in the wrong place...) Of course, if you *do* find anything that claims Windows availability, but you don't have, we'd like to hear about it. :) Jeff Shannon Technician/Programmer Credit International From stuart_clemons@us.ibm.com Thu Jun 6 18:57:02 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Thu, 6 Jun 2002 13:57:02 -0400 Subject: [Tutor] Reading & printing lines from two different files Message-ID: --0__=0ABBE143DFCC294C8f9e8a93df938690918c0ABBE143DFCC294C Content-type: text/plain; charset=US-ASCII Hi all: I have two files, file1 and file2. I want to print the first line from file1, then the first line from file2, then the second line from file 1, then the second line from file 2, etc. Here are my files and what the output should look like: File1.txt First line file 1 Second line file 1 Third line file 1 File2.txt First line file 2 Second line file 2 Third line file 3 This is the output I want when the program is run: First line file 1 First line file 2 Second line file 1 Second line file 2 Third line file 1 Third line file 2 I've tried different looping techniques mainly using variations of the structure below, but I can't seem to get the output I want. Any suggestions ? Thanks. infile1 = open('c:\file1.txt', 'r') infile2 = open ('c:\file2.txt', 'r') for line1 in infile1.readlines(): print line1 for line2 in infile2.readlines() print line2 --0__=0ABBE143DFCC294C8f9e8a93df938690918c0ABBE143DFCC294C Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Hi all:

I have two files, file1 and file2. I want to print the first line from file1, then the first line from file2, then the second line from file 1, then the second line from file 2, etc.

Here are my files and what the output should look like:

File1.txt
First line file 1
Second line file 1
Third line file 1

File2.txt
First line file 2
Second line file 2
Third line file 3

This is the output I want when the program is run:

First line file 1
First line file 2
Second line file 1
Second line file 2
Third line file 1
Third line file 2

I've tried different looping techniques mainly using variations of the structure below, but I can't seem to get the output I want. Any suggestions ? Thanks.

infile1 = open('c:\file1.txt', 'r')
infile2 = open ('c:\file2.txt', 'r')
for line1 in infile1.readlines():
print line1
for line2 in infile2.readlines()
print line2
--0__=0ABBE143DFCC294C8f9e8a93df938690918c0ABBE143DFCC294C-- From jeff@ccvcorp.com Thu Jun 6 19:48:15 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jun 2002 11:48:15 -0700 Subject: [Tutor] Reading & printing lines from two different files References: Message-ID: <3CFFAE6F.F218950@ccvcorp.com> stuart_clemons@us.ibm.com wrote: > Hi all: > > I have two files, file1 and file2. I want to print the first line > from file1, then the first line from file2, then the second line > from file 1, then the second line from file 2, etc. What do you want to do if one file is shorter than the other? The basic method I would use would probably go something like this -- import sys file1 = open('file1', 'r') file2 = open('file2', 'r') while 1: line1 = file1.readline() sys.stdout.write(line1) line2 = file2.readline() sys.stdout.write(line2) if not line1 and not line2: break This will print interleaved lines until one file is exhausted, print the remaining lines from the other file, and then break. You can alter this behavior by adjusting the conditions for the break statement. For example, 'if not line1 or not line2' would cause printing to stop as soon as either file is exhausted. You're probably wondering what that sys.stdout.write() stuff is. I used that instead of print, because print will add newlines (and sometimes spaces). Often this is useful, but since you're reading lines from a file, they already have a newline at the end of them. I *could* strip that newline off before printing, but there's another problem. When one file is exhausted (we've reached EOF on it), readline() will return an empty string, and printing that empty string will output an extra space. I could test for an empty line, too (either before or after stripping the newline), but it's easier to use sys.stdout.write(), which sends an exact string to the standard output, without doing any of the "helpful" formatting that print does. This way, I use the newlines from the file without needing to fiddle with them, and write()ing an empty string does nothing -- exactly what I want. Hope this helps... Jeff Shannon Technician/Programmer Credit International From ak@silmarill.org Thu Jun 6 20:01:39 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Thu, 6 Jun 2002 15:01:39 -0400 Subject: [Tutor] Reading & printing lines from two different files In-Reply-To: References: Message-ID: <20020606190139.GA4566@ak.silmarill.org> On Thu, Jun 06, 2002 at 01:57:02PM -0400, stuart_clemons@us.ibm.com wrote: > > Hi all: > > I have two files, file1 and file2. I want to print the first line from > file1, then the first line from file2, then the second line from file 1, > then the second line from file 2, etc. > > Here are my files and what the output should look like: > > File1.txt > First line file 1 > Second line file 1 > Third line file 1 > > File2.txt > First line file 2 > Second line file 2 > Third line file 3 > > This is the output I want when the program is run: > > First line file 1 > First line file 2 > Second line file 1 > Second line file 2 > Third line file 1 > Third line file 2 > > I've tried different looping techniques mainly using variations of the > structure below, but I can't seem to get the output I want. Any > suggestions ? Thanks. > > infile1 = open('c:\file1.txt', 'r') > infile2 = open ('c:\file2.txt', 'r') > for line1 in infile1.readlines(): > print line1 > for line2 in infile2.readlines() > print line2 > while 1: l = file1.readline() if not l: break print l l = file2.readline() if not l: break print l -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From stuart_clemons@us.ibm.com Thu Jun 6 20:02:36 2002 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Thu, 6 Jun 2002 15:02:36 -0400 Subject: [Tutor] Reading & printing lines from two different files Message-ID: --0__=0ABBE143DFF43EE28f9e8a93df938690918c0ABBE143DFF43EE2 Content-type: text/plain; charset=US-ASCII Thanks Jeff. Your structure works perfectly. I really appreciate the intro to this structure and also the explanation of sys.stdout.write()! I think I can really build off of this. It's coming slowly, but I'm learning. Thanks again, - Stuart ---------------------- Forwarded by Stuart Clemons/Westford/IBM on 06/06/2002 03:09 PM --------------------------- "Jeff Shannon" on 06/06/2002 02:48:15 PM To: stuart_clemons@us.ibm.com cc: tutor@python.org Subject: Re: [Tutor] Reading & printing lines from two different files stuart_clemons@us.ibm.com wrote: > Hi all: > > I have two files, file1 and file2. I want to print the first line > from file1, then the first line from file2, then the second line > from file 1, then the second line from file 2, etc. What do you want to do if one file is shorter than the other? The basic method I would use would probably go something like this -- import sys file1 = open('file1', 'r') file2 = open('file2', 'r') while 1: line1 = file1.readline() sys.stdout.write(line1) line2 = file2.readline() sys.stdout.write(line2) if not line1 and not line2: break This will print interleaved lines until one file is exhausted, print the remaining lines from the other file, and then break. You can alter this behavior by adjusting the conditions for the break statement. For example, 'if not line1 or not line2' would cause printing to stop as soon as either file is exhausted. You're probably wondering what that sys.stdout.write() stuff is. I used that instead of print, because print will add newlines (and sometimes spaces). Often this is useful, but since you're reading lines from a file, they already have a newline at the end of them. I *could* strip that newline off before printing, but there's another problem. When one file is exhausted (we've reached EOF on it), readline() will return an empty string, and printing that empty string will output an extra space. I could test for an empty line, too (either before or after stripping the newline), but it's easier to use sys.stdout.write(), which sends an exact string to the standard output, without doing any of the "helpful" formatting that print does. This way, I use the newlines from the file without needing to fiddle with them, and write()ing an empty string does nothing -- exactly what I want. Hope this helps... Jeff Shannon Technician/Programmer Credit International --0__=0ABBE143DFF43EE28f9e8a93df938690918c0ABBE143DFF43EE2 Content-type: text/html; charset=US-ASCII Content-Disposition: inline

Thanks Jeff. Your structure works perfectly. I really appreciate the intro to this structure and also the explanation of sys.stdout.write()! I think I can really build off of this.

It's coming slowly, but I'm learning.

Thanks again,

- Stuart

---------------------- Forwarded by Stuart Clemons/Westford/IBM on 06/06/2002 03:09 PM ---------------------------

To: stuart_clemons@us.ibm.com
cc: tutor@python.org
Subject: Re: [Tutor] Reading & printing lines from two different files



stuart_clemons@us.ibm.com wrote:

> Hi all:
>
> I have two files, file1 and file2. I want to print the first line
> from file1, then the first line from file2, then the second line
> from file 1, then the second line from file 2, etc.

What do you want to do if one file is shorter than the other?

The basic method I would use would probably go something like this --

import sys

file1 = open('file1', 'r')
file2 = open('file2', 'r')

while 1:
line1 = file1.readline()
sys.stdout.write(line1)
line2 = file2.readline()
sys.stdout.write(line2)
if not line1 and not line2:
break

This will print interleaved lines until one file is exhausted, print
the remaining lines from the other file, and then break. You can
alter this behavior by adjusting the conditions for the break
statement. For example, 'if not line1 or not line2' would cause
printing to stop as soon as either file is exhausted.

You're probably wondering what that sys.stdout.write() stuff is. I
used that instead of print, because print will add newlines (and
sometimes spaces). Often this is useful, but since you're reading
lines from a file, they already have a newline at the end of them. I
*could* strip that newline off before printing, but there's another
problem. When one file is exhausted (we've reached EOF on it),
readline() will return an empty string, and printing that empty string
will output an extra space. I could test for an empty line, too
(either before or after stripping the newline), but it's easier to use
sys.stdout.write(), which sends an exact string to the standard
output, without doing any of the "helpful" formatting that print
does. This way, I use the newlines from the file without needing to
fiddle with them, and write()ing an empty string does nothing --
exactly what I want.

Hope this helps...

Jeff Shannon
Technician/Programmer
Credit International




--0__=0ABBE143DFF43EE28f9e8a93df938690918c0ABBE143DFF43EE2-- From amd@atlas.ucpel.tche.br Thu Jun 6 21:44:23 2002 From: amd@atlas.ucpel.tche.br (Aurelio Magalhaes Dias) Date: Thu, 6 Jun 2002 17:44:23 -0300 (BRT) Subject: [Tutor] SWIG !!! Message-ID: Hi, I'm writing a Python/C++ API, and I would like to know if exists a good tutorial for working with SWIG and classes. Thanks, Aur=E9lio. ----------------------------------------- Aur=E9lio Magalh=E3es Dias Ci=EAncia da Computa=E7=E3o UCPel - RS - Brasil ----------------------------------------- From dyoo@hkn.eecs.berkeley.edu Thu Jun 6 22:40:53 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Jun 2002 14:40:53 -0700 (PDT) Subject: [Tutor] Reading & printing lines from two different files In-Reply-To: <20020606190139.GA4566@ak.silmarill.org> Message-ID: > > Here are my files and what the output should look like: > > > > File1.txt > > First line file 1 > > Second line file 1 > > Third line file 1 > > > > File2.txt > > First line file 2 > > Second line file 2 > > Third line file 3 > > > > This is the output I want when the program is run: > > > > First line file 1 > > First line file 2 > > Second line file 1 > > Second line file 2 > > Third line file 1 > > Third line file 2 > > > > > while 1: > l = file1.readline() > if not l: break > print l > l = file2.readline() > if not l: break > print l We can use another approach, using zip(), if both files aren't too long and are of the same length: ### for (line1, line2) in zip(file1.readlines(), file2.readlines()): print line1 print line2 ### zip() will ruffle-shuffle the two lists, to make it easy to grab corresponding elements. (If the files are actually much longer, we might not need to abandon this appraoch: we can use a variation of the zip() function by using Python 2.2 generators that's less of a memory hog.) From phthenry@earthlink.net Thu Jun 6 22:30:51 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Thu, 6 Jun 2002 17:30:51 -0400 Subject: [Tutor] time module missing Message-ID: <20020606173051.A5545@localhost.localdomain> I uninstalled python 2.2 and re-installed python 2.1 yesterday. Everything worked fine, including scripts that used the time module. However, when I try to installed 4Suite, it informed me that it could not find the time module. I fired up python, and found that it is in fact missing. I know I'm overlooking something simple. In order to unistall 2.2, I renamed the 2.2 library "python2.2.temp." I did the same with the executable in /usr/bin. I then ran ./configure, then make, and the make install. If I do import os I get no error. I believe time is a built in module (?). I can't find any module name time in my library. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From phthenry@earthlink.net Thu Jun 6 22:50:12 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Thu, 6 Jun 2002 17:50:12 -0400 Subject: [Tutor] time module missing In-Reply-To: <20020606173051.A5545@localhost.localdomain> References: <20020606173051.A5545@localhost.localdomain> Message-ID: <20020606175012.A6010@localhost.localdomain> On Thu, Jun 06, 2002 at 05:30:51PM -0400, Paul Tremblay wrote: > From: Paul Tremblay > To: tutor@python.org > User-Agent: Mutt/1.3.21i > Subject: [Tutor] time module missing > Date: Thu, 6 Jun 2002 17:30:51 -0400 > > I uninstalled python 2.2 and re-installed python 2.1 yesterday. > Everything worked fine, including scripts that used the time > module. However, when I try to installed 4Suite, it informed me > that it could not find the time module. I fired up python, and > found that it is in fact missing. > Never mind. I had to set a variable called PYTHONHOME in order to gnucash. I set this variable to /home/usr/lib/python2.1. I just unset this variable, and python can now find the time module. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From israel@lith.com Thu Jun 6 23:49:27 2002 From: israel@lith.com (Israel Evans) Date: Thu, 6 Jun 2002 15:49:27 -0700 Subject: [Tutor] Levels of Politeness, or Granularity and Placement of Methods? Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C20DAC.69974E15 Content-Type: text/plain I have a question for the Tutor Community that pertains to OOP and, um other stuff like that. :-) Let's say that I have a couple of types of objects: A Player and a Card. ##### #The Player would have look a little like this...(no methods or functions yet) class Player: def __init__(self, name): self.name = name self.coolness = 0 self.pythonicallity = 0 self.hand = [] self.applied_cards = [] #The Card would have look a little like this...(no methods or functions yet) class Card: def __init__(self, name, suit, effects): self.name = name self.suit = suit self.effects = effects #Here I'll set up a couple of Cards cool_card = Card('coolio', 'ice', {'coolness': 10} snake_card = Card('Pythorlo the Pseudo Coder', 'slitherin', {'pythonicallity':10} And gather them into a list called deck. # deck = [cool_card, snake_card] Now I've got a couple of functions for applying the effects of the card to the Player's attributes, but I'm wondering how "polite" I should make them. As it stands, the functions I have, take a look at the cards' innards and applies the effects to the Players attributes. For instance the applyCard function... # inside Player def applyCard(self, deck, card): self.applied_cards.append(deck.pop(card)) for effect in card.effects: self.__dict__[effect] = card[effect] Instead of grubbing around inside of the card should the Player politely ask the Card for the effect data and wait for an answer, then apply what given to it to it's attributes? Maybe something like the following... # inside Card def reportEffects(self): return self.effects # inside Player def applyCard(self, deck, card) self.applied_cards.append(deck.pop(card)) effects = card.reportEffects() for effect in effects: self.__dict__[effect] = effects[effect] I guess what I'm asking is : Should "Communicate" with each other like equals, or should they "Use" each other. It seems that the more polite an object is the easier it will be for the objects it deals with to change how they work internally, but still retain functionality later on. What would your suggestions be on this subject? Thanks, ~Israel~ ------_=_NextPart_001_01C20DAC.69974E15 Content-Type: text/html Content-Transfer-Encoding: quoted-printable

 

I have a question for the Tutor Community that = pertains to OOP and, um other stuff like that.  J=

 

Let's say that I have a couple of types of = objects:  A Player and a = Card.

 

 

#####

#The Player would have look a little like this...(no methods or functions = yet)

 

class<= font size=3D2 face=3DArial> = Player:

       &nbs= p;    def __init__(self, = name):

       &nbs= p;           &nbs= p;    self.name =3D name

       &nbs= p;           &nbs= p;    self.coolness =3D 0

       &nbs= p;           &nbs= p;    self.pythonicallity =3D = 0

       &nbs= p;           &nbs= p;    self.hand =3D []

       &nbs= p;           &nbs= p;    self.applied_cards =3D = []

 

#The Card would have look a little like this...(no methods or functions = yet)

 

class<= font size=3D2 face=3DArial> = Card:

       &nbs= p;    def __init__(self, name, suit, = effects):

       &nbs= p;           &nbs= p;    self.name =3D name

       &nbs= p;           &nbs= p;    self.suit =3D suit

       &nbs= p;           &nbs= p;    self.effects =3D = effects

 

#Here I'll set up a = couple of Cards

 

cool_card =3D Card('coolio', 'ice', {'coolness': 10}

snake_card =3D Card('Pythorlo the = Pseudo Coder', 'slitherin', = {'pythonicallity':10}

 

 

And gather them into a list called = deck.

#

deck =3D [cool_card, snake_card]

 

 

Now I've got a couple of functions for applying the effects of the card to the Player's attributes, but I'm wondering how "polite" I should make them.

 

As it stands, the functions I have, take a look at the cards' innards and applies the effects to the = Players attributes. For instance the applyCard = function...

 

# inside = Player

       &nbs= p;    def applyCard(self, = deck, card):

       &nbs= p;           &nbs= p;    self.applied_cards.append(deck.pop(card))

       &nbs= p;           &nbs= p;    for effect in card.effects:
       &nbs= p;           &nbs= p;           &nbs= p;    self.__dict__[effect] = =3D card[effect]

 

Instead of grubbing around inside of the card should = the Player politely ask the Card for the effect data and wait for an = answer, then apply what given to it to it's = attributes?

Maybe something like the = following...

 

# inside = Card

       &nbs= p;    def reportEffects(self):

       &nbs= p;           &nbs= p;    return self.effects

 

# inside = Player

       &nbs= p;    def applyCard(self, = deck, card)

       &nbs= p;           &nbs= p;    self.applied_cards.append(deck.pop(card))

       &nbs= p;           &nbs= p;    effects =3D card.reportEffects()

       &nbs= p;           &nbs= p;    for effect in effects:
       &nbs= p;           &nbs= p;           &nbs= p;    self.__dict__[effect] = =3D effects[effect]

 

 

I guess what I'm asking is = :  Should "Communicate" with each other like equals, or should they "Use" each other.  It seems that the more polite = an object is the easier it will be for the objects it deals with to change how = they work internally, but still retain functionality later on. =

 

What would your suggestions be on this = subject?

 

Thanks,

       &nbs= p;           &nbs= p;   

 

 

~Israel<= font size=3D2 face=3D"Courier New">~

 

------_=_NextPart_001_01C20DAC.69974E15-- From dman@dman.ddts.net Fri Jun 7 00:10:49 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu, 6 Jun 2002 18:10:49 -0500 Subject: [Tutor] computers In-Reply-To: <3CFF9224.4C5939AB@ccvcorp.com> References: <5.1.0.14.0.20020603222933.02398a30@mail.hal-pc.org> <200206060646.35212.scot@possum.in-berlin.de> <3CFF9224.4C5939AB@ccvcorp.com> Message-ID: <20020606231049.GA23333@dman.ddts.net> --ew6BAiZeqk4r7MaW Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jun 06, 2002 at 09:47:32AM -0700, Jeff Shannon wrote: | "Scot W. Stevenson" wrote: =20 | > (And, concerning another list thread here, wouldn't this be another rea= son | > to use Java instead of Python?) |=20 | In a word, no. ;) First of all, on many platforms Java (IIRC) | emulates threads in a nonthreaded environment ("green" threads), | with semantics that are similar to Python's GIL (but weaker, because | the GIL is typically released in extensions).=20 I know for a fact that the Blackdown port of Sun's JDK uses native threads on linux. On solaris I know the admin/user has a choice between native and "green" (user-space) threads. If you want an empirical comparision of green and native threads on Solaris/SPARC configurations look around at java.sun.com. I once read an article there on the topic, and it included graphs as well. Still, there are advantages to java's green threads over python's threads on a multiproc system. Java's green threads are User Space threads -- they consume only a single kernel-level thread. Thus java will be (naturally) constrained to a single CPU. Python uses kernel-level threads, and you can end up with a multi-threaded python app hogging both CPUs but not making effective use of both of them. | Second, and more importantly, efficient use of multiple processors | (even if Java offered that) is typically a poor reason to choose a | language to develop in -- as mentioned above, it's probably not | going to result in a faster program. And if you really needed that | efficiency, then you should be coding in C, not Java. =20 Wholeheartedly agreed on both points. | The point of using Python is that it's easier/faster to develop | software with it. The (hypothetical) advantages that Java offers | for SMP environments are rarely going to be enough of a benefit to | override the extra costs of developing in Java. Right. If you really need (or just want) to take full adavantage of SMP hardware you need to use separate processes anyways with some sort of efficient IPC (or shmem?) between them. The problem with threads is=20 1) they lead to greater programmer error -- not synchronizing when necessary -- deadlock -- bottlenecks due to locking (and thus blocking other threads) 2) they have overhead and must interact in unusual ways. For one thing you can't kill a thread from another thread. The best you can do is ask it to die and hope it behaves well. There is no "SIGKILL" equilvalent for threads because they are part of the same process. With separate processes you can kill an external process. HTH, -D --=20 Pleasant words are a honeycomb, sweet to the soul and healing to the bones. Proverbs 16:24 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --ew6BAiZeqk4r7MaW Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAjz/6/kACgkQO8l8XBKTpRSd0wCfSry71+SqUdlGn+HqU0rIXcYX EKEAn1zKn3tzT73iMiANI114ufFzbkFN =EJ9e -----END PGP SIGNATURE----- --ew6BAiZeqk4r7MaW-- From idiot1@netzero.net Fri Jun 7 06:07:54 2002 From: idiot1@netzero.net (Kirk 'Deliberatus' Bailey) Date: Fri, 07 Jun 2002 01:07:54 -0400 Subject: [Tutor] ouch... Message-ID: <3D003FA9.3A5DB129@netzero.net> my computer died. This comes to you from my wife Bea's computer. HDD controller board done screwed the pooch, bought the farm, failed the smoke test. 4 years of work, poof. DAMN glad most of it is in the server. From pmcnally@alltel.net Fri Jun 7 07:22:26 2002 From: pmcnally@alltel.net (Paul McNally) Date: Fri, 7 Jun 2002 00:22:26 -0600 Subject: [Tutor] ouch... References: <3D003FA9.3A5DB129@netzero.net> Message-ID: <00b401c20deb$b16ad740$3b5928a2@adsl.navix.net> It's passed on! This computer is no more! It has ceased to be! It's expired and gone to meet 'is maker! It's a stiff! Bereft of life, it rests in peace! It's electronic processes are now 'istory! It's off the twig! It kicked the bucket, It's shufflled off 'is mortal coil, run down the curtain and joined the bleedin' choir invisibile!! THIS IS AN EX-COMPUTER!! ----- Original Message ----- From: "Kirk 'Deliberatus' Bailey" To: ; ; ; Sent: Thursday, June 06, 2002 11:07 PM Subject: [Tutor] ouch... my computer died. This comes to you from my wife Bea's computer. HDD controller board done screwed the pooch, bought the farm, failed the smoke test. 4 years of work, poof. DAMN glad most of it is in the server. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Fri Jun 7 07:41:06 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 6 Jun 2002 23:41:06 -0700 (PDT) Subject: [Tutor] ouch... In-Reply-To: <3D003FA9.3A5DB129@netzero.net> Message-ID: On Fri, 7 Jun 2002, Kirk 'Deliberatus' Bailey wrote: > my computer died. This comes to you from my wife Bea's computer. HDD > controller board done screwed the pooch, bought the farm, failed the > smoke test. 4 years of work, poof. Ouch. Sorry to hear that! > DAMN glad most of it is in the server. You're very lucky. Backing up data is very prudent, even if it is on a server. With hard drive capacities in the tens of gigabytes, there's so much more to be lost in a hard drive crash. I almost lost my web page and all my source code when my school's server died! Without backups, all that source code would have been flushed. From scot@possum.in-berlin.de Fri Jun 7 07:54:04 2002 From: scot@possum.in-berlin.de (Scot W. Stevenson) Date: Fri, 7 Jun 2002 08:54:04 +0200 Subject: [Tutor] Reading & printing lines from two different files In-Reply-To: References: Message-ID: <200206070854.04671.scot@possum.in-berlin.de> Hi there,=20 Danny Yoo wrote: > (If the files are actually much longer, we might not need to abandon > this appraoch: we can use a variation of the zip() function by using > Python 2.2 generators that's less of a memory hog.) Would this be something like: =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D from __future__ import generators file_one =3D 'text1.txt' file_two =3D 'text2.txt' def generate_line(filename): thisfile =3D open(filename, 'r') for line in thisfile: yield line gen_one =3D generate_line(file_one) gen_two =3D generate_line(file_two) while 1: try: print gen_one.next() print gen_two.next() except StopIteration: break =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D This does work here, tho it seems like an awful lot of code compared with= =20 your zip-and-readlines combination. Is there any simple way to explain wh= y=20 this is not such a memory hog? One thing I'm not sure of in the example above is where to put the=20 thisfile.close() line to close those files again. My computer doesn't see= m=20 any worse for not closing them, but it does seem like bad manners... Y, Scot --=20 Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From alex@gabuzomeu.net Fri Jun 7 08:47:32 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Fri, 07 Jun 2002 09:47:32 +0200 Subject: [Tutor] computers In-Reply-To: <20020606225012.14592.65415.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020607093024.00b72620@pop3.norton.antivirus> Hello, At 18:50 06/06/2002 -0400, you wrote: >Date: Thu, 06 Jun 2002 09:47:32 -0700 >From: "Jeff Shannon" >Subject: Re: [Tutor] computers >The real advantage to multithreading is that it separates your program into >distinct, logical tasks, making it easier to understand what's going on (if >you're separating tasks right ;) ). Only in very special cases does >multithreading really help with program speed. Could multithreading make a Web app more responsive? Here is the scheme I have in mind: imagine a Web app where a page can be edited in a form. When the user saves a page: - the page is processed somehow (for instance, it is indexed); - the page is saved to disk or in a database; - the updated page is displayed back to the user. => Could the processing and the saving tasks be subcontracted to worker threads so that the main program can return faster and the updated page is displayed faster? Thanks. Alexandre From pythontutor@venix.com Fri Jun 7 14:22:20 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri, 07 Jun 2002 09:22:20 -0400 Subject: [Tutor] Levels of Politeness, or Granularity and Placement of Methods? References: Message-ID: <3D00B38C.8060309@venix.com> I would recommend using setattr(self, attr, value) rather than self.__dict__[attr] = value setattr() uses the regular __getattr__ and __setattr__ functions and will therefore use any special handling that you code for your class. Direct assignment to the dictionary is useful when you MUST avoid the normal handling, but I would not use it otherwise. My rules of thumb are that classes should be as ignorant of each other as possible. Typically, a class knows the names of methods in the other classes that it relies on. When a method would simply be getProperty, I normally just access the property directly (e.g. self.prop = obj.prop). In Python, this is very reasonable because the obj.__getattr__ can easily provide any special handling that a getProperty method would have implemented. (Also there are new features in Python 2.2 for property handling.) In your case, Card.effects is a dictionary. (self.__dict__[effect] = effects[effect]) The Player knows that Card.effects is a dictionary. The Player applies effects by assigning the effects dictionary to self. This is more class knowledge than I like. My inclination would be to either have: card.applyEffects( obj) where obj would be a player, but could be any object or create an Effects class that implements effect.apply( obj) as in Card. The apply method might return a list of changed attributes. #in Player self.applied_cards.append(deck.pop(card)) changes = card.applyEffects( self) for change in changes: __player responds to change from effects__ NOTE, this means you need to watch out for attribute name conflicts! If this is a real concern use an Effects Class to package the effect names. The player.effects are updated from/by the card.effects depending on which seems to fit. card.effects.applyTo( player.effects) versus player.effects.updateFrom( card.effects) HTH Israel Evans wrote: > > > I have a question for the Tutor Community that pertains to OOP and, um > other stuff like that. J > > > ~Israel~ -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dman@dman.ddts.net Fri Jun 7 18:45:26 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Fri, 7 Jun 2002 12:45:26 -0500 Subject: [Tutor] computers In-Reply-To: <4.3.2.7.2.20020607093024.00b72620@pop3.norton.antivirus> References: <20020606225012.14592.65415.Mailman@mail.python.org> <4.3.2.7.2.20020607093024.00b72620@pop3.norton.antivirus> Message-ID: <20020607174526.GA14600@dman.ddts.net> --OXfL5xGRrasGEqWY Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Jun 07, 2002 at 09:47:32AM +0200, Alexandre Ratti wrote: | Hello, |=20 |=20 | At 18:50 06/06/2002 -0400, you wrote: | >Date: Thu, 06 Jun 2002 09:47:32 -0700 | >From: "Jeff Shannon" | >Subject: Re: [Tutor] computers |=20 | >The real advantage to multithreading is that it separates your program i= nto | >distinct, logical tasks, making it easier to understand what's going on = (if | >you're separating tasks right ;) ). Only in very special cases does | >multithreading really help with program speed. |=20 | Could multithreading make a Web app more responsive? It *could*. One web server (medusa, written in python) is quite responsive, but isn't threaded at all. It uses select() to handle reading/writing from/to multiple sockets without the overhead that threads or IPC introduce. | Here is the scheme I=20 | have in mind: imagine a Web app where a page can be edited in a form. Whe= n=20 | the user saves a page: | - the page is processed somehow (for instance, it is indexed); | - the page is saved to disk or in a database; | - the updated page is displayed back to the user. |=20 | =3D> Could the processing and the saving tasks be subcontracted to worker= =20 | threads so that the main program can return faster and the updated page i= s=20 | displayed faster? Sure. If the saving is mainly IO bound, then multiple threads would help you spread your CPU time around. You could also do it with multiple processes. For example, once the processing is done, fork a separate process to save to the db and immediately return the post-processed page to the user. Of course, that method prevents the server from notifying the user if a problem occurs with the db. -D --=20 There are six things the Lord hates, seven that are detestable to him : haughty eyes, a lying tongue, hands that shed innocent blood, a heart that devises wicked schemes, feet that are quick to rush into evil, a false witness who pours out lies and a man who stirs up dissension among brothers. Proverbs 6:16-19 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --OXfL5xGRrasGEqWY Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0A8TYACgkQO8l8XBKTpRRJaQCfVKiIltKgTx8HiyUuUjtukgMu VFIAn1etQXC2w+OpeQubhiSeZzgIK/N6 =Cl2f -----END PGP SIGNATURE----- --OXfL5xGRrasGEqWY-- From jeff@ccvcorp.com Fri Jun 7 18:49:38 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jun 2002 10:49:38 -0700 Subject: [Tutor] computers References: <4.3.2.7.2.20020607093024.00b72620@pop3.norton.antivirus> Message-ID: <3D00F231.D92A825A@ccvcorp.com> Alexandre Ratti wrote: > >From: "Jeff Shannon" > > >The real advantage to multithreading is that it separates your program into > >distinct, logical tasks, making it easier to understand what's going on (if > >you're separating tasks right ;) ). Only in very special cases does > >multithreading really help with program speed. > > Could multithreading make a Web app more responsive? Here is the scheme I > have in mind: imagine a Web app where a page can be edited in a form. When > the user saves a page: > - the page is processed somehow (for instance, it is indexed); > - the page is saved to disk or in a database; > - the updated page is displayed back to the user. > > => Could the processing and the saving tasks be subcontracted to worker > threads so that the main program can return faster and the updated page is > displayed faster? Well, it *might* return the updated page faster, but it might not. If all of these threads share the same processor, then it will take the same amount of time to do all the processing, whether it's in one thread or three -- in fact, it'll take a tiny bit *more* time to do it in three, because you've got the overhead of switching between the threads. However, if the thread that returns the updated page gets scheduled first, then that will happen sooner. But you *could* always write a single-threaded app that would return the updated page before saving data into a database, thus guaranteeing the order would be what you prefer -- at the cost of a certain amount of added complexity. It's an open question whether the complexity of multithreading (concurrency, deadlocks, etc) is worse than the complexity of explicitly maintaining multiple states in a single thread. There's costs and benefits to both ways, and which pays off best depends on the circumstances. (Isn't that always how it is? ;) ) Jeff Shannon Technician/Programmer Credit International From sarmstrong13@mac.com Fri Jun 7 19:10:56 2002 From: sarmstrong13@mac.com (SA) Date: Fri, 07 Jun 2002 13:10:56 -0500 Subject: [Tutor] Tkinter crash help please. Message-ID: Hi Everyone- I've installed python, tcl, tk on my MacOSX 10.1.5 system using the --enable-frameworks configuration. I have a framework for tcl,tk,and python under my /Library/Frameworks directory. When I run a simple button code in a python script: #!/usr/bin/env python import sys from Tkinter import * def die(event): sys.exit() root = Tk() button = Button(root) button["text"] = "Hello" button.bind("", die) button.pack() root.mainloop() I get the following output in my shell(tcsh by the way): original argc=2 original argv[0] = "python" original argv[1] = "./ave.py" modified argc=2 modified argv[0] = "python" modified argv[1] = "./ave.py" Nothing happens. So I then hit Ctrl-C to stop the script and I get the following Traceback error: Traceback (most recent call last): File "./ave.py", line 14, in ? root.mainloop() File "/Library/Frameworks/Python.framework/Versions/2.2/lib/python2.2/lib-tk/Tkin ter.py", line 929, in mainloop self.tk.mainloop(n) KeyboardInterrupt It looks like it is calling the correct Tkinter Module, but nothing is bein displayed. If however I enter the code line for line in the Python.app that I compile, I get the proper button widget. Maybe I'm wrong (because I definitely do NOT fully understand the Mac OSX Frameworks system yet), but if the coded is properly calling the correct Tkinter module, it should not matter whether or not it is done within the Python.app or by calling python from within Python.app. Is this correct? Is there a way to do this on a Mac? (other than MacPython wich works only on pre OSX systems and doe not take advantage of the BSD under OSX) Thanks. SA From phthenry@earthlink.net Fri Jun 7 22:10:07 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Fri, 7 Jun 2002 17:10:07 -0400 Subject: [Tutor] rtf to xml regexp question Message-ID: <20020607171007.B6866@localhost.localdomain> I have found a java utility that does a pretty good job of converting rtf to xml. I had played around with the idea of writing a parser myself, but realized it was pretty coplicated. However, this utility does not convert footnotes. Before I run the utlity, I want to convert footnotes into this format: As Schmoo claims footnote text at bottom of page. Quoted from Title The present rtf format looks like this: \pard\plain Now a footnote. As Schmoo claims {\fs18\up6 \chftn {\footnote \pard\plain \s246 \fs20 {\fs18\up6 \chftn }footnote at bottom of page.Quoted from {\i Title}}}\par Majix, the rtf convertor will take care of a lot of this text, converting the above to:

Now a footnote. As Schmoo claims

I am only inerested in the rtf text between {\footnote and }}}. There are a few tricky parts, though. The text may break over several lines. Also, if the actual title of the book does not end the footnote reference,than the text I am interested in will end in two }} rather than three. The best method is to start a search that finds {\footnote. It should add one to a footnote counter. Then the search should continue from that point. If it finds another {, then it should add another to the footnote counter. If it finds a }, then it should subtract 1 from the footnote counter. It should stop searchiing when it finds a } and when the footnote counter is 0. I don't know how to do this in Python. I remember that in perl you could start searching from where you left off. Thanks! Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From shendric@arches.uga.edu Fri Jun 7 16:27:41 2002 From: shendric@arches.uga.edu (shendric@arches.uga.edu) Date: Fri, 7 Jun 2002 10:27:41 -0500 Subject: [Tutor] creating tables Message-ID: <1023460061.smmsdV1.1.1@mail.arches.uga.edu> Hi all, Thanks for the help with exit handling and what not. Here's another application that I'm playing with. I'd like to have a widget that is a little editable table. It has a fixed number of columns, but can have as many rows as the user wishes. I came up with a class for a table row, but I'm trying to decide on the best implementation for creating new rows, when the user wants to create a new one. There has been so much discussion on dynamically creating classes, so I hate to bring it up again, but it's kind of crucial here, I think, and I'm still trying to get a handle on the details. In essence, the idea here is that when a user requests (by an event), a new row is created in the table. I'd like for each new class to be uniquely identified, because the program will need to eventually export the contents of the cells to a file. So, it would need to iterate over each instance and export that instance's contents. Also, the user might want to remove a row, in which case, the instance would need to be removed. Sounds like a list, to me. So, I guess the question is: can I create a list of class instances, adding a new instance every time the user requests, where the reference can be removed when the instance is destroyed? Sorry if this sounds a bit cryptic, and a bunch of questions packed into one, but if anyone's got any ideas for any part of it, they would be very welcome. Also, if there's already a module to handle such a table, that would be cool, too. Sean From williammperry08@cox.net Sat Jun 8 06:41:02 2002 From: williammperry08@cox.net (William Perry) Date: Sat, 08 Jun 2002 00:41:02 -0500 Subject: [Tutor] re: computers In-Reply-To: References: Message-ID: <200206080041020277.1055805B@smtp.central.cox.net> --=====_10235148629881=_ Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Win98 DOES NOT support multi-processors, you need to change os (XP Pro (not= home) or NT) ron Stoner wrote: Thanks Stuart, That's what I was thinking. I wondered if programs would run faster. I= was looking into it to make my graphics work, ie: 3D modeling, take less= time to use. When doing animation it currently takes me like a half-hour= to save my work. This is not a gross overestamation either. It then= turns out to be less than 30 sec of animation when I play it. Would= having multiple processors make it more efficient? Thanks, Cameron Stoner ----- Original Message ----- From: stuart_clemons@us.ibm.com To: tutor@python.org Sent: Tuesday, June 04, 2002 2:20 PM Subject: [Tutor] re: computers FYI. Even if your OS, such as NT, is capable of running on a= multi-processor system, it does not mean that your programs or compilers= will run any faster than when run on a single processor system. Most= programs and compilers do not take advantage of multi-processor systems,= which is something most people don't seem to realise. In fact, in some= cases a single processor system will complete tasks faster than a= multi-processor system. So, for most people, having a multiprocessor= system is a waste time, money, and resources. --=====_10235148629881=_ Content-Type: text/html; charset="us-ascii" Win98 DOES NOT support multi-processors, you need to change os (XP Pro (not home) or NT)


ron Stoner wrote:
Thanks Stuart,
 
That's what I was thinking.  I wondered if programs would run faster.  I was looking into it to make my graphics work, ie: 3D modeling, take less time to use.  When doing animation it currently takes me like a half-hour to save my work.  This is not a gross overestamation either.  It then turns out to be less than 30 sec of animation when I play it.  Would having multiple processors make it more efficient?
 
Thanks,
Cameron Stoner
----- Original Message -----
Sent: Tuesday, June 04, 2002 2:20 PM
Subject: [Tutor] re: computers

FYI. Even if your OS, such as NT, is capable of running on a multi-processor system, it does not mean that your programs or compilers will run any faster than when run on a single processor system. Most programs and compilers do not take advantage of multi-processor systems, which is something most people don't seem to realise. In fact, in some cases a single processor system will complete tasks faster than a multi-processor system. So, for most people, having a multiprocessor system is a waste time, money, and resources.

--=====_10235148629881=_-- From donni@melwestmarket.com Sat Jun 8 08:40:45 2002 From: donni@melwestmarket.com (Dimitrije Nikic) Date: Sat, 8 Jun 2002 17:40:45 +1000 (AUS Eastern Standard Time) Subject: [Tutor] Is there a function for refreshing what's in the console? Message-ID: <3D01B4FD.000007.47955@athlon900.vic.optushome.com.au> --------------Boundary-00=_XNMDWCW0000000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Is there a function for refreshing what's in the console? (Eg. delete eve= rything printed previously in the window) --------------Boundary-00=_XNMDWCW0000000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Is there a function for refreshing what's in the console? (Eg. d= elete=20 everything printed previously in the window)

=09 =09 =09 =09 =09 =09 =09
_________________________________________________
Bravenet IncrediMail - Email ha= s finally=20 evolved -
Click=20 Here
--------------Boundary-00=_XNMDWCW0000000000000-- From donni@melwestmarket.com Sat Jun 8 10:14:27 2002 From: donni@melwestmarket.com (Dimitrije Nikic) Date: Sat, 8 Jun 2002 19:14:27 +1000 (AUS Eastern Standard Time) Subject: [Tutor] Time function Message-ID: <3D01CAF3.000005.84443@athlon900.vic.optushome.com.au> --------------Boundary-00=_30RD6RO0000000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Is there a function that returns the time on the computer the script is r= un on? I found some functions on the net but they did not show it in the right f= ormat. I want it to show the hour and the minutes (just like the clock in= windows and linux on the taskbar). Thank you for your help :) --------------Boundary-00=_30RD6RO0000000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Is there a function that returns the time on the computer the = script=20 is run on?
I found some functions on the net but they did not show it in = the=20 right format. I want it to show the hour and the minutes (just like= the=20 clock in windows and linux on the taskbar).
 
Thank you for your help :)
=09 =09 =09 =09 =09 =09 =09
_________________________________________________
Bravenet IncrediMail - Email ha= s finally=20 evolved -
Click=20 Here
--------------Boundary-00=_30RD6RO0000000000000-- From donni@melwestmarket.com Sat Jun 8 10:37:06 2002 From: donni@melwestmarket.com (Dimitrije Nikic) Date: Sat, 8 Jun 2002 19:37:06 +1000 (AUS Eastern Standard Time) Subject: [Tutor] Beep sound for Linux Message-ID: <3D01D042.000005.09639@athlon900.vic.optushome.com.au> --------------Boundary-00=_U1SD6RO0000000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I heard of beep sounds for Windows only, but is there a function for beep= sounds in Linux? --------------Boundary-00=_U1SD6RO0000000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I heard of beep sounds for Windows only, but is there a functi= on for=20 beep sounds in Linux?
=09 =09 =09 =09 =09 =09 =09
_________________________________________________
Bravenet IncrediMail - Email ha= s finally=20 evolved -
Click=20 Here
--------------Boundary-00=_U1SD6RO0000000000000-- From glingl@aon.at Sat Jun 8 12:16:58 2002 From: glingl@aon.at (Gregor Lingl) Date: Sat, 8 Jun 2002 13:16:58 +0200 Subject: [Tutor] Time function References: <3D01CAF3.000005.84443@athlon900.vic.optushome.com.au> Message-ID: <001401c20ede$014a2480$1615a8c0@mega> This is a multi-part message in MIME format. ------=_NextPart_000_0011_01C20EEE.C48CC3C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Things like these can easiliy be found in the Python Library Reference = (or in the Global Module Index) for instance via Python Help in IDLE, or: http://www.python.org/doc/current/download.html So I was able to produce immediately: >>> import time >>> time.time() 1023534027.09 >>> time.gmtime() (2002, 6, 8, 11, 1, 20, 5, 159, 0) >>> time.asctime(time.gmtime()) 'Sat Jun 08 11:01:43 2002' >>> time.asctime(time.localtime()) 'Sat Jun 08 13:02:09 2002' >>> "%02d:%02d:%02d" % time.localtime()[3:6] '13:02:37' and so on, what you want ... Regards Gregor ----- Original Message -----=20 From: Dimitrije Nikic=20 To: Python User Group=20 Sent: Saturday, June 08, 2002 11:14 AM Subject: [Tutor] Time function Is there a function that returns the time on the computer the = script is run on? I found some functions on the net but they did not show it in the = right format. I want it to show the hour and the minutes (just like the = clock in windows and linux on the taskbar). Thank you for your help :)=20 =20 =20 _________________________________________________ Bravenet IncrediMail - Email has finally evolved - Click Here=20 ------=_NextPart_000_0011_01C20EEE.C48CC3C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 
Things like these can easiliy be found = in the=20 Python Library Reference (or
in the Global Module Index) for instance = via Python Help in IDLE, or:
 
http://www.pytho= n.org/doc/current/download.html
 
So I was able to produce = immediately:
 
>>> import time
>>> = time.time()
1023534027.09
>>> time.gmtime()
(2002, 6, = 8, 11,=20 1, 20, 5, 159, 0)
>>> time.asctime(time.gmtime())
'Sat = Jun 08=20 11:01:43 2002'
>>> time.asctime(time.localtime())
'Sat = Jun 08=20 13:02:09 2002'
>>> "%02d:%02d:%02d" %=20 time.localtime()[3:6]
'13:02:37'
and so on, what you want = ...
 
Regards
Gregor
 
 
----- Original Message -----=20
From: Dimitrije=20 Nikic
Sent: Saturday, June 08, 2002 11:14 AM
Subject: [Tutor] Time function

Is there a function that returns the time on the computer the = script=20 is run on?
I found some functions on the net but they did not show it in = the=20 right format. I want it to show the hour and the minutes (just = like the=20 clock in windows and linux on the taskbar).
 
Thank you for your help :)
_________________________________________________
Bravenet IncrediMail - Email = has finally=20 evolved -
Click=20 Here
------=_NextPart_000_0011_01C20EEE.C48CC3C0-- From dman@dman.ddts.net Sat Jun 8 16:27:55 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat, 8 Jun 2002 10:27:55 -0500 Subject: [Tutor] Is there a function for refreshing what's in the console? In-Reply-To: <3D01B4FD.000007.47955@athlon900.vic.optushome.com.au> References: <3D01B4FD.000007.47955@athlon900.vic.optushome.com.au> Message-ID: <20020608152755.GA17642@dman.ddts.net> --5mCyUwZo2JvN/JJP Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Jun 08, 2002 at 05:40:45PM +1000, Dimitrije Nikic wrote: | Is there a function for refreshing what's in the console? (Eg. | delete everything printed previously in the window) Yes and no. There are a couple of ways you can do this, one doesn't really work, one is not wholly cross-platform. The problem is knowing what the user's console looks like (eg how big it is, etc) and how to tell it to clear. The way that doesn't really work is to assume you know how many lines it will contain and do something like this : print "\n"*24 That works for a VT-100 and work-alikes that only have 24 lines on the screen. When I work in gnome-terminal, it too has 24 lines (but it allows that to be changed arbitrarily). If I work in my linux console I have about 64 lines on screen. That's why it doesn't really work. If some user gets a bigger screen, that won't push the text all the way off it. The way that works is to use the ncurses library. Of course, Microsoft didn't feel the need to provide a curses implementation on their platform, so it doesn't work on Windows unless you require the use of cygwin (to emulate UNIX :-)). ncurses is a great library because it abstracts away the details of each and every terminal ever made and handles the interaction with the terminal for you. You simply tell it what you want it to do. I've never done any curses programming before, but I've heard that it isn't the easiest thing to learn. HTH, -D --=20 Whoever gives heed to instruction prospers, and blessed is he who trusts in the Lord. Proverbs 16:20 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --5mCyUwZo2JvN/JJP Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0CInoACgkQO8l8XBKTpRTT9QCgtQv/CE96NQAqdzHe/wq9cNx+ DiQAn3lbF7QD9p1uI0DGqjsQx9x5wFMs =muc/ -----END PGP SIGNATURE----- --5mCyUwZo2JvN/JJP-- From sarmstrong13@mac.com Sat Jun 8 17:29:32 2002 From: sarmstrong13@mac.com (SA) Date: Sat, 08 Jun 2002 11:29:32 -0500 Subject: [Tutor] Newbie OOP Question. Message-ID: Hi Everyone- I'm still trying to grasp this OOP concept in Python. Can someone tell me the difference between a function, a module, and a class? Since Python defines them all as objects, how do they differ outside of being called from inside the script or outside the script? Thanks. SA From ak@silmarill.org Sat Jun 8 18:15:59 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 8 Jun 2002 13:15:59 -0400 Subject: [Tutor] Beep sound for Linux In-Reply-To: <3D01D042.000005.09639@athlon900.vic.optushome.com.au> References: <3D01D042.000005.09639@athlon900.vic.optushome.com.au> Message-ID: <20020608171559.GA428@ak.silmarill.org> On Sat, Jun 08, 2002 at 07:37:06PM +1000, Dimitrije Nikic wrote: > I heard of beep sounds for Windows only, but is there a function for beep sounds in Linux? > > print '\a' -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ak@silmarill.org Sat Jun 8 18:35:44 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sat, 8 Jun 2002 13:35:44 -0400 Subject: [Tutor] Newbie OOP Question. In-Reply-To: References: Message-ID: <20020608173544.GA493@ak.silmarill.org> On Sat, Jun 08, 2002 at 11:29:32AM -0500, SA wrote: > Hi Everyone- > > I'm still trying to grasp this OOP concept in Python. Can someone tell > me the difference between a function, a module, and a class? Since Python > defines them all as objects, how do they differ outside of being called from > inside the script or outside the script? > > Thanks. > SA > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Module is a file that has some code in it. Module may include many functions and classes in it (or just a few lines of code. A function is a chunk of code that may take in some data and then return some other data: def func(data_in): [do stuff] return data_out a class usually contains a few functions, say a Tree class would have grow_roots and grow_leaves functions, and would also have a boolean attribute alive: tree.alive = 1. Oh, and there'd be a function tree.die that would set tree.alive to 0. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From lonetwin@yahoo.com Sat Jun 8 11:28:37 2002 From: lonetwin@yahoo.com (Steve) Date: Sat, 8 Jun 2002 15:58:37 +0530 Subject: [Tutor] Time function In-Reply-To: <3D01CAF3.000005.84443@athlon900.vic.optushome.com.au> References: <3D01CAF3.000005.84443@athlon900.vic.optushome.com.au> Message-ID: <20020608102837.80A8C2F4A8@mercury.sapatmt> Hi there, On Saturday 08 June 2002 02:44 pm, you wrote: > Is there a function that returns the time on the computer the script is run > on? I found some functions on the net but they did not show it in the right > format. I want it to show the hour and the minutes (just like the clock in > windows and linux on the taskbar). You may want to look at the time module (doc. included within the standard Python documentation and also at http://www.python.org/doc/current/lib/module-time.html ) Anyways, here is what you needed in an interpreter session: ----------------------------------------- Python 2.2.1 (#3, May 8 2002, 19:51:42) [GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.ctime() 'Sat Jun 8 15:49:39 2002' >>> time.ctime().split()[3] '15:53:43' >>> ------------------------------------------ Hope that helps Peace Steve -- Most people have two reasons for doing anything -- a good reason, and the real reason. From lonetwin@yahoo.com Sat Jun 8 11:32:39 2002 From: lonetwin@yahoo.com (Steve) Date: Sat, 8 Jun 2002 16:02:39 +0530 Subject: [Tutor] Beep sound for Linux In-Reply-To: <3D01D042.000005.09639@athlon900.vic.optushome.com.au> References: <3D01D042.000005.09639@athlon900.vic.optushome.com.au> Message-ID: <20020608103240.007AC2F4A8@mercury.sapatmt> Hi There, On Saturday 08 June 2002 03:07 pm, you wrote: > I heard of beep sounds for Windows only, but is there a function for beep > sounds in Linux? RE: did you mean this ... >>> print "\a" Peace Steve -- Q: Why did the chicken cross the road? A: To see his friend Gregory peck. Q: Why did the chicken cross the playground? A: To get to the other slide. From purplebo@babylonia.flatirons.org Sat Jun 8 20:09:05 2002 From: purplebo@babylonia.flatirons.org (Chris Avery) Date: Sat, 8 Jun 2002 13:09:05 -0600 Subject: [Tutor] Re: Time Function In-Reply-To: <20020608111801.12146.60842.Mailman@mail.python.org>; from tutor-request@python.org on Sat, Jun 08, 2002 at 07:18:01AM -0400 References: <20020608111801.12146.60842.Mailman@mail.python.org> Message-ID: <20020608130905.A27711@babylonia.flatirons.org> time.strftime() returns the time you want. time.strftime("%h-%m") or something like that should work. Good Luck! -- +++++++++++++++++++ Chris Avery, KC0KTH +++++++++++++++++++ From sarmstrong13@mac.com Sat Jun 8 21:29:37 2002 From: sarmstrong13@mac.com (SA) Date: Sat, 08 Jun 2002 15:29:37 -0500 Subject: [Tutor] Tkinter Help Please. Message-ID: Hi Everyone- Can someone explain what _tkinter in the Tkinter.py refers to? Specifically from line:35 of Tkinter.py import _tkinter # If this fails your Python may not be configured for Tk Ok how do I compile Python to be configured for Tk and where is the _tkinter module located? Thanks. SA From marcolinux@linuxbr.com.br Sat Jun 8 21:41:26 2002 From: marcolinux@linuxbr.com.br (Marc) Date: Sat, 8 Jun 2002 17:41:26 -0300 Subject: [Tutor] Beep sound for Linux In-Reply-To: <3D01D042.000005.09639@athlon900.vic.optushome.com.au> References: <3D01D042.000005.09639@athlon900.vic.optushome.com.au> Message-ID: <20020608174126.A1125@marcolab.net> Dimitrije Nikic (donni@melwestmarket.com) wrote: > I heard of beep sounds for Windows only, but is there a function for beep sounds in Linux? Some time ago I was playing with a nice beep program: beep. You can control the freq and duration of a beep.The only problem: it must run suid root :/ You can get it at http://johnath.com/beep/beep-1.2.2.tar.gz Test with: $ beep -n -f 1500 -l 2000 -n 200 -l 3000 Should beep three times: a default,1500Hz for 2 seconds, 200Hz for 3 seconds. Then I made script to play with it. Feel free to improve it :) ############################################################# ############################################################# #!/usr/bin/env python import os #tunes for beeporama: (frequence,duration) tune1=[(1000,320),(900,10),(500,410),(400,10),(340,410),(300,10)] tune2=[(1000,10),(500,10),(440,20),(340,2),(720,4),(880,40)] tune=tune2 cmd='beep -f100 -l1 ' for i,j in tune: cmd=cmd + ' -n -f '+ str(i) + ' -l'+str(j) os.system(cmd) ############################################################# ############################################################# Lame, but I was able to play some sounds for different situations like incoming mail, ppp up/down, firewall alerts, etc. Does any one know if is possible to find a way to get some "tunes" ? Maybe extract from MIDI files or something like that. It would be very nice to play some real music :) Hope it helps. Good luck. From dyoo@hkn.eecs.berkeley.edu Sat Jun 8 22:48:45 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Jun 2002 14:48:45 -0700 (PDT) Subject: [Tutor] Tkinter Help Please. In-Reply-To: Message-ID: On Sat, 8 Jun 2002, SA wrote: > Hi Everyone- > Can someone explain what _tkinter in the Tkinter.py refers to? > > Specifically from line:35 of Tkinter.py > > import _tkinter # If this fails your Python may not be configured for Tk Hi SA, This '_tkinter' module is a low-level module that supports Tkinter; it gets compiled automatically if your system has Tk support. > Ok how do I compile Python to be configured for Tk and where is the > _tkinter module located? If you already have the Tk libraries installed, you may want to make sure that the development 'header libraries' are also around; otherwise, Python can't build the '_tkinter' library. What kind of system are you running? Using a package management system can simplify this. For example, on my Debian Linux system, I just need to make sure I have the 'tk8.3-dev' package installed. On a Red Hat Linux system, the developmental packages usually have a '-devel' suffix at the end of their package names. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sat Jun 8 23:03:14 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 8 Jun 2002 15:03:14 -0700 (PDT) Subject: [Tutor] Beep sound for Linux In-Reply-To: <20020608174126.A1125@marcolab.net> Message-ID: > Lame, but I was able to play some sounds for different situations like > incoming mail, ppp up/down, firewall alerts, etc. > > Does any one know if is possible to find a way to get some "tunes" ? > Maybe extract from MIDI files or something like that. It would be very > nice to play some real music :) Hmmm... maybe something in Pygame might help? The game "SolarWolf", http://www.pygame.org/shredwheat/solarwolf/ uses "XM" formatted files for its songs, so Pygame definitely has some tools here for playing music. There are utilities available to convert MIDI to XM, so one possiblity is to convert to XM, and then use Pygame to play it. Good luck! From phthenry@earthlink.net Sat Jun 8 23:23:50 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat, 8 Jun 2002 18:23:50 -0400 Subject: [Tutor] rtf to xml regexp question In-Reply-To: <20020607171007.B6866@localhost.localdomain> References: <20020607171007.B6866@localhost.localdomain> Message-ID: <20020608182349.A10617@localhost.localdomain> I'm responding to my own question. I've done a lot of research the past few days, and rezlize that for my needs I really needed a parser or state machine. As with many things with programming and linux, it is always frustrating at first. Then once you understand, you think "Ah, that is a much simpler solution!" That is how I feel about state machines. I have been killing myself with regular expressions. No more! Paul PS I'v included my code below, in case anyone is interested. The only problem I am having at this point is that the state machine is putting a space after my "{", but I think I can write a sub-routine to strip trailing spaces. PSS Originally this message was a plea for help. My regular expressions were so greedy that they were overlapping each other. But as soon as I started writing this email, the solution came to me! ******************************* !/usr/bin/python from Plex import * ##from Plex.Traditional import re class MyScanner(Scanner): def begin_footnote(self, text): self.produce('##Footnote', '') if self.nesting_level == 0: self.begin('footnote') self.nesting_level = self.nesting_level + 1 def end_something(self, text): self.nesting_level = self.nesting_level - 1 if self.nesting_level == 0: self.produce('##END OF FOOTNOTE##','') self.begin('') else: self.produce('}','') def begin_open_bracket(self, text): self.produce('{','') self.nesting_level = self.nesting_level + 1 string = Rep1(AnyBut("{}")) lexicon = Lexicon([ (Str(r"{\footnote"), begin_footnote), State('footnote', [ (Str(r"{\footnote"), begin_footnote), (Str("}"), end_something), (Str(r"{"), begin_open_bracket), (string, TEXT) ]), (string, TEXT), (Str("{"), TEXT), (Str("}"), TEXT), ]) def __init__(self, file, name): Scanner.__init__(self, self.lexicon, file, name) self.nesting_level = 0 filename = "/home/paul/paultemp/my_file.txt" file = open(filename, "r") scanner = MyScanner(file, filename) while 1: token = scanner.read() if token[0] is None: break print token[0], -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From sarmstrong13@mac.com Sun Jun 9 03:26:37 2002 From: sarmstrong13@mac.com (SA) Date: Sat, 08 Jun 2002 21:26:37 -0500 Subject: [Tutor] Newbie Question Again. Message-ID: Hi Everyone- I'm running Python on Mac OSX. (bsd based system) How do I call a program from outside Python to be run from within my Python script/ In other words if I have an executable file, say "someprogram", how would I execute this program from within a python script. Thanks. SA From dman@dman.ddts.net Sun Jun 9 04:01:57 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat, 8 Jun 2002 22:01:57 -0500 Subject: [Tutor] Newbie Question Again. In-Reply-To: References: Message-ID: <20020609030157.GA23916@dman.ddts.net> --X1bOJ3K7DJ5YkBrT Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Jun 08, 2002 at 09:26:37PM -0500, SA wrote: | Hi Everyone- |=20 | I'm running Python on Mac OSX. (bsd based system) How do I call a | program from outside Python to be run from within my Python script/ In ot= her | words if I have an executable file, say "someprogram", how would I execute | this program from within a python script. There are various ways depending on what you want to do with it. In the simplest case, this works : import os os.system( "command" ) -D --=20 "GUIs normally make it simple to accomplish simple actions and impossible to accomplish complex actions." --Doug Gwyn (22/Jun/91 in comp.unix.wizards) =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --X1bOJ3K7DJ5YkBrT Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0CxSUACgkQO8l8XBKTpRQ35gCffgo8DqrDIvax98w5d3LO74fu 4p0AoKDTThLPT0FaikbcGEKK3QXNbUfF =bs4X -----END PGP SIGNATURE----- --X1bOJ3K7DJ5YkBrT-- From beercanz@hotmail.com Sun Jun 9 03:12:29 2002 From: beercanz@hotmail.com (Guess Who? Me) Date: Sun, 09 Jun 2002 02:12:29 +0000 Subject: [Tutor] Python Question - Repeating output. Message-ID:
I downloaded python yesterday and am working through the tutorial. I got to http://www.honors.montana.edu/~jjc/easytut/easytut/node6.html, the part about while. I couldn't get it, because if a=0, and a=a+1, then wouldn't 0=1???
 
And I kept trying to make my own program with while, but they keep giving me infinite answers. Here's what I did:
 
#I need an idea to make a program using "while". So I'll be lame.
a=input("Pick a number that is not lame:")
while a==69:
    print "Good job!"
while a !=69:
    print "Moron."
It gave me infinite "Moron." or "Good job!"s.
So basically - any clearer definitions of while? And why does my little program keep giving me infinite loops??
Thanks.
 
 


Chat with friends online, try MSN Messenger: Click Here
From dyoo@hkn.eecs.berkeley.edu Sun Jun 9 08:00:00 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 9 Jun 2002 00:00:00 -0700 (PDT) Subject: [Tutor] Newbie Question Again. In-Reply-To: Message-ID: On Sat, 8 Jun 2002, SA wrote: > I'm running Python on Mac OSX. (bsd based system) How do I call a > program from outside Python to be run from within my Python script/ In > other words if I have an executable file, say "someprogram", how would I > execute this program from within a python script. Hi SA, We can use the os.system() call to run external commands. For example: ### import os print "The return code from os.system('ls') is", os.system('ls') ### will run the 'ls' command, and give back to us a errorlevel value. If we want to grab the 'standard out' output of that external program, then the os.popen() command is more useful. Here's an example: ### >>> process_file = os.popen('ls -l gift/') >>> process_file.readline() 'total 36\n' >>> print process_file.read() -rw-r--r-- 1 dyoo dyoo 1598 May 22 22:25 directed_point.py -rw-r--r-- 1 dyoo dyoo 3573 May 22 22:35 directed_point.pyc -rw-r--r-- 1 dyoo dyoo 1628 May 22 22:26 main.py -rw-r--r-- 1 dyoo dyoo 2647 May 22 22:25 names.py -rw-r--r-- 1 dyoo dyoo 3691 May 22 22:35 names.pyc -rw-r--r-- 1 dyoo dyoo 3377 May 22 22:25 starfield.py -rw-r--r-- 1 dyoo dyoo 3598 May 22 22:35 starfield.pyc -rw-r--r-- 1 dyoo dyoo 2010 May 22 22:25 three_d.py -rw-r--r-- 1 dyoo dyoo 3590 May 22 22:35 three_d.pyc ### If you want to read more about these functions, you can find more details in the Python Standard Library. Here's are some links you might find useful: http://www.python.org/doc/lib/os-procinfo.html http://www.python.org/doc/lib/os-newstreams.html http://www.python.org/doc/lib/module-popen2.html (There are some other functions with the name 'exec...' in the 'os' module, but they're probably not what you want: the 'exec...' functions end up actually replacing the Python program altogether --- Python reliquishes complete control to the 'exec'ed program.) If you have more questions, please feel free to ask. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Jun 9 08:11:48 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 9 Jun 2002 00:11:48 -0700 (PDT) Subject: [Tutor] Python Question - Repeating output. In-Reply-To: Message-ID: On Sun, 9 Jun 2002, Guess Who? Me wrote: > I downloaded python yesterday and am working through the tutorial. I got > to http://www.honors.montana.edu/~jjc/easytut/easytut/node6.html, the > part about while. I couldn't get it, because if a=0, and a=a+1, then > wouldn't 0=1??? Ah! The thing is that '=' in many programming languages does not mean equality: in Python, it's a symbol for 'assignment'. If it helps, if you see: a = a + 1 try crossing your eyes so that the '=' sign looks more like an arrow: a <-- a + 1 This says, "the value of the 'a + 1' expression will be assigned into the 'a' variable." There's a sense of time, a sense of "state" involved here that may not jive with the math that you may be used to. At one point, the 'a' variable contains '0', and after executing a few statements, time passes, and now it might contain '1'. So it's not math: it's more like simulation, or like scratch paper. Dunno if that made much sense. *grin* > And I kept trying to make my own program with while, but they keep > giving me infinite answers. Here's what I did: > > #I need an idea to make a program using "while". So I'll be lame. > a=input("Pick a number that is not lame:") > while a==69: > print "Good job!" > while a !=69: > print "Moron." > It gave me infinite "Moron." or "Good job!"s. > So basically - any clearer definitions of while? You had the right idea: the only problem is that the code doesn't give the user the opportunity to revise the value of 'a'. It's as if a child were asking "Are we there yet? Are we there yet?" even before the parents have a chance to holler "Not yet". Here's one way to fix that: ### a = input("Pick a number that is not lame:") while a==69: print "Good job!" while a !=69: print "Moron." a = input("Play it again, Sam: ") ### And that might help more. Computers are stupid machinery, so they'll do pointless things until we tell them not to. *grin* Note that what gets repeated in a while loop is ONLY what's indented underneath it. Hope this helps! From glingl@aon.at Sun Jun 9 08:27:37 2002 From: glingl@aon.at (Gregor Lingl) Date: Sun, 9 Jun 2002 09:27:37 +0200 Subject: [Tutor] Python Question - Repeating output. References: Message-ID: <001001c20f87$21afdbd0$1615a8c0@mega> ----- Original Message ----- From: "Danny Yoo" To: "Guess Who? Me" > > Here's one way to fix that: > ....... > ### > a = input("Pick a number that is not lame:") > while a==69: > print "Good job!" > while a !=69: > print "Moron." > a = input("Play it again, Sam: ") > ### > > deh! still buggy (or did you intend infinite good jobs with 69?): Pick a number that is not lame:69 Good job! Good job! Good job! Good job! Good job! Good job! Good job! Good job! Traceback (most recent call last): File "C:/____arbeit____/Py/infinit.py", line 3, in ? print "Good job!" File "C:\Python22\Tools\idle\PyShell.py", line 679, in write self.shell.write(s, self.tags) File "C:\Python22\Tools\idle\PyShell.py", line 670, in write raise KeyboardInterrupt KeyboardInterrupt The following might help more: a = input("Pick a number that is not lame:") while a!=0: if a==69: print "Good job!" else: print "Moron." a = input("Play it again, Sam: ") print "Huuuh!" which works like this: >>> Pick a number that is not lame:77 Moron. Play it again, Sam: 70 Moron. Play it again, Sam: 69 Good job! Play it again, Sam: 69 Good job! Play it again, Sam: 0 Huuuh! >>> (or I misunderstood the question due to incomplete knowledge of English) Gregor From dyoo@hkn.eecs.berkeley.edu Sun Jun 9 08:33:58 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 9 Jun 2002 00:33:58 -0700 (PDT) Subject: [Tutor] Re: Time Function [strftime / strptime] In-Reply-To: <20020608130905.A27711@babylonia.flatirons.org> Message-ID: On Sat, 8 Jun 2002, Chris Avery wrote: > time.strftime() returns the time you want. > time.strftime("%h-%m") or something like that should work. By the way, you may find this post useful: http://groups.google.com/groups?selm=mailman.1023213423.29408.clpa-moderators%40python.org time.strptime() is the function that does the inverse of strftime(): it reads date strings back into the "epoch seconds" that Python can easily work with... but it appears to be available only on Unix systems. However, the message above refers to a pure Python implementation of the time.strptime() function, so if you ever need to use it in a non-Unix environment, this might be useful. Good luck! From dyoo@hkn.eecs.berkeley.edu Sun Jun 9 08:44:24 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 9 Jun 2002 00:44:24 -0700 (PDT) Subject: [Tutor] Is there a function for refreshing what's in the console? In-Reply-To: <3D01B4FD.000007.47955@athlon900.vic.optushome.com.au> Message-ID: On Sat, 8 Jun 2002, Dimitrije Nikic wrote: > Is there a function for refreshing what's in the console? (Eg. delete > everything printed previously in the window) There's the silly answer of: ### for i in range(80): print ### *grin* But you're probably thinking something more on the lines of clearing the whole screen, and having the cursor at the top. For that, if you're running Windows, try: ### import os os.system('cls') ### If you're running a Unix: ### import os os.system('clear') ### As you can tell, the problem is that it's somewhat system dependent, and I don't think anyone's written a nice module that hides this dependency yet. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Jun 9 08:48:13 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 9 Jun 2002 00:48:13 -0700 (PDT) Subject: [Tutor] Python Question - Repeating output. In-Reply-To: <001001c20f87$21afdbd0$1615a8c0@mega> Message-ID: > > Here's one way to fix that: > > > ....... > > > ### > > a = input("Pick a number that is not lame:") > > while a==69: > > print "Good job!" > > while a !=69: > > print "Moron." > > a = input("Play it again, Sam: ") > > ### > > > > > > deh! still buggy (or did you intend infinite good jobs with 69?): > > Pick a number that is not lame:69 > Good job! > Good job! > Good job! > Good job! > Good job! > Good job! > Good job! > Good job! Yikes! Well, at least it's complementary. *grin* I was thinking of that second infinite loop, but you're right: the first bug sideswiped me. I have tunnel vision, which helps when I'm hunting specific bugs, but I sometimes don't look at the big picture. Thanks for the correction! From donni@melwestmarket.com Sun Jun 9 10:28:57 2002 From: donni@melwestmarket.com (Dimitrije Nikic) Date: Sun, 9 Jun 2002 19:28:57 +1000 (AUS Eastern Standard Time) Subject: [Tutor] Thanks for your help guys... Message-ID: <3D031FD9.000009.49799@athlon900.vic.optushome.com.au> --------------Boundary-00=_9CMFMY50000000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Thank you all people for helping me with the clear and time functions. i = appreciate it :) although i still need the beep function which works for linux i'm glad i joined this user group :) --------------Boundary-00=_9CMFMY50000000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Thank you all people for helping me with the clear and time=20 functions. i appreciate it :)
although i still need the beep function which works for linux<= /DIV>
i'm glad i joined this user group :)
=09 =09 =09 =09 =09 =09 =09
_________________________________________________
Bravenet IncrediMail - Email ha= s finally=20 evolved -
Click=20 Here
--------------Boundary-00=_9CMFMY50000000000000-- From glide@slingshot.co.nz Sun Jun 9 21:15:46 2002 From: glide@slingshot.co.nz (Graeme Andrew) Date: Mon, 10 Jun 2002 08:15:46 +1200 Subject: [Tutor] Menu Code ... ? Message-ID: <200206100815.46576.glide@slingshot.co.nz> Hi All, I am new to Python and was wondering if anyone can point be to some sampl= e=20 'Menu' type code. I am assuming that there are no built in menu commands= ? The python code I am writing is server based and acts as an installation= =20 script for out software. So must run on Windows and Unix. The menu part I= am=20 intending to make data driven .. ie read the 'ini' file and display a men= u=20 accordingly. There is no GUI requiremnt for the menu. ... closest thing = I=20 can think of at the moment is the Red Hat Linux install program ... which= is=20 evidently python based. Any ideas would be appreciated ... Thanks in advance Graeme Andrew Kiwi =20 From ak@silmarill.org Sun Jun 9 21:55:17 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sun, 9 Jun 2002 16:55:17 -0400 Subject: [Tutor] Menu Code ... ? In-Reply-To: <200206100815.46576.glide@slingshot.co.nz> References: <200206100815.46576.glide@slingshot.co.nz> Message-ID: <20020609205517.GA9985@ak.silmarill.org> On Mon, Jun 10, 2002 at 08:15:46AM +1200, Graeme Andrew wrote: > Hi All, > > I am new to Python and was wondering if anyone can point be to some sample > 'Menu' type code. I am assuming that there are no built in menu commands ? > > The python code I am writing is server based and acts as an installation > script for out software. So must run on Windows and Unix. The menu part I am > intending to make data driven .. ie read the 'ini' file and display a menu > accordingly. There is no GUI requiremnt for the menu. ... closest thing I > can think of at the moment is the Red Hat Linux install program ... which is > evidently python based. > > Any ideas would be appreciated ... > > Thanks in advance > Graeme Andrew > Kiwi > Do you mean something like this: def do_this(): ... def do_that(): ... menu = { 'a': do_this, 'b': do_that, } answer = raw_input() # run chosen function menu[answer]() > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From neutron878@cayuse.net Mon Jun 10 01:17:29 2002 From: neutron878@cayuse.net (Ricardo Ortega) Date: Sun, 9 Jun 2002 20:17:29 -0400 Subject: [Tutor] integer Message-ID: <000001c21014$4c547930$96a594ce@neutronxmmrdqk> This is a multi-part message in MIME format. ------=_NextPart_000_0001_01C20FF2.C542D930 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable How can I get an integer from a string example: =91BLK 15423 L=92 How can I get just the integer from that string if I didn=92t know what = it looked like before hand all I new is that there was a number somewhere in the string. --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.370 / Virus Database: 205 - Release Date: 6/5/2002 =20 ------=_NextPart_000_0001_01C20FF2.C542D930 Content-Type: text/html; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable

How can I get an integer from a string example: = =91BLK 15423 L=92

How can I get just the integer from that string if I = didn=92t know what it looked like before hand all I new is that there was a = number somewhere in the string.


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.370 / Virus Database: 205 - Release Date: 6/5/2002

------=_NextPart_000_0001_01C20FF2.C542D930-- From dman@dman.ddts.net Mon Jun 10 02:13:11 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sun, 9 Jun 2002 20:13:11 -0500 Subject: [Tutor] Re: integer In-Reply-To: <000001c21014$4c547930$96a594ce@neutronxmmrdqk> References: <000001c21014$4c547930$96a594ce@neutronxmmrdqk> Message-ID: <20020610011311.GA1725@dman.ddts.net> --IS0zKkzwUGydFO0o Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, Jun 09, 2002 at 08:17:29PM -0400, Ricardo Ortega wrote: | How can I get an integer from a string example: ?BLK 15423 L? | How can I get just the integer from that string if I didn?t know what it | looked like before hand all I new is that there was a number somewhere | in the string. In general, parsing an arbitrary string with no predefined structure is impossible. If I throw random data at you, how would you make any sense out of it, unless we first agree on some structure? Random data looks much like grafiti does. OTOH, if you know something about the string, for example the one you gave above, it can be parsed : # start with the data s_org =3D "?BLK 15423 L?" # split it on the spaces, and keep just the number part s_num =3D s_org.split( ' ' )[1] # now try and convert it to an integer. be aware that if the data is # malformed (eg a corrupt file) the conversion will fail try : number =3D int( s_num ) except ValueError , err : print "Couldn't convert '%s' to a number.\n%s" % ( s_num , str( err ) ) HTH, -D --=20 Microsoft is to operating systems & security .... .... what McDonald's is to gourmet coo= king =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --IS0zKkzwUGydFO0o Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0D/ScACgkQO8l8XBKTpRTrYgCfVMXM+Gz6+6knTJiOp2FwpaNA uWEAn3sYeRtDFPYbis4M0DtehjcqLgtt =hFWH -----END PGP SIGNATURE----- --IS0zKkzwUGydFO0o-- From urnerk@qwest.net Sun Jun 9 23:21:04 2002 From: urnerk@qwest.net (Kirby Urner) Date: Sun, 9 Jun 2002 18:21:04 -0400 Subject: [Tutor] integer In-Reply-To: <000001c21014$4c547930$96a594ce@neutronxmmrdqk> References: <000001c21014$4c547930$96a594ce@neutronxmmrdqk> Message-ID: <200206091821.04509.urnerk@qwest.net> On Sunday 09 June 2002 08:17 pm, Ricardo Ortega wrote: > How can I get an integer from a string example: =91BLK 15423 L=92 > How can I get just the integer from that string if I didn=92t know what= it > looked like before hand all I new is that there was a number somewhere > in the string. Hi Ricardo: Import the regular expression (regexp) module, named re: >>> import re Then compile a search pattern. The one below looks for any string of one= or more digits. You only need to compile this pattern once, then use it ove= r and over. >>> srch =3D re.compile("[0-9]+") =20 Now here's a short function that uses the search method of the srch objec= t (created by your re.compile()). If it gets a result, it'll return the matching segment, otherwise it returns the empty string. >>> def getstr(thestr): =09m =3D srch.search(thestr) =09if m: return m.group() =09else: return '' Here it is in action: =09 >>> getstr("BLK 15423 L") '15423' Another example: >>> getstr("RRS 44523LL 12P") '44523' As written, we're only picking up the first match in the string, but=20 with tweaks could get them all. You can adapt the above for your own purposes. For a lot of interesting reading on regular expressions in Python, see: http://py-howto.sourceforge.net/regex/regex.html Kirby PS: instead of "[0-9]+" as the pattern, you could use "\d+" and get the same result, as \d means the same as [0-9] i.e. "any decimal digit". From lha2@columbia.edu Mon Jun 10 04:22:37 2002 From: lha2@columbia.edu (Lloyd Hugh Allen) Date: Sun, 09 Jun 2002 23:22:37 -0400 Subject: [Tutor] integer References: <000001c21014$4c547930$96a594ce@neutronxmmrdqk> Message-ID: <3D041B7D.933B96D5@mail.verizon.net> Don't know why netscape isn't quoting the message, but too lazy to do something about it. Maybe because it had been formatted text? The query had been, "how do you pull an integer out of the middle of a string?" This seems to do the trick, as long as you only want the first integer and it is an integer, not a float (would require more work). Would also want to do something like "answer = int(strbuild)" at the end in order for the number to be a number: Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> foo = "blk 15423 l" >>> sentinel = '' >>> strbuild = '' >>> for letter in foo: if letter.isdigit(): sentinel = 1 strbuild += letter elif sentinel: break >>> strbuild '15423' From jgregorio@ultrasw.com Mon Jun 10 06:12:02 2002 From: jgregorio@ultrasw.com (Josh Gregorio) Date: Sun, 09 Jun 2002 22:12:02 -0700 Subject: [Tutor] Linux verson of msvcrt Message-ID: <3D043522.8050502@ultrasw.com> What is the GNU/Linux/Unix equivalent to import msvcrt msvcrt.getch() ? I found the windows version in the docs because I knew what to look for--but I can't find how to getch() from Linux. Is there a way to use getch() (or something else that will wait for the user to press some key) that works the same in Windows and GNU/Linux? Thanks, Josh ps Does anyone have any tips for searching documentation when you don't know the proper names for what you are looking for? From billintucson@yahoo.com Mon Jun 10 07:22:55 2002 From: billintucson@yahoo.com (Bill Gillespie) Date: Sun, 9 Jun 2002 23:22:55 -0700 (PDT) Subject: [Tutor] Where best to start? First program to: login, read from and close a serial line? Message-ID: <20020610062255.51796.qmail@web11802.mail.yahoo.com> Hi Folks, I was very happy to find this resource. I'm a new guy and am just starting to learn to do some simple programming, and Python is my first "real programming" language. It's very exciting! My first programming project: At work we have a "floor and oil temperature control system". I would like to build a simple GUI, allowing us to interrogate, display and change these two values: 1) OIL set point 2) FLOOR set point The Tkinter (GUI) part looks learnable - but I don't know where to start in terms of --> logging into a remote machine (in Xterm from a Linux machine - to a sun os machine) --> opening a serial line on it (I normally just type "tip oftc" to connect ) --> interrogating the embedded device on it, (two seperate commands ask for current - or order a change) --> and then logging out again. ($. closes the connection) then I log out of the machine) Any advice on the general idea of what should take place will be most welcome. Thanks much, Bill __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From papamountain@yahoo.com Mon Jun 10 09:57:18 2002 From: papamountain@yahoo.com (Richard) Date: Mon, 10 Jun 2002 01:57:18 -0700 (PDT) Subject: [Tutor] Just learning Message-ID: <20020610085718.35047.qmail@web12205.mail.yahoo.com> --0-84738498-1023699438=:34063 Content-Type: text/plain; charset=us-ascii Hello all! I have installed Python and have started to play around a bit. It seems very interesting, and fun. Perhaps in the near future, I will be of a level where I can have a recourse with some of you and exchange ideas. I look forward to it! --------------------------------- Do You Yahoo!? Sign-up for Video Highlights of 2002 FIFA World Cup --0-84738498-1023699438=:34063 Content-Type: text/html; charset=us-ascii

Hello all!

I have installed Python and have started to play around a bit. It seems very interesting, and fun. Perhaps in the near future, I will be of a level where I can have a recourse with some of you and exchange ideas. I look forward to it!



Do You Yahoo!?
Sign-up for Video Highlights of 2002 FIFA World Cup --0-84738498-1023699438=:34063-- From wolf_binary@hotmail.com Mon Jun 10 13:56:47 2002 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Mon, 10 Jun 2002 07:56:47 -0500 Subject: [Tutor] reference material Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0013_01C21054.5EC10300 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hi all, I wanted to know what you guys recommend for reference material on = Tkinter widgets. I need a source of all the attributes to each one so I = know what I can do to my widgets. Also, if you have any recomendations = for general python programming reference book or online source let me = know. =20 Thanks, Cameron Stoner ------=_NextPart_000_0013_01C21054.5EC10300 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
hi all,
 
I wanted to know what you guys = recommend for=20 reference material on Tkinter widgets.  I need a source of all the=20 attributes to each one so I know what I can do to my widgets.  = Also, if you=20 have any recomendations for general python programming reference book or = online=20 source let me know. 
 
Thanks,
Cameron = Stoner
------=_NextPart_000_0013_01C21054.5EC10300-- From pythontutor@venix.com Mon Jun 10 14:26:33 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon, 10 Jun 2002 09:26:33 -0400 Subject: [Tutor] Linux verson of msvcrt References: <3D043522.8050502@ultrasw.com> Message-ID: <3D04A909.9080108@venix.com> http://mail.python.org/pipermail/tutor/2002-April/013989.html [Tutor] program to count keys with timer display and clock display I asked a somewhat similar question back in April. This response from Paul was quite helpful. It use PyGame. Alan Gauld also supplied a refernce to his website pointing out how to use TKinter for processing the keystrokes. Josh Gregorio wrote: > What is the GNU/Linux/Unix equivalent to > import msvcrt > msvcrt.getch() ? > > I found the windows version in the docs because I knew what to look > for--but I can't find how to getch() from Linux. Is there a way to use > getch() (or something else that will wait for the user to press some > key) that works the same in Windows and GNU/Linux? > > Thanks, > Josh > > ps Does anyone have any tips for searching documentation when you don't > know the proper names for what you are looking for? > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From urnerk@qwest.net Mon Jun 10 16:27:37 2002 From: urnerk@qwest.net (Kirby Urner) Date: Mon, 10 Jun 2002 08:27:37 -0700 Subject: [Tutor] Where best to start? First program to: login, read from and close a serial line? In-Reply-To: <20020610062255.51796.qmail@web11802.mail.yahoo.com> Message-ID: <4.2.0.58.20020610082145.01be7c00@pop3.norton.antivirus> > >Any advice on the general idea of what should take place will be most >welcome. > >Thanks much, > >Bill Hi Bill -- Probably easiest if you can wrap Python around the system commands you already use. t = popen('cmd') will execute 'cmd' (what you'd normally enter in the shell) and t.readlines() will give back a list of what 'cmd' returns, e.g. in the Python shell: >>> from os import popen >>> t = popen('ls') >>> for line in t.readlines(): print line, should echo a directory listing to your screen. So you should be able to pop up GUI widgets ala Tkinter which wrap your existing system commands. While testing, you might write some dummy scripts on a standalone box to simulate the commands and their return values. Kirby From sarmstrong13@mac.com Mon Jun 10 14:46:25 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 10 Jun 2002 08:46:25 -0500 Subject: [Tutor] reference material In-Reply-To: Message-ID: > This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. --B_3106550447_373257 Content-type: text/plain; charset="US-ASCII" Content-transfer-encoding: 7bit Start with www.python.org. There are many different links to online tutorials there under the Documents section. Good Luck. SA On 6/10/02 7:56 AM, "Cameron Stoner" wrote: > hi all, > > I wanted to know what you guys recommend for reference material on Tkinter > widgets. I need a source of all the attributes to each one so I know what I > can do to my widgets. Also, if you have any recomendations for general python > programming reference book or online source let me know. > > Thanks, > Cameron Stoner > --B_3106550447_373257 Content-type: text/html; charset="US-ASCII" Content-transfer-encoding: quoted-printable Re: [Tutor] reference material Start with www.python.org.

There are many different links to online tutorials there under the Document= s section.

Good Luck.
SA

On 6/10/02 7:56 AM, "Cameron Stoner" <wolf_binary@hotmail.com&= gt; wrote:

hi all,

I wanted to know what you guys rec= ommend for reference material on Tkinter widgets.  I need a source of a= ll the attributes to each one so I know what I can do to my widgets.  A= lso, if you have any recomendations for general python programming reference= book or online source let me know.  

Thanks,
Cameron Stoner


--B_3106550447_373257-- From sarmstrong13@mac.com Mon Jun 10 16:39:37 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 10 Jun 2002 10:39:37 -0500 Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module and class) In-Reply-To: <15620.49909.679355.726113@12-248-41-177.client.attbi.com> Message-ID: On 6/10/02 10:17 AM, "Skip Montanaro" wrote: > Here's my take on things: > > * A function is an action to perform using a set of input arguments and > returning a set of output arguments. For example: > >>>> print sin(47) > 0.123573122745 > Got it. > * A class associates a chunk of data with a set of functions which operate > on that data. The first argument to each function in a class (typically > called a "method" in Python) is a reference to the data stored in that > instance of the class. For example: > > import math > class Point: > def __init__(self, x, y): > self.x = x > self.y = y > > def polar(self): > return math.sqrt(self.x**2+self.y**2), math.atan2(self.y, self.x) > So the "def __init__" is a function in the class and is assigning the variables x and y as attributes of the class, correct? If so, are the variables x and y supplied outside of the class (I guess this would be global)? > * A module is an object that partitions the namespace in a hierarchy. For > example, you can have a function named "sin" which is distinct from the > sin function in the math module ("math.sin"). Modules used in a > straightforward way only add a single extra level of hierarchy to the > namespace. Packages generalize this concept to multiple levels (modules > inside modules). A module is more or less, in very general terms, a package of classes and/or functions that are then imported into the __main__ program, correct? One last question, sorry if this is very basic but I feel these terms need better definitions for newbies like me (the only other languages I have experience with are Qbasic and HTML) what is a namespae? Is that analagous to pwd of the program? For instance, if the program is currently in one are of the script doing work, would that be considered the namespace? See everything I read explains these terms in definitions that are readibly understandable by people with programming experience. I kind of need a "layman's" terms tutorial because I'm so new to programming. But this has been very helpful dialogue in defining these terms and I feel the people on this list have been very helpful. Thank You all. Thanks. SA From phthenry@earthlink.net Mon Jun 10 17:20:38 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon, 10 Jun 2002 12:20:38 -0400 Subject: [Tutor] parsing--is this right? Message-ID: <20020610122037.A26494@localhost.localdomain> I have just stumbled across the concept of parsing and parsing grammars, and wondered if I am using the right tool. I haved downloaded and installed plex in order to parse a rtf document. The rtf looks like this: {\footnote {\i an italicized word} {\i maybe another italicized word} text } In order to parse this text, I use a counter to count the number of open and closed curly brackets. I am following the tutorial in doing this. However, I am wondering if plex does things the wrong way. If I understand things correctly, you should not have to count brackets. A parser should use the grammar to understand what state you are in. I have looked at another example using the rtf example of another parser, mxTextTools. This parser does not count tags at all. I like plex because it was the only parser that I could get to work! However, I am wondering if it lacks the power a parser should have, and if I should devote my time to a better tool. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From alex@gabuzomeu.net Mon Jun 10 18:06:36 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Mon, 10 Jun 2002 19:06:36 +0200 Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module and class) In-Reply-To: <20020610154108.24837.15883.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020610184206.00b99a20@pop3.norton.antivirus> At 11:41 10/06/2002 -0400, you wrote: >Date: Mon, 10 Jun 2002 10:39:37 -0500 >From: SA >Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module >and class) > > import math > > class Point: > > def __init__(self, x, y): > > self.x = x > > self.y = y > > > > def polar(self): > > return math.sqrt(self.x**2+self.y**2), math.atan2(self.y, > self.x) > >So the "def __init__" is a function in the class and is assigning the >variables x and y as attributes of the class, correct? Yes. A function used in a class is usually called a "method". >If so, are the variables x and y supplied outside of the class Correct. They are parameters that are passed when the method (__init__()) is called. >(I guess this would be global)? Within __init__(), x and y are local variables. Hence they disappear when the method exits. That's why they are reassigned to self.x and self.y. self.x and self.y are attributes that survive as long as the class instance. >A module is more or less, in very general terms, a package of classes >and/or functions that are then imported into the __main__ program, correct? Yes, sounds reasonable. >One last question, sorry if this is very basic but I feel these terms need >better definitions for newbies like me (the only other languages I have >experience with are Qbasic and HTML) what is a namespae? Is that analagous >to pwd of the program? As I understand it, namespaces are related to scope of variables. Namespaces are similar to nested containers that holds variables. When you use a variable, Python looks up its value in the nearest, smallest namespace (i.e. local). If it cannot find it, it will look a bit farther (eg. the namespace of the current class instance). Still missing? Then it looks in the global namespace. Still missing? Python looks in the built-in namespace. What, still missing? Python gives up and raise an error. I think namespaces can be pictured as small boxes in larger boxes. Values are searched in smaller boxes first. Also, the smaller the box, the shorter the variable lifetime. >See everything I read explains these terms in definitions that are readibly >understandable by people with programming experience. I kind of need a >"layman's" terms tutorial because I'm so new to programming. Here is a small test to try and make it more concrete: ## globalFoo = "I am a global variable." class Test: classFoo = "I am a class variable." def __init__(self): self.instanceFoo = "I am an instance variable." localFoo = "I am a local variable." print globalFoo print self.classFoo print self.instanceFoo print localFoo if __name__ == "__main__": t = Test() ## Cheers. Alexandre From dyoo@hkn.eecs.berkeley.edu Mon Jun 10 19:00:17 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Jun 2002 11:00:17 -0700 (PDT) Subject: [Tutor] Just learning In-Reply-To: <20020610085718.35047.qmail@web12205.mail.yahoo.com> Message-ID: On Mon, 10 Jun 2002, Richard wrote: > I have installed Python and have started to play around a bit. It seems > very interesting, and fun. Perhaps in the near future, I will be of a > level where I can have a recourse with some of you and exchange ideas. I > look forward to it! Hi Richard, We'll be happy to hear from you! Please feel free to ask questions on the list when you feel comfortable. Good luck! From skip@pobox.com Mon Jun 10 18:26:52 2002 From: skip@pobox.com (Skip Montanaro) Date: Mon, 10 Jun 2002 12:26:52 -0500 Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module and class) In-Reply-To: References: <15620.49909.679355.726113@12-248-41-177.client.attbi.com> Message-ID: <15620.57692.735525.490352@12-248-41-177.client.attbi.com> >> * A class associates a chunk of data with a set of functions which >> operate on that data. The first argument to each function in a >> class (typically called a "method" in Python) is a reference to the >> data stored in that instance of the class. For example: >> >> import math >> class Point: >> def __init__(self, x, y): >> self.x = x >> self.y = y >> >> def polar(self): >> return math.sqrt(self.x**2+self.y**2), math.atan2(self.y, self.x) >> SA> So the "def __init__" is a function in the class and is assigning SA> the variables x and y as attributes of the class, correct? If so, SA> are the variables x and y supplied outside of the class (I guess SA> this would be global)? __init__ is the constructor for the class. It's called for you when you instantiate the class appropriately. You create an instance of the class like so: mypoint = Point(1,0) >> * A module is an object that partitions the namespace in a hierarchy. SA> A module is more or less, in very general terms, a package of SA> classes and/or functions that are then imported into the __main__ SA> program, correct? Even more generally, a package of objects. Conceptually, it's no different than how you'd carve up the namespace you live in outside of programming. Ambiguous names need qualification. If you wife says, "Honey, bring me up a can of paint from the basement for the blue wall", and you have several rooms painted in several shades of blue, you'd need a qualifier to decide what room the paint was for. SA> One last question, sorry if this is very basic but I feel these SA> terms need better definitions for newbies like me (the only other SA> languages I have experience with are Qbasic and HTML) what is a SA> namespae? Is that analagous to pwd of the program? For instance, if SA> the program is currently in one are of the script doing work, would SA> that be considered the namespace? Yes, it is more or less like the filesystem hierarchy. In the current directory, a reference to "blue.txt" would reference a file in the current directory. One significant difference is that Python's module/package system doesn't have a syntax for referring to the current module's parent (no ".."). -- Skip Montanaro (skip@pobox.com - http://www.mojam.com/) Boycott Netflix - they spam - http://www.musi-cal.com/~skip/netflix.html From dyoo@hkn.eecs.berkeley.edu Mon Jun 10 20:07:06 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Jun 2002 12:07:06 -0700 (PDT) Subject: [Tutor] Reading & printing lines from two different files In-Reply-To: <200206070854.04671.scot@possum.in-berlin.de> Message-ID: [Warning: this generator stuff depends on Python 2.2; we could mimic it with Python 2.1, but it takes a little more work.] > def generate_line(filename): > thisfile = open(filename, 'r') > for line in thisfile: > yield line Actually, we can get this one for free --- Files implement the "iterators" interface already, so we can say: ### def generate_line(filename): return iter(open(file)) ### What this returns us is an "iterator", something that marches through, a line at a time. Here's an example that shows what a file iterator looks like: ### >>> file_iter = iter(open('/usr/share/dict/words')) >>> file_iter >>> file_iter.next() 'Aarhus\n' >>> file_iter.next() 'Aaron\n' >>> file_iter.next() 'Ababa\n' >>> file_iter.next() 'aback\n' >>> file_iter.next() 'abaft\n' ### > while 1: > try: > print gen_one.next() > print gen_two.next() > except StopIteration: > break > > ================================== > > This does work here, tho it seems like an awful lot of code compared with > your zip-and-readlines combination. Is there any simple way to explain why > this is not such a memory hog? readlines() sucks all of the lines into memory all at once, saving these lines in a list. Usually, this is a good thing, because it allows us to look at any particular line --- we could look at line 42, or line 1009, or line 4, or ... without having to do anything more than a simple list element access. What we get is the ability to "randomly-access" any line in a file, and that's quite convenient. But there is a cost to using readlines(): we load the whole file into memory. This becomes an issue if we're dealing with huge text files. When we use iterators, we tell Python to sequentially march through our sequence. No more random access, but on the other hand, we only read a line at a time. So that's where the savings come in. Here's a way of having the best of both works: making this look nice, and having it be efficient too: ### def zipiter(*sequences): """A generator version of the zip() function.""" sequence_iters = [iter(seq) for seq in sequences] while 1: next_row = [seq_iter.next() for seq_iter in sequence_iters] yield tuple(next_row) def printAlternatingLines(file1, file2): for (line1, line2) in zipiter(file1, file2): print line1 print line2 ### (Warning: I have not tested this code yet. I know this is going to bite me, so I'll double check this tonight to make sure it works.) > One thing I'm not sure of in the example above is where to put the > thisfile.close() line to close those files again. My computer doesn't > seem any worse for not closing them, but it does seem like bad > manners... We can leave it off in many cases, since Python will garbage collect files that aren't accessible. However, if we're writing some content into a file, closing the file explicitely is a good idea, just to make sure our mess is cleaned up. *grin* (Actually, the Jython variant of Python requires explicit file closing() when we write. See: http://www.jython.org/cgi-bin/faqw.py?req=show&file=faq03.008.htp for more details.) Hope this helps! From alan.gauld@bt.com Mon Jun 10 22:27:04 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 10 Jun 2002 22:27:04 +0100 Subject: [Tutor] Python Question - Repeating output. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21533F9EE@mbtlipnt02.btlabs.bt.co.uk> >, the part about while. I couldn't get it, because > if a=0, and a=a+1, then wouldn't 0=1??? This is a common problem for folks who speak math ;-) In fact its so commoon some languages use a different symbol for assigning values such as ':='. Thus Pascal would write your line as: a := a+1 which is read 'a' becomes 'a' plus one. So in python the '=' symbol doesn't mean 'is equal to' as in math, rather it means 'becomes' or 'takes on the value of' and is called the 'assignment operator' The math like equality test that you are used to is performed in Python with the double equal: a == a + 1 which is always false as you would expect because mathematically it's nonsensical! > a=input("Pick a number that is not lame:")
> while a==69: # note you correctly used == here > print "Good job!" > while a !=69: > print "Moron."
You only set the value of a once before going into the loop. Try this instead: a=input("Pick a number that is not lame:") while a != 69: print 'Moron!' a=input("Pick a number that is not lame:") print "Good job" Now we change the value of a each time round the while loop. Notice too that we only need one loop. The Good Job gets printed only when the while condition is false and the loop stops running. > So basically - any clearer definitions of while? You could try my tutor under the Looping topic :-) Basically the usual construct is: set up initial condition(a above) while condition: do something modify the test condition Yours failed to change the test condition so it just kept on going round and round. HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Jun 10 22:27:02 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 10 Jun 2002 22:27:02 +0100 Subject: [Tutor] Newbie OOP Question. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB21533F9ED@mbtlipnt02.btlabs.bt.co.uk> > I'm still trying to grasp this OOP concept in Python. Can > someone tell me the difference between a function, a module, > and a class? In programming a module is a generic term for any kind of reusable software. In Pythin specifically it is formalised as a file containing Python program code that can be 'import'ed into another Python session or program. A module in the Python sense can encompass class definitions or functions or both as well as data and constant definitions. The re module is a good example whereby you can use a functional interface or compile a regex into an object and call methods on it, both from the same module. It also defines some constants which are used top control the interpretation of regular expressions within those functions and methods. (A method is just a jargon term for a function defined within a class) A class is a type of module in a programming sense and is often implemented inside a module in the pythonic sense. A class is a template for a set of functions(methods) and the set of variables upon which they operate. (These variables are often called the state holders of the objects produced from the class.) We can create many different instances of a class each with its own "copy" of the methods and data. The methods will be identical in functionality but use the data values from the local instance. HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From sarmstrong13@mac.com Mon Jun 10 22:36:41 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 10 Jun 2002 16:36:41 -0500 Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module and class) In-Reply-To: <4.3.2.7.2.20020610184206.00b99a20@pop3.norton.antivirus> Message-ID: On 6/10/02 12:06 PM, "Alexandre Ratti" wrote: > > Here is a small test to try and make it more concrete: > > ## > globalFoo = "I am a global variable." > > class Test: > classFoo = "I am a class variable." > > def __init__(self): > self.instanceFoo = "I am an instance variable." > localFoo = "I am a local variable." > print globalFoo > print self.classFoo > print self.instanceFoo > print localFoo > > if __name__ == "__main__": > t = Test() > ## > > > Cheers. > > Alexandre > > Ok. This is all beginning to make more sense now. Just a couple of more questions: 1. How does "print self.classFoo" know to print classFoo if the classFoo variable is defined prior to the __init__(self) function? 2. What is the purpose of the line "if __name__ == "__main__":"? (How does it work and why do you use this instead of just running "t = Test"?) Thanks again in advance. Everyone here has been very helpful. Thanks. SA From alan.gauld@bt.com Mon Jun 10 22:45:43 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 10 Jun 2002 22:45:43 +0100 Subject: [Tutor] reference material Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C640@mbtlipnt02.btlabs.bt.co.uk> > I wanted to know what you guys recommend for reference material on = > Tkinter widgets. My primary source is the O'Reilly Tcl/Tk in a Nutshell Its all Tcl based but its easy to translate. Next stop is the online Tkinter reference by F Lundh When that fails I turn to Graysons Tkinter book Finally, I read the source code! Unfortunately that happens more often than I'd like :-( > recomendations for general python programming > reference book or online source Books are Beasleys Essential Python and Lutz Programming Python. Very different books but both good one past the basics. Online the best is the standard docs plus the SIGS. Followed by the Dive into Python site Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@bt.com Mon Jun 10 22:47:04 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 10 Jun 2002 22:47:04 +0100 Subject: [Tutor] Linux verson of msvcrt Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C641@mbtlipnt02.btlabs.bt.co.uk> > What is the GNU/Linux/Unix equivalent to > import msvcrt > msvcrt.getch() ? import curses curses.getch() Alan G. From aicolburn@yahoo.com Mon Jun 10 22:52:17 2002 From: aicolburn@yahoo.com (Alan Colburn) Date: Mon, 10 Jun 2002 14:52:17 -0700 (PDT) Subject: [Tutor] Newbie Q's Message-ID: <20020610215217.25441.qmail@web20505.mail.yahoo.com> Hi all-- I have two quick questions for you. First, if I have a list made up of integers, is there a simple command to let me find the sum of the integers (and assign the value to a variable)? I've been able to do it, but based on my miniscule knowledge of C++ something tells me there's an easier way :-) Second, as a way to practice what I've started learning, I decided to try making a (non-graphical)Blackjack game. I've got it set up so that when cards are drawn from a deck, they go into a list (one for the player, one for the dealer). (That's where my question above comes from.) The biggest difficulty I'm having is dealing with aces, which can be valued at 1 or 11. I thought I had everything figured out, until a hand came up that had two aces in it :-) I'm sure many people have tried making this kind of a program. How did you (or would you) deal with this aspect of the program? Thanks for your help! It's great having this resource available. -- Al (aicolburn@yahoo.com) __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From sarmstrong13@mac.com Mon Jun 10 22:59:48 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 10 Jun 2002 16:59:48 -0500 Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module and class) In-Reply-To: <15620.57692.735525.490352@12-248-41-177.client.attbi.com> Message-ID: On 6/10/02 12:26 PM, "Skip Montanaro" wrote: > > SA> One last question, sorry if this is very basic but I feel these > SA> terms need better definitions for newbies like me (the only other > SA> languages I have experience with are Qbasic and HTML) what is a > SA> namespae? Is that analagous to pwd of the program? For instance, if > SA> the program is currently in one are of the script doing work, would > SA> that be considered the namespace? > > Yes, it is more or less like the filesystem hierarchy. In the current > directory, a reference to "blue.txt" would reference a file in the current > directory. One significant difference is that Python's module/package > system doesn't have a syntax for referring to the current module's parent > (no ".."). Ahh. Now that may prove interesting. Would it be beneficial to make a reserved command like .. That pops you back into the parent namespace? Thanks. SA From alan.gauld@bt.com Mon Jun 10 22:54:25 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 10 Jun 2002 22:54:25 +0100 Subject: [Tutor] Re: Newbie OOP Question. (diff between function, modu le and class) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C642@mbtlipnt02.btlabs.bt.co.uk> > So the "def __init__" is a function in the class and is assigning the > variables x and y as attributes of the class, correct? Correct, and is a special magic method that Python calls when you create an instance of the class. > variables x and y supplied outside of the class When you instantiate it you pass the values in: x,y = 7,8 pt = Point(3,4) pt2 = Point(x,y) Creates two instances of Point. One with x,y set to 3,4 the other set to 7,8 > A module is more or less, in very general terms, a package of > classes and/or functions that are then imported into the > __main__ program, correct? Yes altho they could be imported into another module too. > these terms need better definitions for newbies That's a large part of what my web tutor tries to do! > what is a namespace? Is that analagous to pwd of the program? No. Its to do with the visibility of a name within a program. Its explained in the 'Whats in a Name?' topic on my web site. > understandable by people with programming experience. I kind of need a > "layman's" terms tutorial because I'm so new to programming. Thats exactly what my tutor is for, especially useful to you might be the 'namespaces', 'modules and functions' and OOP topics. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From alex@gabuzomeu.net Mon Jun 10 23:05:22 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Tue, 11 Jun 2002 00:05:22 +0200 Subject: [Tutor] Re: Newbie OOP Question.(diff between function, module and class) In-Reply-To: References: <4.3.2.7.2.20020610184206.00b99a20@pop3.norton.antivirus> Message-ID: <4.3.2.7.2.20020610235755.00b6b350@pop3.norton.antivirus> At 16:36 10/06/2002 -0500, SA wrote: > > globalFoo = "I am a global variable." > > > > class Test: > > classFoo = "I am a class variable." > > > > def __init__(self): > > self.instanceFoo = "I am an instance variable." > > localFoo = "I am a local variable." > > print globalFoo > > print self.classFoo > > print self.instanceFoo > > print localFoo > > > > if __name__ == "__main__": > > t = Test() >1. How does "print self.classFoo" know to print classFoo if the classFoo > variable is defined prior to the __init__(self) function? Here, classFoo is a class attribute, whereas instanceFoo is an instance attribute. A class attribute is defined when the class is defined; it is available in all class instances (they share a common copy of the class attribute). >2. What is the purpose of the line "if __name__ == "__main__":"? (How does >it work and why do you use this instead of just running "t = Test"?) This is often used in Python for testing code. This condition is only true when the module is executed as standalone code; it is not true when the module is imported into another module. So you can store testing code after this condition; it won't run when the module is imported. If you just use "t = Test" as top-level code in the module, it will be executed everytime (even when the code is imported into another module), which may not be what you want. Cheers. Alexandre From dyoo@hkn.eecs.berkeley.edu Mon Jun 10 23:02:37 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Jun 2002 15:02:37 -0700 (PDT) Subject: [Tutor] parsing--is this right? In-Reply-To: <20020610122037.A26494@localhost.localdomain> Message-ID: On Mon, 10 Jun 2002, Paul Tremblay wrote: > I have just stumbled across the concept of parsing and parsing > grammars, and wondered if I am using the right tool. > > I haved downloaded and installed plex in order to parse a rtf > document. The rtf looks like this: > > {\footnote {\i an italicized word} {\i maybe another italicized > word} text } Hi Paul, Hmmm... if the structure is always described by braces, perhaps it might be easier to do a "recursive descent" parse through the message. Here's a sample parser that shows how the technique works. ### import re class Chunk: """We'll break up our data into Chunk pieces.""" def __init__(self, type, data): self.type, self.data = type, data def __str__(self): if type(self.data) == type([]): stringed_data = [str(d) for d in self.data] return "TYPE %s: [%s]" % (self.type, ''.join(stringed_data)) else: return str(self.data) def parse(tokens): assert tokens, "Why are you trying to parse nothing?" if tokens[0] == '{': tokens.pop(0) ## Eat the leading bracket. type = tokens.pop(0) collected_chunks = [] while tokens[0] != '}': collected_chunks.append(parse(tokens)) tokens.pop(0) ## Eat the closing bracket. return Chunk(type, collected_chunks) else: ## Single token new_chunk = Chunk('text', tokens.pop(0)) return new_chunk def tokenize(text): "A toy tokenizer just for demonstration purposes." def nonEmpty(thing): return len(thing) > 0 return filter(nonEmpty, re.split(r'([{}]|\s+)', text)) if __name__ == '__main__': EXAMPLE_TEXT = r"""{\footnote {\i an italicized word} {\i maybe another italicized word} text }""".replace('\n', ' ') print parse(tokenize(EXAMPLE_TEXT)) ### The brackets make it really easy to detect boundaries where the parser should clump things together. I used a pathetically silly tokenizer() function to do some initial preprocessing of the text: Plex would probably do a better job at it. > In order to parse this text, I use a counter to count the number > of open and closed curly brackets. I am following the tutorial in > doing this. > > However, I am wondering if plex does things the wrong way. Plex is a tool for breaking the text into "tokens" that are easier to look at. However, it's not enough. You'll probably want to use a parsing technique like recursive descent, or use a specialized parser-building tool. We can talk about it more if you'd like. > If I understand things correctly, you should not have to count brackets. > A parser should use the grammar to understand what state you are in. Yes, exactly. The grammar that the example parser above is reading might be described as: ;;; Chunk := text # 'A "Chunk" is made of a piece of text | '{' Type Chunk* '}' # 'or a bunch of Chunks between two # brackets, associated with a particular # chunk type. ;;; With a parser, there's no need to count how deeply we're nested, as grammars allow for a recursive definition that can go arbitrarily deep. > However, I am wondering if it lacks the power a parser should have, and > if I should devote my time to a better tool. I've had some experience with the SPARK parser, and it's a nice tool: http://pages.cpsc.ucalgary.ca/~aycock/spark/ I used it a while back when I was playing with Pythonica, and it seemed to work very well. The only caveat I could make was that, back then, if there was an error in the grammar, SPARK wouldn't give good error messages. I'm not sure if this complaints can be made now: perhaps this has been fixed. Another parser that I've heard good things about is Amit Patel's YAPPS parser: http://theory.stanford.edu/~amitp/Yapps/ Anyway, I hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Jun 10 23:28:28 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 10 Jun 2002 15:28:28 -0700 (PDT) Subject: [Tutor] Python Question - Repeating output. [defining special methods] In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB21533F9EE@mbtlipnt02.btlabs.bt.co.uk> Message-ID: > The math like equality test that you are used to is performed in Python > with the double equal: > > a == a + 1 > > which is always false as you would expect because mathematically it's > nonsensical! That is, unless we're working in modulo arithmetic; ### class ModNumber: def __init__(self, n, m): self.n, self.m = n % m, m def __add__(self, other): return ModNumber((self.n + other.n), self.m) def __str__(self): return "%s modulo %s" % (self.n, self.m) def __coerce__(self, other): if type(other) == type(42): return (self, ModNumber(other, self.m)) def __eq__(self, other): return (self.n, self.m) == (other.n, other.m) ### "Modulo arithmetic" wraps around a particular modulus, just as a clock's hands wrap around twelve. Here's an example of this modulo "clock" arithmetic: ### >>> print ModNumber(5, 12) + 9 2 modulo 12 ## Nine hours after six o'clock is ## three o'clock. We have to account ## for the fact that humans count by one, ## not zero. >>> ModNumber(0, 1) == ModNumber(0, 1) + 1 1 ### I'm sorry, I just couldn't resist. *grin* From wesc@deirdre.org Tue Jun 11 00:05:06 2002 From: wesc@deirdre.org (wesc@deirdre.org) Date: Mon, 10 Jun 2002 16:05:06 -0700 (PDT) Subject: [Tutor] [ANN] BayPIGgies meeting Wed 6/12 7:30pm Message-ID: <200206102305.QAA28427@alpha.ece.ucsb.edu> What: Python for (Perl) Programmers Who: Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) When: Wednesday, June 12, 2002 Where: Stanford University, Palo Alto, CA Time: 7:30pm - 9pm This is a talk aimed at introducing Python to programmers familar with Perl and other languages, and serves as a warm-up to the full tutorial that will be presented at the O'Reilly Open Source Convention in San Diego near the end of July. Although the non-Python examples use Perl, it's aimed at experienced programmers of all sorts. Our guest speaker is Aahz, long-time active member of the Python community. He has been kicking around the computer industry for more than two decades, doing tech support, programming, consulting, tech writing, and training. Aahz recently signed a book contract for an intermediate-level Python book, which will be published in early 2003. More information + directions: http://deirdre.org/baypiggies/ -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, Š 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://deirdre.org/baypiggies wesley.j.chun :: wesc at deirdre.org cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ From shalehperry@attbi.com Tue Jun 11 00:49:50 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 10 Jun 2002 16:49:50 -0700 (PDT) Subject: [Tutor] parsing--is this right? In-Reply-To: Message-ID: > >> In order to parse this text, I use a counter to count the number >> of open and closed curly brackets. I am following the tutorial in >> doing this. >> >> However, I am wondering if plex does things the wrong way. > > Plex is a tool for breaking the text into "tokens" that are easier to look > at. However, it's not enough. You'll probably want to use a parsing > technique like recursive descent, or use a specialized parser-building > tool. We can talk about it more if you'd like. > > to be more explicit here. plex is a lexer not a parser. the lexer reads input and decides what each piece it sees is. This information is passed to the parser. foo { bar } would result in: word brace word brace being sent to the parser. This is why you find yourself counting, you are implementing a parser based on the tokens the lexer is sending you. From HaakJ@masirv.com Tue Jun 11 00:59:17 2002 From: HaakJ@masirv.com (Jim Haak) Date: Mon, 10 Jun 2002 16:59:17 -0700 Subject: [Tutor] retreiving email file attachments Message-ID: <9C9781ADDB73C549BC4D8E837BF8450E08C5D6@mail-socal01> Does anyone have an example of using poplib to read an Inbox and then passing the messages to the email package? I am trying to parse zipped attachments. I've written low level code using just poplib.POP3 that works fine in most cases, but the RFC variations in the headers makes it difficult to consistently find the attachment boundaries. If I could just get the email module to accept what I'm getting from poplib retr() function.... Since the email module wants a file, I've tried writing all the 'lines' to a file, but that doesn't seem to work. This is probably really easy, but Python is my first and only language experience and I still haven't groked all that class stuff yet. From jeff@ccvcorp.com Tue Jun 11 01:43:48 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon, 10 Jun 2002 17:43:48 -0700 Subject: [Tutor] retreiving email file attachments References: <9C9781ADDB73C549BC4D8E837BF8450E08C5D6@mail-socal01> Message-ID: <3D0547C4.FA0890FD@ccvcorp.com> Jim Haak wrote: > Does anyone have an example of using poplib to read an Inbox and then > passing the messages to the email package? I am trying to parse zipped > attachments. [...] > > Since the email module wants a file, I've tried writing all the 'lines' to a > file, but that doesn't seem to work. I haven't done this myself, but here's some ideas for you to research. The POP3.retr() method returns a tuple, the second member of which is (iirc) a list of lines. You can probably safely discard the other two items. lines = pop.retr(n)[1] You need to feed a file to the email module, but saving all of this to a file would be pointless. The solution is the StringIO (or better yet, cStringIO), which will convert a string into a file-like object. import cStringIO fakefile = cStringIO.StringIO( '\n'.join(lines) ) I use '\n'.join() to convert the list of lines into a single string with newline separators, then feed that to StringIO to create a file-like object. This object is (for most purposes) no different than the object returned by open(filename). You should then be able to give this StringIO object to the email package. Hope that this helps... Jeff Shannon Technician/Programmer Credit International From dman@dman.ddts.net Tue Jun 11 02:52:54 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon, 10 Jun 2002 20:52:54 -0500 Subject: [Tutor] Re: parsing--is this right? In-Reply-To: References: <20020610122037.A26494@localhost.localdomain> Message-ID: <20020611015254.GA15533@dman.ddts.net> --2oS5YaxWCcQjTEyO Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Jun 10, 2002 at 03:02:37PM -0700, Danny Yoo wrote: | On Mon, 10 Jun 2002, Paul Tremblay wrote: |=20 | > I have just stumbled across the concept of parsing and parsing | > grammars, and wondered if I am using the right tool. | > | > I haved downloaded and installed plex in order to parse a rtf | > document. The rtf looks like this: | > | > {\footnote {\i an italicized word} {\i maybe another italicized | > word} text } =20 | > However, I am wondering if plex does things the wrong way. |=20 | Plex is a tool for breaking the text into "tokens" that are easier to look | at. However, it's not enough. You'll probably want to use a parsing | technique like recursive descent, or use a specialized parser-building | tool. We can talk about it more if you'd like. =20 Isn't there some sort of lex/yacc clone for python? lex (or flex, if you use the GNU version) is a lexical analyzer generator for C. It is often used in conjuction with yacc (or bision, if you use the GNU version) which is a "compiler compiler" (for C). (yacc =3D=3D Yet Another Compiler Compiler) The combination of lex and yacc allows rapid development of a flexible and robust parser for your C program. With lex you simply specify regex patterns for identifying the tokens (I think plex is supposed to do the same sort of thing), and those tokens are passed into the "compiler" that yacc generates. You tell yacc what the EBNF (aka CFG, Context-Free Grammar) grammar is of your language and it generates the necessary C code to recognize it from the tokens lex passes it. It's somewhat complicated to try and explain with no prior background, but it's a really neat setup. In one lab, in a matter of hours, a friend and I implemented a calculator using lex and yacc. That calculator was quite flexible, allowed whitespace in various ways (like real tools such as the C compiler or python allow) and allowd C-style comments. Previously I had implemented a similar tool in C++ with a larger group and we spent weeks on it. It had a much stricter use of whitespace because the parser was all hand-coded and didn't use regex at all. The difference between hand-coding your own parser from scratch and using a generated one is significant. If I were you, I would try to find an existing tool if you can. Look for an RTF parser (though I don't think you're likely to find a decent one unless you disassemble MS Word) or a parser generator like lex/yacc. HTH, -D --=20 The wise in heart are called discerning, and pleasant words promote instruction. Proverbs 16:21 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --2oS5YaxWCcQjTEyO Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0FV/UACgkQO8l8XBKTpRQ3yACfY9yjD1yCgHWYadT/TI91xYOq gWUAn18BCF5dcN5wwE4XlookheQh230F =pwPL -----END PGP SIGNATURE----- --2oS5YaxWCcQjTEyO-- From dman@dman.ddts.net Tue Jun 11 02:54:53 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon, 10 Jun 2002 20:54:53 -0500 Subject: [Tutor] Re: Re: Newbie OOP Question.(diff between function, module and class) In-Reply-To: References: <15620.57692.735525.490352@12-248-41-177.client.attbi.com> Message-ID: <20020611015453.GB15533@dman.ddts.net> --LpQ9ahxlCli8rRTG Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Jun 10, 2002 at 04:59:48PM -0500, SA wrote: | On 6/10/02 12:26 PM, "Skip Montanaro" wrote: | > SA> One last question, sorry if this is very basic but I feel these | > SA> terms need better definitions for newbies like me (the only other | > SA> languages I have experience with are Qbasic and HTML) what is a | > SA> namespae? Is that analagous to pwd of the program? For instance, = if | > SA> the program is currently in one are of the script doing work, wou= ld | > SA> that be considered the namespace? | >=20 | > Yes, it is more or less like the filesystem hierarchy. In the current | > directory, a reference to "blue.txt" would reference a file in the curr= ent | > directory. One significant difference is that Python's module/package | > system doesn't have a syntax for referring to the current module's pare= nt | > (no ".."). | | Ahh. Now that may prove interesting. Would it be beneficial to make a | reserved command like .. That pops you back into the parent namespace? import foo bar =3D foo baz =3D foo spam =3D foo What's the parent namespace of module foo? IOW, no. Also, using such a feature would also break good module design. -D --=20 Yes, Java is so bulletproofed that to a C programmer it feels like being in= a straightjacket, but it's a really comfy and warm straightjacket, and the wo= rld would be a safer place if everyone was straightjacketed most of the time. -- Mark 'Kamikaze' Hu= ghes =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --LpQ9ahxlCli8rRTG Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0FWG0ACgkQO8l8XBKTpRRdYQCgsz8wD+CbrM8hUu7+44di3qKD Fi0Ani3CVo+T79QsViNoziA1Lh+uFAn6 =7DBz -----END PGP SIGNATURE----- --LpQ9ahxlCli8rRTG-- From dman@dman.ddts.net Tue Jun 11 03:06:08 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon, 10 Jun 2002 21:06:08 -0500 Subject: [Tutor] Re: Where best to start? First program to: login, read from and close a serial line? In-Reply-To: <20020610062255.51796.qmail@web11802.mail.yahoo.com> References: <20020610062255.51796.qmail@web11802.mail.yahoo.com> Message-ID: <20020611020608.GC15533@dman.ddts.net> --DIOMP1UsTsWJauNi Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, Jun 09, 2002 at 11:22:55PM -0700, Bill Gillespie wrote: | Hi Folks, |=20 | I was very happy to find this resource. I'm a new guy and am just | starting to learn to do some simple programming, and Python is my first | "real programming" language. It's very exciting! |=20 | My first programming project:=20 | At work we have a "floor and oil temperature control system". I would | like to build a simple GUI, allowing us to interrogate, display and | change these two values:=20 |=20 | 1) OIL set point=20 | 2) FLOOR set point |=20 |=20 | The Tkinter (GUI) part looks learnable - but I don't know where to | start in terms of=20 |=20 | --> logging into a remote machine=20 | (in Xterm from a Linux machine - to a sun os machine) What program do you usually use? telnet? ssh? =20 In unix-land it is really easy to piggy back off of stuff like this. For example if you are using telnet, you can open a pipe to it like this : import os tpipe_in , tpipe_out =3D os.popen2( [ "/usr/bin/telnet" , "the.host.name" ]= ) which gives you 2 file-like objects -- tpipe_in and tpipe_out -- which are connected to the stdin and stdout of the telnet program. In this manner your python program can act just a like a person sitting at the machine running telnet. | --> opening a serial line on it | (I normally just type "tip oftc" to connect ) Opening a device (such as a serial port) is easy in unix. I wrote a (simple!) daemon a while ago to log data read from the serial port. To open the serial port, use the_port =3D open( "/dev/ttyS0" , "r+" ) (note: this opens the device on the local machine) If you are using a command that you invoke through telnet, just feed the text through the pipe you opened above. =20 | --> interrogating the embedded device on it, | (two seperate commands ask for current - or order a change) =20 If this is just a mattter of sending some text (command) and then reading the output (text) back, just use the pipe you opened above. It's as simple as working with plain old files on the local disk. =20 | --> and then logging out again. | ($. closes the connection) then I log out of the machine) Send the sequence "$.\n" to the pipe's input, send the logout command, and close both ends of the pipe. =20 | Any advice on the general idea of what should take place will be most | welcome.=20 Unix was well designed around the use of files and pipes. Working with a pipe is just as easy as working with any other file, and so is working with various devices (such as the serial port) and network sockets. Read some UNIX texts on pipes and files to get a better handle on that. I would start with a simple console-based system. You could have it be interactive, or even just too dumb to do more than one thing. Experiment with it and see how to get everything working and how to do decent error handling. As you get a better handle on that, build it up to having a full GUI or whatever is actually necessary. (GUI's are complex, and if you can keep it down to a simple command line you'll be better off, IMO) =20 HTH, -D --=20 An anxious heart weighs a man down, but a kind word cheers him up. Proverbs 12:25 =20 GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --DIOMP1UsTsWJauNi Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0FWxAACgkQO8l8XBKTpRQbmQCgk+kf/7MbGH7nefKPv3+QZACr N+0An0zLY3FDf4wv1USlUh02XJvnlGSt =n5pW -----END PGP SIGNATURE----- --DIOMP1UsTsWJauNi-- From phthenry@earthlink.net Tue Jun 11 04:21:15 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon, 10 Jun 2002 23:21:15 -0400 Subject: [Tutor] parsing--is this right? In-Reply-To: References: <20020610122037.A26494@localhost.localdomain> Message-ID: <20020610232114.D26494@localhost.localdomain> On Mon, Jun 10, 2002 at 03:02:37PM -0700, Danny Yoo wrote: > > Hmmm... if the structure is always described by braces, perhaps it might > be easier to do a "recursive descent" parse through the message. Here's a > sample parser that shows how the technique works. > First, thanks for your post, and thanks also to Sean and Derrick. Sean made a nice distinction between a parser and lexer. Derrick suggested I used a parser already written. In fact, I haven't been able to find a parser in python to parse rtf. The only thing I found was in java, a nice utility called majix. However, for some bizzare reason, this utility eliminates footnotes rather than tag them. Danny, I had a few questions about how all this code works. Keep in mind I'm new to python. I see that you pass a list of tokesn to the parser method in the class chunk. (1)I don't understand how this method continues to read each item in the list. (2) I don't understand why you don't have to create an object first to use this method. (3) I don't understand how you can call on the Chunk method, when it is the name of a class. (4) I don't understand how this code would work if the tokens were broken over lines. I guess you could read the file in as lines and set your example text to lines. I posted my code written in plex a few emails ago with the subject "rtf to xml regexp question." Despite having to count brackets, this code is easier for me to understand. It seems that my code lets the lexer do most of the dirty work. > I've had some experience with the SPARK parser, and it's a nice tool: > > http://pages.cpsc.ucalgary.ca/~aycock/spark/ > > I used it a while back when I was playing with Pythonica, and it seemed to > work very well. The only caveat I could make was that, back then, if > there was an error in the grammar, SPARK wouldn't give good error > messages. I'm not sure if this complaints can be made now: perhaps this > has been fixed. > > > > Another parser that I've heard good things about is Amit Patel's YAPPS > parser: > > http://theory.stanford.edu/~amitp/Yapps/ > > > Yes, I've heard some good things about SPARK. I couldn't find any documentation on it, though! I also found a good parser called simpleparse, which is based on the module written in C called mxTextTools. Simpleparse has a very nice interface. However, I got an error message when using code straight from a tutorial. There is acutally a python special interest group (sig) just for parsing. It was established in Feburary, and only one person has posted to it. Thanks! Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From sarmstrong13@mac.com Tue Jun 11 04:47:38 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 10 Jun 2002 22:47:38 -0500 Subject: [Tutor] CGI Question. Message-ID: Is there a way to capture when the user clicks a link in a web page? In other words, If the link in a python generated web page was actually a variable that when clicked calls another function in the program that displays some pre-formatted text? I know an anchor will call the linked page in HTML, but what I'm wanting to do is set up a cgi script that displays text in the body of the web page depending upon a link that is clicked, but handle all of the variables within the python cgi script instead of coding a bunch of HTML pages and linking them all. Thanks. SA From mikew@screaminet.com Tue Jun 11 00:42:10 2002 From: mikew@screaminet.com (Tinman) Date: Mon, 10 Jun 2002 18:42:10 -0500 Subject: [Tutor] loop problem Message-ID: <3D053952.4090709@screaminet.com> I've been reading Alan's book on learning to program with Python. I'm currently working with the chapter on loops. I have an idea for a loop that I can't quite figure out. This is what I want to do. 1.Multiply 1 by 2 2.Take the result and multiply by 2 3.So on and so on thirty times 4.Print the final result I tried this: for i in range(1,31): b = i * 2 print b This prints 1 -30 times 2 as I'm sure you can tell. I can't figure out how to take each result an double it. Can anyone help a hapless Python newbie? From shalehperry@attbi.com Tue Jun 11 06:26:52 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon, 10 Jun 2002 22:26:52 -0700 (PDT) Subject: [Tutor] loop problem In-Reply-To: <3D053952.4090709@screaminet.com> Message-ID: On 10-Jun-2002 Tinman wrote: > I've been reading Alan's book on learning to program with Python. I'm > currently working with the chapter on loops. I have an idea for a loop > that I can't quite figure out. This is what I want to do. > > 1.Multiply 1 by 2 > 2.Take the result and multiply by 2 > 3.So on and so on thirty times > 4.Print the final result > > I tried this: > > for i in range(1,31): > b = i * 2 > print b > > This prints 1 -30 times 2 as I'm sure you can tell. I can't figure out > how to take each result an double it. Can anyone help a hapless Python > newbie? > total = 2 # total starts at 1 * 2 for i in range(2,31): # start at 2 total = total * 2 print total is this what you mean? From dylan.belsey@baesystems.com Tue Jun 11 06:35:08 2002 From: dylan.belsey@baesystems.com (BELSEY, Dylan) Date: Tue, 11 Jun 2002 15:05:08 +0930 Subject: [Tutor] loop problem Message-ID: <86C3892A0C52D411AF5000A0C9EAA3B963207C@wtntex1.baea.com.au> I don't have Alan's book to see what you are referring to but have a look at the following. I think it is a solution. From what I can ascertain, you are trying to find the result for 2^30 = 1073741824 ?? The following code should do it. You don't have to use the index of the for loop and must reset "b" at the start. Also, if you only want the final result then print outside the loop. Hope this helps. PS: just observed that Sean Perry had the same idea!! >>> b = 1 >>> for i in range(1,31): b = b*2 print b 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864 134217728 268435456 536870912 1073741824 >>> -----Original Message----- From: Tinman [mailto:mikew@screaminet.com] Sent: Tuesday, 11 June 2002 09:42 To: tutor@python.org Subject: [Tutor] loop problem I've been reading Alan's book on learning to program with Python. I'm currently working with the chapter on loops. I have an idea for a loop that I can't quite figure out. This is what I want to do. 1.Multiply 1 by 2 2.Take the result and multiply by 2 3.So on and so on thirty times 4.Print the final result I tried this: for i in range(1,31): b = i * 2 print b This prints 1 -30 times 2 as I'm sure you can tell. I can't figure out how to take each result an double it. Can anyone help a hapless Python newbie? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From pydan@danshafer.com Tue Jun 11 09:02:33 2002 From: pydan@danshafer.com (Dan Shafer) Date: Tue, 11 Jun 2002 01:02:33 -0700 Subject: [Tutor] Creating an Identifier or Object Name from a String? Message-ID: <5.1.0.14.0.20020611005842.029526e0@mail.hurrah.com> I have a need to refer to a number of objects which have been named field1, field2, field3, etc. I want to set a property in each object in a loop. I thought this should work: for ct in range(1,4): objToUpdate = "field" + str(ct) objToChange = eval(objToUpdate) # seems like it should produce "field1" first time through the loop, etc. objToChange.text = inputList[ct] #inputList is generated prior to entering the loop and is a list of string values This produces an error indicating that string objects don't have a text attribute. So clearly objToChange is still a string at this point. I suspect this is tricky but if someone could help.... Dan Shafer, Chief Scribe and Tablet Keeper PythonCard Open Source Project http://pythoncard.sourceforge.net From dyoo@hkn.eecs.berkeley.edu Tue Jun 11 09:10:04 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 11 Jun 2002 01:10:04 -0700 (PDT) Subject: [Tutor] Creating an Identifier or Object Name from a String? In-Reply-To: <5.1.0.14.0.20020611005842.029526e0@mail.hurrah.com> Message-ID: On Tue, 11 Jun 2002, Dan Shafer wrote: > I have a need to refer to a number of objects which have been named > field1, field2, field3, etc. I want to set a property in each object in > a loop. Instead of having them as separate variables, is it possible to keep them grouped together in a list or dictionary? That way, it's easier to work with them as a group, without the complexities of eval(). > I thought this should work: > > for ct in range(1,4): > objToUpdate = "field" + str(ct) > objToChange = eval(objToUpdate) # seems like it should produce > "field1" first time through the loop, etc. > objToChange.text = inputList[ct] #inputList is generated prior to > entering the loop and is a list of string values So since your inputList is already a list, that may be a good hint that symmetry will help. *grin* Try something like: ### objects = [field1, field2, field3] ### Add as many objects as you ### have for i in range(len(objects)): objects[i].text = inputlist[i] ### But I didn't see anything obviously wrong with your initial approach. One suggestion would be to check the value of field1, field2, field3, right before the loop. Also, if you can show us the literal error message, that may give more clues as to why it's doing weird things. From glingl@aon.at Tue Jun 11 09:35:47 2002 From: glingl@aon.at (Gregor Lingl) Date: Tue, 11 Jun 2002 10:35:47 +0200 Subject: [Tutor] Creating an Identifier or Object Name from a String? References: <5.1.0.14.0.20020611005842.029526e0@mail.hurrah.com> Message-ID: <3D05B663.B87BF27@rg16.asn-wien.ac.at> I Tried it and it worked (?!) Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> class K: pass >>> field1 = K() >>> field2 = K() >>> field3 = K() >>> for ct in range(1,4): obj="field"+str(ct) objTC=eval(obj) objTC.text=['a','b',str(ct)] >>> field1.text ['a', 'b', '1'] >>> field2.text ['a', 'b', '2'] >>> field3.text ['a', 'b', '3'] >>> Gregor Dan Shafer schrieb: > I have a need to refer to a number of objects which have been named field1, > field2, field3, etc. I want to set a property in each object in a loop. > > I thought this should work: > > for ct in range(1,4): > objToUpdate = "field" + str(ct) > objToChange = eval(objToUpdate) # seems like it should produce > "field1" first time through the loop, etc. > objToChange.text = inputList[ct] #inputList is generated prior to > entering the loop and is a list of string values > > This produces an error indicating that string objects don't have a text > attribute. So clearly objToChange is still a string at this point. > > I suspect this is tricky but if someone could help.... > > Dan Shafer, Chief Scribe and Tablet Keeper > PythonCard Open Source Project > http://pythoncard.sourceforge.net > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alex@gabuzomeu.net Tue Jun 11 11:03:11 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Tue, 11 Jun 2002 12:03:11 +0200 Subject: [Tutor] parsing--is this right? In-Reply-To: <20020611032902.22231.72658.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020611115152.00d80180@pop3.norton.antivirus> Hi Paul, At 23:29 10/06/2002 -0400, you wrote: >Date: Mon, 10 Jun 2002 23:21:15 -0400 >From: Paul Tremblay >Subject: Re: [Tutor] parsing--is this right? [Parsing RTF data:] >Sean made a nice distinction between a parser and lexer. Derrick >suggested I used a parser already written. In fact, I haven't >been able to find a parser in python to parse rtf. You may want to look at these references: http://www.foretec.com/python/workshops/1998-11/tut_com.html http://starship.python.net/crew/pirx/spam7/ There is a short RTF parser example in Python in the downloadable slideshow. Cheers. Alexandre From alan.gauld@bt.com Tue Jun 11 14:09:36 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 11 Jun 2002 14:09:36 +0100 Subject: [Tutor] Newbie Q's Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C644@mbtlipnt02.btlabs.bt.co.uk> > I have two quick questions for you. First, if I have a > list made up of integers, is there a simple command to > let me find the sum of the integers (and assign the > value to a variable)? The most direct way is with a loop: result = 0 for num in numlist: result += num Or using Pythons reduce function: result = reduce(operator.add, numlist) Which does the same thing. > The biggest difficulty I'm having is dealing with > aces, which can be valued at 1 or 11. I thought I had > everything figured out, until a hand came up that had > two aces in it :-) I'm sure many people have tried > making this kind of a program. How did you (or would > you) deal with this aspect of the program? Special cases need special code. For blackjack you would count the Ace as 11 if the total was <= 21 else count them as 1... So something like the following untested code: def AddCards(cardlist): tot = reduce(operator.add, cardlist) if tot > 21: #too high while 11 in cardlist: #do we have high aces? if tot-10 <= 21: # total too high so use low ace pos = cardist.index(11) cardlist[pos] = 1 # change from 11 to 1 tot = reduce(operator.add, cardlist) return tot Theres probably a neater way but that might help... Alan g From alan.gauld@bt.com Tue Jun 11 14:16:43 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 11 Jun 2002 14:16:43 +0100 Subject: [Tutor] Re: Newbie OOP Question. (diff between function, modu le and class) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C645@mbtlipnt02.btlabs.bt.co.uk> > > system doesn't have a syntax for referring to the current > module's parent > > (no ".."). > Ahh. Now that may prove interesting. Would it be beneficial to make a > reserved command like .. That pops you back into the parent namespace? There is sort of its the global statement: z = 42 def f(x): z = 2*x return z This creates a new z with value twice x. If we really want to access the external(global z) we can do so like this: def f(x): global z z = 2*x return z Now we modify the external z instead of creating a new one. Generally this is a bad idea and you should pass the value into the function for modification: def f(x,y): y = 2*x return y But this still doesn't change the global z even if we pass it in as y, we have to assign the result: z = f(5,z) This now modifies global z asnd makes its value available to the function(as the parameter y). HTH, Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From marcolinux@linuxbr.com.br Tue Jun 11 13:50:11 2002 From: marcolinux@linuxbr.com.br (Marc) Date: Tue, 11 Jun 2002 09:50:11 -0300 Subject: [Tutor] Newbie Q's In-Reply-To: <20020610215217.25441.qmail@web20505.mail.yahoo.com> References: <20020610215217.25441.qmail@web20505.mail.yahoo.com> Message-ID: <20020611095011.A11084@marcolab.proconet> Alan Colburn (aicolburn@yahoo.com) wrote: > Second, as a way to practice what I've started > learning, I decided to try making a > (non-graphical)Blackjack game. I've got it set up so > that when cards are drawn from a deck, they go into a > list (one for the player, one for the dealer). (That's > where my question above comes from.) Hi Alan. This link might be of your interest: http://www.ibiblio.org/obp/thinkCSpy/chap15.htm Hope it helps. .:: Marcolinux ::. From lonetwin@subdimension.com Tue Jun 11 14:28:05 2002 From: lonetwin@subdimension.com (lonetwin_SubD) Date: Tue, 11 Jun 2002 18:58:05 +0530 Subject: [Tutor] Tk question Message-ID: <20020611132805.B15372F4C6@mercury.sapatmt> Hi ppl, For convenience sake, I wrote a wrapper around the 'cal' command on my linux box (and bound it to a shortcut keystroke on my Window manager). There is one problem tho', I just can't figure out how to get the first and last lines aligned properly. I tried passing anchor="w" while initialising the Label but that does not seem to help .....any pointers ?? Here's the code (maybe someone else might find it useful too :)). Note : I specifically set the font to "fixed" b'cos with variable width fonts spaces are "thinner" than characters and that screws up the display. --------------------------------------- #!/usr/bin/python import os cal="/usr/bin/cal.orig" args = ''.join(os.sys.argv[1:]) out = os.popen('%s %s' % (cal, args)).read() if os.environ.has_key('DISPLAY'): from Tkinter import * Master = Frame() Master.master.title("Tkcal") Sub = Label(Master, font='fixed', text=out) Master.grid(ipadx=2, ipady=2) Sub.grid() Master.mainloop() else: print out ---------------------------------------- Peace Steve PS: Maybe you are wondering why I did this, well I can only say that I find myself using the keyboard 95% of the time when in windowmaker (my preferred wm). Also, I've got a similar (shortcut) "front-end" to "ispell -a", I'll send it across if anybody is interested. -- The prettiest women are almost always the most boring, and that is why some people feel there is no God. -- Woody Allen, "Without Feathers" From jeff@ccvcorp.com Tue Jun 11 17:59:07 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 11 Jun 2002 09:59:07 -0700 Subject: [Tutor] Newbie Q's References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C644@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3D062C5B.58EE422E@ccvcorp.com> alan.gauld@bt.com wrote: > > The biggest difficulty I'm having is dealing with > > aces, which can be valued at 1 or 11. I thought I had > > everything figured out, until a hand came up that had > > two aces in it :-) > Special cases need special code. For blackjack you would > count the Ace as 11 if the total was <= 21 else count them > as 1... > So something like the following untested code: > > def AddCards(cardlist): > tot = reduce(operator.add, cardlist) > if tot > 21: #too high > while 11 in cardlist: #do we have high aces? > if tot-10 <= 21: # total too high so use low ace > pos = cardist.index(11) > cardlist[pos] = 1 # change from 11 to 1 > tot = reduce(operator.add, cardlist) > return tot It seems to me that this code will also cause problems if there are two aces. :) This will reduce *all* aces in the hand to 1, not just enough of them to drop the score just below 21. Also, it's not really necessary to check whether switching the ace from high to low will drop the total below 21 -- ISTM that any high ace should be converted to low before declaring the hand busted. Perhaps something like this would work better... def AddCards(cardlist): tot = reduce(operator.add, cardlist) while tot > 21 and 11 in cardlist: pos = cardlist.index(11) cardlist[pos] = 1 tot = reduce(operator.add, cardlist) return tot This is still not terribly efficient ('value in list' and list.index() are slow for large lists), but should be good enough for a blackjack game (which would not have large lists or too terribly strict speed requirements ;) ). One thing that could speed it up would be to combine the two searches: def AddCards(cardlist): tot = reduce(operator.add, cardlist) while tot > 21: pos = cardlist.index(11) # returns the index, or -1 if not found if pos >= 0: cardlist[pos] = 1 tot = reduce(operator.add, cardlist) else: break # exit 'while' if there are no high aces return tot I'm sure that further improvements are possible (such as eliminating the multiple reduce() calls), but this should be good enough for now. :) Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Tue Jun 11 17:57:21 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 11 Jun 2002 17:57:21 +0100 Subject: [Tutor] loop problem Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C64C@mbtlipnt02.btlabs.bt.co.uk> > 1.Multiply 1 by 2 > 2.Take the result and multiply by 2 > 3.So on and so on thirty times > 4.Print the final result > First, thanks for the well stated problem specification, it always helps :-) > I tried this: > b = 1 # initialise b > for i in range(1,31): > b = i * 2 # replace this with b = b * 2 > print b Should work. Just use the range to count the number of iterations but the number to multiply is b not i. (Try renaming b to result and see if it becomes clearer - using variable names that match your problem statement is usally a good dea - check the chapter on Style. BTW Your function just works out the 30th power of two so the same end result comes (faster) from: print pow(2,30) But that doesn't display intermediate values or teach you about loops ;-) Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From skip@pobox.com Tue Jun 11 14:35:39 2002 From: skip@pobox.com (Skip Montanaro) Date: Tue, 11 Jun 2002 08:35:39 -0500 Subject: [Tutor] Re: Newbie OOP Question. (diff between function, modu le and class) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C645@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C645@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <15621.64683.637593.221998@12-248-41-177.client.attbi.com> skip> system doesn't have a syntax for referring to the current module's skip> parent (no ".."). sa> Ahh. Now that may prove interesting. Would it be beneficial to make sa> a reserved command like .. That pops you back into the parent sa> namespace? alan> There is sort of its the global statement: Not quite what I was referring to (I was equating module namespaces and file system directories), but I agree, in the context of a function the global statement does "pop you up" one level. Skip From dyoo@hkn.eecs.berkeley.edu Tue Jun 11 18:19:00 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 11 Jun 2002 10:19:00 -0700 (PDT) Subject: [Tutor] parsing--is this right? In-Reply-To: <20020610232114.D26494@localhost.localdomain> Message-ID: On Mon, 10 Jun 2002, Paul Tremblay wrote: > I see that you pass a list of tokesn to the parser method in the class > chunk. > [some text cut and moved around] > > (2) I don't understand why you don't have to create an object first to > use this method. > > (3) I don't understand how you can call on the Chunk method, when > it is the name of a class. Hi Paul: Actually, the parse() function is meant to be standalone: it's not a method. I'm only using Chunk() to group the data together, and to make it easier to extract the command type later on. > (4) I don't understand how this code would work if the tokens were > broken over lines. I guess you could read the file in as lines and set > your example text to lines. As long as we first do all of the tokenization before parsing, we should be ok. In many cases, we want to break down this parsing task into two tasks: 1. Breaking our text file into a bunch of recognizable tokens 2. Figuring out the structure between those tokens. By breaking it down this way, both tasks can become simpler. The rtf parser I wrote only recognizes two categories of tokens: the beginning of boundaries (brackets "{}"), and everything else. Since it groups these tokens into those two categories, it doesn't have to worry about newlines. That's why a lot of parsers are paired together with tokenizers, so that the parser can avoid thinking about content, and concentrate more on categories. > (1)I don't understand how this method continues to read each item in the > list. This parser progressively eats more and more of the tokens by using the pop() method of lists. It simultaneously removes an element from our tokens list, and returns that element back to us. For example: ### >>> tokens = ['hello', 'world', 'this', 'is', 'a', 'test'] >>> tokens.pop(0) 'hello' >>> tokens.pop(0) 'world' >>> tokens.pop(0) 'this' >>> tokens.pop(0) 'is' >>> tokens.pop(0) 'a' >>> tokens.pop(0) 'test' >>> tokens.pop(0) Traceback (most recent call last): File "", line 1, in ? IndexError: pop from empty list ### If it helps, I can try simplifying the parser a little more for clarity. We can get rid of Chunk() class stuff altogether, and break up that parse() function into two pieces to make its intent a little clearer. ### import re def parse(tokens): """Parses one thing, given a source of tokens. That one thing can be either a single piece of text, or a bracketed list.""" if tokens[0] == '{': return parseList(tokens) ## Case 1 else: return tokens.pop(0) ## Case 2 def parseList(tokens): """To parse a bracketed list, continue parsing the rest of the token stream until we hit the end of the bracketed list.""" tokens.pop(0) ## Eat the leading bracket. collected_pieces = [] while tokens[0] != '}': collected_pieces.append(parse(tokens)) tokens.pop(0) ## Eat the closing bracket. return collected_pieces def tokenize(text): def nonEmpty(thing): return len(thing.strip()) > 0 return filter(nonEmpty, re.split(r'(\{|\}|\s)', text)) ### Please feel free to ask more questions! Good luck to you. From rickp@telocity.com Tue Jun 11 18:44:07 2002 From: rickp@telocity.com (Rick Pasotto) Date: Tue, 11 Jun 2002 13:44:07 -0400 Subject: [Tutor] Tk question In-Reply-To: <20020611132805.B15372F4C6@mercury.sapatmt> References: <20020611132805.B15372F4C6@mercury.sapatmt> Message-ID: <20020611174406.GA21236@tc.niof.net> Add a justify option to your call to Label(): Sub = Label(Master, font='fixed', text=out, justify=LEFT) On Tue, Jun 11, 2002 at 06:58:05PM +0530, lonetwin_SubD wrote: > Hi ppl, > For convenience sake, I wrote a wrapper around the 'cal' command on my > linux box (and bound it to a shortcut keystroke on my Window manager). There > is one problem tho', I just can't figure out how to get the first and last > lines aligned properly. I tried passing anchor="w" while initialising the > Label but that does not seem to help .....any pointers ?? > > Here's the code (maybe someone else might find it useful too :)). > > Note : I specifically set the font to "fixed" b'cos with variable width fonts > spaces are "thinner" than characters and that screws up the display. > > --------------------------------------- > #!/usr/bin/python > import os > > cal="/usr/bin/cal.orig" > args = ''.join(os.sys.argv[1:]) > out = os.popen('%s %s' % (cal, args)).read() > > if os.environ.has_key('DISPLAY'): > from Tkinter import * > Master = Frame() > Master.master.title("Tkcal") > Sub = Label(Master, font='fixed', text=out) > Master.grid(ipadx=2, ipady=2) > Sub.grid() > Master.mainloop() > else: > print out > ---------------------------------------- > > Peace > Steve > > PS: Maybe you are wondering why I did this, well I can only say that I find > myself using the keyboard 95% of the time when in windowmaker (my preferred > wm). Also, I've got a similar (shortcut) "front-end" to "ispell -a", I'll > send it across if anybody is interested. > > -- > The prettiest women are almost always the most boring, and that is why > some people feel there is no God. > -- Woody Allen, "Without Feathers" > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- "Life is like an over long drama through which we sit being nagged by the vague memories of having read the reviews." -- John Updike Rick Pasotto rickp@telocity.com http://www.niof.net From HaakJ@masirv.com Tue Jun 11 19:30:06 2002 From: HaakJ@masirv.com (Jim Haak) Date: Tue, 11 Jun 2002 11:30:06 -0700 Subject: [Tutor] retreiving email file attachments Message-ID: <9C9781ADDB73C549BC4D8E837BF8450E08C5DD@mail-socal01> Jeff, Thanks very much. That works great. Jim Haak *-----Original Message----- *From: Jeff Shannon [mailto:jeff@ccvcorp.com] *Sent: Monday, June 10, 2002 5:44 PM *To: Jim Haak *Cc: 'tutor@python.org' *Subject: Re: [Tutor] retreiving email file attachments * * * * *Jim Haak wrote: * *> Does anyone have an example of using poplib to read an Inbox and then *> passing the messages to the email package? I am trying to *parse zipped *> attachments. [...] *> *> Since the email module wants a file, I've tried writing all *the 'lines' to a *> file, but that doesn't seem to work. * *I haven't done this myself, but here's some ideas for you to research. * *The POP3.retr() method returns a tuple, the second member of *which is (iirc) a *list of lines. You can probably safely discard the other two items. * *lines = pop.retr(n)[1] * *You need to feed a file to the email module, but saving all of *this to a file *would be pointless. The solution is the StringIO (or better *yet, cStringIO), *which will convert a string into a file-like object. * *import cStringIO *fakefile = cStringIO.StringIO( '\n'.join(lines) ) * *I use '\n'.join() to convert the list of lines into a single *string with newline *separators, then feed that to StringIO to create a file-like *object. This *object is (for most purposes) no different than the object returned by *open(filename). You should then be able to give this StringIO *object to the *email package. * *Hope that this helps... * *Jeff Shannon *Technician/Programmer *Credit International * * * From phthenry@earthlink.net Tue Jun 11 19:55:47 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue, 11 Jun 2002 14:55:47 -0400 Subject: [Tutor] parsing--is this right? In-Reply-To: References: <20020610232114.D26494@localhost.localdomain> Message-ID: <20020611145546.A31120@localhost.localdomain> On Tue, Jun 11, 2002 at 10:19:00AM -0700, Danny Yoo wrote: > > Actually, the parse() function is meant to be standalone: it's not a > method. I'm only using Chunk() to group the data together, and to make > it easier to extract the command type later on. Ah, I missed these lines in your original code: new_chunk = Chunk('text', tokens.pop(0)) return new_chunk new_chunk is your object. Yes, the parser by itself is not part of the Chunk class. (Part of the confusion has to do with how indentation marks different parts of code in python, a feature that first caused me to go "yuck," but one which I now love. When reading someone else's code, there is a tendancy to miss what is nested.) One of the confusing things for me is that in your code, a function calls itself. This makes me really think. I doubt there is another way to write this code, since the text being tokenized has a nested structure. Let me repeat: this makes me think! It is more complicated than the normal way I program which is to get a chunk of text, send it to some subroutine, get another chunk, send it to another subroutine. Nonetheless, looking at the code, I see exactly how it works. > > The rtf parser I wrote only recognizes two categories of tokens: the > beginning of boundaries (brackets "{}"), and everything else. Since it > groups these tokens into those two categories, it doesn't have to worry > about newlines. That's why a lot of parsers are paired together with > tokenizers, so that the parser can avoid thinking about content, and > concentrate more on categories. > Okay, so from here how would you change this text? I would want it to look like this: an italicized word maybe another italicized word text > > > (1)I don't understand how this method continues to read each item in the > > list. I understood how pop worked, but I didn't see how your code kept using pop, because I didn't see how the routine called on itself. Last question: How doe lexers (or parsers?) like plex or SPARK fit into our model? In actuality, I simlified my problem, though not by too much. A more represenative implementation of rtf colde looks like this: 1 \pard\plain This is normal text 2 \par 3 \pard\plain 4 \pard\plain \s1\fi720 this text has an assigned style"\par 5 \pard\plain Now a footnote. As Schmoo said "Be 6 great!"{\fs18\up6 \chftn {\footnote \pard\plain \s246 \fs20 7 {\fs18\up6 \chftn }footnote at bottom of page}}\par The above text uses the delimeters "\pard" to mark a paragraph style. If the word documents has used a style, then the next bit of information, the \s1 found in the fourth line, tells what typye of informatin the paragraph contains. For example, in microsoft word, you might have called all paragraphs that indent 1 inch a "block" style. You might call all paragrahs that contain quotes a "quote" style. Microsoft word lables them \s1, and \s2, or "style 1" , "style2." Hence, the TYPE now becomes \pard \s1. We need to know when this style ends and a new one begins. Rtf says that a new style begins when you encounter another \pard delimter. There is an exception: if this \pard delimeter is within a footnote, the previous style has not terminated. So our model becomes more complicated. However, the plex lexer would handle this simplified model easily. As you probably know from using SPARK, you can set states in the lexer. Hence, once the lexer is in the "footnote" state, it treats the delimeter \pard totally different than it would if it found it outside of the state. I'm not necessarily looking for a specific solution here; I am just trying to learn about parsers. Thanks for your help! Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From phthenry@earthlink.net Tue Jun 11 20:01:26 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue, 11 Jun 2002 15:01:26 -0400 Subject: [Tutor] parsing--is this right? In-Reply-To: <4.3.2.7.2.20020611115152.00d80180@pop3.norton.antivirus> References: <20020611032902.22231.72658.Mailman@mail.python.org> <4.3.2.7.2.20020611115152.00d80180@pop3.norton.antivirus> Message-ID: <20020611150126.B31120@localhost.localdomain> On Tue, Jun 11, 2002 at 12:03:11PM +0200, Alexandre Ratti wrote: > You may want to look at these references: > > http://www.foretec.com/python/workshops/1998-11/tut_com.html > http://starship.python.net/crew/pirx/spam7/ > > There is a short RTF parser example in Python in the downloadable slideshow. This web page states that COM can only be used on windows, which does me no good because I use linux. . The slideshow is in powerpoint, which I can't view. There is a self-executing program which I downloaded, but this again only runs on windows. It seems a bit odd that a python programmer would chose a proprietary source to display his tutorial. Why not use html or pdf? Thanks anyway Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From pythontutor@venix.com Tue Jun 11 20:33:06 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Tue, 11 Jun 2002 15:33:06 -0400 Subject: [Tutor] parsing--is this right? References: <20020611032902.22231.72658.Mailman@mail.python.org> <4.3.2.7.2.20020611115152.00d80180@pop3.norton.antivirus> <20020611150126.B31120@localhost.localdomain> Message-ID: <3D065072.8000505@venix.com> I saved the .PPT as an RTF file. Hopefully, that will work for you. http://www.tpk.net/~lkvam/xsuo9du4.rtf Let me know when you have gotten it and I will clear it off the server. Paul Tremblay wrote: > On Tue, Jun 11, 2002 at 12:03:11PM +0200, Alexandre Ratti wrote: > > >>You may want to look at these references: >> >>http://www.foretec.com/python/workshops/1998-11/tut_com.html >>http://starship.python.net/crew/pirx/spam7/ >> >>There is a short RTF parser example in Python in the downloadable slideshow. >> > > This web page states that COM can only be used on windows, which > does me no good because I use linux. . The slideshow is in > powerpoint, which I can't view. There is a self-executing > program which I downloaded, but this again only runs on > windows. > > It seems a bit odd that a python programmer would chose a > proprietary source to display his tutorial. Why not use html or > pdf? > > Thanks anyway > > Paul > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dman@dman.ddts.net Tue Jun 11 21:22:27 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Tue, 11 Jun 2002 15:22:27 -0500 Subject: [Tutor] Re: parsing--is this right? In-Reply-To: <20020611145546.A31120@localhost.localdomain> References: <20020610232114.D26494@localhost.localdomain> <20020611145546.A31120@localhost.localdomain> Message-ID: <20020611202227.GB28144@dman.ddts.net> --JYK4vJDZwFMowpUq Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, Jun 11, 2002 at 02:55:47PM -0400, Paul Tremblay wrote: =20 | One of the confusing things for me is that in your code, a | function calls itself. This is a programming style/technique known as recursion. Recursion is really effective when the problem can be defined in terms of itself. Parsing nested structures (the {} in your RTF) is well suited for recursion (and hence the name 'recursive descent' parser). Another example of recursion is the factorial operation. n! =3D n * n-1 * n-2 * ... * 2 * 1 The "..." can be shown with recursion : def fact( n ) : if n =3D=3D 1 : return 1 else: return n * fact( n-1 ) Of course, for factorial, a faster implementation can be devised, but the most natural definition of it is recursive. (don't try this fact() on anything other than an integer >=3D 1 otherwise you'll get some bad results :-)) -D --=20 "...the word HACK is used as a verb to indicate a massive amount of nerd-like effort." -Harley Hahn, A Student's Guide to Unix =20 Jabber ID : dman@dman.ddts.net GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --JYK4vJDZwFMowpUq Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0GXAMACgkQO8l8XBKTpRQYRACffh49CdNjFAz/blTkXxNx+Nm8 18EAnAl4gF1qSCBgBHXe6ACXDdmoOQxO =OmJL -----END PGP SIGNATURE----- --JYK4vJDZwFMowpUq-- From dyoo@hkn.eecs.berkeley.edu Tue Jun 11 22:06:57 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 11 Jun 2002 14:06:57 -0700 (PDT) Subject: [Tutor] parsing--is this right? In-Reply-To: <20020611145546.A31120@localhost.localdomain> Message-ID: > Okay, so from here how would you change this text? I would want it to > look like this: > > an italicized word maybe another > italicized word text Ah! Let's say that the parsing went perfectly, and somehow we have a function that transforms the string: ### >>> EXAMPLE_TEXT = r"""{\footnote {\i an italicized word} {\i ... maybe another italicized word} text }""".replace('\n', ' ') >>> parsed_doc = parse(tokenize(EXAMPLE_TEXT)) >>> parsed_doc ['\\footnote', ['\\i', 'an', 'italicized', 'word'], ['\\i', 'maybe', 'another', 'italicized', 'word'], 'text'] ### In our parsed document, each command is the first element in a list. This representation is nice because it mirrors the nested nature of the tags: lists can contain inner lists. How do we go from EXAMPLE_TEXT to a marked-up string? We might want to add XML tags for whenever we see a list. Here's an initial attempt to do this: ### def toXML(structure): if type(structure) == type([]): tag = structure[0][1:] ## secondary slice removes leading '/' text_pieces = [str(s) for s in structure[1:]] return "<%(tag)s>%(text)s" % \ { 'tag' : tag, 'text' : ''.join(text_pieces) } else: return str(structure) ### Let's see how it works: ### >>> print toXML(parsed_doc) ['\\i', 'an', 'italicized', 'word']['\\i', 'maybe', 'another', 'italicized', 'word']text ### Almost. The only problem is that it only transformed the very outer layer of this onion, but we want to permeate the whole structure with tags. Although we hate to hurt it's feelings, we have to say the truth: toXML() is "shallow". The section that transformed the stuff in between the tags was the statement: text_pieces = [str(s) for s in structure[1:]] And this is the source of the shallowness: we're just calling str(). But instead of directly calling str() on each piece in between, the trick is to apply toXML() again to each inner piece! That way, we guarantee that the inner lists are also transformed properly: ### >>> def toXMLDeeply(structure): ... if type(structure) == type([]): ... tag = structure[0][1:] ## secondary slice removes leading '/' ... text_pieces = [toXML(s) for s in structure[1:]] ... return "<%(tag)s>%(text)s" % \ ... { 'tag' : tag, ... 'text' : ''.join(text_pieces) } ... else: ... return str(structure) ... >>> print toXMLDeeply(parsed_doc) anitalicizedwordmaybeanotheritalicizedwordtext ### The transformation wasn't perfect, because my parsing step had wiped out whitespace in my parsed_doc, so that needs to be fixed. Still, it almost works. *grin* This is another example of a recursive function, so this might seem like a weird little function at first. I have to go at the moment, but I'll try looking at your other question later. Talk to you soon! From GBunting864@Worldsavings.com Tue Jun 11 22:09:16 2002 From: GBunting864@Worldsavings.com (Bunting, Glen, IG) Date: Tue, 11 Jun 2002 14:09:16 -0700 Subject: [Tutor] zipfile module Message-ID: <3BD366A4D49B7D4FAD4E41E4C99784B9A90FD0@OK1EMS2.worldsavings.com> Hi,=20 I am trying to figure out how to use the zipfile module so I can use it to = unzip some text files and zip them back up again after some text processing= has happened. The documentation that I have found is very minimal for thi= s module. Can someone show me how it is supposed to be used so I can unzip= files and zip them up again later. TIA Glen ***************************************************************************= ** If you are not the intended recipient of this e-mail, please notify=20 the sender immediately. The contents of this e-mail do not amend=20 any existing disclosures or agreements unless expressly stated. ***************************************************************************= ** From dyoo@hkn.eecs.berkeley.edu Tue Jun 11 22:17:32 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 11 Jun 2002 14:17:32 -0700 (PDT) Subject: [Tutor] parsing--is this right? In-Reply-To: Message-ID: On Tue, 11 Jun 2002, Danny Yoo wrote: > And this is the source of the shallowness: we're just calling str(). > But instead of directly calling str() on each piece in between, the > trick is to apply toXML() again to each inner piece! That way, we > guarantee that the inner lists are also transformed properly: > [code of toXML()] > def toXML(structure): > if type(structure) == type([]): > tag = structure[0][1:] ## secondary slice removes leading '/' > text_pieces = [str(s) for s in structure[1:]] > return "<%(tag)s>%(text)s" % \ > { 'tag' : tag, > 'text' : ''.join(text_pieces) } > else: > return str(structure) > ### > >>> def toXMLDeeply(structure): > ... if type(structure) == type([]): > ... tag = structure[0][1:] ## secondary slice removes leading '/' > ... text_pieces = [toXML(s) for s in structure[1:]] > ... return "<%(tag)s>%(text)s" % \ > ... { 'tag' : tag, > ... 'text' : ''.join(text_pieces) } > ... else: > ... return str(structure) > ... > >>> print toXMLDeeply(parsed_doc) > anitalicizedwordmaybeanotheritalicizedwordtext > ### > > > The transformation wasn't perfect, because my parsing step had wiped out > whitespace in my parsed_doc, so that needs to be fixed. Still, it almost > works. *grin* But note that if you have three levels of nesting, you'll still get weird output, because the third level won't be marked up properly. Yikes! Ummm... I'll pretend that I didn't goof up, and say that if you understand what's happening, you'll know how to fix this bug. *grin* From pydan@danshafer.com Tue Jun 11 23:13:11 2002 From: pydan@danshafer.com (Dan Shafer) Date: Tue, 11 Jun 2002 15:13:11 -0700 Subject: [Tutor] Creating an Identifier or Object Name from a String? In-Reply-To: References: <5.1.0.14.0.20020611005842.029526e0@mail.hurrah.com> Message-ID: <5.1.0.14.0.20020611151236.02a9e218@mail.hurrah.com> Thanks, Danny. With your code as a clue for a starting point, I got this working just fine for list and dictionaries. Appreciate it. At 01:10 AM 6/11/2002 -0700, Danny Yoo wrote: >On Tue, 11 Jun 2002, Dan Shafer wrote: > > > I have a need to refer to a number of objects which have been named > > field1, field2, field3, etc. I want to set a property in each object in > > a loop. > >Instead of having them as separate variables, is it possible to keep them >grouped together in a list or dictionary? That way, it's easier to work >with them as a group, without the complexities of eval(). > > > > I thought this should work: > > > > for ct in range(1,4): > > objToUpdate = "field" + str(ct) > > objToChange = eval(objToUpdate) # seems like it should produce > > "field1" first time through the loop, etc. > > objToChange.text = inputList[ct] #inputList is generated prior to > > entering the loop and is a list of string values > > >So since your inputList is already a list, that may be a good hint that >symmetry will help. *grin* Try something like: > >### >objects = [field1, field2, field3] ### Add as many objects as you > ### have >for i in range(len(objects)): > objects[i].text = inputlist[i] >### > > >But I didn't see anything obviously wrong with your initial approach. >One suggestion would be to check the value of field1, field2, field3, >right before the loop. Also, if you can show us the literal error >message, that may give more clues as to why it's doing weird things. Dan Shafer, Chief Scribe and Tablet Keeper PythonCard Open Source Project http://pythoncard.sourceforge.net From pydan@danshafer.com Tue Jun 11 23:14:01 2002 From: pydan@danshafer.com (Dan Shafer) Date: Tue, 11 Jun 2002 15:14:01 -0700 Subject: [Tutor] Creating an Identifier or Object Name from a String? In-Reply-To: <3D05B663.B87BF27@rg16.asn-wien.ac.at> References: <5.1.0.14.0.20020611005842.029526e0@mail.hurrah.com> Message-ID: <5.1.0.14.0.20020611151320.02aa79d0@mail.hurrah.com> I think I was putting the eval step in the wrong place or something. Anyway, thanks to your comment and Danny Yoo's feedback, I got my program working just fine so it does the right thing with lists and with dictionaries. Thanks! At 10:35 AM 6/11/2002 +0200, Gregor Lingl wrote: >I Tried it and it worked (?!) > >Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32 >Type "copyright", "credits" or "license" for more information. >IDLE 0.8 -- press F1 for help > >>> class K: > pass > > >>> field1 = K() > >>> field2 = K() > >>> field3 = K() > >>> for ct in range(1,4): > obj="field"+str(ct) > objTC=eval(obj) > objTC.text=['a','b',str(ct)] > > > >>> field1.text >['a', 'b', '1'] > >>> field2.text >['a', 'b', '2'] > >>> field3.text >['a', 'b', '3'] > >>> > >Gregor > > >Dan Shafer schrieb: > > > I have a need to refer to a number of objects which have been named field1, > > field2, field3, etc. I want to set a property in each object in a loop. > > > > I thought this should work: > > > > for ct in range(1,4): > > objToUpdate = "field" + str(ct) > > objToChange = eval(objToUpdate) # seems like it should produce > > "field1" first time through the loop, etc. > > objToChange.text = inputList[ct] #inputList is generated prior to > > entering the loop and is a list of string values > > > > This produces an error indicating that string objects don't have a text > > attribute. So clearly objToChange is still a string at this point. > > > > I suspect this is tricky but if someone could help.... > > > > Dan Shafer, Chief Scribe and Tablet Keeper > > PythonCard Open Source Project > > http://pythoncard.sourceforge.net > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor Dan Shafer, Chief Scribe and Tablet Keeper PythonCard Open Source Project http://pythoncard.sourceforge.net From terjeja@hotmail.com Tue Jun 11 23:31:01 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Tue, 11 Jun 2002 22:31:01 +0000 Subject: [Tutor] Win32com/Excel Message-ID: I try to open Excel thru win32com. I write: >>>from win32com.client import Dispatch >>>xlApp = Dispatch("Excel.Application") >>>xlApp.Visible = 1 I get the frame of Excel, but not the spreadsheet. Even if I write: >>>xlApp.Workbooks.Add() it doesn't give me the ability to look whats there. I get the frame around the spreadsheet, and the menues at the top, as well as the paperclip. The paperclip works, the menus are selectable, but does not work. And the space where the spreadsheet should have been gives me a "picture" of what is on the desktop. (Other open windows in the background and so forth). I can move the Excel frame around, and the background follows along. I use the newest version of both Python and Win32com, and have tried this on two computers. 1 with Win98 and 1 with win2k. Same result... Anyone seen this before? And managed to solve it? Thanks, Terje _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp. From pythontutor@venix.com Wed Jun 12 00:29:36 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Tue, 11 Jun 2002 19:29:36 -0400 Subject: [Tutor] Win32com/Excel References: Message-ID: <3D0687E0.8040006@venix.com> xlBook = xlApp.Workbooks.Add() sheet = xlBook.Worksheets('Sheet1') row1,col1,row2,col2 = 1,1,3,4 #3 rows, 4 cols return sheet.Range(sheet.Cells(row1, col1), sheet.Cells(row2, col2)).Value Terje Johan Abrahamsen wrote: > I try to open Excel thru win32com. I write: > >>>> from win32com.client import Dispatch >>>> xlApp = Dispatch("Excel.Application") >>>> xlApp.Visible = 1 >>> > > I get the frame of Excel, but not the spreadsheet. Even if I write: > >>>> xlApp.Workbooks.Add() >>> > it doesn't give me the ability to look whats there. I get the frame > around the spreadsheet, and the menues at the top, as well as the > paperclip. The paperclip works, the menus are selectable, but does not > work. And the space where the spreadsheet should have been gives me a > "picture" of what is on the desktop. (Other open windows in the > background and so forth). I can move the Excel frame around, and the > background follows along. I use the newest version of both Python and > Win32com, and have tried this on two computers. 1 with Win98 and 1 with > win2k. Same result... Anyone seen this before? And managed to solve it? > > Thanks, > Terje > > _________________________________________________________________ > Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From seiji_funai@yahoo.com Wed Jun 12 00:57:28 2002 From: seiji_funai@yahoo.com (Seiji Funai) Date: Tue, 11 Jun 2002 16:57:28 -0700 (PDT) Subject: [Tutor] Continuously slower program Message-ID: <20020611235728.37878.qmail@web21310.mail.yahoo.com> --0-1648986577-1023839848=:35018 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline This is a test for the beginning of a meter that I'm writing for a GUI. The application slows continuously. Does my computer just suck, or is there something I can do? Please let me know. Thanks! __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com --0-1648986577-1023839848=:35018 Content-Type: text/plain; name="testMeter.py" Content-Description: testMeter.py Content-Disposition: inline; filename="testMeter.py" from Tkinter import * import math class TestMeter: def __init__(self, master): testMeterFrame = Frame(master) testMeterFrame.pack() self.count = 0 self.box = 8, 8, 57, 57 self.testMeterCanvas = Canvas(testMeterFrame, bg = "gray", width = 65, height = 65) self.testMeterCanvas.grid(row = 1, column = 1) self.testMeterCanvas.create_oval(2, 2, 63, 63, fill = "black") self.testMeterCanvas.create_oval(5, 5, 60, 60, fill = "gray") self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.testMeterCanvas.create_line(33, 33, 33, 8, fill = "red") self.testMeterCanvas.create_text(33, 47, text = "M1") self.testMeterCanvas.create_text(10, 38, text = "0") self.testMeterCanvas.create_text(55, 38, text = "1") self.startButton = Button(testMeterFrame, text = "Start", command = self.start) self.startButton.grid(row = 2, column = 1, sticky = W+E+N+S) def start(self): self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") while 1: self.count = self.count + .1 if self.count == 1000: self.count = 0 self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.x = 25 * math.sin(self.count) + 33 self.y = -25 * math.fabs(math.cos(self.count)) + 33 self.testMeterCanvas.create_line(33, 33, self.x, self.y, fill = "red") root.update() def stop(self): self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.testMeterCanvas.create_line(33, 33, 33, 8, fill = "red") root = Tk() testMeter = TestMeter(root) root.mainloop() --0-1648986577-1023839848=:35018-- From dman@dman.ddts.net Wed Jun 12 03:28:39 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Tue, 11 Jun 2002 21:28:39 -0500 Subject: [Tutor] Re: Continuously slower program In-Reply-To: <20020611235728.37878.qmail@web21310.mail.yahoo.com> References: <20020611235728.37878.qmail@web21310.mail.yahoo.com> Message-ID: <20020612022838.GA3199@dman.ddts.net> --VS++wcV0S1rZb1Fb Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, Jun 11, 2002 at 04:57:28PM -0700, Seiji Funai wrote: | This is a test for the beginning of a meter that I'm | writing for a GUI. The application slows | continuously. Does my computer just suck, or is there | something I can do? Please let me know. I tried it out on my system ... and I noticed that the CPU was pegged right when the meter started moving slower. When I closed the window I got an exception out of Tcl. I don't know Tcl or Tk at all so I can't really help you with this, but I can say it isn't a result of your particular platform. -D --=20 After you install Microsoft Windows XP, you have the option to create user accounts. If you create user accounts, by default, they will have an account type of administrator with no password. -- bugtraq =20 Jabber ID : dman@dman.ddts.net GnuPG key : http://dman.ddts.net/~dman/public_key.gpg --VS++wcV0S1rZb1Fb Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0GsdYACgkQO8l8XBKTpRSKZgCfeTF6UJhF3328zPc6/uSMlaZO vEYAoIC4fT1JA7Xnf7KHgi+CPaFij6yv =sZG4 -----END PGP SIGNATURE----- --VS++wcV0S1rZb1Fb-- From lonetwin@subdimension.com Wed Jun 12 07:34:32 2002 From: lonetwin@subdimension.com (lonetwin_SubD) Date: Wed, 12 Jun 2002 12:04:32 +0530 Subject: [Tutor] Tk question In-Reply-To: <20020611174406.GA21236@tc.niof.net> References: <20020611132805.B15372F4C6@mercury.sapatmt> <20020611174406.GA21236@tc.niof.net> Message-ID: <20020612063433.0B5272F4C6@mercury.sapatmt> Hey Rick, Thanx for the reply.....the thing with tkinter is that I don't know where to look for info ....not because there is a lack of it ...but because the resources that are there are so very detailed that one can easily get confused/lost (that's how I got to trying "anchor" to solve the text justification.). I have a copy of "Tkinter reference: A GUI for Python" on my system, don't remember where I got it from. I'm sure the option might be mentioned _somewhere-in-there_ .....but where was not too obvious. In any case I should be blaming my laziness. BTW, are there any good resources for *lazy* ppl., like a quick indexed reference for tkinter (along the lines of Python Quick reference at http://www.brunningonline.net/simon/python/PQR.html ) Peace Steve On Tuesday 11 June 2002 11:14 pm, you wrote: > Add a justify option to your call to Label(): > > Sub = Label(Master, font='fixed', text=out, justify=LEFT) > > On Tue, Jun 11, 2002 at 06:58:05PM +0530, lonetwin_SubD wrote: > > Hi ppl, > > For convenience sake, I wrote a wrapper around the 'cal' command on > > my linux box (and bound it to a shortcut keystroke on my Window manager). > > There is one problem tho', I just can't figure out how to get the first > > and last lines aligned properly. I tried passing anchor="w" while > > initialising the Label but that does not seem to help .....any pointers > > ?? > > > > Here's the code (maybe someone else might find it useful too :)). > > > > Note : I specifically set the font to "fixed" b'cos with variable width > > fonts spaces are "thinner" than characters and that screws up the > > display. > > > > --------------------------------------- > > #!/usr/bin/python > > import os > > > > cal="/usr/bin/cal.orig" > > args = ''.join(os.sys.argv[1:]) > > out = os.popen('%s %s' % (cal, args)).read() > > > > if os.environ.has_key('DISPLAY'): > > from Tkinter import * > > Master = Frame() > > Master.master.title("Tkcal") > > Sub = Label(Master, font='fixed', text=out) > > Master.grid(ipadx=2, ipady=2) > > Sub.grid() > > Master.mainloop() > > else: > > print out > > ---------------------------------------- > > > > Peace > > Steve > > > > PS: Maybe you are wondering why I did this, well I can only say that I > > find myself using the keyboard 95% of the time when in windowmaker (my > > preferred wm). Also, I've got a similar (shortcut) "front-end" to "ispell > > -a", I'll send it across if anybody is interested. > > > > -- > > The prettiest women are almost always the most boring, and that is why > > some people feel there is no God. > > -- Woody Allen, "Without Feathers" > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor -- Kleeneness is next to Godelness. From phthenry@earthlink.net Wed Jun 12 03:38:14 2002 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue, 11 Jun 2002 22:38:14 -0400 Subject: [Tutor] parsing--is this right? In-Reply-To: References: <20020611145546.A31120@localhost.localdomain> Message-ID: <20020611223814.E31120@localhost.localdomain> On Tue, Jun 11, 2002 at 02:06:57PM -0700, Danny Yoo wrote: Thanks Derrick and Danny. Recursion is both intuitive and counter-intuitive. For example, Derrick showed a fairly simple example using a factorial. But what happens to the return in this line? return n * fact( n-1 ) You think of return as getting one value, but the return somehow has to wait and build up a value. Also, how come the function doesn't return 1? The first part of the function says that it should return 1 if n is equal to one. At some point, n becomes 1. So why don't we see 1, and why doesn't the function stop? On the other hand, recusion is intuititve in a way that is just beyond my reach. I say this because I have written so much duplicate code, and I'm always thinking, "How can I re-use this code?" Of course, not all of this code is an example of recursion, but I bet if I went back and looked, some of the problems would be. Anyway, all this should give me a bit to think about for a while. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From mhammond@skippinet.com.au Wed Jun 12 04:08:24 2002 From: mhammond@skippinet.com.au (Mark Hammond) Date: Wed, 12 Jun 2002 13:08:24 +1000 Subject: [Tutor] RE: [python-win32] Win32com/Excel In-Reply-To: Message-ID: > I try to open Excel thru win32com. I write: > >>>from win32com.client import Dispatch > >>>xlApp = Dispatch("Excel.Application") > >>>xlApp.Visible = 1 > > I get the frame of Excel, but not the spreadsheet. Even if I write: > >>>xlApp.Workbooks.Add() > it doesn't give me the ability to look whats there. I get the > frame around > the spreadsheet, and the menues at the top, as well as the paperclip. The > paperclip works, the menus are selectable, but does not work. And > the space > where the spreadsheet should have been gives me a "picture" of what is on > the desktop. (Other open windows in the background and so forth). > I can move > the Excel frame around, and the background follows along. I use > the newest > version of both Python and Win32com, and have tried this on two > computers. 1 > with Win98 and 1 with win2k. Same result... Anyone seen this before? And > managed to solve it? On my machine, your code seems to work fine - excel repaints and is fully responsive. The new worksheet is created and can be interacted with. This occasionally happens when an existing Excel instance is already running. If your program crashed the last time you ran it, you may need to kill the Excel.exe process manually. If you see this behaviour inside a more complex app only, then it may be that you need to occasionally pump a message loop - pythoncom.PumpWaitingMessages() is often suitable. Mark. From dyoo@hkn.eecs.berkeley.edu Wed Jun 12 10:36:08 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 12 Jun 2002 02:36:08 -0700 (PDT) Subject: [Tutor] parsing--is this right? [function evaluation / errors for fun and profit] In-Reply-To: <20020611223814.E31120@localhost.localdomain> Message-ID: On Tue, 11 Jun 2002, Paul Tremblay wrote: > Recursion is both intuitive and counter-intuitive. For example, Derrick > showed a fairly simple example using a factorial. But what happens to > the return in this line? > > return n * fact( n-1 ) > > You think of return as getting one value, but the return somehow has to > wait and build up a value. Yes, it has to evaluate the value of 'n * fact(n-1)', but this is not so different from other expressions that use functions as little helpers. Let's take one example of how Python builds up values, a hypotenuse calculator: ### def hypotenuse(side1, side2): return math.sqrt(square(side1) + square(side2)) def square(x): return x * x ### This hypotenuse() function tells us how long a diagonal to a right triangle would be, if we knew the lengths of the other two sides. In order for hypotenuse() function to work, it has to pass off some of the work over to the square() function. In fact, we can actually see this delegation in action if we deliberately put a bug into square(): ### >>> import math >>> def hypotenuse(side1, side2): ... return math.sqrt(square(side1) + square(side2)) ... >>> def square(x): ... return a * b ... >>> hypotenuse(3, 4) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in hypotenuse File "", line 2, in square NameError: global name 'a' is not defined ### If we look at the traceback error, it actual says something like "While I was trying to compute hypotenuse, to do that, I had to do a square()ing... but while I was trying to compute square, I ran into a problem." So hypotenuse() actually passes the torch to squares() first. Once square()'s done, then square() can 'return' the torch back to hypotenuse(). That's why both functions are listed in this "traceback". Here's a more dramatic example of the way Python calculates: let's reuse that factorial() example, but let's be mischevious again: we'll put in a fatal flaw that makes factorial() break down if we try to calculate factorial(0): ### >>> def factorial(x): ... if x == 0: ... print "I'm going to break down." ... print 0 / 0 ## This is deliberate. ... return x * factorial(x-1) ... >>> factorial(0) I'm going to break down. Traceback (most recent call last): File "", line 1, in ? File "", line 4, in factorial ZeroDivisionError: integer division or modulo by zero ### Yup, it breaks down predictably. But what happens if we put larger values of 'x' in there? ### >>> factorial(4) I'm going to break down. Traceback (most recent call last): File "", line 1, in ? File "", line 5, in factorial File "", line 5, in factorial File "", line 5, in factorial File "", line 5, in factorial File "", line 4, in factorial ZeroDivisionError: integer division or modulo by zero ### The error message is subtly different: there's a bunch more lines of Python complaining! And that's because to calculate factorial(4), Python sees that it has to calculate factorial(3)... but to calculate factorial(3), it has to first calculate factorial (2)... etc. So factorial() shows up multiple times, once for every time it had to use itself as a helper. If you ever have time to browse through a bookstore, try flipping through Douglas Hofstadter's book, "Godel Escher Bach". There's a very cool chapter called "Little Harmonic Labyrinth", and it captures the idea of recursion very well. Gotta sleep now. Hope this was helpful! From donni@melwestmarket.com Wed Jun 12 12:15:19 2002 From: donni@melwestmarket.com (Dimitrije Nikic) Date: Wed, 12 Jun 2002 21:15:19 +1000 (AUS Eastern Standard Time) Subject: [Tutor] Whats the module for sounds in dos and linux? Message-ID: <3D072D47.000005.42785@athlon900.vic.optushome.com.au> --------------Boundary-00=_J9BL6RO0000000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Whats the module for sounds in dos and linux? i want to be able to use th= e beep() and playsound() function in dos and linux.... thanx for the help --------------Boundary-00=_J9BL6RO0000000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Whats the module for sounds in dos and linux? i want to be able = to use=20 the beep() and playsound() function in dos and linux....

thanx for the help
=09 =09 =09 =09 =09 =09 =09
_________________________________________________
Bravenet IncrediMail - Email ha= s finally=20 evolved -
Click=20 Here
--------------Boundary-00=_J9BL6RO0000000000000-- From sarmstrong13@mac.com Wed Jun 12 15:03:13 2002 From: sarmstrong13@mac.com (SA) Date: Wed, 12 Jun 2002 09:03:13 -0500 Subject: [Tutor] Continuously slower program In-Reply-To: <20020611235728.37878.qmail@web21310.mail.yahoo.com> Message-ID: On 6/11/02 6:57 PM, "Seiji Funai" wrote: > This is a test for the beginning of a meter that I'm > writing for a GUI. The application slows > continuously. Does my computer just suck, or is there > something I can do? Please let me know. > > Thanks! > I'm no expert on Tkinter, so I'll only give you the results from my running of the program: I ran this in Xdarwin on an Apple G4 Powerbook w/ 512 M of RAM running OSX. I ran the script alongside top to gauge cpu usage. CPU usage by the user (me), because top spits usage down amongst system and user, during the running of this script jumped from roughly 30% to a rough average of 75% with 85% being the maximum amount I saw. So I would have to concur that it is NOT your sytem that is causing the problem. Something in the app is draining CPU cycles. If I had to guess, and I definitely could be wrong, I would say your problem may lie in this section: def start(self): self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") while 1: self.count = self.count + .1 if self.count == 1000: self.count = 0 self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.x = 25 * math.sin(self.count) + 33 self.y = -25 * math.fabs(math.cos(self.count)) + 33 self.testMeterCanvas.create_line(33, 33, self.x, self.y, fill = "red") root.update() Good Luck. SA From arcege@speakeasy.net Wed Jun 12 17:49:32 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 12 Jun 2002 12:49:32 -0400 Subject: [Tutor] Continuously slower program In-Reply-To: <20020611235728.37878.qmail@web21310.mail.yahoo.com> References: <20020611235728.37878.qmail@web21310.mail.yahoo.com> Message-ID: <20020612164932.GD895@speakeasy.net> On Tue, Jun 11, 2002 at 04:57:28PM -0700, Seiji Funai wrote: > This is a test for the beginning of a meter that I'm > writing for a GUI. The application slows > continuously. Does my computer just suck, or is there > something I can do? Please let me know. Your problem is that you continually create new canvas objects inside the while loop. You should be creating the objects once, and changing them as needed. That was increasing the processing of the Canvas object, increasing the memory of it, and sucking up CPU time. Below are the changes to your code. (Lines starting with "-" are removed, and lines starting with "+" have been added.) You want to capture the canvas id of the red line, then change its coordinates inside the loop with the "coords" method to the Canvas object. -Arcege from Tkinter import * import math class TestMeter: def __init__(self, master): testMeterFrame = Frame(master) testMeterFrame.pack() self.count = 0 self.box = 8, 8, 57, 57 self.testMeterCanvas = Canvas(testMeterFrame, bg = "gray", width = 65, height = 65) self.testMeterCanvas.grid(row = 1, column = 1) self.testMeterCanvas.create_oval(2, 2, 63, 63, fill = "black") self.testMeterCanvas.create_oval(5, 5, 60, 60, fill = "gray") self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.testMeterCanvas.create_line(33, 33, 33, 8, fill = "red") self.testMeterCanvas.create_text(33, 47, text = "M1") self.testMeterCanvas.create_text(10, 38, text = "0") self.testMeterCanvas.create_text(55, 38, text = "1") self.startButton = Button(testMeterFrame, text = "Start", command = self.start) self.startButton.grid(row = 2, column = 1, sticky = W+E+N+S) def start(self): self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") + self.x = 25 * math.sin(self.count) + 33 + self.y = -25 * math.fabs(math.cos(self.count)) + 33 + self.c = self.testMeterCanvas.create_line(33, 33, self.x, self.y, fill="red") while 1: self.count = self.count + .1 if self.count == 1000: self.count = 0 - self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.x = 25 * math.sin(self.count) + 33 self.y = -25 * math.fabs(math.cos(self.count)) + 33 - self.testMeterCanvas.create_line(33, 33, self.x, self.y, fill = "red") + self.testMeterCanvas.coords(self.c, 33, 33, self.x, self.y) root.update() def stop(self): self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.testMeterCanvas.create_line(33, 33, 33, 8, fill = "red") root = Tk() testMeter = TestMeter(root) root.mainloop() From alan.gauld@bt.com Wed Jun 12 18:35:31 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 12 Jun 2002 18:35:31 +0100 Subject: [Tutor] Tk question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C650@mbtlipnt02.btlabs.bt.co.uk> > BTW, are there any good resources for *lazy* ppl., like > a quick indexed reference for tkinter I already mentioned Tcl/Tk in a Nutshell from O'Reilly which is Tcl based. Also Grayson's book has a quick reference to all the widgets as an appendix. Alan G. From sarmstrong13@mac.com Wed Jun 12 19:32:09 2002 From: sarmstrong13@mac.com (SA) Date: Wed, 12 Jun 2002 13:32:09 -0500 Subject: [Tutor] Continuously slower program In-Reply-To: <20020612164932.GD895@speakeasy.net> Message-ID: On 6/12/02 11:49 AM, "Michael P. Reilly" wrote: > On Tue, Jun 11, 2002 at 04:57:28PM -0700, Seiji Funai wrote: >> This is a test for the beginning of a meter that I'm >> writing for a GUI. The application slows >> continuously. Does my computer just suck, or is there >> something I can do? Please let me know. > > Your problem is that you continually create new canvas objects inside the > while loop. You should be creating the objects once, and changing them > as needed. That was increasing the processing of the Canvas object, > increasing the memory of it, and sucking up CPU time. > I get the following error when I run the revamped script: File "./TestMeter2.py", line 35 self.testMeterCanvas.coords(self.c, 33, 33, self.x, self.y) ^ SyntaxError: invalid syntax What did I do wrong? Thanks. SA From sarmstrong13@mac.com Wed Jun 12 19:35:35 2002 From: sarmstrong13@mac.com (SA) Date: Wed, 12 Jun 2002 13:35:35 -0500 Subject: [Tutor] Tk question In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C650@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On 6/12/02 12:35 PM, "alan.gauld@bt.com" wrote: >> BTW, are there any good resources for *lazy* ppl., like >> a quick indexed reference for tkinter > Try: http://www.pythonware.com/library/tkinter/introduction/index.htm http://www.python.org/topics/tkinter/doc.html http://www.python.org/topics/tkinter/ There are some good links here. Good Luck. SA From jeff@ccvcorp.com Wed Jun 12 20:13:02 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed, 12 Jun 2002 12:13:02 -0700 Subject: [Tutor] Continuously slower program References: Message-ID: <3D079D3D.FE47AF78@ccvcorp.com> SA wrote: > > I get the following error when I run the revamped script: > File "./TestMeter2.py", line 35 > self.testMeterCanvas.coords(self.c, 33, 33, self.x, self.y) > ^ > SyntaxError: invalid syntax > > What did I do wrong? Often when Python throws a SyntaxError at the beginning of a line, the problem is really with the previous line. Can you cut&paste the entire method that this is from? That way, we can see a bit more context, and and can probably spot the error easier. Jeff Shannon Technician/Programmer Credit International From arcege@speakeasy.net Wed Jun 12 20:16:49 2002 From: arcege@speakeasy.net (Michael P. Reilly) Date: Wed, 12 Jun 2002 15:16:49 -0400 Subject: [Tutor] Continuously slower program In-Reply-To: References: <20020612164932.GD895@speakeasy.net> Message-ID: <20020612191649.GF895@speakeasy.net> --jI8keyz6grp/JLjh Content-Type: text/plain; charset=us-ascii Content-Disposition: inline On Wed, Jun 12, 2002 at 01:32:09PM -0500, SA wrote: > On 6/12/02 11:49 AM, "Michael P. Reilly" wrote: > > > On Tue, Jun 11, 2002 at 04:57:28PM -0700, Seiji Funai wrote: > >> This is a test for the beginning of a meter that I'm > >> writing for a GUI. The application slows > >> continuously. Does my computer just suck, or is there > >> something I can do? Please let me know. > > > > Your problem is that you continually create new canvas objects inside the > > while loop. You should be creating the objects once, and changing them > > as needed. That was increasing the processing of the Canvas object, > > increasing the memory of it, and sucking up CPU time. > > > I get the following error when I run the revamped script: > File "./TestMeter2.py", line 35 > self.testMeterCanvas.coords(self.c, 33, 33, self.x, self.y) > ^ > SyntaxError: invalid syntax > > What did I do wrong? I'm not sure... the line looks correct. Is the indentation correct? The error suggests that it is not indented with the rest of the block. (Don't align the line with the commented line, but with the other lines.) I'm enclosing the changes that I had made; maybe it can help you. -Arcege --jI8keyz6grp/JLjh Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="testMeter.py" from Tkinter import * import math class TestMeter: def __init__(self, master): testMeterFrame = Frame(master) testMeterFrame.pack() self.count = 0 self.box = 8, 8, 57, 57 self.testMeterCanvas = Canvas(testMeterFrame, bg = "gray", width = 65, height = 65) self.testMeterCanvas.grid(row = 1, column = 1) self.testMeterCanvas.create_oval(2, 2, 63, 63, fill = "black") self.testMeterCanvas.create_oval(5, 5, 60, 60, fill = "gray") self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.testMeterCanvas.create_line(33, 33, 33, 8, fill = "red") self.testMeterCanvas.create_text(33, 47, text = "M1") self.testMeterCanvas.create_text(10, 38, text = "0") self.testMeterCanvas.create_text(55, 38, text = "1") self.startButton = Button(testMeterFrame, text = "Start", command = self.start) self.startButton.grid(row = 2, column = 1, sticky = W+E+N+S) def start(self): self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.x = 25 * math.sin(self.count) + 33 self.y = -25 * math.fabs(math.cos(self.count)) + 33 self.c = self.testMeterCanvas.create_line(33, 33, self.x, self.y, fill="red") while 1: self.count = self.count + .1 if self.count == 1000: self.count = 0 # self.testMeterCanvas.create_arc(self.box, start = 0, extent = 180, fill = "white") self.x = 25 * math.sin(self.count) + 33 self.y = -25 * math.fabs(math.cos(self.count)) + 33 # self.testMeterCanvas.create_line(33, 33, self.x, self.y, fill = "red") self.testMeterCanvas.coords(self.c, 33, 33, self.x, self.y) root.update() def stop(self): self.testMeterCanvas.coords(self.c, 33, 33, 33, 8) root = Tk() testMeter = TestMeter(root) root.mainloop() --jI8keyz6grp/JLjh-- From sarmstrong13@mac.com Wed Jun 12 20:46:06 2002 From: sarmstrong13@mac.com (SA) Date: Wed, 12 Jun 2002 14:46:06 -0500 Subject: [Tutor] Continuously slower program In-Reply-To: <20020612191649.GF895@speakeasy.net> Message-ID: On 6/12/02 2:16 PM, "Michael P. Reilly" wrote: > > I'm not sure... the line looks correct. Is the indentation correct? > The error suggests that it is not indented with the rest of the block. > (Don't align the line with the commented line, but with the other lines.) > > I'm enclosing the changes that I had made; maybe it can help you. > > -Arcege > > That did the trick. It works now without the speed dropoff and according to top it is only taking between 65-73% of the CPU user cycles. Wher as before it was between 75-83%. Thanks. SA From glingl@aon.at Wed Jun 12 22:08:24 2002 From: glingl@aon.at (Gregor Lingl) Date: Wed, 12 Jun 2002 23:08:24 +0200 Subject: [Tutor] Continuously slower program References: <20020612164932.GD895@speakeasy.net> <20020612191649.GF895@speakeasy.net> Message-ID: <009101c21255$4ae35dd0$1615a8c0@mega> ----- Original Message ----- From: "Michael P. Reilly" To: Sent: Wednesday, June 12, 2002 9:16 PM Subject: Re: [Tutor] Continuously slower program > > I'm enclosing the changes that I had made; maybe it can help you. > > -Arcege > I downloaded and ran your program and it worked well. However, when looking at the running the meter one observes every 10 to 15 seconds (on my machine) a sudden slowdown for half a second approximately. So this, I think, is a visualization of garbage collection - which could be problematic when programming for instance actino games or some sorts of animation. There come the following questions to my mind: - Is it possible to distribute garbage collection smoothely over the entire process or to control its occurence in some other way? - Where comes this g.c. from? Which part of the program uses that memory, which has to be cleared up? (Maybe some repeatedly generated local variables in the math - stuff?) - Does the g.c. come from the Python interpreter or from the underlying Tcl/Tk? Thanks in advance for your insight creating remarks Gregor P.S.: I also observe, that there are Tkinter programs, which produce really strange error messages when closed properly (by clicking on the windows-closing icon 'X'): .... File "C:\Python22\lib\lib-tk\Tkinter.py", line 1927, in coords self.tk.splitlist( TclError: invalid command name ".8642816.8647440" whereas others don't do that. Who knows, which feature of a TKinter program is responsible for this unfriendly behaviour and how to avoid it. From lonrunr02@juno.com Wed Jun 12 02:32:19 2002 From: lonrunr02@juno.com (john p kensin) Date: Tue, 11 Jun 2002 21:32:19 -0400 Subject: [Tutor] about python Message-ID: <20020611.213220.1376.0.lonrunr02@juno.com> i like python, but i cant get it to work, i have tried the help files and stuff, but there is always an error, and when i write something in notepad, save it as .txt, i import it, it says i have to save, i do, then it says syntax error, or something else, im talking about the examples in the guide. ________________________________________________________________ GET INTERNET ACCESS FROM JUNO! Juno offers FREE or PREMIUM Internet access for less! Join Juno today! For your FREE software, visit: http://dl.www.juno.com/get/web/. From sheila@thinkspot.net Thu Jun 13 05:29:43 2002 From: sheila@thinkspot.net (Sheila King) Date: Wed, 12 Jun 2002 21:29:43 -0700 Subject: [Tutor] about python In-Reply-To: <20020611.213220.1376.0.lonrunr02@juno.com> Message-ID: <736549652A2@kserver.org> On Tue, 11 Jun 2002 21:32:19 -0400, john p kensin wrote: > i like python, but i cant get it to work, i have tried the help > files and stuff, but there is always an error, and when i write > something in notepad, save it as .txt, i import it, it says i have > to save, i do, then it says syntax error, or something else, im > talking about the examples in the guide. Don't save the files as .txt. Save them as .py. To do this in Notepad, when you click on the File Menu, choose "Save As..." and when you go to enter the file name in the box for that, type the file name in quotes like this: "example.py" Then Notepad will let you save with a file extension different from txt. Hopefully that will help? Have you tried using IDLE? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org From sarmstrong13@mac.com Thu Jun 13 18:35:01 2002 From: sarmstrong13@mac.com (SA) Date: Thu, 13 Jun 2002 12:35:01 -0500 Subject: [Tutor] I'm tring to translate a Tcl/Tk program into Python. Message-ID: Hi Everyone- I am trying to translate a tcl program that use tk into python. I seem to be going along fine until I get to the process that wants to "catch" the results onto one text screen. Here is what I am looking at: proc python {} { catch {exec /sw/bin/python -c [.t1 get 0.0 end]} output .t2 delete 0.0 end .t2 insert end $output } Basically, this process catches the output from running the code in the text widget .t1 through python -c and places it into the variable ouput. The text widget .t2 is then cleared and the contents of the variable $output are displayed in the text widget .t2. I can translate all of the widgets into python/tkinter code, but I'm not sure about how to translate this process. Is there a function similar to "catch" in Python? Thanks. SA From ak@silmarill.org Thu Jun 13 18:39:17 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Thu, 13 Jun 2002 13:39:17 -0400 Subject: [Tutor] Whats the module for sounds in dos and linux? In-Reply-To: <3D072D47.000005.42785@athlon900.vic.optushome.com.au> References: <3D072D47.000005.42785@athlon900.vic.optushome.com.au> Message-ID: <20020613173917.GA5265@ak.silmarill.org> On Wed, Jun 12, 2002 at 09:15:19PM +1000, Dimitrije Nikic wrote: > Whats the module for sounds in dos and linux? i want to be able to use the beep() and playsound() function in dos and linux.... > thanx for the help There isn't one. You can beep by doing "pring '\a'" and you can play sounds from PyGame, I believe. -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From jeff@ccvcorp.com Thu Jun 13 18:52:05 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jun 2002 10:52:05 -0700 Subject: [Tutor] I'm tring to translate a Tcl/Tk program into Python. References: Message-ID: <3D08DBC4.72A05446@ccvcorp.com> SA wrote: > Hi Everyone- > > I am trying to translate a tcl program that use tk into python. I seem > to be going along fine until I get to the process that wants to "catch" the > results onto one text screen. Here is what I am looking at: > > proc python {} { > catch {exec /sw/bin/python -c [.t1 get 0.0 end]} output > .t2 delete 0.0 end > .t2 insert end $output > } Where you're doing catch {exec ...} in tcl, for Python you'll want to look into using os.popen('command ...'), which will start a new process execute 'command', and returns a file-object that represents the stdout of the new process. You can then get that output by calling out.readlines(), or whatever. (Note that reading more from this file than is currently available, can cause your program to block.) Of course, if the command that you're executing is another Python script, you may be better off just importing it instead of spawning a new shell and interpreter for it... :) Jeff Shannon Technician/Programmer Credit International From terjeja@hotmail.com Thu Jun 13 19:48:38 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Thu, 13 Jun 2002 18:48:38 +0000 Subject: [Tutor] Format columns in Excel Message-ID: I am trying to change a column in Excel with Win32Com. So far I have tried this: class chkxl: xlApp = Dispatch("Excel.Application") xlApp.Workbooks.Open("agent.xls") agent = xlApp.Workbooks("agent.xls").Sheets("Sheet1") def __init__(self): chkxl.agent.Columns(10).Style.Name = "number" (There is more to it, so for example chkxl.agent.Cells(2,2).Value = "Hello" works) The style.Name = "number" I found with the helper in Excel. It is supposed to work in VBA, but doesn't seem to work in Python. What would I write to get it to make the column into numbers? Thanks, Terje _________________________________________________________________ Chat with friends online, try MSN Messenger: http://messenger.msn.com From dyoo@hkn.eecs.berkeley.edu Thu Jun 13 20:14:03 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 13 Jun 2002 12:14:03 -0700 (PDT) Subject: [Tutor] I'm tring to translate a Tcl/Tk program into Python. In-Reply-To: Message-ID: On Thu, 13 Jun 2002, SA wrote: > Hi Everyone- > > I am trying to translate a tcl program that use tk into python. I seem > to be going along fine until I get to the process that wants to "catch" the > results onto one text screen. Here is what I am looking at: > > proc python {} { > catch {exec /sw/bin/python -c [.t1 get 0.0 end]} output > .t2 delete 0.0 end > .t2 insert end $output > } > > Basically, this process catches the output from running the code in the > text widget .t1 through python -c and places it into the variable ouput. > The text widget .t2 is then cleared and the contents of the variable > $output are displayed in the text widget .t2. > > I can translate all of the widgets into python/tkinter code, but I'm not > sure about how to translate this process. Is there a function similar to > "catch" in Python? Hi SA, Yes, it sounds like the 'os.popen()' function: we can us os.popen to run external commands. What we get back from it a file object that can capture the text output. For example: ### >>> dictionary = os.popen('cat /usr/share/dict/words') >>> dictionary.readline() 'Aarhus\n' >>> dictionary.readline() 'Aaron\n' >>> dictionary.readline() 'Ababa\n' >>> dictionary.readline() 'aback\n' ### So it works almost exactly as if we were opening a regular file, except this "file" comes from running a particular program. Hope this helps! From sarmstrong13@mac.com Thu Jun 13 20:21:11 2002 From: sarmstrong13@mac.com (SA) Date: Thu, 13 Jun 2002 14:21:11 -0500 Subject: [Tutor] Thank You. Message-ID: Than You everyone for your help. Thanks. SA From sarmstrong13@mac.com Thu Jun 13 20:45:59 2002 From: sarmstrong13@mac.com (SA) Date: Thu, 13 Jun 2002 14:45:59 -0500 Subject: [Tutor] Tkinter script error. Message-ID: Hi Everyone- I'm practicing Tkinter from http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm. When I run the following Python script: from Tkinter import * class MyDialog: def __init__(self, parent): top = self.top = Toplevel(parent) Label(top, text="Value").pack() self.e = Entry(top) self.e.pack(padx=5) b = Button(top, text="OK", command=self.ok) b.pack(pady=5) def ok(self): print "value is", self.e.get() self.top.destroy() root = Tk() Button(root, text="Hello!").pack() root.update() d = MyDialog(root) root.wait_window(d.top) I get the following error: Traceback (most recent call last): File "(string)", line 22 in ? File "(string)", line 11 in __init__ File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1817, in __init__ Widget.__init__(self, master, 'button', cnf, kw) File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1756, in __init__ self.tk.call( TclError: unkown option "-test" Any ideas what is causing this? Thanks. SA From rickp@telocity.com Thu Jun 13 21:16:37 2002 From: rickp@telocity.com (Rick Pasotto) Date: Thu, 13 Jun 2002 16:16:37 -0400 Subject: [Tutor] Tkinter script error. In-Reply-To: References: Message-ID: <20020613201637.GF21236@tc.niof.net> OK, now, confess. You didn't cut-n-paste, did you? The line in your message: > b = Button(top, text="OK", command=self.ok) in your code is probably: > b = Button(top, test="OK", command=self.ok) On Thu, Jun 13, 2002 at 02:45:59PM -0500, SA wrote: > Hi Everyone- > > I'm practicing Tkinter from > http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm. > When I run the following Python script: > > from Tkinter import * > > class MyDialog: > > def __init__(self, parent): > > top = self.top = Toplevel(parent) > > Label(top, text="Value").pack() > > self.e = Entry(top) > self.e.pack(padx=5) > > b = Button(top, text="OK", command=self.ok) > b.pack(pady=5) > > def ok(self): > > print "value is", self.e.get() > > self.top.destroy() > > root = Tk() > Button(root, text="Hello!").pack() > root.update() > > d = MyDialog(root) > > root.wait_window(d.top) > > I get the following error: > > Traceback (most recent call last): > File "(string)", line 22 in ? > File "(string)", line 11 in __init__ > File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1817, in __init__ > Widget.__init__(self, master, 'button', cnf, kw) > File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1756, in __init__ > self.tk.call( > TclError: unkown option "-test" > > > Any ideas what is causing this? > Thanks. > SA > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- "Love is much like a wild rose, beautiful and calm, but willing to draw blood in its defense." -- Mark A. Overby Rick Pasotto rickp@telocity.com http://www.niof.net From dyoo@hkn.eecs.berkeley.edu Thu Jun 13 21:28:58 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 13 Jun 2002 13:28:58 -0700 (PDT) Subject: [Tutor] Tkinter script error. In-Reply-To: Message-ID: On Thu, 13 Jun 2002, SA wrote: > I'm practicing Tkinter from > http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm. > When I run the following Python script: > > from Tkinter import * > > class MyDialog: > > def __init__(self, parent): > > top = self.top = Toplevel(parent) > > Label(top, text="Value").pack() > > self.e = Entry(top) > self.e.pack(padx=5) > > b = Button(top, text="OK", command=self.ok) > b.pack(pady=5) > > def ok(self): > > print "value is", self.e.get() > > self.top.destroy() > > root = Tk() > Button(root, text="Hello!").pack() > root.update() > > d = MyDialog(root) > > root.wait_window(d.top) > > I get the following error: > > Traceback (most recent call last): > File "(string)", line 22 in ? > File "(string)", line 11 in __init__ > File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1817, in __init__ > Widget.__init__(self, master, 'button', cnf, kw) > File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1756, in __init__ > self.tk.call( > TclError: unkown option "-test" Hmmm... This is a weird one! I tested out your program on my computer, and it looked ok. The word 'test' looks awfully similar to the word 'text', so my first guess is that there might be a spelling error when the program was typed in. Can you check this again? From ATrautman@perryjudds.com Thu Jun 13 21:31:35 2002 From: ATrautman@perryjudds.com (Alan Trautman) Date: Thu, 13 Jun 2002 15:31:35 -0500 Subject: [Tutor] Tkinter script error. Message-ID: <75EDF89FDE81D511840D00A0C9AD25DD0261A2DF@CORP_EXCHANGE> -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Thursday, June 13, 2002 3:29 PM To: SA Cc: tutor Subject: Re: [Tutor] Tkinter script error. On Thu, 13 Jun 2002, SA wrote: > I'm practicing Tkinter from > http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm. > When I run the following Python script: > > from Tkinter import * > > class MyDialog: > > def __init__(self, parent): > > top = self.top = Toplevel(parent) > > Label(top, text="Value").pack() > > self.e = Entry(top) > self.e.pack(padx=5) > > b = Button(top, text="OK", command=self.ok) > b.pack(pady=5) > > def ok(self): > > print "value is", self.e.get() > > self.top.destroy() > > root = Tk() > Button(root, text="Hello!").pack() > root.update() > > d = MyDialog(root) > > root.wait_window(d.top) > > I get the following error: > > Traceback (most recent call last): > File "(string)", line 22 in ? > File "(string)", line 11 in __init__ > File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1817, in __init__ > Widget.__init__(self, master, 'button', cnf, kw) > File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1756, in __init__ > self.tk.call( > TclError: unkown option "-test" This script run well on my PC using IDLE are you using a command line interface with this? From sarmstrong13@mac.com Thu Jun 13 23:54:15 2002 From: sarmstrong13@mac.com (SA) Date: Thu, 13 Jun 2002 17:54:15 -0500 Subject: [Tutor] Tkinter script error. In-Reply-To: <75EDF89FDE81D511840D00A0C9AD25DD0261A2DF@CORP_EXCHANGE> Message-ID: Yes, I think this is my spelling error. Unfortunately I am a bad typer. Thank you all for your patience. Thanks. SA From flaxeater@yahoo.com Fri Jun 14 00:41:29 2002 From: flaxeater@yahoo.com (Chad Crabtree) Date: Thu, 13 Jun 2002 16:41:29 -0700 (PDT) Subject: [Tutor] FTP Question In-Reply-To: <20020613160005.2485.68960.Mailman@mail.python.org> Message-ID: <20020613234129.10828.qmail@web11605.mail.yahoo.com> I previously asked how one can get the IP address of thier local machine The information was very helpful and I finaly wrote the script to do what I needed to. I have also learned why the interactive interpreter is so amazingly awesome. However I have a question when I was uploading the file I f=open('file','rb') #opened the ftpconnect and logged in ftp.storbinary('STOR file',f) f.close() However it occured to me that I could do it differently So I tried it on the Interpreter and it did work however it brought up another question I did this #after connecting and logging in ftp.storbinary('STOR file',open('file','rb)) and this method was successful which supprised me however I'm wondering if this file is now just floating around in memory, because I couldn't figure out how to close it. Hmmmm Thank you so much for you time I really Appreciate all the discusion on this List it has been very illuminating __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From sheila@thinkspot.net Fri Jun 14 00:50:08 2002 From: sheila@thinkspot.net (Sheila King) Date: Thu, 13 Jun 2002 16:50:08 -0700 Subject: [Tutor] FTP Question In-Reply-To: <20020613234129.10828.qmail@web11605.mail.yahoo.com> Message-ID: On Thu, 13 Jun 2002 16:41:29 -0700 (PDT), Chad Crabtree wrote: > #after connecting and logging in ftp.storbinary('STOR > file',open('file','rb)) > > > and this method was successful which supprised me however I'm > wondering if this file is now just floating around in memory, > because I couldn't figure out how to close it. Hmmmm The file closes itself. Since you did not assign any "identifier" or variable name to reference the object, it will close as soon as you are done working with it. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org From mico@cbn.net.id Fri Jun 14 01:17:28 2002 From: mico@cbn.net.id (Mico Siahaan) Date: Fri, 14 Jun 2002 07:17:28 +0700 Subject: [Tutor] Convert man file into readable text file Message-ID: <5.1.0.14.0.20020614071008.00a704d0@pop.cbn.net.id> I'm a newbie. I want to make a python script to convert a man file into a readable text file so I can edit it with a text editors. So far, I made this: import string fin = open("wget.man","r") fout = open("wget.test","w") while 1: line = fin.readline() if line == "": break for ch in line: if ch not in string.printable: idx = line.find(ch) temp = line[:idx] + line[idx+1:] newline = temp else: newline = line fout.write(newline) fin.close() fout.close() And it gives a wrong result. I understand it is because I don't understand the structure of man files. Can anyone give me a correct example, please? Thanks. Mico Siahaan --- E-mail : mico at cbn dot net dot id From dman@dman.ddts.net Fri Jun 14 02:57:47 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu, 13 Jun 2002 20:57:47 -0500 Subject: [Tutor] Re: FTP Question In-Reply-To: References: <20020613234129.10828.qmail@web11605.mail.yahoo.com> Message-ID: <20020614015747.GA28056@dman.ddts.net> --sm4nu43k4a2Rpi4c Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Thu, Jun 13, 2002 at 04:50:08PM -0700, Sheila King wrote: | On Thu, 13 Jun 2002 16:41:29 -0700 (PDT), Chad Crabtree wrote: | > #after connecting and logging in ftp.storbinary('STOR | > file',open('file','rb)) | > | > | > and this method was successful which supprised me however I'm | > wondering if this file is now just floating around in memory, | > because I couldn't figure out how to close it. Hmmmm |=20 | The file closes itself. |=20 | Since you did not assign any "identifier" or variable name to=20 | reference the object, it will close as soon as you are done working=20 | with it. This assumes that no dangling references exist. It also assumes there are no bugs in the interpreter that could crash it before that happens. I think it is better practice to assign it to a handle and explicitly close() it when you are done. -D --=20 One OS to rule them all, one OS to find them, One OS to bring them all and in the darkness bind them, In the Land of Redmond, where the Shadows lie. =20 http://dman.ddts.net/~dman/ --sm4nu43k4a2Rpi4c Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0JTZsACgkQO8l8XBKTpRSngACfVKfQ8CeVrOcMiReNTX8OHkZK /2cAn1EMZZ+7B0JUdav+QegXyZI+1NP8 =vr2N -----END PGP SIGNATURE----- --sm4nu43k4a2Rpi4c-- From dman@dman.ddts.net Fri Jun 14 03:13:26 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Thu, 13 Jun 2002 21:13:26 -0500 Subject: [Tutor] Re: Convert man file into readable text file In-Reply-To: <5.1.0.14.0.20020614071008.00a704d0@pop.cbn.net.id> References: <5.1.0.14.0.20020614071008.00a704d0@pop.cbn.net.id> Message-ID: <20020614021326.GB28056@dman.ddts.net> --Bn2rw/3z4jIqBvZU Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Jun 14, 2002 at 07:17:28AM +0700, Mico Siahaan wrote: | I'm a newbie. I want to make a python script to convert a man file into a= =20 | readable text file $ man It outputs text itself. $ man | vim - Ok, so it has backspace characters in it to achieve bold and underline on terminals. (in vim) :%s/.^H//g (where ^H is a literal Ctrl-H character, entered by pressing ^V^H) Even better yet, in your .vimrc put this line : " enable the :Man command runtime ftplugin/man.vim and in ~/.bashrc put this : function man() { vim -c 'set nolist' -c ":Man $@" } then when you run 'man' in your shell you'll see the man page (in full color!) in a vim buffer. In addition, when you are in vim you can type :Man to get 's manpage in a buffer. It's really cool. (note: this requires vim 6 or newer and the man.vim plugin distributed with it) | so I can edit it with a text editors. If you want to edit a manpage you should learn troff. Man pages are written in troff format, and then troff (or groff) processes them to generate the properly formatted output for your display. Dumping out plain ascii and editing that won't have any long-term effects. (eg the maintainer of the manpage isn't going to accept a patch from it) | So far, I made this: |=20 | import string | fin =3D open("wget.man","r") | fout =3D open("wget.test","w") |=20 | while 1: | line =3D fin.readline() | if line =3D=3D "": | break | for ch in line: | if ch not in string.printable: | idx =3D line.find(ch) | temp =3D line[:idx] + line[idx+1:] | newline =3D temp | else: | newline =3D line | fout.write(newline) |=20 | fin.close() | fout.close() |=20 | And it gives a wrong result. How is it wrong? I'm not going to guess. Actuall, I will. It's wrong because all the characters in the troff source are already printable so you won't have changed anything. | I understand it is because I don't understand the structure of man | files. groff does. It is a troff processor. | Can anyone give me a correct example, please? Thanks. One way is using the existing tools on the shell. It would require less effort : $ man man | sed -e 's/.\x08//g' > man.text (or the equivalent vim commands given above) =20 If you want to use python instead of vim or sed or somesuch existing tool : import os , re input =3D os.popen( "man man" ) out =3D open( "output.text" , "w" ) for line in input : # requires python 2.2 out.write( re.sub( r'.\x08' , '' , line ) ) out.close() in.close() =20 (it does the same thing as all the other solutions I presented, but is clearly a lot more work/code) HTH, -D --=20 The light of the righteous shines brightly, but the lamp of the wicked is snuffed out. Proverbs 13:9 =20 http://dman.ddts.net/~dman/ --Bn2rw/3z4jIqBvZU Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0JUUYACgkQO8l8XBKTpRQACACfYZpCW3kHG5KVj1Osrr3V9tjP VAAAoIPsc4WWeSIk5whzkMR2wfxpa4Q9 =2kMQ -----END PGP SIGNATURE----- --Bn2rw/3z4jIqBvZU-- From sheila@thinkspot.net Fri Jun 14 03:17:22 2002 From: sheila@thinkspot.net (Sheila King) Date: Thu, 13 Jun 2002 19:17:22 -0700 Subject: [Tutor] Re: FTP Question In-Reply-To: <20020614015747.GA28056@dman.ddts.net> Message-ID: On Thu, 13 Jun 2002 20:57:47 -0500, Derrick 'dman' Hudson wrote: > | Since you did not assign any "identifier" or variable name to > | reference the object, it will close as soon as you are done > | working with it. > > > This assumes that no dangling references exist. It also assumes > there are no bugs in the interpreter that could crash it before > that happens. I think it is better practice to assign it to a > handle and explicitly close() it when you are done. Personally, this is how I usually handle my file routines as well. However, I was recently had someone review code I'd written, where I did as you suggest (created a reference to the file, and then specifically closed it), and when this much more experienced and knowledgeable person reviewed my code, he wrote: The following code: f = open(HTML_template_file, 'r') HTML_data = f.read() f.close() could just as easily be replace with: f = open(HTML_template_file[, 'r']).read() Matter of personal preference, I guess. These comments were written by the author of the following software: http://untroubled.org/ Now, your statements make good sense to me. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org From sarmstrong13@mac.com Fri Jun 14 04:13:32 2002 From: sarmstrong13@mac.com (SA) Date: Thu, 13 Jun 2002 22:13:32 -0500 Subject: [Tutor] More Tkinter Help Please Message-ID: Hi Everyone- I have another Tkinter question for you. I'm still trying to translate "that previously mentioned" Tcl/Tk program into Python/Tkinter. The following is all of the code I've managed so far: from Tkinter import * import sys import os class PyShell: def __init__(self, top): f = Frame(top) f.pack() self.t1 = Text(f, height="12", width="84", font="Courier 12") self.t1.pack(side=TOP, pady=2) self.t2 = Text(f, height="12", width="84", bg="lightblue", font="Courier 12") self.t2.pack(side=TOP, pady=2) self.b1 = Button(f, text="Execute", command=self.expyth) self.b1.pack(side=LEFT) self.b2 = Button(f, text="Clear Input", command=self.clearin) self.b2.pack(side=LEFT) self.b3 = Button(f, text="Clear Output", command=self.clearout) self.b3.pack(side=LEFT) self.b4 = Button(f, text="Save Input", command=self.savin) self.b4.pack(side=LEFT) def clearin(self): self.t1.delete(0,END) def clearout(self): self.t2.delete(0,END) def expyth(self): output = os.popen("python -c").t1() self.t2.delete(0,END) sys.stdout.write.t2(output) def savin(self): pass root = Tk() app = PyShell(root) root.mainloop() When I run this I get the following error: Traceback (most recent call last): File "PyShell.py", line 45, in ? app = PyShell(root) File "PyShell.py", line 17, in __init__ self.b1 = Button(f, text="Execute", command=self.expyth) AttributeError: PyShell instance has no attribute 'expyth' Any ideas on what I'm doing wrong here? Thanks. SA From iumarumo@eidosnet.co.uk Fri Jun 14 11:27:48 2002 From: iumarumo@eidosnet.co.uk (ibraheem umaru-mohammed) Date: Fri, 14 Jun 2002 11:27:48 +0100 Subject: [Tutor] Re: Convert man file into readable text file In-Reply-To: <20020614021326.GB28056@dman.ddts.net> References: <5.1.0.14.0.20020614071008.00a704d0@pop.cbn.net.id> <20020614021326.GB28056@dman.ddts.net> Message-ID: <20020614102748.GB20962@micromuse.com> [Derrick 'dman' Hudson wrote...] . . . -| | Can anyone give me a correct example, please? Thanks. -| -| One way is using the existing tools on the shell. It would require -| less effort : -| $ man man | sed -e 's/.\x08//g' > man.text -| -| (or the equivalent vim commands given above) -| If you have the "col" command you can do the following: $ man man | col -b | vim - Kindest regards, --ibs. -- ibraheem umaru-mohammed www.micromuse.com --0-- From alan.gauld@bt.com Fri Jun 14 12:18:13 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 14 Jun 2002 12:18:13 +0100 Subject: [Tutor] Tkinter script error. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C657@mbtlipnt02.btlabs.bt.co.uk> > When I run the following Python script: Is this actually cut n paste or did you retype it? > > def __init__(self, parent): > .... > b = Button(top, text="OK", command=self.ok) > b.pack(pady=5) > > I get the following error: > > Traceback (most recent call last): > File "(string)", line 22 in ? > File "(string)", line 11 in __init__ Indicates the problem is with the button. > TclError: unkown option "-test" Suggests you are trying to set an attribute called test which doesn't exist. Could it be you have a typo in the real code whereby you set "test" instead of "text" as shown in the code above? Just a thought. Alan G. From alan.gauld@bt.com Fri Jun 14 12:22:20 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 14 Jun 2002 12:22:20 +0100 Subject: [Tutor] Convert man file into readable text file Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C658@mbtlipnt02.btlabs.bt.co.uk> > I'm a newbie. I want to make a python script to convert a man > file into a readable text file As an excercise fine but you could just do: nroff -man foo.man > foo.txt Its easier, faster and probably more useful since it will create the paragraphs and headings etc correctly.... Alan G. From rob@uselesspython.com Fri Jun 14 13:28:20 2002 From: rob@uselesspython.com (Rob Andrews) Date: Fri, 14 Jun 2002 07:28:20 -0500 Subject: [Tutor] [slightly OT?] Python at Technipal.com Message-ID: <3D09E164.4090806@uselesspython.com> In a pleasant turn of events, a new site called Technipal.com (devoted to providing info and resources for novice and experienced programmers) has taken my suggestion and added a Python section: http://www.technipal.com/directory/dlanguages/dpython/index.html If anyone would consider taking a look and suggesting your own favorite link(s) to the webmaster there, it might help out. BTW, Useless Python hasn't dropped back into dormancy these last few weeks. I'm just taking a C++ class that meets every day at nearby Belhaven College, so I have a little less time to manage at the moment. Thanks to Python (and the Tutor List) helping me get a handle on so many important concepts, I'm currently holding steady at an A+ average in the class and helping the other students! Of course, I'm my usual Python Evangelist self in the class every day, and the instructor was impressed with the very size of Useless Python (a fact attibutable primarily to your source code submissions). "This is one BIG site!" he said. peace, Rob From cheshire_cat_sf@yahoo.com Fri Jun 14 15:21:59 2002 From: cheshire_cat_sf@yahoo.com (Britt Green) Date: Fri, 14 Jun 2002 07:21:59 -0700 (PDT) Subject: [Tutor] Python-based Blog Software? In-Reply-To: <20020614020302.22138.4434.Mailman@mail.python.org> Message-ID: <20020614142159.58018.qmail@web14107.mail.yahoo.com> Anyone know if there's any Python-based weblog software, similiar perhaps to Slashcode or Scoop? Google isn't returning anything.... Britt ===== "The ocean, she is strange and wonderous, filled with animals that disturb even a Frenchman." __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From alan.gauld@bt.com Fri Jun 14 17:05:50 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 14 Jun 2002 17:05:50 +0100 Subject: [Tutor] Re: FTP Question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C65E@mbtlipnt02.btlabs.bt.co.uk> > specifically closed it), and when this much more experienced and > knowledgeable person reviewed my code, he wrote: > > The following code: > f = open(HTML_template_file, 'r') > HTML_data = f.read() > f.close() > could just as easily be replace with: > f = open(HTML_template_file[, 'r']).read() > Matter of personal preference, I guess. Then he was wrong... it should be: HTML_data = open(HTML_template_file[, 'r']).read() and I assume the [, 'r'] bit is just to show its optionality... Personally I use the specific assignment but I do suspect thats just left over paranoia from my C/C++ days :-) Alan g. From charlie@begeistert.org Fri Jun 14 19:40:10 2002 From: charlie@begeistert.org (Charlie Clark) Date: Fri, 14 Jun 2002 18:40:10 +0000 Subject: [Tutor] re: Python based Blog software In-Reply-To: <20020614160004.23404.72623.Mailman@mail.python.org> References: <20020614160004.23404.72623.Mailman@mail.python.org> Message-ID: <20020614184210.14143.17@bepc.1023995658.fake> On 2002-06-14 at 16:00:04 [+0000], you wrote: > Anyone know if there's any Python-based weblog software, similiar > perhaps to Slashcode or Scoop? Google isn't returning anything.... Just in case nobody else has got round to it: look at Squishdot for Zope. Because Zope is so useful most people use Zope for CM in Python because they're good and, therefore, lazy programmers. Charlie From alan.gauld@bt.com Fri Jun 14 17:46:35 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 14 Jun 2002 17:46:35 +0100 Subject: [Tutor] More Tkinter Help Please Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C660@mbtlipnt02.btlabs.bt.co.uk> > class PyShell: > def __init__(self, top): > self.b1 = Button(f, text="Execute", command=self.expyth) > self.b1.pack(side=LEFT) > > def expyth(self): > output = os.popen("python -c").t1() > self.t2.delete(0,END) > sys.stdout.write.t2(output) > When I run this I get the following error: > > Traceback (most recent call last): > AttributeError: PyShell instance has no attribute 'expyth' I think its because at the time that init is defined it can't see self.expyth because its not been defined yet. Try moving the init method after all the other methods? However I'm not really happy with that answer because init shouldn't run till you create an instance which is after you define the class, so I could very well be wrong! Alan G. From sarmstrong13@mac.com Fri Jun 14 18:03:21 2002 From: sarmstrong13@mac.com (SA) Date: Fri, 14 Jun 2002 12:03:21 -0500 Subject: [Tutor] Re: Translating Tcl/Tk code into Python/Tkinter help please... In-Reply-To: References: Message-ID: On 6/14/02 3:59 AM, in article m3sn3qs0ba.fsf@fkogtsp1.bmc.uu.se, "Thomas Sicheritz-Ponten" wrote: > "try" and "exec" is used instead of "catch" > but in this case you could use commands.getoutput > > Untested code: > > import commands > from Tkinter import * > > > def execute_python_code1(): > global t1, t2 > > txt = t1.get(0.0, END) > com = "/sw/bin/python -c %s" txt > > try: > output = commands.getoutput(com) > except: > output = 'Error running command: %s' % com > > t2.delete(0.0, END) > t2.insert(END,output) > > > > # getoutput returns errors as catch does, so there is no need to use > try/except > # IMHO, you should strip newlines from the command returned from the text > widget > > def execute_python_code2(): > t2.delete(0.0, END) > output = commands.getoutput(com = "/sw/bin/python -c %s" % t1.get(0.0, > END).strip()) > t2.insert(END,output) > > Thank You Everyone for your help. I changed: def execute_python_code2(): t2.delete(0.0, END) output = commands.getoutput(com = "/sw/bin/python -c %s" % t1.get(0.0, END).strip()) t2.insert(END,output) to: def execute_python_code2(): t2.delete(0.0, END) output = commands.getoutput(t1.get(0.0,END) t2.insert(END,output) This seems to do the trick. I can now enter a python command in t1 hit the execute button and the result is printed in t2. This seems to accomplish what I need. Once again, thank you everyone. Thanks. SA From jeff@ccvcorp.com Fri Jun 14 19:14:33 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri, 14 Jun 2002 11:14:33 -0700 Subject: [Tutor] Re: FTP Question References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C65E@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <3D0A3289.5AC57FFE@ccvcorp.com> alan.gauld@bt.com wrote: > > specifically closed it), and when this much more experienced and > > knowledgeable person reviewed my code, he wrote: > > > > The following code: > > f = open(HTML_template_file, 'r') > > HTML_data = f.read() > > f.close() > > could just as easily be replace with: > > f = open(HTML_template_file[, 'r']).read() > > Then he was wrong... it should be: > > HTML_data = open(HTML_template_file[, 'r']).read() > > and I assume the [, 'r'] bit is just to show its optionality... > > Personally I use the specific assignment but I do suspect > thats just left over paranoia from my C/C++ days :-) Actually, I think it's justified paranoia. As I understand it, in Jython timely finalization is not guaranteed (because it uses Java's GC, which does not immediately clean up). This means that the re-coded example, with no explicit close(), leaves the file open for some undefined length of time. For files open for reading, this is not so bad, but files that are written to in this way will not be written to disk (because the buffer is never flushed) until the file is closed, and there's no way to know when that might be (if ever -- a program crash will kill your data without ever writing it out). Allowing GC to implicitly close files does work in CPython, but.... while I don't envision my code running under Jython, I'd rather avoid techniques that are known to be implementation-dependent (just as I try to write platform-portable code as much as possible, despite that I almost exclusively run under Windows). And anyhow, explicit is better than implicit. ;) Jeff Shannon Technician/Programmer Credit International From jimmy_130@lycos.com Fri Jun 14 22:13:00 2002 From: jimmy_130@lycos.com (James M Lang) Date: Fri, 14 Jun 2002 17:13:00 -0400 Subject: [Tutor] Question about sprites Message-ID: I heard from a friend that in the videogame world that sprites are programmed by telling the computer or videogame console where each pixel or dot was. That sounds kinda tedious. Couldn't you just load a picture? Is that possible? _______________________________________________________ WIN a first class trip to Hawaii. Live like the King of Rock and Roll on the big Island. Enter Now! http://r.lycos.com/r/sagel_mail/http://www.elvis.lycos.com/sweepstakes From jimmy_130@lycos.com Fri Jun 14 22:13:00 2002 From: jimmy_130@lycos.com (James M Lang) Date: Fri, 14 Jun 2002 17:13:00 -0400 Subject: [Tutor] Question about sprites Message-ID: I heard from a friend that in the videogame world that sprites are programmed by telling the computer or videogame console where each pixel or dot was. That sounds kinda tedious. Couldn't you just load a picture? Is that possible? _______________________________________________________ WIN a first class trip to Hawaii. Live like the King of Rock and Roll on the big Island. Enter Now! http://r.lycos.com/r/sagel_mail/http://www.elvis.lycos.com/sweepstakes From shendric@arches.uga.edu Fri Jun 14 23:18:56 2002 From: shendric@arches.uga.edu (shendric@arches.uga.edu) Date: Fri, 14 Jun 2002 17:18:56 -0500 Subject: [Tutor] Runtime Errors Message-ID: <1024089536.smmsdV1.1.1@mail.arches.uga.edu> Hi all, I've got a script I'm working on that is a kind of spreadsheet. There are a fixed number of 4 cells in each row, but the idea would be to have as many rows as one wishes. The algorithm for the spreadsheet works fine, but I get a RuntimeError when I try to load a tab-delimited text file into the cells. The loading algorithm is this: 1. Open a text file 2. Read the lines of the text file into a list (readlines()) 3. Take each line and do the following: a. create an instance of the TranscriptionCell class, which is a class that includes four Tkinter Pmw.ScrolledText widgets b. append that instance to a list c. put the contents of the first part of the line into the first text widget, then the second into the second, etc. 4. close the file I get the following error: RuntimeError: maximum recursion depth exceeded Now, I've gotten it to go just fine with only a few rows, but not if there are a lot of them. Anyway, here's the code for the algorithm above. Is it just simply too much to have that many instances of a class with that many scrolling textboxes? def openTrans(self, event=None): ind = 0 self.rowlist=[] file = askopenfile(title="Open Transcript File", filetypes=(("text files", "*.txt"),("All files", "*"))) try: filetoread = open(file.name, 'r') except: print "file open error" pass try: filecontents = filetoread.readlines() filetoread.close() for x in filecontents: rowcontents = x.split("\t") self.rowlist.append(TranscriptionCell(self.inner, row=self.row)) try: self.rowlist[ind].TTime.settext(rowcontents[0]) except: pass try: self.rowlist[ind].TSpeak.settext(rowcontents[1]) except: pass try: self.rowlist[ind].TTrans.textBox.settext(rowcontents[2]) except: pass try: self.rowlist[ind].Comments.settext(rowcontents[3]) except: pass self.row = self.row + 1 ind = ind + 1 except: pass From paulsid@shaw.ca Fri Jun 14 22:34:52 2002 From: paulsid@shaw.ca (Paul Sidorsky) Date: Fri, 14 Jun 2002 15:34:52 -0600 Subject: [Tutor] Question about sprites References: Message-ID: <3D0A617C.75B9420@shaw.ca> James M Lang wrote: > I heard from a friend that in the videogame world that sprites are > programmed by telling the computer or videogame console where each > pixel or dot was. That sounds kinda tedious. Couldn't you just load > a picture? Is that possible? I think perhaps some of the details might have got lost somewhere in the description. Sprites generally do indeed work by drawing a picture as you suggested. For simple games you just keep one coordinate in memory and draw the entire picture at that point. This coordinate is called the "hotspot". Regardless of whether the picture is a giant space ship or a tiny projectile, you only need one coordinate for it. The hotspot can be put anywhere within the picture. Popular choices are the top left (because it's the easiest to manage) and the centre (because you can do simple radius-based collision detection). Fancier systems might define the hotspot differently for each sprite or might have multiple hotspots for each sprite to allow for fancier collision algorithms. For example you might make each pixel on the edge of the sprite (e.g. the spaceship) a hotspot; this would perfectly define the boundary of the ship so your collisions would be very accurate. Of course this does take more computing power and does get more tedious as you suggested. If you're interested in doing stuff with sprites in Python, pygame now comes with a really cool sprite module which will manage lots of things for you. The sprite module is written in Python itself so you can see how it manages everything too - check sprite.py in your site-packages directory. BTW I'm not in the videogame industry by any means, I'm just a hobbyist game programmer. "Real game programmers" probably do things much more sophisticatedly, especially nowadays. -- ====================================================================== Paul Sidorsky Calgary, Canada paulsid@shaw.ca http://members.shaw.ca/paulsid/ From ponderor@lycos.com Fri Jun 14 22:41:54 2002 From: ponderor@lycos.com (Dean Goodmanson) Date: Fri, 14 Jun 2002 14:41:54 -0700 Subject: [Tutor] Python based blog software Message-ID: Are you looking to figure out the code or use a Python friendly blogger? Check out the latest source for PythonCard for Blog Client code samples. There a few solutions for Python friendly blogger's from Python frienldy Zope. Closest to Slashcode is "Squishdot" at www.squishdot.org . I'd suggest trying it out through a www.freezope.org account. It's very customizable, here are a few implementations from My use as a blog : http://nomad.freezope.org/weblog , to elegantly simple: ZopeNewbies: http://www.zopenewbies.net , or with consistent icons: http://www.pault.com/X and finally as a heavily used news/discussion site: http://dot.kde.org/ The source is primarily Zope related, so probably not the best arena for a Python newbie. For a Blog Server in Python I believe there's an interesting project here: http://community.scriptmeridian.org/16433 Best Regards, Dean _______________________________________________________ WIN a first class trip to Hawaii. Live like the King of Rock and Roll on the big Island. Enter Now! http://r.lycos.com/r/sagel_mail/http://www.elvis.lycos.com/sweepstakes From urnerk@qwest.net Sat Jun 15 00:41:14 2002 From: urnerk@qwest.net (Kirby Urner) Date: Fri, 14 Jun 2002 16:41:14 -0700 Subject: [Tutor] Python-based Blog Software? Message-ID: <5.1.1.6.0.20020614164102.01fe6610@pop3.norton.antivirus> At 07:21 AM 6/14/2002 -0700, Britt Green wrote: >Anyone know if there's any Python-based weblog software, similiar >perhaps to Slashcode or Scoop? Google isn't returning anything.... > >Britt > This might best come under the Zope category. Most efforts Pythonic are focussed on customizing this versatile flagship web application server from Digital Creations (free to download, many paid consultants to make it do whatever; CMF design big these days). Kirby From mico@cbn.net.id Sat Jun 15 02:05:31 2002 From: mico@cbn.net.id (Mico Siahaan) Date: Sat, 15 Jun 2002 08:05:31 +0700 Subject: [Tutor] Making Python modules with C Message-ID: <5.1.0.14.0.20020615075405.00ad3010@pop.cbn.net.id> I tried to make Python dynamic modules with C (pyd files). I followed the 'Extending and Embedding the Python Interpreter' tutorial from ActiveState Python documentation, but failed. I guess the tutorial written for Linux user or Microsoft Visual C++ (as it mentioned in Chapter 4 of the Tutorial). The problem is: in my Window machine I don't have Visual C++ (I don't have money to buy it :( ). I only have lcc-win32 compiler. So, anybody ever used lcc-win32 compiler to build Python modules. Mico Siahaan --- E-mail : mico at cbn dot net dot id From mico@cbn.net.id Sat Jun 15 01:53:59 2002 From: mico@cbn.net.id (Mico Siahaan) Date: Sat, 15 Jun 2002 07:53:59 +0700 Subject: [Tutor] Convert man file into readable text file In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C658@mbtlipnt02.btlabs .bt.co.uk> Message-ID: <5.1.0.14.0.20020615075133.00acf200@pop.cbn.net.id> At 12:22 PM 6/14/2002 +0100, alan.gauld@bt.com wrote: > > I'm a newbie. I want to make a python script to convert a man > > file into a readable text file > >As an excercise fine but you could just do: > >nroff -man foo.man > foo.txt > >Its easier, faster and probably more useful since it will >create the paragraphs and headings etc correctly.... > >Alan G. Thanks. Actually I'm using Windows. I copied a man file into my Windows machine then tried to read that man file. So, I guess I should process the file first with nroff before copy it into my Windows machine. :) Mico Siahaan --- E-mail : mico at cbn dot net dot id From dyoo@hkn.eecs.berkeley.edu Sat Jun 15 07:23:10 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Jun 2002 23:23:10 -0700 (PDT) Subject: [Tutor] Making Python modules with C In-Reply-To: <5.1.0.14.0.20020615075405.00ad3010@pop.cbn.net.id> Message-ID: On Sat, 15 Jun 2002, Mico Siahaan wrote: > I followed the 'Extending and Embedding the Python Interpreter' tutorial > from ActiveState Python documentation, but failed. I guess the tutorial > written for Linux user or Microsoft Visual C++ (as it mentioned in > Chapter 4 of the Tutorial). The problem is: in my Window machine I don't > have Visual C++ (I don't have money to buy it :( ). I only have > lcc-win32 compiler. So, anybody ever used lcc-win32 compiler to build > Python modules. Hi Mico, Yikes, this sounds like a really specialized question. You might want to ask your question on the 'comp.lang.python' newsgroup; there are a few compiler gurus there who can probably help you with lcc. I did a quick scan through the Python README file, and there's a chance that cygwin will work for you. Cygwin is a port of the GCC tools to Windows, and you can find out more information here: http://sources.redhat.com/cygwin/ Ah! Take a look at the "How to Debug Python Extensions on Windows with Open Source Tools" HOWTO: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82826 Looks like there's no need to go for Visual C++ after all. *grin* Anyway, hope this helps! From dyoo@hkn.eecs.berkeley.edu Sat Jun 15 07:53:18 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Jun 2002 23:53:18 -0700 (PDT) Subject: [Tutor] Runtime Errors In-Reply-To: <1024089536.smmsdV1.1.1@mail.arches.uga.edu> Message-ID: On Fri, 14 Jun 2002 shendric@arches.uga.edu wrote: > I've got a script I'm working on that is a kind of spreadsheet. There > are a fixed number of 4 cells in each row, but the idea would be to have > as many rows as one wishes. The algorithm for the spreadsheet works > fine, but I get a RuntimeError when I try to load a tab-delimited text > file into the cells. > > The loading algorithm is this: > > 1. Open a text file > 2. Read the lines of the text file into a list (readlines()) > 3. Take each line and do the following: > a. create an instance of the TranscriptionCell class, which is a > class that includes four Tkinter Pmw.ScrolledText widgets > b. append that instance to a list > c. put the contents of the first part of the line into the first > text widget, then the second into the second, etc. > 4. close the file Sounds reasonable enough. Yes, this should work. > > I get the following error: > RuntimeError: maximum recursion depth exceeded Hmmm... does the error message also give a clue in which function, and around which line it goes bonkers? > Now, I've gotten it to go just fine with only a few rows, but not if > there are a lot of them. We'll have to look through the code to see where the recursion's coming from. Reading... hmmm... It might not be such a good idea to wrap every statement with exception handling like: ### try: self.rowlist[ind].TTime.settext(rowcontents[0]) except: pass try: self.rowlist[ind].TSpeak.settext(rowcontents[1]) except: pass ### Doing just a 'pass' when an exception occurs is like an ostrich that puts its head in the sand: We're ignoring any potentially bad problems! If the first row setting fails, it's probable that the whole rowcontents list has some weirdness that should be reported to the user. To make this function easier to debug, we can strip out some of the exception handling code, and put a traceback.print_exc() call in the code: ### def openTrans(self, event=None): file = askopenfile(title="Open Transcript File", filetypes=(("text files", "*.txt"), ("All files", "*"))) filetoread = open(file.name, 'r') filecontents = filetoread.readlines() filetoread.close() ind = 0 self.rowlist=[] for x in filecontents: rowcontents = x.split("\t") self.rowlist.append(TranscriptionCell(self.inner, row=self.row)) try: self.rowlist[ind].TTime.settext(rowcontents[0]) self.rowlist[ind].TSpeak.settext(rowcontents[1]) self.rowlist[ind].TTrans.textBox.settext(rowcontents[2]) self.rowlist[ind].Comments.settext(rowcontents[3]) except: traceback.print_exc() self.row = self.row + 1 ind = ind + 1 ### The traceback.print_exc() should tell us if there's something else that's going weird. Hmmm.... but I don't see any obvious recursion here. Can you show the last few previous lines of the error message as well? It'll help us to find where exactly the recursion is occuring. Sounds like a tricky bug, but don't worry, we're bound to squish it. *grin* Talk to you later! From dyoo@hkn.eecs.berkeley.edu Sat Jun 15 07:56:36 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 14 Jun 2002 23:56:36 -0700 (PDT) Subject: [Tutor] More Tkinter Help Please In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C660@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Fri, 14 Jun 2002 alan.gauld@bt.com wrote: > > class PyShell: > > def __init__(self, top): > > self.b1 = Button(f, text="Execute", command=self.expyth) > > self.b1.pack(side=LEFT) > > > > def expyth(self): > > output = os.popen("python -c").t1() > > self.t2.delete(0,END) > > sys.stdout.write.t2(output) > > > When I run this I get the following error: > > > > Traceback (most recent call last): AttributeError: PyShell instance > > has no attribute 'expyth' > > I think its because at the time that init is defined it can't see > self.expyth because its not been defined yet. Try moving the init > method after all the other methods? > > > However I'm not really happy with that answer because init shouldn't run > till you create an instance which is after you define the class, so I > could very well be wrong! Hi SA, Following up: did you find out what was causing this weird AttributeError? I'm just curious to know. *grin* Talk to you later! From alex@gabuzomeu.net Sat Jun 15 12:26:30 2002 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Sat, 15 Jun 2002 13:26:30 +0200 Subject: [Tutor] Python-based Blog Software? In-Reply-To: <20020614160004.23404.72623.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20020615132349.00b23f00@pop3.norton.antivirus> Hi Britt, At 12:00 14/06/2002 -0400, tutor-request@python.org wrote: >Date: Fri, 14 Jun 2002 07:21:59 -0700 (PDT) >From: Britt Green >Subject: [Tutor] Python-based Blog Software? > >Anyone know if there's any Python-based weblog software, similiar >perhaps to Slashcode or Scoop? Google isn't returning anything.... Take a look at pyBlog. "A blogging framework coded entirely in Python. Highly customizable. Both user and developer documentation are included in the file. Just unpack in the directory where you want pyBlog to be kept." http://www.ocf.berkeley.edu/~bac/Askewed_Thoughts/HTML/code/python.php3 >"The ocean, she is strange and wonderous, filled with animals that disturb >even a Frenchman." Nope. We eat them. Bwa ha ha! Alex From dman@dman.ddts.net Sat Jun 15 14:46:55 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat, 15 Jun 2002 08:46:55 -0500 Subject: [Tutor] Re: Convert man file into readable text file In-Reply-To: <5.1.0.14.0.20020615075133.00acf200@pop.cbn.net.id> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C658@mbtlipnt02.btlabs.bt.co.uk> <5.1.0.14.0.20020615075133.00acf200@pop.cbn.net.id> Message-ID: <20020615134655.GA16490@dman.ddts.net> --UlVJffcvxoiEqYs2 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Jun 15, 2002 at 07:53:59AM +0700, Mico Siahaan wrote: | At 12:22 PM 6/14/2002 +0100, alan.gauld@bt.com wrote: | >> I'm a newbie. I want to make a python script to convert a man | >> file into a readable text file | > | >As an excercise fine but you could just do: | > | >nroff -man foo.man > foo.txt | > | >Its easier, faster and probably more useful since it will | >create the paragraphs and headings etc correctly.... | | Thanks. Actually I'm using Windows. I copied a man file into my Windows= =20 | machine then tried to read that man file. | So, I guess I should process the file first with nroff before copy it int= o=20 | my Windows machine. :) Install cygwin. When you do, you'll get 'man', 'groff', 'sed', 'awk', 'vim', and all the other nice tools that are so essential to the usability of any system. -D --=20 Do not be afraid of those who kill the body but cannot kill the soul. Rather be afraid of the One who can destroy both soul and body in hell. Matthew 10:28 =20 http://dman.ddts.net/~dman/ --UlVJffcvxoiEqYs2 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0LRU4ACgkQO8l8XBKTpRTPUQCdEzuZ1/3Y7R76U2GxN7JC+yKL hKkAnA3+Nze/agF2IGFQgPERZkTlOj3I =lZvD -----END PGP SIGNATURE----- --UlVJffcvxoiEqYs2-- From mico@cbn.net.id Sat Jun 15 09:55:25 2002 From: mico@cbn.net.id (Mico Siahaan) Date: Sat, 15 Jun 2002 15:55:25 +0700 Subject: [Tutor] Making Python modules with C In-Reply-To: References: <5.1.0.14.0.20020615075405.00ad3010@pop.cbn.net.id> Message-ID: <5.1.0.14.0.20020615155207.00aded40@pop.cbn.net.id> At 11:23 PM 6/14/2002 -0700, you wrote: Thanks. > > I followed the 'Extending and Embedding the Python Interpreter' tutorial > > from ActiveState Python documentation, but failed. I guess the tutorial > > written for Linux user or Microsoft Visual C++ (as it mentioned in > > Chapter 4 of the Tutorial). The problem is: in my Window machine I don't > > have Visual C++ (I don't have money to buy it :( ). I only have > > lcc-win32 compiler. So, anybody ever used lcc-win32 compiler to build > > Python modules. > >Hi Mico, > >Yikes, this sounds like a really specialized question. You might want to >ask your question on the 'comp.lang.python' newsgroup; there are a few >compiler gurus there who can probably help you with lcc. OK, I'll try it. >I did a quick scan through the Python README file, and there's a chance >that cygwin will work for you. Cygwin is a port of the GCC tools to >Windows, and you can find out more information here: > > http://sources.redhat.com/cygwin/ I used gcc (cygwin) and got this error message: In file included from include/Python.h:54, from spammodule.c:1: include/pyport.h:422: #error "LONG_BIT definition appears wrong for platform (ba d gcc/glibc config?)." What does it mean? Ang how to solve it? Mico Siahaan --- E-mail : mico at cbn dot net dot id From dman@dman.ddts.net Sat Jun 15 23:51:26 2002 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat, 15 Jun 2002 17:51:26 -0500 Subject: [Tutor] Re: Making Python modules with C In-Reply-To: <5.1.0.14.0.20020615155207.00aded40@pop.cbn.net.id> References: <5.1.0.14.0.20020615075405.00ad3010@pop.cbn.net.id> <5.1.0.14.0.20020615155207.00aded40@pop.cbn.net.id> Message-ID: <20020615225126.GA21248@dman.ddts.net> --VbJkn9YxBvnuCH5J Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Jun 15, 2002 at 03:55:25PM +0700, Mico Siahaan wrote: | At 11:23 PM 6/14/2002 -0700, you wrote: =20 | >I did a quick scan through the Python README file, and there's a chance | >that cygwin will work for you. Cygwin is a port of the GCC tools to | >Windows, and you can find out more information here: | > | > http://sources.redhat.com/cygwin/ |=20 | I used gcc (cygwin) and got this error message: |=20 | In file included from include/Python.h:54, from spammodule.c:1: | include/pyport.h:422: #error "LONG_BIT definition appears wrong for=20 | platform (ba | d gcc/glibc config?)." |=20 | What does it mean? Ang how to solve it? Last time I saw that error message, it was on a RH 7.0 machine and it was caused by a buggy libc. Here's the code that is causing that : #if LONG_BIT !=3D 8 * SIZEOF_LONG /* 04-Oct-2000 LONG_BIT is apparently (mis)defined as 64 on some recent * 32-bit platforms using gcc. We try to catch that here at compile-time * rather than waiting for integer multiplication to trigger bogus * overflows. */ #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc confi= g?)." #endif Python's build system is built to figure out what the limits of the basic C data types are on your platform (because C isn't very precise about it). Python needs that information so it can properly detect and handle overflows and stuff like that. I have an x86 system (ia32), so for me the relvant sizes are : LONG_MAX 2147483647=20 LONG_BIT 32=20 SIZEOF_LONG 4=20 That RH 7.0 box I mentioned had LONG_BIT set to 64, which is why python barfed ( 4*64 !=3D 2147483647 ). The best solution is to get a fixed libc, but on that RH box I simply modified /usr/include/bits/xopen_lim.h to set LONG_BIt to the correct value. =20 HTH, -D --=20 Better a little with righteousness than much gain with injustice. Proverbs 16:8 =20 http://dman.ddts.net/~dman/ --VbJkn9YxBvnuCH5J Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj0LxO4ACgkQO8l8XBKTpRTVnwCgm1/DysGxBmnP1TpJHJqrCIim GtAAoJAl8T8Id8zbvoQbWeY3BppGuUWH =sofc -----END PGP SIGNATURE----- --VbJkn9YxBvnuCH5J-- From sarmstrong13@mac.com Sun Jun 16 02:57:03 2002 From: sarmstrong13@mac.com (SA) Date: Sat, 15 Jun 2002 20:57:03 -0500 Subject: [Tutor] More Tkinter Help Please In-Reply-To: Message-ID: On 6/15/02 1:56 AM, "Danny Yoo" wrote: > > > On Fri, 14 Jun 2002 alan.gauld@bt.com wrote: > >>> class PyShell: >>> def __init__(self, top): >>> self.b1 = Button(f, text="Execute", command=self.expyth) >>> self.b1.pack(side=LEFT) >>> >>> def expyth(self): >>> output = os.popen("python -c").t1() >>> self.t2.delete(0,END) >>> sys.stdout.write.t2(output) >> >>> When I run this I get the following error: >>> >>> Traceback (most recent call last): AttributeError: PyShell instance >>> has no attribute 'expyth' >> >> I think its because at the time that init is defined it can't see >> self.expyth because its not been defined yet. Try moving the init >> method after all the other methods? >> >> >> However I'm not really happy with that answer because init shouldn't run >> till you create an instance which is after you define the class, so I >> could very well be wrong! > > > Hi SA, > > Following up: did you find out what was causing this weird AttributeError? > I'm just curious to know. *grin* > > > Talk to you later! > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Sorry. I've been busy and have not had a chance to reply yet. Yes I was able to figure the issue. It had to do with cut and pasting between a vi file and a bbedit file. I messed up my tabs. I rewrote the whole program with the correct tabs and everything runs now.(with a few other changes.) I'm now working on the "save" button and am having a bit of trouble. I think it stems from my lack of OO understanding. Here is what I have so far: from Tkinter import * import os import commands import tkSimpleDialog class PyShell: def clearin(self): self.t1.delete(0.0,END) def clearout(self): self.t2.delete(0.0,END) def expyth(self): self.t2.delete(0.0, END) self.output = commands.getoutput(self.t1.get(0.0, END)) self.t2.insert(END, self.output) def __init__(self, top): self.t1 = Text(top, height="12", width="84", font="Courier 12") self.t1.pack(side=TOP, pady=2) f = Frame(top) f.pack() self.b1 = Button(f, text="Execute", command=self.expyth) self.b1.pack(side=LEFT) self.b2 = Button(f, text="Clear Input", command=self.clearin) self.b2.pack(side=LEFT) self.b3 = Button(f, text="Clear Output", command=self.clearout) self.b3.pack(side=LEFT) self.b4 = Button(f, text="Save Input", command=Saving) self.b4.pack(side=LEFT) self.t2 = Text(top, height="12", width="84", bg="lightblue", font="Courier 12") self.t2.pack(side=TOP, pady=2) class Saving(tkSimpleDialog.Dialog): def savin(self, question): Label(question, text="Directory:").grid(row=0) Label(question, text="Filename:").grid(row=1) self.e1 = Entry(question) self.e2 = Entry(question) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) def apply(self): dir = self.e1.get() fn = self.e2.get() sav = dir + fn savfile = open(sav, "w") for line in self.t1.readlines(): savefile.write(line) osavefile.close() root = Tk() app = PyShell(root) root.mainloop() I think the problem is with: class Saving(tkSimpleDialog.Dialog): Since this is not a child of the PyShell class and therefore is not inheriting? from this class? I think if I make PyShell inherit from tkSimpleDialog.Dialog and Saving inherit from PyShell, this might work? What do you think? Thanks. SA From dyoo@hkn.eecs.berkeley.edu Sun Jun 16 19:33:43 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 16 Jun 2002 11:33:43 -0700 (PDT) Subject: [Tutor] More Tkinter Help Please [callbacks and embedded functions] In-Reply-To: Message-ID: > I'm now working on the "save" button and am having a bit of trouble. I > think it stems from my lack of OO understanding. Here is what I have so > far: > [code cut] > > I think the problem is with: > class Saving(tkSimpleDialog.Dialog): > > Since this is not a child of the PyShell class and therefore is not > inheriting? from this class? I think if I make PyShell inherit from > tkSimpleDialog.Dialog and Saving inherit from PyShell, this might work? > What do you think? I'm not too familiar with tkSimpleDialog.Dialog, so I'm not quite sure if there's a problem with inheritance. Can you explain more what problems you're running into with this code? Ah! I think that for this statement: self.b4 = Button(f, text="Save Input", command=Saving) if 'tkSimpleDialog' is the tkSimpleDialog that's in the 'Introduction To Tkinter' tutorial: http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm then we need to do a little extra: the dialog box needs to know its parent window when it's being constructed! Let's take a look at the definition of tkSimpleDialog.Dialog again: ### Sample of tkSimpleDialog.py # File: tkSimpleDialog.py from Tkinter import * import os class Dialog(Toplevel): def __init__(self, parent, title = None): ### So when we create a Dialog box, this dialog box must take in an additional 'parent' parameter. However, back in your code: self.b4 = Button(f, text="Save Input", command=Saving) When the fourth button is pressed, it tries to call the Saving dialog constructor with no parameters: this may be the problem that you're running into. We'd like to be able to do something like: self.b4 = Button(f, text="Save Input", command=Saving(f)) since 'f' is the frame parent that we'd like to attach the Dialog to... but the problem with this is that Python will actually call Saving(f). It calls it too soon, because, to Python, Saving(f) is a function call, so it just evaluates it straightaway. We need a way to create a callback function that knows about 'f', enough so that it can do a 'Saving(f)' when our button is pressed. What to do? The solution actually isn't too bad: ### def saving_callback(): Saving(f) self.b4 = Button(f, text="Save Input", command=saving_callback) ### That is, we can actually embed a small function called 'saving_callback', and we can pass that off to as the button callback. The miniature function has access to all the local variables of its parent, which is why saving_callback() can say 'f' without problems. Functions within functions will be weird if you haven't seen it before, so here's another example to demonstrate the idea: ### >>> def suffixAppenderMaker(suffix): ... def appender(word): ... return word + '-' + suffix ... return appender ... >>> ed_maker = suffixAppenderMaker('ed') >>> ed_maker('walk') 'walk-ed' >>> ed_maker('dance') 'dance-ed' >>> ed_maker('wick') 'wick-ed' ### Please feel free to ask more questions on this. (I'm getting over a cold, so most of this may just be incoherant. *grin*) From mista2kool@yahoo.com Sun Jun 16 19:39:36 2002 From: mista2kool@yahoo.com (mista kool) Date: Sun, 16 Jun 2002 11:39:36 -0700 (PDT) Subject: [Tutor] cdrw wroting Message-ID: <20020616183936.13927.qmail@web21503.mail.yahoo.com> how do you write your programs to cdr __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From dyoo@hkn.eecs.berkeley.edu Sun Jun 16 20:47:11 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 16 Jun 2002 12:47:11 -0700 (PDT) Subject: [Tutor] cdrw wroting In-Reply-To: <20020616183936.13927.qmail@web21503.mail.yahoo.com> Message-ID: On Sun, 16 Jun 2002, mista kool wrote: > how do you write your programs to cdr Hi Mista, Your question isn't really related to Python or programming, so we probably aren't the best people to ask about this. You may get better help about CDR stuff by visiting: http://www.cdrfaq.org/ That page has a lot of information about recording CDR's, and may help you find the information you're looking for. Good luck to you! From alan.gauld@bt.com Sun Jun 16 22:43:45 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 16 Jun 2002 22:43:45 +0100 Subject: [Tutor] More Tkinter Help Please Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C661@mbtlipnt02.btlabs.bt.co.uk> > Yes I was able to figure the issue. It had to do with cut and pasting > between a vi file and a bbedit file. I messed up my tabs. Interesting. That usually gives rise to a more explicit error about indenting. Howwever so ong as yuou fixed it... :-) > I'm now working on the "save" button and am having a bit of > trouble. > Here is what I have so far: > class PyShell: > def clearin(self): > self.t1.delete(0.0,END) > def expyth(self): > self.t2.delete(0.0, END) > self.output = commands.getoutput(self.t1.get(0.0, END)) > self.t2.insert(END, self.output) Just a wee point but as your GUIs get bigger this styule of t1,t2 etc will get really hard to maintain. Its much better to name the control variables aftyer their function, thus the above might become: def clearin(self): self.tInput.delete(0.0,END) def expyth(self): self.tOutput.delete(0.0, END) self.output = commands.getoutput(self.tInput.get(0.0, END)) self.tOutput.insert(END, self.output) This makes it clearer whats happening while keeping the first letter prefix to indicate what kind of widget is involved. > def __init__(self, top): > .... > self.b1 = Button(f, text="Execute", command=self.expyth) similarly: self.bExec = Button(.... etc. > class Saving(tkSimpleDialog.Dialog): > def savin(self, question): > Label(question, text="Directory:").grid(row=0) > Label(question, text="Filename:").grid(row=1) > self.e1 = Entry(question) > self.e2 = Entry(question) and here: self.eDir = Entry(... self.eFile = Entry(... makes it easier later to remember which Entry you want to read/modify. > I think the problem is with: > class Saving(tkSimpleDialog.Dialog): > > Since this is not a child of the PyShell class and therefore is not > inheriting from this class? Inheriting means that your class is the "same kind of thing" that the parent is. PyShell is an Application not a Dialog. If your Saving class is a type of Dialog (which I assume it is) then you are inheriting correctly. But your Saving class has no init method so the widgets etc are not created etc. The 'savin' method would need to be called from somewhere but isn't. (Danny has also discussed the need to pass in a parent when you call the constructor). Without an init the class will be constructed using the inherited init from tkSimpleDialog but it doesn't know about your savin method... At least I think that's the problem, I've never actually used tkSimpleDialog in anger but thats how I remembwer it working! Alan g From alan.gauld@bt.com Sun Jun 16 22:50:27 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 16 Jun 2002 22:50:27 +0100 Subject: [Tutor] Python based blog software Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C662@mbtlipnt02.btlabs.bt.co.uk> OK, I bite. What the heck is a blog?! This one obviously slipped by me somewhere.... Alan G From alan.gauld@bt.com Sun Jun 16 22:54:16 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun, 16 Jun 2002 22:54:16 +0100 Subject: [Tutor] Convert man file into readable text file Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C663@mbtlipnt02.btlabs.bt.co.uk> > >nroff -man foo.man > foo.txt > Thanks. Actually I'm using Windows. I copied a man file into > my Windows machine then tried to read that man file. Well you could get a copy of GNU groff I guess but thats probably overkill :-) OTOH You could install Cygwin (which every Windows user should have) which has man and groff etc available... > So, I guess I should process the file first with nroff before > copy it into my Windows machine. :) Yeah, that would work too I suppose ;-) Alan g From ak@silmarill.org Mon Jun 17 01:27:07 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Sun, 16 Jun 2002 20:27:07 -0400 Subject: [Tutor] Python based blog software In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C662@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C662@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020617002707.GA808@ak.silmarill.org> On Sun, Jun 16, 2002 at 10:50:27PM +0100, alan.gauld@bt.com wrote: > OK, I bite. > > What the heck is a blog?! > This one obviously slipped by me somewhere.... > > Alan G Something like slashdot or kuro5hin.org. A web discussion site.. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From sarmstrong13@mac.com Mon Jun 17 04:25:57 2002 From: sarmstrong13@mac.com (SA) Date: Sun, 16 Jun 2002 22:25:57 -0500 Subject: [Tutor] More Tkinter Help Please [callbacks and embedded functions] In-Reply-To: Message-ID: Ok. So I guess my question is, if I have a program that has these two calsses, how do I call the second class(which would be a popup dialog box for saving the test in e1 to a file) from a button that is defined and packed in the first class? Basically I have two text fields and four buttons. One button executes whatever code is typed in the first text field and displays the out put in the second text field. The next two buttons clear one of the text fields. And the fourth button should popup a new dialog that has two entry fields. When the Save button is pushed in the dialog box, the the second class will take the entries from the dialog box as the absolute path to the save file and save the text from the first text field in the first class to the user designated savefile. As for the naming conventions used in the book, I realize they are not very readable. That is because they are carryovers from a Tcl/Tk program. When I get everything working properly, I plan on changing them to more readable terms. Thanks. SA From purplebo@babylonia.flatirons.org Mon Jun 17 05:15:19 2002 From: purplebo@babylonia.flatirons.org (Chris Avery) Date: Sun, 16 Jun 2002 22:15:19 -0600 Subject: [Tutor] Files and Dictionaries Message-ID: <20020616221519.A22437@babylonia.flatirons.org> Hi all! I was wondering if it were possible to write a dictionary to a user's home directory so that it could be called later. For instance, I have a dictionary full of meat and wine that compliments that meat, I want to save a copy of all the meat and wine in the dictionary so I can append to it when I run the program again. Hope that made sense. -C -- +++++++++++++++++++ Chris Avery, KC0KTH +++++++++++++++++++ From ak@silmarill.org Mon Jun 17 05:35:17 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 17 Jun 2002 00:35:17 -0400 Subject: [Tutor] Files and Dictionaries In-Reply-To: <20020616221519.A22437@babylonia.flatirons.org> References: <20020616221519.A22437@babylonia.flatirons.org> Message-ID: <20020617043517.GA3301@ak.silmarill.org> On Sun, Jun 16, 2002 at 10:15:19PM -0600, Chris Avery wrote: > Hi all! > I was wondering if it were possible to write a dictionary to a user's home directory so that it could be called later. For instance, I have a dictionary full of meat and wine that compliments that meat, I want to save a copy of all the meat and wine in the dictionary so I can append to it when I run the program again. > > Hope that made sense. Sure, that's done by shelve module. If I remember right, here's how you can use it: sh = shelve.open("test.dict") # that'll be the name of the file sh["test"] = 2 sh.close() # next time program is started sh = shelve.open("test.dict") print sh["test"] > -C > -- > +++++++++++++++++++ > Chris Avery, KC0KTH > +++++++++++++++++++ > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From ponderor@lycos.com Mon Jun 17 05:59:36 2002 From: ponderor@lycos.com (Dean Goodmanson) Date: Sun, 16 Jun 2002 21:59:36 -0700 Subject: [Tutor] Python based blog software Message-ID: >What the heck is a blog?! Arg! I've carelessy used of jargon in this venue. "blog" is short/jargon for a Web Logging system. weBLOGing. WhatIs.com Definition: http://whatis.techtarget.com/definition/0,,sid9_gci213547,00.html Here are some articles on the wonders of weblogging: (in no particular order) "Essential Blogging Public Review": http://www.oreillynet.com/pub/wlg/1460 Others: http://www.oreillynet.com/pub/a/javascript/2002/01/01/cory.html http://www.oreillynet.com/pub/a/javascript/2002/06/13/megnut.html http://www.oreillynet.com/pub/wlg/1460 On a personal note, Thanks for "Learn to Program Using Python". I didn't purchase it to learn programming, but to learn Python. The book (and language) appealed to my profesional ideals and I've been enjoying the wide world of Python for the last year or so. You're praise for "The Pragmatic Programmer" is my best example of this. Best Regards, Dean _______________________________________________________ WIN a first class trip to Hawaii. Live like the King of Rock and Roll on the big Island. Enter Now! http://r.lycos.com/r/sagel_mail/http://www.elvis.lycos.com/sweepstakes From dyoo@hkn.eecs.berkeley.edu Mon Jun 17 07:43:39 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 16 Jun 2002 23:43:39 -0700 (PDT) Subject: [Tutor] cdrw writing In-Reply-To: <20020617032942.73810.qmail@web21505.mail.yahoo.com> Message-ID: > > Your question isn't really related to Python or programming, so we > > probably aren't the best people to ask about this. You may get better > > help about CDR stuff by visiting: > > > > http://www.cdrfaq.org/ > > > > That page has a lot of information about recording CDR's, and may help > > you find the information you're looking for. Good luck to you! > > how do you write a python pro. to a cdr I'm still not quite sure I understand: a Python program is just a text file, so just saving the source file to a CDR should be enough to save it permanently. I'm very sure that I'm misinterpreting your question, so I have to ask for clarification. What do you plan to do after you write your program to CDR? Do you plan to share your programs with others afterwards? Do you want to make it run automatically if it's inserted into a Windows computer? Again, my apologies for my confusion! Please make sure to send your replies to 'tutor@python.org', and not just to me, so that the others can bail me out when I make mistakes. From alan.gauld@bt.com Mon Jun 17 12:00:33 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 17 Jun 2002 12:00:33 +0100 Subject: [Tutor] More Tkinter Help Please [callbacks and embedded func tions] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C666@mbtlipnt02.btlabs.bt.co.uk> > So I guess my question is, if I have a program that has > these two calsses, how do I call the second class > from a button that is defined and packed in the > first class? Thats easy. The first class can see the second class definition. Therefore you can use the solution Danny shopwed you, namely create an event handler that instantiates the second class, passing parameters to the constructor as required. > When the Save button is pushed in the dialog box, the the > second class will take the entries from the dialog box as > the absolute path to the save file and save the text from > the first text field in the first class You could do this by passing the text as a parameter to the Saver class in the constructor. However the conventional way to do this (as in How MS Word, IDLE etc do it) is to use the SaveAs dialog to obtain and test for validity the path/filename then make that available to the parent class to actually save the data(since that PyShell class owns the data - it is responsible. The responsibility of the dialog is to find out *where* to save it) This the Save method looks something like this: def Save(self): SaveDialog = Saver(self) filepath = SaveDialog.path f = open(filepath,'w') f.write(tOutput) f.close Usually there is a way to call the SaveAs dialog modally such that it treturns a boolean result indicating whether a valid filename has been created. Check the tkSimpleDialog docs to see if such exists. However I seem to recall that Tk has a standard SaveAs type dialog already built that mimics the platform(Windows or Unix) SaveAs dialog so maybe you could use it. HTH, Alan G From shendric@arches.uga.edu Mon Jun 17 16:36:57 2002 From: shendric@arches.uga.edu (shendric@arches.uga.edu) Date: Mon, 17 Jun 2002 10:36:57 -0500 Subject: [Tutor] Runtime Errors Message-ID: <1024324617.smmsdV1.1.1@mail.arches.uga.edu> Hi, Thanks for the response. Sorry to just be replying. Been out of email range for the weekend. Anyway, I took your advice and eliminated the try-except pairs, using the traceback function, instead. I still get the error, but here's the full error output: File "C:\Documents and Settings\Administrator\Desktop\VTrans\AudioTranscriber2.py", line 239, in ? root.mainloop() File "C:\Python22\lib\lib-tk\Tkinter.py", line 929, in mainloop self.tk.mainloop(n) File "C:\PYTHON22\Pmw\Pmw_0_8_5\lib\PmwBase.py", line 1694, in __call__ _reporterror(self.func, args) File "C:\PYTHON22\Pmw\Pmw_0_8_5\lib\PmwBase.py", line 1741, in _reporterror for tr in traceback.extract_tb(exc_traceback): RuntimeError: maximum recursion depth exceeded Sean ---------Included Message---------- >Date: Fri, 14 Jun 2002 23:53:18 -0700 (PDT) >From: "Danny Yoo" >To: >Cc: "Python Tutor" >Subject: Re: [Tutor] Runtime Errors > > > >On Fri, 14 Jun 2002 shendric@arches.uga.edu wrote: > >> I've got a script I'm working on that is a kind of spreadsheet. There >> are a fixed number of 4 cells in each row, but the idea would be to have >> as many rows as one wishes. The algorithm for the spreadsheet works >> fine, but I get a RuntimeError when I try to load a tab-delimited text >> file into the cells. >> >> The loading algorithm is this: >> >> 1. Open a text file >> 2. Read the lines of the text file into a list (readlines()) >> 3. Take each line and do the following: >> a. create an instance of the TranscriptionCell class, which is a >> class that includes four Tkinter Pmw.ScrolledText widgets >> b. append that instance to a list >> c. put the contents of the first part of the line into the first >> text widget, then the second into the second, etc. >> 4. close the file > >Sounds reasonable enough. Yes, this should work. > >> >> I get the following error: >> RuntimeError: maximum recursion depth exceeded > > >Hmmm... does the error message also give a clue in which function, and >around which line it goes bonkers? > > >> Now, I've gotten it to go just fine with only a few rows, but not if >> there are a lot of them. > > >We'll have to look through the code to see where the recursion's coming >from. Reading... hmmm... It might not be such a good idea to wrap every >statement with exception handling like: > >### > try: > self.rowlist[ind].TTime.settext(rowcontents[0]) > except: > pass > try: > self.rowlist[ind].TSpeak.settext(rowcontents[1]) > except: > pass >### > >Doing just a 'pass' when an exception occurs is like an ostrich that puts >its head in the sand: We're ignoring any potentially bad problems! If >the first row setting fails, it's probable that the whole rowcontents list >has some weirdness that should be reported to the user. > > > >To make this function easier to debug, we can strip out some of the >exception handling code, and put a traceback.print_exc() call in the code: > >### >def openTrans(self, event=None): > file = askopenfile(title="Open Transcript File", > filetypes=(("text files", "*.txt"), > ("All files", "*"))) > filetoread = open(file.name, 'r') > filecontents = filetoread.readlines() > filetoread.close() > ind = 0 > self.rowlist=[] > for x in filecontents: > rowcontents = x.split("\t") > self.rowlist.append(TranscriptionCell(self.inner, > row=self.row)) > try: > self.rowlist[ind].TTime.settext(rowcontents[0]) > self.rowlist[ind].TSpeak.settext(rowcontents[1]) > self.rowlist[ind].TTrans.textBox.settext(rowcontents[2]) > self.rowlist[ind].Comments.settext(rowcontents[3]) > except: > traceback.print_exc() > self.row = self.row + 1 > ind = ind + 1 >### > > >The traceback.print_exc() should tell us if there's something else that's >going weird. Hmmm.... but I don't see any obvious recursion here. Can >you show the last few previous lines of the error message as well? It'll >help us to find where exactly the recursion is occuring. > > >Sounds like a tricky bug, but don't worry, we're bound to squish it. >*grin* Talk to you later! > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > ---------End of Included Message---------- From terjeja@hotmail.com Mon Jun 17 17:54:35 2002 From: terjeja@hotmail.com (Terje Johan Abrahamsen) Date: Mon, 17 Jun 2002 16:54:35 +0000 Subject: [Tutor] Library reference Message-ID: I run PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32. (from first line when started) And I am now looking through the Python Library Referece release 2.2.1. On page 17-19 there are string methods. So, I assume that to get access, I write: >>>import string >>>from string import* But, I can not use all the string methods that are described. For example, string.istitle() doesn't work. It cannot find it. Encode() is not found either. How can I use these and others? Eg capitalize() does work. I can't see any note saying that you have to do something different to use capitalize() than title() in the library ref. What do I do wrong? Thanks, Terje _________________________________________________________________ Send and receive Hotmail on your mobile device: http://mobile.msn.com From jeff@ccvcorp.com Mon Jun 17 19:09:10 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon, 17 Jun 2002 11:09:10 -0700 Subject: [Tutor] Library reference References: Message-ID: <3D0E25C5.8F9172EF@ccvcorp.com> Terje Johan Abrahamsen wrote: > I run PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on > win32. (from first line when started) And I am now looking through the > Python Library Referece release 2.2.1. On page 17-19 there are string > methods. So, I assume that to get access, I write: > >>>import string > >>>from string import* First of all, there is a subtle but important distinction between "string methods" and the "string module". When you type 'import string', you're getting access to the string module, and you use the functions in it by typing, for instance, >>> mylist = string.split(mystring) The second line that you've typed ('from string import *') is unnecessary and probably a bad idea. What that does to take all the functions in the string module's namespace and insert them into the current namespace. This *might* seem handy, because now instead of typing string.split() you only need to type split() ... but this is often a trap. :) If you have any *other* function named split() in your current namespace, then you'll only be able to access *one* of them -- whichever was bound last. The worst part of this is that you don't really *know* what names the string module uses, so you're just hoping that none of those names will conflict with any other names you're using. And if there *are* any conflicts, there's a chance that it will be subtle enough that you'll never notice the difference until you're running a marathon debugging session to track down some odd erratic behavior in your latest big project... In short, best to avoid using the 'from somemodule import *' idiom unless you're *sure* that the module was designed for that. > But, I can not use all the string methods that are described. > For example, string.istitle() doesn't work. It cannot find it. Encode() is > not found either. How can I use these and others? Eg capitalize() does work. > I can't see any note saying that you have to do something different to use > capitalize() than title() in the library ref. What do I do wrong? Now, as I mentioned before, string *methods* are different from module string. String methods are called just like other object methods -- by using an object reference as a qualifier, and in this case, the object should be a string. What you were doing is, I presume, something like this: >>> import string >>> string.istitle("I Am A String") Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'istitle' ...but istitle() is not part of the string module, it's a string method. Try this instead: >>> "I Am A String".istitle() 1 >>> "I am a string".istitle() 0 >>> mystring = "I Am A String" >>> mystring.istitle() 1 >>> Does that make more sense now? :) Jeff Shannon Technician/Programmer Credit International From ak@silmarill.org Mon Jun 17 19:07:03 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Mon, 17 Jun 2002 14:07:03 -0400 Subject: [Tutor] Library reference In-Reply-To: References: Message-ID: <20020617180703.GA4988@ak.silmarill.org> On Mon, Jun 17, 2002 at 04:54:35PM +0000, Terje Johan Abrahamsen wrote: > I run PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on > win32. (from first line when started) And I am now looking through the > Python Library Referece release 2.2.1. On page 17-19 there are string > methods. So, I assume that to get access, I write: > >>>import string > >>>from string import* > > But, I can not use all the string methods that are described. > For example, string.istitle() doesn't work. It cannot find it. Encode() is > not found either. How can I use these and others? Eg capitalize() does > work. I can't see any note saying that you have to do something different > to use capitalize() than title() in the library ref. What do I do wrong? > > Thanks, Terje They were moved to string methods - i.e. instead of doing string.istitle("test") you have to do "test".istitle(). string module is going to be phased out some time in the future, iirc. > > _________________________________________________________________ > Send and receive Hotmail on your mobile device: http://mobile.msn.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From sarmstrong13@mac.com Mon Jun 17 21:22:25 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 17 Jun 2002 15:22:25 -0500 Subject: [Tutor] More Tkinter Help Please [callbacks and embedded functions] In-Reply-To: Message-ID: On 6/16/02 1:33 PM, "Danny Yoo" wrote: > > I'm not too familiar with tkSimpleDialog.Dialog, so I'm not quite sure if > there's a problem with inheritance. Can you explain more what problems > you're running into with this code? > > > Ah! I think that for this statement: > > self.b4 = Button(f, text="Save Input", command=Saving) > > > if 'tkSimpleDialog' is the tkSimpleDialog that's in the 'Introduction To > Tkinter' tutorial: > > http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm > > > then we need to do a little extra: the dialog box needs to know its parent > window when it's being constructed! Let's take a look at the definition > of tkSimpleDialog.Dialog again: > > > ### Sample of tkSimpleDialog.py > # File: tkSimpleDialog.py > > from Tkinter import * > import os > > class Dialog(Toplevel): > > def __init__(self, parent, title = None): > ### > > > So when we create a Dialog box, this dialog box must take in an additional > 'parent' parameter. However, back in your code: > > self.b4 = Button(f, text="Save Input", command=Saving) > > When the fourth button is pressed, it tries to call the Saving dialog > constructor with no parameters: this may be the problem that you're > running into. We'd like to be able to do something like: > > self.b4 = Button(f, text="Save Input", command=Saving(f)) > > since 'f' is the frame parent that we'd like to attach the Dialog to... > but the problem with this is that Python will actually call Saving(f). It > calls it too soon, because, to Python, > > Saving(f) > > is a function call, so it just evaluates it straightaway. We need a way > to create a callback function that knows about 'f', enough so that it can > do a 'Saving(f)' when our button is pressed. What to do? > > > > > > The solution actually isn't too bad: > > ### > def saving_callback(): Saving(f) > self.b4 = Button(f, text="Save Input", command=saving_callback) > ### > > That is, we can actually embed a small function called 'saving_callback', > and we can pass that off to as the button callback. The miniature > function has access to all the local variables of its parent, which is why > saving_callback() can say 'f' without problems. > Ok. Now I get a different error: Exception in Tkinter callback Traceback (most recent call last): File "/sw/src/root-python-2.2.1-6/sw/lib/python2.2/lib-tk/Tkinter.py", line 1292, in __call__ return apply(self.func, args) TypeError: saving_callback() takes no arguments (1 given) Also where does the f come from? Is it from the f = Frame(top) in the __init__ portion of the PyShell calss? If so, how would this carry over the saving_callback function? Would the Dialog Box be separate from the initial frame? Thanks in advance. SA From dyoo@hkn.eecs.berkeley.edu Mon Jun 17 21:44:40 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 17 Jun 2002 13:44:40 -0700 (PDT) Subject: [Tutor] More Tkinter Help Please [callbacks and embedded functions] In-Reply-To: Message-ID: > > The solution actually isn't too bad: > > > > ### > > def saving_callback(): Saving(f) > > self.b4 = Button(f, text="Save Input", command=saving_callback) > > ### > > > > That is, we can actually embed a small function called > > 'saving_callback', and we can pass that off to as the button callback. > > The miniature function has access to all the local variables of its > > parent, which is why saving_callback() can say 'f' without problems. > > > > > Ok. Now I get a different error: > > Exception in Tkinter callback > Traceback (most recent call last): > File "/sw/src/root-python-2.2.1-6/sw/lib/python2.2/lib-tk/Tkinter.py", > line 1292, in __call__ > return apply(self.func, args) > TypeError: saving_callback() takes no arguments (1 given) Hmmm! When does the error occur? Also, can you show us the source code of that Dialog box again? I just want to check something quick. The error message doesn't make too much sense to me yet, because button command callbacks shouldn't be sending any arguments over to us. (Tkinter "event" callbacks, on the other hand, send off an 'event' object, and are used for things like keyboard input.) > Also where does the f come from? Is it from the f = Frame(top) in the > __init__ portion of the PyShell calss? If so, how would this carry over > the saving_callback function? >From Python 2.1 onward, inner functions are allowed to carry the variables of the outer function. If you're running Python 2.1, you may need the line: ### from __future__ import nested_scopes ### to get this to kick in, but in Python 2.2, this nesting functionality comes for free. Since saving_callback() is defined with the __init__ of our PyShell class, it gets access to the local variables of PyShell.__init__, including that 'f' variable. > Would the Dialog Box be separate from the initial frame? That was my assumption --- I thought that dialog boxes open up a new window. Dialogs also prevent interactivity with the parent window until the dialog window itself is closed, I think. Good luck to you! From sarmstrong13@mac.com Mon Jun 17 22:06:23 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 17 Jun 2002 16:06:23 -0500 Subject: [Tutor] More Tkinter Help Please [callbacks and embedded functions] In-Reply-To: Message-ID: Ok. Here's the code: from Tkinter import * import os import commands import tkSimpleDialog class PyShell: def saving_callback(): Saving(f) def clearin(self): self.t1.delete(0.0,END) def clearout(self): self.t2.delete(0.0,END) def expyth(self): self.t2.delete(0.0, END) self.output = commands.getoutput(self.t1.get(0.0, END)) self.t2.insert(END, self.output) def __init__(self, top): self.t1 = Text(top, height="12", width="84", font="Courier 12") self.t1.pack(side=TOP, pady=2) f = Frame(top) f.pack() self.b1 = Button(f, text="Execute", command=self.expyth) self.b1.pack(side=LEFT) self.b2 = Button(f, text="Clear Input", command=self.clearin) self.b2.pack(side=LEFT) self.b3 = Button(f, text="Clear Output", command=self.clearout) self.b3.pack(side=LEFT) self.b4 = Button(f, text="Save Input", command=self.saving_callback) self.b4.pack(side=LEFT) self.t2 = Text(top, height="12", width="84", bg="lightblue", font="Courier 12") self.t2.pack(side=TOP, pady=2) class Saving(tkSimpleDialog.Dialog): def savin(self, question): Label(question, text="Directory:").grid(row=0) Label(question, text="Filename:").grid(row=1) self.e1 = Entry(question) self.e2 = Entry(question) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) def apply(self): self.dir = self.e1.get() self.fn = self.e2.get() self.sav = self.dir + self.fn self.savfile = open(self.sav, "w") for line in self.t1.readlines(): self.savefile.write(line) self.savefile.close() root = Tk() app = PyShell(root) root.mainloop() Now if I move def saving_callback(): Saving(f) within __init__, I get two same windows when I launch the app. I then click the Save button, a Dialog box pops up , but only with the OK and Cancel buttons and no entries. When I click OK I get the following error: Traceback (most recent call last): File "/sw/src/root-python-2.2.1-6/sw/lib/python2.2/lib-tk/Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "/sw/src/root-python-2.2.1-6/sw/lib/python2.2/lib-tk/tkSimpleDialog.py", line 126, in ok self.apply() File "PyShell.py", line 41, in apply self.dir = self.e1.get() AttributeError: Saving instance has no attribute 'e1' I'm assuming this is because the dialogbox is popping up without the entry fields so there is no value to get. I think the problem may be solved by using Toplevel, but I will have to investigate this further so that I understand how to apply the Toplevel widget. Thanks in advance. SA From scot@possum.in-berlin.de Tue Jun 18 00:07:21 2002 From: scot@possum.in-berlin.de (Scot W. Stevenson) Date: Tue, 18 Jun 2002 01:07:21 +0200 Subject: [Tutor] More Tkinter Help Please In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C666@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C666@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <200206180107.21311.scot@possum.in-berlin.de> Hello -=20 > However I seem to recall that Tk has a standard SaveAs type dialog > already built that mimics the platform(Windows or Unix) SaveAs dialog > so maybe you could use it. It is called "asksaveasfilename" and lives in tkFileDialog. I used it in = a=20 small program something like=20 from tkFileDialog import * ... name =3D asksaveasfilename(initialfile=3Da_name) where a_name is a suggestion that you give the user. Saves a lot of time,= =20 it does.=20 Unfortunately, most of the beginner's Python books as well as "Python and= =20 Tkinter Programming" don't give much documentation on these standard=20 dialogs; I ended up figuring out the parameters for asksaveasfilename by=20 giving fake versions (like "parrot=3Ddead") and reading the error message= s. Y, Scot --=20 Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From adolfo158@yahoo.es Mon Jun 17 22:59:48 2002 From: adolfo158@yahoo.es (=?iso-8859-1?q?Adolfo=20Aguirre?=) Date: Mon, 17 Jun 2002 23:59:48 +0200 (CEST) Subject: [Tutor] Search MS-Word Message-ID: <20020617215948.94486.qmail@web21209.mail.yahoo.com> Hi: I am just starting to learn Python and I have a practical need. I need to search for strings in hundreds of .doc and .txt documents. I am in W98 with Python 2.1.1 - I figure if I you could tell me how to do a basic string search, I can start from there to learn how to do more sophisticated searches. Appreciating any help on this subject, Adolfo Now in Mexico Usually in santa Barbara, California _______________________________________________________________ Copa del Mundo de la FIFA 2002 El único lugar de Internet con vídeos de los 64 partidos. ĄApúntante ya! en http://fifaworldcup.yahoo.com/fc/es/ From dyoo@hkn.eecs.berkeley.edu Tue Jun 18 00:39:38 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 17 Jun 2002 16:39:38 -0700 (PDT) Subject: [Tutor] More Tkinter Help Please [Dialog windows] In-Reply-To: Message-ID: On Mon, 17 Jun 2002, SA wrote: > class Saving(tkSimpleDialog.Dialog): > def savin(self, question): > Label(question, text="Directory:").grid(row=0) > Label(question, text="Filename:").grid(row=1) > self.e1 = Entry(question) > self.e2 = Entry(question) > self.e1.grid(row=0, column=1) > self.e2.grid(row=1, column=1) > def apply(self): > self.dir = self.e1.get() > self.fn = self.e2.get() > self.sav = self.dir + self.fn > self.savfile = open(self.sav, "w") > for line in self.t1.readlines(): > self.savefile.write(line) > self.savefile.close() Hi SA, I took another look at the tkSimpleDialog stuff on the Tkinter Introduction page: http://www.pythonware.com/library/tkinter/introduction/dialog-windows.htm Are you sure that the 'savin' method is supposed to be named that way? I think you mean to call it 'body' instead! The dialog layout assumes that it can call the body() and buttonbox() methods to customize the dialog display. Without customization, it'll default to a simple yes/no dialog box. To customize the appearance of the Saving dialog box, you'll want to write your own versions of body() and buttonbox(). The Tkinter Introduction above has an example for doing this: ### # File: dialog2.py import tkSimpleDialog class MyDialog(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="First:").grid(row=0) Label(master, text="Second:").grid(row=1) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) return self.e1 # initial focus def apply(self): first = string.atoi(self.e1.get()) second = string.atoi(self.e2.get()) print first, second # or something ### (It doesn't override the buttonbar() method, so by default, it has the "Ok" and "Cancel" buttons in there. Using the right method names is important when we inherit from parent classes, because the parent class expects to call specific methods. > Now if I move def saving_callback(): Saving(f) within __init__, I get two Yes, this should be within. Having it outside won't work because there wouldn't be a context, a way of knowing what 'f' meant. Hope this helps! From sarmstrong13@mac.com Tue Jun 18 04:11:00 2002 From: sarmstrong13@mac.com (SA) Date: Mon, 17 Jun 2002 22:11:00 -0500 Subject: [Tutor] More Tkinter Help Please [Dialog windows] In-Reply-To: Message-ID: Ok. The Dialog box is now popping up like it should. The only problem comes when I click on OK in the dialog box. Instead of saving the text in t1 to the file it gives an error: Exception in Tkinter callback Traceback (most recent call last): File "/sw/src/root-python-2.2.1-6/sw/lib/python2.2/lib-tk/Tkinter.py", line 1292, in __call__ return apply(self.func, args) File "/sw/src/root-python-2.2.1-6/sw/lib/python2.2/lib-tk/tkSimpleDialog.py", line 126, in ok self.apply() File "PyShell.py", line 47, in apply for line in self.t1.readlines(): AttributeError: Saving instance has no attribute 't1' I would of thought that t1 is still defined from PyShell when called in the class Saving since it is being called in PyShell.__init__. Is this not correct. See below: from Tkinter import * import os import commands import tkSimpleDialog class PyShell: def clearin(self): self.t1.delete(0.0,END) def clearout(self): self.t2.delete(0.0,END) def expyth(self): self.t2.delete(0.0, END) self.output = commands.getoutput(self.t1.get(0.0, END)) self.t2.insert(END, self.output) def __init__(self, top): def saving_callback(): Saving(top) t1 = Text(top, height="12", width="84", font="Courier 12") t1.pack(side=TOP, pady=2) f = Frame(top) f.pack() b1 = Button(f, text="Execute", command=self.expyth) b1.pack(side=LEFT) b2 = Button(f, text="Clear Input", command=self.clearin) b2.pack(side=LEFT) b3 = Button(f, text="Clear Output", command=self.clearout) b3.pack(side=LEFT) b4 = Button(f, text="Save Input", command=saving_callback) b4.pack(side=LEFT) t2 = Text(top, height="12", width="84", bg="lightblue", font="Courier 12") t2.pack(side=TOP, pady=2) class Saving(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="Directory:").grid(row=0) Label(master, text="Filename:").grid(row=1) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) return self.e1 def apply(self): self.dir = self.e1.get() self.fn = self.e2.get() self.sav = self.dir + self.fn self.savfile = open(self.sav, "w") for line in self.t1.readlines(): self.savefile.write(line) self.savefile.close() root = Tk() app = PyShell(root) root.mainloop() Thanks in advance. SA From idiot1@netzero.net Tue Jun 18 04:18:09 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Mon, 17 Jun 2002 23:18:09 -0400 Subject: [Tutor] mod python for apache Message-ID: <3D0EA671.B7B9F7FA@netzero.net> I can't find it. But it's out there. Looking over the site, not finding. Grrrr... OK, where do I go to find the module for apache to compile python into it, like I can do for perl? From idiot1@netzero.net Tue Jun 18 04:33:57 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Mon, 17 Jun 2002 23:33:57 -0400 Subject: [Tutor] found it Message-ID: <3D0EAA25.F03437B9@netzero.net> http://www.modpython.org/ From beercanz@hotmail.com Tue Jun 18 03:04:10 2002 From: beercanz@hotmail.com (Guess Who? Me) Date: Tue, 18 Jun 2002 02:04:10 +0000 Subject: [Tutor] Help with functions Message-ID:
def area_square(side):
    return side*side
def area_rectangle(length,width):
    return length*width
def area_circle(radius):
    return radius*radius*3.14
def print_options():
    print "Options:"
    print "'p' to print options."
    print "'as' for area of a square."
    print "'ar' for area of a rectangle."
    print "'ac' for area of a circle."
    print "'q' to quit."
choice="p"
while choice !="q":
    print_options()
    choice=raw_input("Option?:")
    if choice == "as":
        side=input("What is the length of a side?:")
        print area_square(side)
    if choice=="ar":
        length=input("What is the length?:")
        width=input("What is the width?:")
        print area_rectangle(length,width)
    if choice =="ac":
        radius=input("What is the radius?:")
        print area_circle(radius)
print "Thanks for using my program."
 
That is my source code so far. I'm following the tutorial at http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html
and I had a question. Every time I try to get a function to ask for the input of the sides, lenght, width, whatever, it doesn't work. Something funny I found out is that it might work, but then when I quit python and open it again, it doesn't work, saying that ''length' is not defined'. Any thoughts??
 
Thanks!


Get your FREE download of MSN Explorer at http://explorer.msn.com.
From alan.gauld@bt.com Tue Jun 18 10:48:23 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 18 Jun 2002 10:48:23 +0100 Subject: [Tutor] More Tkinter Help Please [Dialog windows] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C668@mbtlipnt02.btlabs.bt.co.uk> > The Dialog box is now popping up like it should. The only > problem comes when I click on OK in the dialog box. > Instead of saving the text in t1 to the file it gives > ... > AttributeError: Saving instance has no attribute 't1' > > > I would of thought that t1 is still defined from PyShell when > called in the class Saving since it is being called in PyShell Nope, the new instance has no knoiwledge of whats in Pyshell - that's object encapsulation at work. You will have to pass either a reference to PyShell to Saving (Which you do already via the f constructor parameter) and then access t1 via that refe5rence or pass the t1 string directly to Saving. However as I said in my message yesterday the conventional way to do this is for SAving to pass back the filename/path to PyShell and let it save the data - PyShell owns the t1 text so it should be responsible for saving it. The dialog's responsibility is limited to getting the right file location from the user - thats why its called a "dialog"! Alan G. From alan.gauld@bt.com Tue Jun 18 11:03:26 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 18 Jun 2002 11:03:26 +0100 Subject: [Tutor] Search MS-Word Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C66A@mbtlipnt02.btlabs.bt.co.uk> > I need to search for strings in hundreds of .doc and > .txt documents. I am in W98 with Python 2.1.1 - doc files may pose a problem because they are in a proprietary binary format. The only satisfactory way might be to use COM to access the files via Wordpad or something. However for basic text searching it's much easier. For an exact match just use the string find() function import string string.find("Some string here", txtfile.read()) Or use the new string methods: txtfile.read().find("Some string here") If you need to pattern matcvh then you need the re module which has a search() function much like the string modules find() function except instead of a string you pass in a regular expression. My advice would be: get it working with string first then move to re later Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From rob@uselesspython.com Tue Jun 18 12:26:28 2002 From: rob@uselesspython.com (Rob Andrews) Date: Tue, 18 Jun 2002 06:26:28 -0500 Subject: [Tutor] Help with functions References: Message-ID: <3D0F18E4.8090104@uselesspython.com> I saved your program as functionHelp.py and imported it into IDLE. It ran without any flaws that I noticed. Rob http://uselesspython.com Guess Who? Me wrote: > def area_square(side): > return side*side > > def area_rectangle(length,width): > return length*width > > def area_circle(radius): > return radius*radius*3.14 > > def print_options(): > print "Options:" > print "'p' to print options." > print "'as' for area of a square." > print "'ar' for area of a rectangle." > print "'ac' for area of a circle." > print "'q' to quit." > > choice="p" > while choice !="q": > print_options() > choice=raw_input("Option?:") > if choice == "as": > side=input("What is the length of a side?:") > print area_square(side) > if choice=="ar": > length=input("What is the length?:") > width=input("What is the width?:") > print area_rectangle(length,width) > if choice =="ac": > radius=input("What is the radius?:") > print area_circle(radius) > print "Thanks for using my program." > > > > That is my source code so far. I'm following the tutorial at > http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html > > and I had a question. Every time I try to get a function to ask for the > input of the sides, lenght, width, whatever, it doesn't work. Something > funny I found out is that it might work, but then when I quit python and > open it again, it doesn't work, saying that ''length' is not defined'. > Any thoughts?? > > > > Thanks! > > > ------------------------------------------------------------------------ > Get your FREE download of MSN Explorer at http://explorer.msn.com > . > _______________________________________________ Tutor maillist - > Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From sarmstrong13@mac.com Tue Jun 18 14:28:01 2002 From: sarmstrong13@mac.com (SA) Date: Tue, 18 Jun 2002 08:28:01 -0500 Subject: [Tutor] More Tkinter Help Please [Dialog windows] In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C668@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On 6/18/02 4:48 AM, "alan.gauld@bt.com" wrote: > However as I said in my message yesterday the conventional way > to do this is for SAving to pass back the filename/path to > PyShell and let it save the data - PyShell owns the t1 text > so it should be responsible for saving it. The dialog's > responsibility is limited to getting the right file location > from the user - thats why its called a "dialog"! > > Alan G. > Ok. I'm trying this, but my question is still how do I pass the variable sav from: def apply(self): dir = self.e1.get() fn = self.e2.get() sav = dir + fn return sav In the class Saving to the class PyShell? Although my original question was how to pas the variable t1 from PyShell to Saving, I now need to find out how to pass the variable sav from Saving to PyShell. Now I do not expect you all to do all the work for me, since the whole purpose of this exercise is for my learning experience, so if you just want to point the way to specific documentation or hint (real well) to where I need to look for this info, that will also be fine. I do appreciate all of the help everyone has given me in this exercise, I've gathered a lot of information that is sometimes glossed over in tutorials because you are expected to know all of this stuff already. Thanks Again. SA From wolf_binary@hotmail.com Tue Jun 18 16:18:16 2002 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Tue, 18 Jun 2002 10:18:16 -0500 Subject: [Tutor] bits taken by variable type Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0016_01C216B1.75CD3380 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, Coming from a C++ view point, how do you know if a variable in Python is = unsigned long int or some other modified variable type? How do you know = how much precision a number is stored at? =20 Thanks, Cameron Stoner ------=_NextPart_000_0016_01C216B1.75CD3380 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi all,
 
Coming from a C++ view point, how do = you know if a=20 variable in Python is unsigned long int or some other modified variable=20 type?  How do you know how much precision a number is stored = at? =20
 
Thanks,
Cameron = Stoner
------=_NextPart_000_0016_01C216B1.75CD3380-- From alan.gauld@bt.com Tue Jun 18 17:07:33 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 18 Jun 2002 17:07:33 +0100 Subject: [Tutor] More Tkinter Help Please [Dialog windows] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C670@mbtlipnt02.btlabs.bt.co.uk> > I'm trying this, but my question is still how do I pass the > variable sav > from: > def apply(self): > dir = self.e1.get() > fn = self.e2.get() > sav = dir + fn > return sav There are several options but I'd recommend writing a method of the Saving class to fetch the filename. You also need to create a member attriobute of Saving to store the value of course... def apply(self): #as above except last line dir = self.e1.get() fn = self.e2.get() self.name = dir + fn # assign to instance variable def getName(self): # inside Saving class return self.name # return instance variable Then when you create the Saving class you assign to a local variable. def doSave(self): # inside Pyshell class saveDialog = Saving(f) # auto calls apply etc filename = saveDialog.getName() self.saveText(filename) del(saveDialog) > how to pass the variable sav from Saving to PyShell. Don't pass the data - it belongs to the object. Get the object to give you the data on request. Thus when you create the instance of Saving you keep the reference and use it to ask for the filename. Alan g. From urnerk@qwest.net Tue Jun 18 15:05:24 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 18 Jun 2002 10:05:24 -0400 Subject: [Tutor] bits taken by variable type In-Reply-To: References: Message-ID: <20020618100524.75be5cb3.urnerk@qwest.net> On Tue, 18 Jun 2002 10:18:16 -0500 "Cameron Stoner" wrote: > Hi all, > > Coming from a C++ view point, how do you know if a variable in Python is unsigned long int or some other modified variable type? How do you know how much precision a number is stored at? > > Thanks, > Cameron Stoner > I'm pretty sure Python's floats are implemented as C doubles. Integers are ints. Obviously long integers (e.g. 9091023810283091283081209381092380192830129L) are special to Python (not native C). Python doesn't try to map its types to underlying C types, from the point of view of the user (of course it has to in code, as CPython's implementation). Floats would seem to be the only type where there'd be a question of precision. With int, it's more a matter of limits, and these are spelled out in the documentation (Python now auto-converts ints to long integers if they overflow). Some extension modules let you work with decimal numbers of much greater precision, but, like Python long integers, these are not native C types (may be well-established in C libraries though). Kirby From urnerk@qwest.net Tue Jun 18 15:09:39 2002 From: urnerk@qwest.net (Kirby Urner) Date: Tue, 18 Jun 2002 10:09:39 -0400 Subject: [Tutor] Help with functions In-Reply-To: References: Message-ID: <20020618100939.02d07112.urnerk@qwest.net> > That is my source code so far. I'm following the tutorial at http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html > and I had a question. Every time I try to get a function to ask for the input of the sides, lenght, width, whatever, it doesn't work. Something funny I found out is that it might work, but then when I quit python and open it again, it doesn't work, saying that ''length' is not defined'. Any thoughts?? > If it works when you quit and go back into Python, it might be a reload issue. If you're in the interpreter and make a change to a .py file in a text editor, and save it, the interpreter will still operate with the old compiled .pyc unless you force a recompile using reload(name_of_module). It's a little trickier if you don't import the module, but members of the module. A workaround is to import the module as well, for the purpose of forcing a reload, and then reissuing the 'from xxx import a,b,c' command as before. This can be done as a function itself. Kirby From alan.gauld@bt.com Tue Jun 18 17:59:58 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 18 Jun 2002 17:59:58 +0100 Subject: [Tutor] bits taken by variable type Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C671@mbtlipnt02.btlabs.bt.co.uk> ------_=_NextPart_001_01C216E9.93F2D030 Content-type: text/plain; charset="iso-8859-1" > Coming from a C++ view point, how do you know if a variable in Python is > unsigned long int or some other modified variable type? In practice, why would you care? > How do you know how much precision a number is stored at? For integers it is import sys print sys.maxint If you need longer than maxint use long integers which are arbitrarily large(effectively) For floats, I'm not sure. Just assume they are big enough and catch exceptions for when they aren't. These are the kind of low level details that Python is trying to shield from you. Alan G. ------_=_NextPart_001_01C216E9.93F2D030 Content-type: text/html; charset="iso-8859-1"
>  Coming from a C++ view point, how do you know if a variable in Python is  
>  unsigned long int or some other modified variable type?   
 
In practice, why would you care?
 
> How do you know how much precision a number is stored at?   
 
For integers it is
 
import sys
print sys.maxint
 
If you need longer than maxint use long integers which are arbitrarily large(effectively)
 
For floats, I'm not sure. Just assume they are big enough and catch exceptions
for when they aren't.
 
These are the kind of low level details that Python is trying to shield from you.
 
Alan G.
 
------_=_NextPart_001_01C216E9.93F2D030-- From alan.gauld@bt.com Tue Jun 18 18:03:34 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 18 Jun 2002 18:03:34 +0100 Subject: [Tutor] More Tkinter Help Please [Dialog windows] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C672@mbtlipnt02.btlabs.bt.co.uk> Rep0lying to my own message! > > how to pass the variable sav from Saving to PyShell. > > Don't pass the data - it belongs to the object. Get the > object to give you the data on request. Thus when you > create the instance of Saving you keep the reference > and use it to ask for the filename. I should add that this is complicated slightly because you are inheriting from tkSimpleDialog so we have to work within the constraints of the protocol which tkSimpleDialog defines. This is not such a bad thing but simply a price we pay for reusing the code and protocol of tkSimpleDialog. Alan G. From dyoo@hkn.eecs.berkeley.edu Tue Jun 18 18:13:08 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 18 Jun 2002 10:13:08 -0700 (PDT) Subject: [Tutor] cdrw writing In-Reply-To: <20020618114014.2810.qmail@web21506.mail.yahoo.com> Message-ID: > > I'm very sure that I'm misinterpreting your question, so I have to ask > > for clarification. What do you plan to do after you write your > > program to CDR? Do you plan to share your programs with others > > afterwards? Do you want to make it run automatically if it's inserted > > into a Windows computer? > > > > Again, my apologies for my confusion! Please make sure to send your > > replies to 'tutor@python.org', and not just to me, so that the others > > can bail me out when I make mistakes. > > > i want to save the programs so they can be ran on another pc with out > useing the internet to open the file so it will autorun like any other > program. Hi Mista, (It's much better to send replies back to 'tutor@python.org', so that the other tutors can help answer your question too. Why settle for one person's hearsay, when you can have everyone's? Seriously though, please send to tutor@python.org.) I think you mean: you want to allow others to run your program without installing Python themselves. If you plan to give your program to other people, you probably want to "package" your program to make it work on other people's computers. There's a program called 'py2exe' that creates executable files that your friends can run directly. Py2exe can be found here: http://py2exe.sourceforge.net/ This utility will take your program and bundle it together to make an EXE. About getting your CD to autorun: I don't have Windows, so I can't help too much here, but take a look at: http://www.pcnineoneone.com/howto/autorun1.html Apparently, as long as there's a 'Autorun.inf' file that points to an EXE, Windows will run it automatically when the CD is inserted. From virketis@post.harvard.edu Tue Jun 18 12:28:21 2002 From: virketis@post.harvard.edu (Pijus Virketis) Date: Tue, 18 Jun 2002 14:28:21 +0300 Subject: [Tutor] Search MS-Word In-Reply-To: <20020617215948.94486.qmail@web21209.mail.yahoo.com> Message-ID:
Adolfo,

>I need to search for strings in= hundreds of .doc and
>.txt documents. I am in W98 with Python= 2.1.1 -

Lets take the two separately.
 
Text files are relatively easy in principle. Depending on= how sophisticated a search you need to conduct, either the= standard Python string search capacities or regular expressions= will do the trick handily. Here is a very simple example using a= file "trivial.txt" containing "My name is= Pijus."
 
>>> source =3D open("c:\\trivial.txt",= "r") #open the file for reading
>>> text =3D source.readlines() #put all text into a= list
>>> import string
>>> for line in text:
            if= string.find(line, "Pijus") !=3D -1: #if= "Pijus" found anywhere
         =       print line
 
This will return the string "My name is Pijus".= See the string module documentation for more information on= find().
 
Word files are a bit more tricky, since Python cannot simply= open one up like it can a straight text file. If you need your= code to work only for Windows, use COM to access M$ Word= directly. You will need to install the win32all extensions= (check out the python.org Windows section to get them). Then,= something along the following lines will happen:
 
>>> import win32com.client
>>> wrdobj =3D= win32com.client.Dispatch("Word.Application")=
>>> wrdobj.Visible =3D 1
 
You should be looking at a nice Word session. This is where= Python sort of ends and the manipulation of the Word COM objects= begin. Off the top of my head, I can only remember how to open a= file:
 
>>>= wrdobj.Documents.Open("some_path")
 
Check out the Word Object Browser and perhaps VBA= documentation to see what you need to do next in order to search= the file you just opened. It should take just one more line of= code to do something similar to the text example.
 
Cheers,
 
Pijus
 
--
"Anyone attempting to generate random numbers by= deterministic means is, of course, living in a state of= sin." -- John Von Neumann
From idiot1@netzero.net Tue Jun 18 18:50:14 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Tue, 18 Jun 2002 13:50:14 -0400 Subject: [Tutor] Bbbulk precedence email header Message-ID: <3D0F72D6.50FB2E19@netzero.net> Some MLM's reject mail with the header "Precedence: Bulk", to help break mail loops. Good idea, so I decided to install it. Well, in the server I captured a email with a bulk precedence. Works fine, TLpost.py exits properly. When I email to it precedence: Bulk, it does not, and handles the message normally. ERG. Anyone wanting to view the existing script can do so at this page: http://www.tinylist.org/TLpost.shtml This is a ssi include of the actual script, so if anything changes, it is IMMEDIATELY reflected on the page. Testing takes place on 'testlist3', so feel free to subscribe to it and play with the thing. All other functions are working properly. -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ From idiot1@netzero.net Tue Jun 18 19:29:47 2002 From: idiot1@netzero.net (Kirk Bailey) Date: Tue, 18 Jun 2002 14:29:47 -0400 Subject: [Tutor] Ah hah! Message-ID: <3D0F7C1B.C21AF8E9@netzero.net> Nutscrape sends it out with a X-Priority header, not as the book discusses as a Precedence header- as is the case with most of my Ezines and allmost all my spam. F***ing nutscrape... Gotta add another header detection snip of code... -- end Respectfully, Kirk D Bailey +---------------------"Thou Art Free." -Eris-----------------------+ | http://www.howlermonkey.net mailto:highprimate@howlermonkey.net | | http://www.tinylist.org +--------+ mailto:grumpy@tinylist.org | +------------------Thinking| NORMAL |Thinking----------------------+ +--------+ From mikew@screaminet.com Tue Jun 18 12:34:22 2002 From: mikew@screaminet.com (mikew@screaminet.com) Date: Tue, 18 Jun 2002 11:34:22 GMT Subject: [Tutor] Help with functions Message-ID: <200206181134.g5IBYMF52615@www.screaminetcorp.com> One problem I found when I cut and pasted your code was the line that says if choice="as"; it should read if choice=="as". Another line below that is also wrong in the same way. After I fixed that it ran fine for me. ----- Original Message ----- From: "Guess Who? Me" To: tutor@python.org Sent: Tue, 18 Jun 2002 02:04:10 +0000 Subject: [Tutor] Help with functions
def area_square(side):     return side*side
def area_rectangle(length,width):     return length*width
def area_circle(radius):     return radius*radius*3.14
def print_options():     print "Options:"     print "'p' to print options."     print "'as' for area of a square."     print "'ar' for area of a rectangle."     print "'ac' for area of a circle."     print "'q' to quit."
choice="p" while choice !="q":     print_options()     choice=raw_input("Option?:")     if choice= "as":         side=input("What is the length of a side?:")         print area_square(side)     if choice=="ar":         length=input("What is the length?:")         width=input("What is the width?:")         print area_rectangle(length,width)     if choice="ac":         radius=input("What is the radius?:")         print area_circle(radius) print "Thanks for using my program."
 
That is my source code so far. I'm following the tutorial at http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html
and I had a question. Every time I try to get a function to ask for the input of the sides, lenght, width, whatever, it doesn't work. Something funny I found out is that it might work, but then when I quit python and open it again, it doesn't work, saying that ''length' is not defined'. Any thoughts??
 
Thanks!


Get your FREE download of MSN Explorer at http://explorer.msn.com. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From sarmstrong13@mac.com Tue Jun 18 20:50:34 2002 From: sarmstrong13@mac.com (SA) Date: Tue, 18 Jun 2002 14:50:34 -0500 Subject: [Tutor] More Tkinter Help Please [Dialog windows] In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C670@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On 6/18/02 11:07 AM, "alan.gauld@bt.com" wrote: > def doSave(self): # inside Pyshell class > saveDialog = Saving(f) # auto calls apply etc > filename = saveDialog.getName() > self.saveText(filename) > del(saveDialog) A couple of things here: I can't use self in "def doSave(self):" because the doSave function is actually inside PyShell.__iniT__. If I use self and place this function inside PyShell but outside of __init__ I get an error claiming the function is asking for on arument but none are given. If I place the function inside __init__ everything works except for the "self.saveText(filename)" portion because there is no instance of self inside the function? So I tried to fiddle around with this function and have the following: def doSave(): SaveDialog = Saving(top) filename = SaveDialog.getName() outfile = t1() out = open(filename, 'w') inf = open(outfile, 'r') for line in inf.readlines(): out.write(line) out.close() Now this actually brings up the popup save dialog and allows the user to chose the directory path and filename, even writes the correct file in the correct place, but there is no data in the file. It is not placing the t1 object's data into the outfile as a string. So I guess my final question is how do I coerce t1 to give its data to outfile as a string? Thanks. SA From sarmstrong13@mac.com Tue Jun 18 22:36:49 2002 From: sarmstrong13@mac.com (SA) Date: Tue, 18 Jun 2002 16:36:49 -0500 Subject: [Tutor] More Tkinter Help Please [Dialog windows] In-Reply-To: Message-ID: > This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. --B_3107263011_2114931 Content-type: text/plain; charset="ISO-8859-1" Content-transfer-encoding: quoted-printable On 6/18/02 2:50 PM, "SA" wrote: >=20 > def doSave(): > SaveDialog =3D Saving(top) > filename =3D SaveDialog.getName() > outfile =3D t1() > out =3D open(filename, 'w') > inf =3D open(outfile, 'r') > for line in inf.readlines(): > out.write(line) > out.close() >=20 Me very Dumb. Me go home now. Me sorry. I can't believe I missed this. I figured it out. Well actually, the method saving the text in t1 was already right before my eyes in the expyth method= . Now I use that and I get the following for the doSave method: def doSave(): SaveDialog =3D Saving(top) filename =3D SaveDialog.getName() outfile =3D t1.get(0.0, END) out =3D open(filename, 'w') out.write(outfile) out.close() I feel really stupid for missing that. Now all of the buttons work the way = I want them to. Below is a copy of the code for anyone who wishes to give it = a try. I like this in place of the command line idle which is all I really have available for my OSX system. This allows you to write the code in the top window and display it=B9s output in the bottom window, unless the output is a gui(which is displayed as a gui window). For me it is cool, because I can hammer away at different things and test them out before I click the save button to save the code. It is a slight ripoff of a Tcl/Tk program I came across that does the same thing for Perl scripts. I would like to eventually come up with a final program that works on Tcl, Perl, or Python (maybe even Ruby) depending on what is fed as the first line of code. If anyone else has some suggestions for it please feel free, or if you have some code to add, add it on and we can see where it goes from here. Thank you very much Alan and Danny for all of your help and guidance.(and patienc= e with me). This has been a really cool learning experience and I find this list very beneficial for my continued learning of Python. Thanks. SA --B_3107263011_2114931 Content-type: text/html; charset="US-ASCII" Content-transfer-encoding: quoted-printable Re: [Tutor] More Tkinter Help Please  [Dialog windows] On 6/18/02 2:50 PM, "SA" <sarmstrong13@ma= c.com> wrote:


>
> def doSave():
>   SaveDialog =3D Saving(top)
>   filename =3D SaveDialog.getName()
>   outfile =3D t1()
>   out =3D open(filename, 'w')
>   inf =3D open(outfile, 'r')
>   for line in inf.readlines():
>       out.write(line)
>   out.close()
>

Me very Dumb. Me go home now. Me sorry.

I can't believe I missed this. I figured it out. Well actually, the method = saving the text in t1 was already right before my eyes in the expyth method.= Now I use that and I get the following for the doSave method:

        def doSave():
            Sav= eDialog =3D Saving(top)
            fil= ename =3D SaveDialog.getName()
            out= file =3D t1.get(0.0, END)
           out = =3D open(filename, 'w')
            out= .write(outfile)
            out= .close()

I feel really stupid for missing that. Now all of the buttons work the way = I want them to. Below is a copy of the code for anyone who wishes to give it= a try. I like this in place of the command line idle which is all I really = have available for my OSX system. This allows you to write the code in the t= op window and display it’s output in the bottom window, unless the out= put is a gui(which is displayed as a gui window). For me it is cool, because= I can hammer away at different things and test them out before I click the = save button to save the code. It is a slight ripoff of a Tcl/Tk program I ca= me across that does the same thing for Perl scripts. I would like to eventua= lly come up with a final program that works on Tcl, Perl, or Python (maybe e= ven Ruby) depending on what is fed as the first line of code. If anyone else= has some suggestions for it please feel free, or if you have some code to a= dd, add it on and we can see where it goes from here. Thank you very much Al= an and Danny for all of your help and guidance.(and patience with me). This = has been a really cool learning experience and I find this list very benefic= ial for my continued learning of Python.

Thanks.
SA
--B_3107263011_2114931-- From sarmstrong13@mac.com Tue Jun 18 22:37:59 2002 From: sarmstrong13@mac.com (SA) Date: Tue, 18 Jun 2002 16:37:59 -0500 Subject: [Tutor] More Tkinter Help Please [Dialog windows] In-Reply-To: Message-ID: Sorry. Forgot to cut and paste the final code: from Tkinter import * import os import commands import tkSimpleDialog class PyShell: def clearin(self): self.t1.delete(0.0,END) def clearout(self): self.t2.delete(0.0,END) def expyth(self): self.t2.delete(0.0, END) self.output = commands.getoutput(self.t1.get(0.0, END)) self.t2.insert(END, self.output) def __init__(self, top): def doSave(): SaveDialog = Saving(top) filename = SaveDialog.getName() outfile = t1.get(0.0, END) out = open(filename, 'w') out.write(outfile) out.close() t1 = Text(top, height="12", width="84", font="Courier 12") t1.pack(side=TOP, pady=2) f = Frame(top) f.pack() b1 = Button(f, text="Execute", command=self.expyth) b1.pack(side=LEFT) b2 = Button(f, text="Clear Input", command=self.clearin) b2.pack(side=LEFT) b3 = Button(f, text="Clear Output", command=self.clearout) b3.pack(side=LEFT) b4 = Button(f, text="Save Input", command=doSave) b4.pack(side=LEFT) t2 = Text(top, height="12", width="84", bg="lightblue", font="Courier 12") t2.pack(side=TOP, pady=2) class Saving(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="Directory:").grid(row=0) Label(master, text="Filename:").grid(row=1) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) return self.e1 def apply(self): dir = self.e1.get() fn = self.e2.get() self.name = dir + fn def getName(self): return self.name root = Tk() app = PyShell(root) root.mainloop() From sarmstrong13@mac.com Tue Jun 18 22:55:13 2002 From: sarmstrong13@mac.com (SA) Date: Tue, 18 Jun 2002 16:55:13 -0500 Subject: Corrected code for PyShell, was:(Re: [Tutor] More Tkinter Help Please [Dialog windows]) In-Reply-To: Message-ID: > This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. --B_3107264114_2181541 Content-type: text/plain; charset="US-ASCII" Content-transfer-encoding: 7bit Ok. I found a bug. I left off all of the self descriptors on the buttons. Here is the corrected code that now works the way I intended (my Bad): #!/usr/bin/env python from Tkinter import * import os import commands import tkSimpleDialog class PyShell: def clearin(self): self.t1.delete(0.0,END) def clearout(self): self.t2.delete(0.0,END) def expyth(self): self.t2.delete(0.0, END) self.output = commands.getoutput(self.t1.get(0.0, END)) self.t2.insert(END, self.output) def __init__(self, top): def doSave(): SaveDialog = Saving(top) filename = SaveDialog.getName() outfile = self.t1.get(0.0, END) out = open(filename, 'w') out.write(outfile) out.close() self.t1 = Text(top, height="12", width="84", font="Courier 12") self.t1.pack(side=TOP, pady=2) f = Frame(top) f.pack() self.b1 = Button(f, text="Execute", command=self.expyth) self.b1.pack(side=LEFT) self.b2 = Button(f, text="Clear Input", command=self.clearin) self.b2.pack(side=LEFT) self.b3 = Button(f, text="Clear Output", command=self.clearout) self.b3.pack(side=LEFT) self.b4 = Button(f, text="Save Input", command=doSave) self.b4.pack(side=LEFT) self.t2 = Text(top, height="12", width="84", bg="lightblue", font="Courier 12") self.t2.pack(side=TOP, pady=2) class Saving(tkSimpleDialog.Dialog): def body(self, master): Label(master, text="Directory:").grid(row=0) Label(master, text="Filename:").grid(row=1) self.e1 = Entry(master) self.e2 = Entry(master) self.e1.grid(row=0, column=1) self.e2.grid(row=1, column=1) return self.e1 def apply(self): dir = self.e1.get() fn = self.e2.get() self.name = dir + fn def getName(self): return self.name root = Tk() app = PyShell(root) root.mainloop() --- Thanks. Sa --B_3107264114_2181541 Content-type: text/html; charset="US-ASCII" Content-transfer-encoding: quoted-printable Corrected code for PyShell, was:(Re: [Tutor] More Tkinter Help Pleas= e  [Dialog windows]) Ok. I found a bug. I left off all of the self descript= ors on the buttons. Here is the corrected code that now works the way I inte= nded (my Bad):
#!/usr/bin/env python
from Tkinter import *
import os
import commands
import tkSimpleDialog

class PyShell:

        def clearin(self):
            &nb= sp;   self.t1.delete(0.0,END)
        def clearout(self):
            &nb= sp;   self.t2.delete(0.0,END)
        def expyth(self):
            &nb= sp;   self.t2.delete(0.0, END)
            &nb= sp;   self.output =3D commands.getoutput(self.t1.get(0.0, END))=
            &nb= sp;   self.t2.insert(END, self.output)
        def __init__(self, top):             &nb= sp;   def doSave():
            &nb= sp;           SaveDia= log =3D Saving(top)
            &nb= sp;           filenam= e =3D SaveDialog.getName()
            &nb= sp;           outfile= =3D self.t1.get(0.0, END)
            &nb= sp;           out =3D o= pen(filename, 'w')
            &nb= sp;           out.wri= te(outfile)
            &nb= sp;           out.clo= se()
            &nb= sp;   self.t1 =3D Text(top, height=3D"12", width=3D"= 84", font=3D"Courier 12")
            &nb= sp;   self.t1.pack(side=3DTOP, pady=3D2)
            &nb= sp;   f =3D Frame(top)
            &nb= sp;   f.pack()
            &nb= sp;   self.b1 =3D Button(f, text=3D"Execute", command=3Ds= elf.expyth)
            &nb= sp;   self.b1.pack(side=3DLEFT)
            &nb= sp;   self.b2 =3D Button(f, text=3D"Clear Input", comma= nd=3Dself.clearin)
            &nb= sp;   self.b2.pack(side=3DLEFT)
            &nb= sp;   self.b3 =3D Button(f, text=3D"Clear Output", comm= and=3Dself.clearout)
            &nb= sp;   self.b3.pack(side=3DLEFT)
            &nb= sp;   self.b4 =3D Button(f, text=3D"Save Input", comman= d=3DdoSave)
            &nb= sp;   self.b4.pack(side=3DLEFT)
            &nb= sp;   self.t2 =3D Text(top, height=3D"12", width=3D"= 84", bg=3D"lightblue", font=3D"Courier 12")
            &nb= sp;   self.t2.pack(side=3DTOP, pady=3D2)

class Saving(tkSimpleDialog.Dialog):


        def body(self, master):             &nb= sp;   Label(master, text=3D"Directory:").grid(row=3D0)<= BR>             &nb= sp;   Label(master, text=3D"Filename:").grid(row=3D1)             &nb= sp;   self.e1 =3D Entry(master)
            &nb= sp;   self.e2 =3D Entry(master)
            &nb= sp;   self.e1.grid(row=3D0, column=3D1)
            &nb= sp;   self.e2.grid(row=3D1, column=3D1)
            &nb= sp;   return self.e1
        def apply(self):
            &nb= sp;   dir =3D self.e1.get()
            &nb= sp;   fn =3D self.e2.get()
            &nb= sp;   self.name =3D dir + fn
        def getName(self):
            &nb= sp;   return self.name


root =3D Tk()
app =3D PyShell(root)
root.mainloop()


---
Thanks.
Sa
--B_3107264114_2181541-- From marcolinux@linuxbr.com.br Tue Jun 18 23:33:19 2002 From: marcolinux@linuxbr.com.br (Marc) Date: Tue, 18 Jun 2002 19:33:19 -0300 Subject: [Tutor] Dynamic change of dictionaries Message-ID: <20020618223319.GA7284@marcolab.proconet> --fUYQa+Pmc3FrFX/N Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Hi people, I need to make a simple monitor for my network. I need to monitor how much each machine is using the bandwidth. The first tool that comes to mind is tcpdump. So far Im able to see how much a given IP shows up with: # tcpdump -nq -i eth0 dst host 10.15.50.3 and port 80 but i need to show it "graphically". Some examples to show what I mean: The following program fakes a tcpdump output for easy testing. # fakeDump.py 18:57:28.1024437448 10.0.0.8.2279 > 10.0.0.3.80: tcp 0 (DF) 18:57:28.1024437448 10.0.0.19.1792 > 10.0.0.3.80: tcp 0 (DF) 18:57:29.1024437449 10.0.0.20.1570 > 10.0.0.3.80: tcp 0 (DF) 18:57:29.1024437449 10.0.0.22.2045 > 10.0.0.3.80: tcp 0 (DF) 18:57:30.1024437450 10.0.0.6.2114 > 10.0.0.3.80: tcp 0 (DF) 18:57:30.1024437450 10.0.0.8.1487 > 10.0.0.3.80: tcp 0 (DF) 18:57:31.1024437451 10.0.0.8.1653 > 10.0.0.3.80: tcp 0 (DF) 18:57:31.1024437451 10.0.0.14.2290 > 10.0.0.3.80: tcp 0 (DF) 18:57:32.1024437452 10.0.0.10.1523 > 10.0.0.3.80: tcp 0 (DF) 18:57:32.1024437452 10.0.0.9.2290 > 10.0.0.3.80: tcp 0 (DF) The interesting part here is the ip number: I need is to tell how much 10.0.0.8 shows up. And 10.0.0.6 . And 10.0.0.22. And .... You get the idea. So I can show it like a gauge. Screenshots :) Pay attention to 10.0.0.6 and how it "disappear" due to no traffic: 10.0.0.8 ###### 10.0.0.6 #### 10.0.0.22 ############## 10.0.0.99 ######## Some minutes later: 10.0.0.8 ####################################### 10.0.0.6 # 10.0.0.22 ######### 10.0.0.99 ######################### Some minutes later: 10.0.0.8 ####################################### 10.0.0.22 ######### 10.0.0.99 ######################### I was thinking about a dictionary. 'IP' : number of show up in X minutes dict={'10.0.0.6':5,'10.0.0.22':33,'10.0.0.8':42} Given the code below, how do I change the dict dynamically with a output like the command above? Thanks in advance for _any_ help. #################################################################### # simulates a traffic monitor import time,os,random header="\t\t\tTraffic Monitor(CTRL+C to exit)" dict={'10.0.0.6':5,'10.0.0.22':33,'10.0.0.8':42} while (1): os.system('clear') print header print time.ctime(time.time()) try: for item in dict: print item,'\t'+'#'*dict[item] dict[item]=dict[item]-1 if dict[item]< 0: # delete idle IPs. del( dict[item]) # = random.randrange (1,65) except RuntimeError: pass time.sleep(1) ################################################################### -- .:: MarcoLinux ::. --fUYQa+Pmc3FrFX/N Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="tcpdump.py" #Fakes a tcpdump output #tcpdump -nq -i eth0 dst host 10.0.0.3 and port 80 #something like: #18:31:27.854995 10.0.0.1.33209 > 10.0.0.3.80: tcp 0 (DF) import time,random while (1): print "%s 10.0.0.%s.%s > 10.0.0.3.80: tcp 0 (DF)"%(time.strftime('%X.%s'),random.randrange(1,25),random.randrange(1024,2500)) time.sleep(0.5) --fUYQa+Pmc3FrFX/N Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="trafego.py" import time,os,random header="\t\t\t\tMonitor Traffic" dict={'10.0.0.6':5,'10.0.0.22':3,'10.0.0.3':2} while (1): os.system('clear') print header print time.ctime(time.time()) try: for item in dict: print item,'\t'+'#'*dict[item] dict[item]=dict[item]-1 if dict[item]< 0: dict[item] = random.randrange (1,65) except RuntimeError: pass time.sleep(1) --fUYQa+Pmc3FrFX/N-- From shalehperry@attbi.com Tue Jun 18 23:43:55 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 18 Jun 2002 15:43:55 -0700 (PDT) Subject: [Tutor] Dynamic change of dictionaries In-Reply-To: <20020618223319.GA7284@marcolab.proconet> Message-ID: > > Given the code below, how do I change the dict dynamically with a output > like the command above? > why not simply ignore 0 count items? for item in dict: if dict[item] == 0: continue # print status bars if you want to preen items, the del dict[item] method is reasonable. From adolfo158@yahoo.es Wed Jun 19 00:01:45 2002 From: adolfo158@yahoo.es (=?iso-8859-1?q?Adolfo=20Aguirre?=) Date: Wed, 19 Jun 2002 01:01:45 +0200 (CEST) Subject: [Tutor] Install failure Message-ID: <20020618230145.16179.qmail@web21208.mail.yahoo.com> HI: I just installed 2.2.1 and the installation process went fine. Problem: The Python command line works, but the Pythonw.exe doesn´t. No window prompts argumenting errors or anything. Just Nothing happens when you click on it. I have W98SE, on a HP PIII-700 laptop. Any help will be appreciated. Adolfo _______________________________________________________________ Copa del Mundo de la FIFA 2002 El único lugar de Internet con vídeos de los 64 partidos. ĄApúntante ya! en http://fifaworldcup.yahoo.com/fc/es/ From jeff@ccvcorp.com Wed Jun 19 00:07:55 2002 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue, 18 Jun 2002 16:07:55 -0700 Subject: [Tutor] Install failure References: <20020618230145.16179.qmail@web21208.mail.yahoo.com> Message-ID: <3D0FBD4B.B3FA7CB2@ccvcorp.com> Adolfo Aguirre wrote: > Problem: > The Python command line works, but the Pythonw.exe > doesn4t. > > No window prompts argumenting errors or anything. Just > Nothing happens when you click on it. The pythonw.exe is not intended to be used alone -- it's intended to run other scripts, without opening a console window. Typically, this is for launching scripts that have their own GUI (such as Tkinter or wxPython scripts) -- you can type (from a DOS prompt, or at Start-->Run) 'pythonw myscript.py', or create a shortcut with that as the target, and your script will run without the extra blank console window that would appear if you used python.exe instead of pythonw.exe. I believe (though I haven't tried it) that pythonw.exe should even work if you drag&drop a script file onto it in Explorer. But, since pythonw.exe has no user interface of its own, it has no apparent effect if you just double-click on it. (You start pythonw.exe, it has no script to run, so it exits -- without ever opening a window that you can see.) Hope this makes sense. Jeff Shannon Technician/Programmer Credit International From beercanz@hotmail.com Wed Jun 19 04:23:34 2002 From: beercanz@hotmail.com (Guess Who? Me) Date: Wed, 19 Jun 2002 03:23:34 +0000 Subject: [Tutor] List help... Message-ID:
and this came up...
## This program runs a test of knowledge

true = 1
false = 0

# First get the test questions
# Later this will be modified to use file io.
def get_questions():
    # notice how the data is stored as a list of lists
    return [["What color is the daytime sky on a clear day?","blue"],\
            ["What is the answer to life, the universe and everything?","42"],\
            ["What is a three letter word for mouse trap?","cat"]]
# This will test a single question
# it takes a single question in
# it returns true if the user typed the correct answer, otherwise false
def check_question(question_and_answer):
    #extract the question and the answer from the list
    question = question_and_answer[0]
    answer = question_and_answer[1]
    # give the question to the user
    given_answer = raw_input(question)
    # compare the user's answer to the testers answer
    if answer == given_answer:
        print "Correct"
        return true
    else:
        print "Incorrect, correct was:",answer
        return false
# This will run through all the questions
def run_test(questions):
    if len(questions) == 0:
        print "No questions were given."
        # the return exits the function
        return
    index = 0
    right = 0
    while index < len(questions):
        #Check the question
        if check_question(questions[index]):
            right = right + 1
        #go to the next question
        index = index + 1
    #notice the order of the computation, first multiply, then divide
    print "You got ",right*100/len(questions),"% right out of",len(questions)

#now lets run the questions
run_test(get_questions())
How is the information stored as a list for the questions and answers?
I don't get the form..a list inside a list. Then it took question_and_answer, and used [0] and [1]
to get the values stored at the first and second positions in the list right?
Basically - how is this structured to work the way it does? I can't seem to figure out
how the answer and question are extracted...
 
Thanks!


Get your FREE download of MSN Explorer at http://explorer.msn.com.
From shalehperry@attbi.com Wed Jun 19 04:53:14 2002 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue, 18 Jun 2002 20:53:14 -0700 (PDT) Subject: [Tutor] List help... In-Reply-To: Message-ID: first, please do not send html to mailing lists, not everyone wants to see html. > How is the information stored as a list for the questions and > answers? I don't get the form..a list inside a list. Then it took > question_and_answer, and used [0] and [1] to get the values stored > at the first and second positions in the list right? Basically - > how is this structured to work the way it does? I can't seem to figure > out how the answer and question are > extracted... Thanks! one of the best things about python is that you can run it interactively and seek guidance directly from python itself. $ python >>> a_list = ['betty', 'veronica', 'sue'] >>> a_list ['betty', 'veronica', 'sue'] >>> len(a_list) 3 >>> a_list[0] 'betty' >>> a_list[1] 'veronica' >>> a_list[2] 'sue' >>> a_list[3] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range In python a list is an indexed ordering of items. The count starts at 0 and goes to len(list) - 1. A list can hold practically anything in python. The example you had was questions and answers. Let's examine that now. q_and_a = [['What is your name?', 'Sean'], ['What is your quest?', 'To seek the Holy Grail'], ['What is the air speed of a swallow?', 'African or European?']] now, let's replace the questions and answers with numbers to make it easier to see: [ [1,2], [3,4], [5,6] ]. As you can see we have here a list containing 3 lists. So q_and_a[0] returns [1,2] in the numerical example or ['What is your name?', 'Sean'] in the real example. >>> q_and_a[0][0] # index the first item's first item 'What is your name?' >>> q_and_a[0][1] 'Sean' or >>> block = q_and_a[0] >>> block[1] 'Sean' or >>> answer = block[1] >>> answer 'Sean' or even >>> question, answer = q_and_a[0] >>> question 'What is your name?' >>> answer 'Sean' That last one translates as this: (question, answer) = ['What is your name?', 'Sean'] and the first item goes to the first variable and the second to the second and so on. Hope this helps some. From alan.gauld@bt.com Wed Jun 19 10:29:11 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 19 Jun 2002 10:29:11 +0100 Subject: [Tutor] More Tkinter Help Please [Dialog windows] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C673@mbtlipnt02.btlabs.bt.co.uk> First, I saw your message where you got it working - good, however there are some concepts obviously not quite clear yet so here is an attempt to pick up the loose ends.... > > def doSave(self): # inside Pyshell class > > I can't use self in "def doSave(self):" because the > doSave function is actually inside PyShell.__iniT__. You use self when defining the method at the class level. You have chosen(as Danny suggested) to put the event handler inside init. Thats OK and you don't need the self parameter. I suggeted putting the event handler at the class level, in which case you do neeed self. Its really a matter of personal preference. > If I use self and place this function > inside PyShell but outside of __init__ I get an error > claiming the function is asking for on arument but none > are given. Nope, you got that error when you put the method in the class but *did not* use self. It complained because the class passed it the object as self but the function didn't expect it! class C: def ok(self): print 'ok' def bad(): # no self defined print 'oops!' def master(self): self.bad() # class calls C.bad(self) get error message c = C() c.ok() c.master() # error here > If I place the function inside > __init__ everything works except for the > "self.saveText(filename)" portion > because there is no instance of self inside the function? Correct, that's why I prefer event handlers to be defined at the class level. This is about 'scoping' or 'namespaces'. Inside a *function* (including one defined inside a method) you can see local variables, parameters and module level names but not class level names. Inside a method you can see the same but since one of the parameters is selfyou thus get access to the object attributes. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From pythontutor@venix.com Wed Jun 19 13:18:52 2002 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed, 19 Jun 2002 08:18:52 -0400 Subject: [Tutor] Dynamic change of dictionaries References: <20020618223319.GA7284@marcolab.proconet> Message-ID: <3D1076AC.9030104@venix.com> Two non-python thoughts about what you are trying to do: MRTG provides perl and C code to issue SNMP requests to collect traffic statistics, graph the stats, and display the graphs in a web page. http://people.ee.ethz.ch/~oetiker/webtools/mrtg/ MRTG: The Multi Router Traffic Grapher This may be over-kill for your purposes. If you are tracking web usage, the squid proxy server would collect stats while also providing caching. http://www.squid-cache.org/ Squid Web Proxy Cache Marc wrote: > Hi people, > I need to make a simple monitor for my network. > I need to monitor how much each machine is using the bandwidth. > The first tool that comes to mind is tcpdump. So far Im able to see how > much a given IP shows up with: > # tcpdump -nq -i eth0 dst host 10.15.50.3 and port 80 > but i need to show it "graphically". > > Some examples to show what I mean: > > The following program fakes a tcpdump output for easy testing. > # fakeDump.py > > 18:57:28.1024437448 10.0.0.8.2279 > 10.0.0.3.80: tcp 0 (DF) > 18:57:28.1024437448 10.0.0.19.1792 > 10.0.0.3.80: tcp 0 (DF) > 18:57:29.1024437449 10.0.0.20.1570 > 10.0.0.3.80: tcp 0 (DF) > 18:57:29.1024437449 10.0.0.22.2045 > 10.0.0.3.80: tcp 0 (DF) > 18:57:30.1024437450 10.0.0.6.2114 > 10.0.0.3.80: tcp 0 (DF) > 18:57:30.1024437450 10.0.0.8.1487 > 10.0.0.3.80: tcp 0 (DF) > 18:57:31.1024437451 10.0.0.8.1653 > 10.0.0.3.80: tcp 0 (DF) > 18:57:31.1024437451 10.0.0.14.2290 > 10.0.0.3.80: tcp 0 (DF) > 18:57:32.1024437452 10.0.0.10.1523 > 10.0.0.3.80: tcp 0 (DF) > 18:57:32.1024437452 10.0.0.9.2290 > 10.0.0.3.80: tcp 0 (DF) > > The interesting part here is the ip number: > I need is to tell how much 10.0.0.8 shows up. > And 10.0.0.6 . > And 10.0.0.22. > And .... You get the idea. > So I can show it like a gauge. Screenshots :) > Pay attention to 10.0.0.6 and how it "disappear" due to no traffic: > > 10.0.0.8 ###### > 10.0.0.6 #### > 10.0.0.22 ############## > 10.0.0.99 ######## > > > Some minutes later: > > 10.0.0.8 ####################################### > 10.0.0.6 # > 10.0.0.22 ######### > 10.0.0.99 ######################### > > Some minutes later: > > 10.0.0.8 ####################################### > 10.0.0.22 ######### > 10.0.0.99 ######################### > > > > I was thinking about a dictionary. > > 'IP' : number of show up in X minutes > dict={'10.0.0.6':5,'10.0.0.22':33,'10.0.0.8':42} > > > Given the code below, how do I change the dict dynamically with a output > like the command above? > > Thanks in advance for _any_ help. > > > #################################################################### > # simulates a traffic monitor > import time,os,random > > header="\t\t\tTraffic Monitor(CTRL+C to exit)" > dict={'10.0.0.6':5,'10.0.0.22':33,'10.0.0.8':42} > > while (1): > os.system('clear') > print header > print time.ctime(time.time()) > try: > for item in dict: > print item,'\t'+'#'*dict[item] > dict[item]=dict[item]-1 > if dict[item]< 0: # delete idle IPs. > del( dict[item]) # = random.randrange (1,65) > except RuntimeError: > pass > time.sleep(1) > ################################################################### > > > > > ------------------------------------------------------------------------ > > #Fakes a tcpdump output > #tcpdump -nq -i eth0 dst host 10.0.0.3 and port 80 > #something like: > #18:31:27.854995 10.0.0.1.33209 > 10.0.0.3.80: tcp 0 (DF) > > import time,random > > while (1): > print "%s 10.0.0.%s.%s > 10.0.0.3.80: tcp 0 (DF)"%(time.strftime('%X.%s'),random.randrange(1,25),random.randrange(1024,2500)) > time.sleep(0.5) > > > > ------------------------------------------------------------------------ > > import time,os,random > header="\t\t\t\tMonitor Traffic" > dict={'10.0.0.6':5,'10.0.0.22':3,'10.0.0.3':2} > while (1): > os.system('clear') > print header > print time.ctime(time.time()) > try: > for item in dict: > print item,'\t'+'#'*dict[item] > dict[item]=dict[item]-1 > if dict[item]< 0: > dict[item] = random.randrange (1,65) > except RuntimeError: > pass > time.sleep(1) > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From sarmstrong13@mac.com Wed Jun 19 14:30:12 2002 From: sarmstrong13@mac.com (SA) Date: Wed, 19 Jun 2002 08:30:12 -0500 Subject: [Tutor] More Tkinter Help Please [Dialog windows] In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C673@mbtlipnt02.btlabs.bt.co.uk> Message-ID: I see what you mean. To get the method to work your way, I have to change a few things in PyShell.__init__: self.f = Frame(top) self.f.pack() Instead of: f = Frame(top) f.pack() That would change your method to the following: def doSave(self): SaveDialog = Saving(self.f) filename = SaveDialog.getName() self.saveText(filename) del(saveDialog) This works. If I do not change the items, I get and undefined f error when I try to save. Another question. SaveText in self.saveText is a user defined method correct? It takes the text from the self.t1 object and loads it into the filename object, correct? Or is selfText a method from another module I did not import, because without the user defined method I get an error saying PyShell instance has no attribute saveText. One more cool thing I think I may have learned from this experience: The def methods in the class are attributes to the object class. Is this correct? (He, He, he, he... This is so cool now.)(I love it when this stuff starts to come together and make sense) So self defines the variables inside the defined object attribute and allows those variables to be used outside of the method and elsewhere in the class object, correct? Does this also allow the variable to be used outside the class, globally? Is this how we were able to pass the data inside the apply class from MyDialog to PyShell by using the return command? Thanks. This has been a wonderful and very big help. SA From alan.gauld@bt.com Wed Jun 19 14:48:24 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 19 Jun 2002 14:48:24 +0100 Subject: [Tutor] More Tkinter Help Please [Dialog windows] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C678@mbtlipnt02.btlabs.bt.co.uk> > I see what you mean. > > To get the method to work your way, I have to change a few things in > PyShell.__init__: > > self.f = Frame(top) > self.f.pack() Correct, looks like you have it now. > Another question. SaveText in self.saveText is a user defined method > correct? Correct. > It takes the text from the self.t1 object and loads > it into the filename object More specifically the *file* object created when you use the filename *string* to open the file. Pedantics. > PyShell instance has no attribute saveText. Not until you define the method. > The def methods in the class are attributes to the object class. > Is this correct? Absolutely. Classes have attributes which are either methods or data. Since functions in Python are objects too the method *names* are just attributes pointing to function objects... In exactly the same way as the other attribbute names just point to raw data items. At that level there is very little difference between a method and a member data variable > (He, He, he, he... This is so cool now.)(I love it when this > stuff starts to come together and make sense) :-) Looks like the light it coming on. > So self defines the variables inside the defined object > attribute and allows those variables to be used outside > of the method and elsewhere in the class Correct. > Does this also allow the variable to be used outside the > class, globally? No, because self is only visible inside the class definition. Of course if you write a method that passes self back as a return value then the reciever can use it to access the class: class C: def f(self): print 'I'm f' return self def spam(self): print 'boo!') c = C() d = c.f() # prints message and returns self d.spam() # prints boo! coz d and c now point to the same C instance > Is this how we were able to pass the data > inside the apply class from MyDialog to PyShell by > using the return command? We didn't. We kept a reference to the dialog when we created it then used that reference to call the getName() method. There was no need to pass anything back to the PyShell, it was all done by the PyShell requesting the data from the dialog. This is all good client-server style programming where the server(dialog here) performs tasks on demand from the client(pyshell here). This ensures that the dialog is reusable by other clients since it doesn't know who/what created/called it. Alan g. Author of the 'Learning to Program' web site http://www.freenetpages.co.uk/hp/alan.gauld From einarth@decode.is Wed Jun 19 15:14:37 2002 From: einarth@decode.is (Einar Th. Einarsson) Date: Wed, 19 Jun 2002 14:14:37 +0000 Subject: [Tutor] Font sizes in Idle Message-ID: <200206191414.38649.einarth@decode.is> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey y'all Does anyone know how to make Idle run with larger fonts? Or have any tips i= n=20 that general directions? When I start Idle it displays the code in ca. 6-7pt letters, which basicall= y=20 sucks as I can't read that small a print (which has frequently landed me in= =20 legal troubles, but that's besides the point ;) I'm using Python 2.2 on RedHat 7.2. Help would be greatly appreciated. - --=20 A conclusion is simply the place where you got tired of thinking. Yours etc. Einar Th. -----BEGIN PGP SIGNATURE----- Version: PGP 6.5.8 iQA/AwUBPRCRzW1/ORZtyd/tEQLzyACbBRFLHrVIphGpk/E01BCfefXj6U0AoLH+ r3uyNeNcorPtu8RGK3ClTGp0 =3DkrbZ -----END PGP SIGNATURE----- From alan.gauld@bt.com Wed Jun 19 17:07:59 2002 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 19 Jun 2002 17:07:59 +0100 Subject: [Tutor] Font sizes in Idle Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20E66C67C@mbtlipnt02.btlabs.bt.co.uk> There is a FAQ entry on this someplace I think. Basically you have to go into one of the IDLE source files(editor.py?) and change the fonts manually - they are hard coded! Unless that's changed recently, I haven't had to do that for a few releases since I'm not using IDLE on Linux... Alan g. > Does anyone know how to make Idle run with larger fonts? Or > have any tips in that general directions? From michael.williams@st-annes.oxford.ac.uk Wed Jun 19 17:58:33 2002 From: michael.williams@st-annes.oxford.ac.uk (Michael Williams) Date: Wed, 19 Jun 2002 17:58:33 +0100 Subject: [Tutor] Font sizes in Idle In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C67C@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20E66C67C@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20020619165833.GA1674@st-annes.oxford.ac.uk> On Wed, Jun 19, 2002 at 05:07:59PM +0100, alan.gauld@bt.com wrote: > There is a FAQ entry on this someplace I think. There's some documentation from a CVS log on this here: http://mail.python.org/pipermail/idle-dev/2001-October/000718.html > Unless that's changed recently, I haven't had to do that for > a few releases since I'm not using IDLE on Linux... For anyone interested, you might prefer IDLEfork which is much more aggresively developed and shaping up into quite a powerful Python editor (it's no Vi but nothing is ;->). See: -- Michael From urnerk@qwest.net Wed Jun 19 18:10:31 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 19 Jun 2002 10:10:31 -0700 Subject: [Tutor] Font sizes in Idle In-Reply-To: <200206191414.38649.einarth@decode.is> Message-ID: <5.1.1.6.0.20020619100750.026d6b20@urnerk/pop.ptld.qwest.net> At 02:14 PM 6/19/2002 +0000, Einar Th. Einarsson wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > >Hey y'all > >Does anyone know how to make Idle run with larger fonts? Or have any tips in >that general directions? Hi Einar -- There are some config files in the IDLE directory. For your setup, I think config-unix is the right place to change font size. I've blown mine up to 14 or something huge like that. I know what you mean about the tiny defaults. Alan must have used an older version, as font sizes are not hard coded in a .py file. Just the other day, I switched to the forked IDLE on my Mandrake 8.2 setup, but I know the config business with user-defined font sizes is the same in the regular IDLE. >When I start Idle it displays the code in ca. 6-7pt letters, which basically >sucks as I can't read that small a print (which has frequently landed me in >legal troubles, but that's besides the point ;) > >I'm using Python 2.2 on RedHat 7.2. Help would be greatly appreciated. > >- -- >A conclusion is simply the place where you got tired of thinking. > >Yours etc. > Einar Th. Kirby From dyoo@hkn.eecs.berkeley.edu Wed Jun 19 18:03:15 2002 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 19 Jun 2002 10:03:15 -0700 (PDT) Subject: [Tutor] Font sizes in Idle In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20E66C67C@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Wed, 19 Jun 2002 alan.gauld@bt.com wrote: > There is a FAQ entry on this someplace I think. > > Basically you have to go into one of the IDLE source > files(editor.py?) and change the fonts manually > - they are hard coded! > > Unless that's changed recently, I haven't had to do that for a few > releases since I'm not using IDLE on Linux... It's changed recently; the IDLE developers pushed out the configuration stuff into a set of files called config-win.txt, config-unix.txt, or config-mac.txt. Einar is running on Red Hat, so config-unix.txt is the file to fix. Good luck! From urnerk@qwest.net Wed Jun 19 18:14:38 2002 From: urnerk@qwest.net (Kirby Urner) Date: Wed, 19 Jun 2002 10:14:38 -0700 Subject: [Tutor] Install failure In-Reply-To: <20020618230145.16179.qmail@web21208.mail.yahoo.com> Message-ID: <5.1.1.6.0.20020619101126.026d44d0@urnerk/pop.ptld.qwest.net> The Windows installer should have created an icon link to IDLE which is the graphical shell available out of the box. This is a great environment in which to first familiarize yourself with Python programming, as the DOS shell is unsuitable as a shell environment, and you certainly don't want to get stuck with Notepad for editing your code (IDLE's text editor is color coded -- gvim for Windows is another option, with syntax files for way more languages than Python). Pythonw.exe by itself is not a shell, but a way of invoking other scripts without opening a console window (as was noted above). Kirby At 01:01 AM 6/19/2002 +0200, you wrote: >HI: > >I just installed 2.2.1 and the installation process >went fine. > >Problem: >The Python command line works, but the Pythonw.exe >doesn=B4t. > >No window prompts argumenting errors or anything. Just >Nothing happens when you click on it. > >I have W98SE, on a HP PIII-700 laptop. > >Any help will be appreciated. > >Adolfo From flaxeater@yahoo.com Wed Jun 19 19:29:49 2002 From: flaxeater@yahoo.com (Chad Crabtree) Date: Wed, 19 Jun 2002 11:29:49 -0700 (PDT) Subject: [Tutor] A Technical Question In-Reply-To: <20020619160004.12742.50274.Mailman@mail.python.org> Message-ID: <20020619182949.22017.qmail@web11602.mail.yahoo.com> I have been playing around with TKinter. I have done pretty much what I have set about. I made a little text box thingy. Any way I wanted to make a delete button that would delete the last line of the text box. However I can not figure out how to interogate the text box so that it tells me how many indexes it has. Here is my Code right now. Mind you it's just a toy, with pretend levers and switches. from Tkinter import * class Application(Frame): def right(self): index=str(self.counter) + "\n" self.textArea.insert(END,index) self.counter=self.counter+1 self.textArea.see(END) def addtotext(self,item): self.textArea.insert(END,item) def delete(self): self.textArea.insert("DELETE",END) def __init__(self, master=None): self.counter=3 self.root=Frame.__init__(self,master) self.grid() self.main=Frame(self.root,relief="groove", border=5) self.main.grid(row=0,column=0,columnspan=2) self.subF=Frame(self.main, relief="raised",border=5) self.subF2=Frame(self.subF,relief="sunken",border=3) self.subF.grid(row=0,column=0) self.subF2.grid(row=0,column=0) self.textArea=Text(self.subF2,height="12",width="30",bg="blue",fg="yellow") self.textArea.grid(column=0,row=0) self.scrBar=Scrollbar(self.subF2) self.scrBar.grid(column=1,row=0,sticky=N+S) self.scrBar.config(command=self.textArea.yview) self.textArea.config(yscrollcommand=self.scrBar.set) self.output=['Hello World\n','How are you doing?\n. I am doing Very well.\n\n\nThere hahahaha',str(8)+"\n",str(self.counter) + "\n"] self.textArea.insert(END,self.output[0]) self.textArea.insert(END,self.output[1]) self.textArea.insert(END,self.output[2]) self.textArea.insert(END,self.output[3]) self.frmButton=Frame(self.root,border=2,relief="sunken") self.frmButton.grid(row=1,column=0,columnspan=2,sticky=N+E+S+W) self.quitButton=Button(self.frmButton,text=" Quit ",command=self.quit) self.quitButton.grid(column=0,row=0,sticky=N+E+S+W,padx=10) self.btnWrite=Button(self.frmButton,text=" Write",command=self.right) self.btnWrite.grid(column=1,row=0,sticky=N+E+S+W,padx=10) self.btnDel=Button(self.frmButton,text="Delete",command=self.delete) self.btnDel.grid(column=2,row=0,sticky=N+E+S+W,padx=10) app=Application() app.master.title("Sample application") app.mainloop() Thank you. __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup http://fifaworldcup.yahoo.com From einarth@decode.is Wed Jun 19 19:37:45 2002 From: einarth@decode.is (Einar Th. Einarsson) Date: Wed, 19 Jun 2002 18:37:45 +0000 Subject: [Tutor] Font sizes in Idle Message-ID: <200206191837.45766.einarth@decode.is> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Scratch that...just found it.... > Excellent, thnx. The config files was what I was looking for. It's a bit= =20 > unusual to keep the config files there (used to finding them in either /e= tc > or in ~/.progname :P) > > Since I'm rambling already I've got another one for you guys (propably ju= st > as simple once you know the answer): > >How do I pass cmd line args to a program I wan't to debug? I.e. something > like 'debug with arguments' or 'run with arguments'. Any debugger is fine > (pdb or pydb (with or without ddd). Preferably without manually editing = > sys.argv each time I run it.... > - --=20 Who's General Failure & why's he reading my disk? Yours etc. Einar Th. -----BEGIN PGP SIGNATURE----- Version: PGP 6.5.8 iQA/AwUBPRDPeW1/ORZtyd/tEQK5aACfQ37rcdCow3puLlmpvW5gv9sKFIMAn3AC PEkl/zmYt19D2zb1zHhe3SVI =3DvT9n -----END PGP SIGNATURE----- From einarth@decode.is Wed Jun 19 19:30:34 2002 From: einarth@decode.is (Einar Th. Einarsson) Date: Wed, 19 Jun 2002 18:30:34 +0000 Subject: [Tutor] Font sizes in Idle In-Reply-To: <5.1.1.6.0.20020619100750.026d6b20@urnerk/pop.ptld.qwest.net> References: <5.1.1.6.0.20020619100750.026d6b20@urnerk/pop.ptld.qwest.net> Message-ID: <200206191830.36198.einarth@decode.is> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Excellent, thnx. The config files was what I was looking for. It's a bit=20 unusual to keep the config files there (used to finding them in either /etc= =20 or in ~/.progname :P) Since I'm rambling already I've got another one for you guys (propably just= as=20 simple once you know the answer): How do I pass cmd line args to a program I wan't to debug? I.e. something l= ike=20 'debug with arguments' or 'run with arguments'. Any debugger is fine (pdb = or=20 pydb (with or without ddd). Preferably without manually editing sys.argv=20 each time I run it.... - --=20 "The axiom 'An honest man has nothing to fear from the police' is currently under review by the Axiom Review Board" -- Terry Prachett, "Men At Arms" Yours etc. Einar Th. On Wednesday 19 June 2002 17:10, Kirby Urner wrote: > At 02:14 PM 6/19/2002 +0000, Einar Th. Einarsson wrote: > >-----BEGIN PGP SIGNED MESSAGE----- > >Hash: SHA1 > > > >Hey y'all > > > >Does anyone know how to make Idle run with larger fonts? Or have any tips > > in that general directions? > > Hi Einar -- > > There are some config files in the IDLE directory. For your setup, > I think config-unix is the right place to change font size. I've blown > mine up to 14 or something huge like that. I know what you mean > about the tiny defaults. > > Alan must have used an older version, as font sizes are not hard coded > in a .py file. > > Just the other day, I switched to the forked IDLE on my Mandrake 8.2 > setup, but I know the config business with user-defined font sizes is > the same in the regular IDLE. > > >When I start Idle it displays the code in ca. 6-7pt letters, which > > basically sucks as I can't read that small a print (which has frequently > > landed me in legal troubles, but that's besides the point ;) > > > >I'm using Python 2.2 on RedHat 7.2. Help would be greatly appreciated. > > > >- -- > >A conclusion is simply the place where you got tired of thinking. > > > >Yours etc. > > Einar Th. > > Kirby -----BEGIN PGP SIGNATURE----- Version: PGP 6.5.8 iQA/AwUBPRDNym1/ORZtyd/tEQI1wwCglatPhyGatEQjk6cccdk4J92IwM4AoID3 xdGVOIXgOdaDTuUbxNYfmdMU =3D+sdI -----END PGP SIGNATURE----- From marcolinux@linuxbr.com.br Wed Jun 19 21:47:51 2002 From: marcolinux@linuxbr.com.br (Marc) Date: Wed, 19 Jun 2002 17:47:51 -0300 Subject: [Tutor] Dynamic change of dictionaries In-Reply-To: References: <20020618223319.GA7284@marcolab.proconet> Message-ID: <20020619204751.GA2675@marcolab.proconet> --uAKRQypu60I7Lcqm Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Sean 'Shaleh' Perry (shalehperry@attbi.com) wrote: > why not simply ignore 0 count items? > > for item in dict: > if dict[item] == 0: continue > > # print status bars > > if you want to preen items, the del dict[item] method is reasonable. Thanks for reply. (And thanks for Lloyd Kvam .The tools you cited are overkill right now. Besides, I want to play with python a little bit. I didn't received your mail, read it in tutor mail archive. I wonder how much fun I have been missing lately :) Hehe, no need to "preen" right now, but if u consider it have to be seem from across the room, the bars are more than welcome :) Your method of ignore item when 0 is nice and have a good side effect: I know that an IP acessed the proxy, thus it is alive. However, it makes a "graph" with too many lines. That's why I want to delete zeroed items, to avoid clutter. I've made a new version of the simulator. And the more I play with it, the more I want to changeit.For example, do you guys know how to change the color of terminal with codes? I've tried (from /etc/rc.d/functions): (SETCOLOR_FAILURE="echo -en \\033[1;31m") $ python >>> red='\\033[1;31m' >>> print red,'supposed 2 b red' \033[1;31m supposed 2 b red :(. Im sure it's trivial to do , but I dont know how. Sugestions? Thanks in advance. --uAKRQypu60I7Lcqm Content-Type: text/plain; charset=us-ascii Content-Disposition: attachment; filename="traffic.py" """ Show a network traffic gauges """ import random,time,os,sys dict={} cnt=100 #talkin'bout preen :) lft='\n'*7+'\t\t\t\t' splashscreen=lft+' Traffic Monitor\n'+lft+'Python Powered (TM)' def increment(item): try: dict[item] += 1 except KeyError: dict[item] = 1 def decrement(): if not dict.__len__: return try: for item in dict: if dict[item] == 0: continue #del (dict[item]) else: dict[item] -= 1 except RuntimeError: pass os.system('clear') print splashscreen time.sleep(2) os.system('clear') while cnt: os.system('clear') #print dict for item in dict: print item,'\t'+'#'*dict[item] ip ='10.15.50.%d' % random.randrange(1,12) increment(ip) if not (cnt % 10): decrement() print cnt cnt=100 cnt-=1 time.sleep(1) --uAKRQypu60I7Lcqm-- From glingl@aon.at Thu Jun 20 00:21:38 2002 From: glingl@aon.at (Gregor Lingl) Date: Thu, 20 Jun 2002 01:21:38 +0200 Subject: [Tutor] A Technical Question References: <20020619182949.22017.qmail@web11602.mail.yahoo.com> Message-ID: <006001c217e8$0fc7a970$1615a8c0@mega> An interactive session with your app shows: >>> app.textArea.get(1.0,10000.0).split('\n') ['Hello World', 'How are you doing?', '. I am doing Very well.', '', '', 'Therehahahaha8', '3', '', ''] >>> # don't know if there is a better way than 10000.0 for length of text >>> len(app.textArea.get(1.0,10000.0).split('\n')) 9 >>> app.textArea.delete(8.0,9.0) >>> app.textArea.get(1.0,10000.0).split('\n') ['Hello World', 'How are you doing?', '. I am doing Very well.', '', '', 'Therehahahaha8', '3', ''] >>> len(app.textArea.get(1.0,10000.0).split('\n')) 8 >>> app.textArea.delete(7.0,8.0) >>> app.textArea.get(1.0,10000.0).split('\n') ['Hello World', 'How are you doing?', '. I am doing Very well.', '', '', 'Therehahahaha8', ''] >>> len(app.textArea.get(1.0,10000.0).split('\n')) 7 >>> app.textArea.delete(6.0,7.0) >>> # last newline seems undeletable >>> app.textArea.get(1.0,10000.0).split('\n') ['Hello World', 'How are you doing?', '. I am doing Very well.', '', '', ''] >>> So I can put this - with minor adaptions - into your delete method: def delete(self): l = len(self.textArea.get(1.0,10000.0).split('\n')) start = str(l-1)+'.0' end = str(l)+ '.0' print l, start, end # comment out after testing! self.textArea.delete(start,end) Sure, this is not very elegant, but it works. In fact even this works: def delete(self): l = len(self.textArea.get(1.0,10000.0).split('\n')) self.textArea.delete(float(l-1),float(l)) ... but it certainly reveals one of the less beautiful features of Tk(inter) Gregor ----- Original Message ----- From: "Chad Crabtree" To: Sent: Wednesday, June 19, 2002 8:29 PM Subject: [Tutor] A Technical Question > I have been playing around with TKinter. I have done > pretty much what I have set about. I made a little > text box thingy. Any way I wanted to make a delete > button that would delete the last line of the text > box. > However I can not figure out how to interogate the > text box so that it tells me how many indexes it has. > > Here is my Code right now. Mind you it's just a toy, > with pretend levers and switches. > > from Tkinter import * > > class Application(Frame): > > def right(self): > index=str(self.counter) + "\n" > self.textArea.insert(END,index) > self.counter=self.counter+1 > self.textArea.see(END) > > def addtotext(self,item): > self.textArea.insert(END,item) > > > def delete(self): > self.textArea.insert("DELETE",END) > > def __init__(self, master=None): > self.counter=3 > self.root=Frame.__init__(self,master) > self.grid() > self.main=Frame(self.root,relief="groove", > border=5) > self.main.grid(row=0,column=0,columnspan=2) > > self.subF=Frame(self.main, > relief="raised",border=5) > > self.subF2=Frame(self.subF,relief="sunken",border=3) > > self.subF.grid(row=0,column=0) > self.subF2.grid(row=0,column=0) > > > self.textArea=Text(self.subF2,height="12",width="30",bg="blue",fg="yellow") > self.textArea.grid(column=0,row=0) > self.scrBar=Scrollbar(self.subF2) > self.scrBar.grid(column=1,row=0,sticky=N+S) > > self.scrBar.config(command=self.textArea.yview) > > self.textArea.config(yscrollcommand=self.scrBar.set) > > self.output=['Hello World\n','How are you doing?\n. > I am doing Very well.\n\n\nThere > hahahaha',str(8)+"\n",str(self.counter) + "\n"] > self.textArea.insert(END,self.output[0]) > self.textArea.insert(END,self.output[1]) > self.textArea.insert(END,self.output[2]) > self.textArea.insert(END,self.output[3]) > > > self.frmButton=Frame(self.root,border=2,relief="sunken") > > self.frmButton.grid(row=1,column=0,columnspan=2,sticky=N+E+S+W) > > > self.quitButton=Button(self.frmButton,text=" > Quit ",command=self.quit) > > self.quitButton.grid(column=0,row=0,sticky=N+E+S+W,padx=10) > > > self.btnWrite=Button(self.frmButton,text=" > Write",command=self.right) > > self.btnWrite.grid(column=1,row=0,sticky=N+E+S+W,padx=10) > > > self.btnDel=Button(self.frmButton,text="Delete",command=self.delete) > > self.btnDel.grid(column=2,row=0,sticky=N+E+S+W,padx=10) > > > > app=Application() > app.master.title("Sample application") > app.mainloop() > > Thank you. > > > __________________________________________________ > Do You Yahoo!? > Yahoo! - Official partner of 2002 FIFA World Cup > http://fifaworldcup.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ak@silmarill.org Thu Jun 20 01:31:33 2002 From: ak@silmarill.org (Andrei Kulakov) Date: Wed, 19 Jun 2002 20:31:33 -0400 Subject: [Tutor] Dynamic change of dictionaries In-Reply-To: <20020619204751.GA2675@marcolab.proconet> References: <20020618223319.GA7284@marcolab.proconet> <20020619204751.GA2675@marcolab.proconet> Message-ID: <20020620003133.GA1587@ak.silmarill.org> On Wed, Jun 19, 2002 at 05:47:51PM -0300, Marc wrote: > Sean 'Shaleh' Perry (shalehperry@attbi.com) wrote: > > > why not simply ignore 0 count items? > > > > for item in dict: > > if dict[item] == 0: continue > > > > # print status bars > > > > if you want to preen items, the del dict[item] method is reasonable. > > Thanks for reply. > > (And thanks for Lloyd Kvam .The tools you cited > are overkill right now. Besides, I want to play with python a little > bit. I didn't received your mail, read it in tutor mail archive. > I wonder how much fun I have been missing lately :) > > Hehe, no need to "preen" right now, but if u consider it have to be seem > from across the room, the bars are more than welcome :) > Your method of ignore item when 0 is nice and have a good side effect: I > know that an IP acessed the proxy, thus it is alive. However, it makes > a "graph" with too many lines. That's why I want to delete zeroed items, to > avoid clutter. You can skip drawing the graph if it's 0: if 0: continue else: draw_bar() - Andrei -- Cymbaline: intelligent learning mp3 player - python, linux, console. get it at: cy.silmarill.org From adolfo158@yahoo.es Thu Jun 20 02:32:47 2002 From: adolfo158@yahoo.es (=?iso-8859-1?q?Adolfo=20Aguirre?=) Date: Thu, 20 Jun 2002 03:32:47 +0200 (CEST) Subject: [Tutor] COM server not starting Message-ID: <20020620013247.55480.qmail@web21203.mail.yahoo.com> Hi: I intalled Python 2.2.1 and followed instructions for starting the COM server as found on a downloaded manual. It did not work. Comments: 1. The pages listed on the manual to firt start, and then test the COM Server where not located where the manual placed them. 2. The Manual I am using is called "Python and ActiveX Scripting" and below I include the text (only a page)with the instructions I followed. Adolfo ======>>>> Python and ActiveX Scripting Important: The installers install (not register) the new implementation. See Installing the AXScript Implementation for details on setting up the new implementation. This documentation covers the following topics: • What is ActiveX Scripting? • Why a new implementation? • Installing the AXScript Implementation. • Using the AXScript Implementation • Debugging PyScript Code What is ActiveX Scripting? ActiveX Scripting is a technology which allows for "plug-in" languages to be used by a host application. Currently, the only hosts which support this technology are provided by Microsoft - the best known ones being Internet Explorer (V3 or better), and Active Server Pages (aka Denali). To test or play with ActiveX Scripting, you will need one of these hosts. Installing the AXScript Implementation. Note Please see the README.HTM in the win32com directory. It contains a link to the "AXScript Demos" page. This page allows you to automatically install the engine But here are the "manual installation" instructions. Installing either win32com or Pythonwin will install the new implementation. All you need to is register it. Perform these steps: • Locate the win32com directory in Windows Explorer. Change to the "win32com\AXScript\Client" directory. • Locate the file "pyscript.py", and double-click on this file. This should cause a "Python.exe" window to appear, and a message appear telling you the server is being registered. (All that need be done here is to run "python.exe pyscript.py", which is what the above procedure will do. However, you can execute that command how-ever you like!) Then test it: • Locate the "win32com\AXScript\Demos\ie" directory. • Double-click on the "foo2.htm" file. You should see Internet Explorer start up, and all buttons with text. If any buttons are blank, it is likely that the server is not correctly registered. (NOTE: If a "Debug Window" appears minimised on your task-bar, it means you are running the old implementation.) • Click on the buttons. Using the AXScript Implementation The language name is "Python". The object model provided to Python is very similar to that provided by VBScript or JScript. All global functions (such as "alert()" in IE) are available, and all objects are available by name (eg "MyForm" is used to reference the form defined with that name in the HTML. Python and Internet Explorer Python and IE work very well together. However, a key difference to the JScript/VBScript implementations is in "local variables". All objects are able to be fully referenced, but not all objects are available as "local variables". For example, in an event handler for a form, you would expect the forms objects (eg, buttons, text boxes, etc.) to be visible locally - ie, you would expect "Text1.Value = 'New Value'" to work - it doesn't! However, the explicit "FormName.Text1.Value" does. Python and Active Server Pages (Denali) To use Python in Active Server Pages (Denali) you must ensure the .ASP files are installed in a location known to the Internet Server. There is a significant limitation when using scripts enclosed with <% tags. The current version of Denali strips all white-space from this code, making it impossible to write "if" (or any other block) statements in this context. Code that uses the