From denise.hartley at gmail.com Fri Jul 1 00:11:56 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 30 Jun 2005 15:11:56 -0700 Subject: [Tutor] A more Pythonic way to do this Message-ID: <8daabe5605063015111d32477a@mail.gmail.com> Hey guys! I have a 'quest,' and at first glance this email looks long, but the problem is probably not as complex as the length implies. Please bear with me, if I could get some advice on this particular problem, it would go along way toward helping me be a better Python programmer. Some of you might remember, a few months ago, I was working on a space invaders game for a birthday present. One of the functions I really wanted to add to the game was to change the enemy "ships" at each new level. Because of my deadline and my newness to Python, I did this in an extremely ugly way. To give you an idea: the original main loop called: enemyship_sprites = createEnemies(screen, enemy_speed) createEnemies looks like this: def createEnemies(screen, speed): enemyship_sprites = EnemySprites(speed) for rows in xrange(5): for cols in xrange(8): enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) enemyship_sprites.draw(screen) return enemyship_sprites It creates an instance of EnemySprites (my holder class) which contains code for when the ships hit bottom, when to update them, etc. It also calls "Enemy()", which looks like this: class Enemy(pygame.sprite.Sprite): def __init__(self, startx, starty): pygame.sprite.Sprite.__init__(self) if level == 1: self.image, self.rect = load_image('salad_ship.bmp', -1) self.rect.centerx = startx self.rect.centery = starty def update(self, direction, go_down): jump = 40 # how much the enemies move to the right/left on each jump if go_down: # if a ship is moving down on this round, # it doesn't move on the x-axys self.rect.move_ip((0, 5)) else: # move a ship in the x-axys. # if direction=1, it moves to the right; -1 to the left self.rect.move_ip((jump * direction, 0)) # maybe it's time for a shot? :) # the chances are 1/30 dice = random.randint(0,30) global enemy_shot_sprites if dice == 1: shot = EnemyShot(self.rect.midtop) enemy_shot_sprites.add(shot) Now, get ready for one of the uglier things you've probably seen lately (!!): Since I can only access the variable "level" from within the main loop, for some reason I thought I couldnt use it in my class definitions (which of course come before and are outside of the mainloop). So within the main loop, I did: if level == 1: enemyship_sprites = createEnemies1(screen, enemy_speed) elif level == 2: enemyship_sprites = createEnemies2(screen, enemy_speed) elif level == 3: enemyship_sprites = createEnemies3(screen, enemy_speed) elif level == 4: enemyship_sprites = createEnemies4(screen, enemy_speed) elif level == 5: enemyship_sprites = createEnemies5(screen, enemy_speed) elif level == 6: enemyship_sprites = createEnemies6(screen, enemy_speed) elif level == 7: enemyship_sprites = createEnemies7(screen, enemy_speed) elif level == 8: enemyship_sprites = createEnemies8(screen, enemy_speed) else: enemyship_sprites = createEnemies9(screen, enemy_speed) And yes, I created 9 different createEnemies, all pretty much carbon copies of each other except that they called Enemy1, Enemy2, Enemy3, etc. And then (you guessed it), I created 9 different Enemy functions, too, so that each one could have its own (different) bitmap. Now... this is just ridiculous. To my credit, I did actually know that at the time. But the day before the birthday, I figured if I could make it work somehow, I would, and I'd make it prettier later. Now just happens to be that later ;) So now that I've got a little more Python experience under my belt (not much, but a little), it occurred to me that when I call createEnemies in the mainloop, I could pass in an argument 'level'. mainloop now starting off with: enemyship_sprites = createEnemies(screen, enemy_speed, level) level is one of my main loop variables, so it'll know what i'm talking about and can take that variable and pass it in when it calls createEnemies. (Btw, please forgive me if I mix up terms like argument and variable or use them in the wrong places, I'm still getting used to them!) In any case, then I changed my createEnemies to look like this: def createEnemies(screen, speed, level): enemyship_sprites = EnemySprites(speed) for rows in xrange(5): for cols in xrange(8): enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) enemyship_sprites.draw(screen) return enemyship_sprites Since the part that changes each level actually matters when the Enemy function gets called (because that's where the bmps are loaded), I made Enemy need 'level': class Enemy(pygame.sprite.Sprite): def __init__(self, startx, starty, level): pygame.sprite.Sprite.__init__(self) if level == 1: self.image, self.rect = load_image('salad_ship.bmp', -1) elif level == 2: (.................etc) self.rect.centerx = startx self.rect.centery = starty (...............etc) Now I know this email is getting hard to read ;) At this point I was thinking I'd have one createEnemies, called in the mainloop, which would take the level and, when it called Enemy to create the ships, use that level argument to determine which bmp to use for the ship itself. One createEnemies(), one Enemy(), there you go. But now it's giving me an error when createEnemies is called, for the enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) line, saying __init__() (and this would be Enemy's init, correct?) takes exactly 4 arguments (3 given): and Enemy's init, as you can see, takes (self, startx, starty, level). But the first argument is just 'self'! I don't have to pass that in.... I never *did*, anyway, in all my Enemy1, Enemy2, Enemy3 code...? I can send the full code for anybody who thinks that would be clearer to look at (ha ha) - I was going to attach it here but it would make the message too big for the list. I know that going through such a messy problem like this is a pain, and questions like this don't always get a lot of responses on the list. My code worked, it was just messy, and so I suppose I could just leave it alone. But I want to clean it up: I want to make it more Pythonic, more organized, more efficient, and would really love any advice anyone could offer. Heck, for all I know, I could just be needing to add a "self.___" somewhere, heaven knows that has tripped me up before! Would love to hear from you guys, and thanks again, Denise From bvande at po-box.mcgill.ca Fri Jul 1 01:31:37 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 30 Jun 2005 19:31:37 -0400 Subject: [Tutor] A more Pythonic way to do this In-Reply-To: <8daabe5605063015111d32477a@mail.gmail.com> References: <8daabe5605063015111d32477a@mail.gmail.com> Message-ID: <42C480D9.7050805@po-box.mcgill.ca> D. Hartley said unto the world upon 30/06/2005 18:11: > Hey guys! > > I have a 'quest,' and at first glance this email looks long, but the > problem is probably not as complex as the length implies. Please bear > with me, if I could get some advice on this particular problem, it > would go along way toward helping me be a better Python programmer. > > Some of you might remember, a few months ago, I was working on a space > invaders game for a birthday present. One of the functions I really > wanted to add to the game was to change the enemy "ships" at each new > level. Because of my deadline and my newness to Python, I did this in > an extremely ugly way. To give you an idea: Hi Denise, I sympathize; I'm one of those on the list given to asking long questions, too. From what you describe, you are right to think there is a smell you ought fix. I don't have a sound enough grasp myself to be useful for the details. But, I wanted to say something about: > But now it's giving me an error when createEnemies is called, for the > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) line, > saying __init__() (and this would be Enemy's init, correct?) takes > exactly 4 arguments (3 given): If you are sure which __init__() is at issue, print is your friend. I've found that when my class hierarchy isn't matching my expectations, things like: class A(object): def __init__(self): print "In A.__init__()" # real logic here def act(self): print "In A.act()" etc. can really help out. I don't know if that'll be enough to push you to seeing the problem, but it can only help :-) Best, Brian vdB From adam.jtm30 at gmail.com Fri Jul 1 01:35:08 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Fri, 1 Jul 2005 00:35:08 +0100 Subject: [Tutor] A more Pythonic way to do this In-Reply-To: <8daabe5605063015111d32477a@mail.gmail.com> References: <8daabe5605063015111d32477a@mail.gmail.com> Message-ID: Here's the problem --> enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) 1,2 1 2 1 0 you've put a braket after +30 which ends the Enemy call. The numbering is +1 for opening braket -1 for closing so 0 is the end of the Enemy call if you understand this. On 6/30/05, D. Hartley wrote: > > Hey guys! > > I have a 'quest,' and at first glance this email looks long, but the > problem is probably not as complex as the length implies. Please bear > with me, if I could get some advice on this particular problem, it > would go along way toward helping me be a better Python programmer. > > Some of you might remember, a few months ago, I was working on a space > invaders game for a birthday present. One of the functions I really > wanted to add to the game was to change the enemy "ships" at each new > level. Because of my deadline and my newness to Python, I did this in > an extremely ugly way. To give you an idea: > > the original main loop called: > enemyship_sprites = createEnemies(screen, enemy_speed) > > createEnemies looks like this: > > def createEnemies(screen, speed): > enemyship_sprites = EnemySprites(speed) > for rows in xrange(5): > for cols in xrange(8): > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) > enemyship_sprites.draw(screen) > return enemyship_sprites > > It creates an instance of EnemySprites (my holder class) which > contains code for when the ships hit bottom, when to update them, etc. > It also calls "Enemy()", which looks like this: > > class Enemy(pygame.sprite.Sprite): > def __init__(self, startx, starty): > pygame.sprite.Sprite.__init__(self) > if level == 1: > self.image, self.rect = load_image('salad_ship.bmp', -1) > self.rect.centerx = startx > self.rect.centery = starty > def update(self, direction, go_down): > jump = 40 # how much the enemies move to the right/left on > each jump > if go_down: > # if a ship is moving down on this round, > # it doesn't move on the x-axys > self.rect.move_ip((0, 5)) > else: > # move a ship in the x-axys. > # if direction=1, it moves to the right; -1 to the left > self.rect.move_ip((jump * direction, 0)) > # maybe it's time for a shot? :) > # the chances are 1/30 > dice = random.randint(0,30) > global enemy_shot_sprites > if dice == 1: > shot = EnemyShot(self.rect.midtop) > enemy_shot_sprites.add(shot) > > > Now, get ready for one of the uglier things you've probably seen lately > (!!): > > Since I can only access the variable "level" from within the main > loop, for some reason I thought I couldnt use it in my class > definitions (which of course come before and are outside of the > mainloop). So within the main loop, I did: > > if level == 1: > enemyship_sprites = createEnemies1(screen, enemy_speed) > elif level == 2: > enemyship_sprites = createEnemies2(screen, enemy_speed) > elif level == 3: > enemyship_sprites = createEnemies3(screen, enemy_speed) > elif level == 4: > enemyship_sprites = createEnemies4(screen, enemy_speed) > elif level == 5: > enemyship_sprites = createEnemies5(screen, enemy_speed) > elif level == 6: > enemyship_sprites = createEnemies6(screen, enemy_speed) > elif level == 7: > enemyship_sprites = createEnemies7(screen, enemy_speed) > elif level == 8: > enemyship_sprites = createEnemies8(screen, enemy_speed) > else: > enemyship_sprites = createEnemies9(screen, enemy_speed) > > And yes, I created 9 different createEnemies, all pretty much carbon > copies of each other except that they called Enemy1, Enemy2, Enemy3, > etc. And then (you guessed it), I created 9 different Enemy > functions, too, so that each one could have its own (different) > bitmap. > > Now... this is just ridiculous. > > To my credit, I did actually know that at the time. But the day before > the birthday, I figured if I could make it work somehow, I would, and > I'd make it prettier later. Now just happens to be that later ;) > > So now that I've got a little more Python experience under my belt > (not much, but a little), it occurred to me that when I call > createEnemies in the mainloop, I could pass in an argument 'level'. > > mainloop now starting off with: > enemyship_sprites = createEnemies(screen, enemy_speed, level) > > level is one of my main loop variables, so it'll know what i'm talking > about and can take that variable and pass it in when it calls > createEnemies. (Btw, please forgive me if I mix up terms like argument > and variable or use them in the wrong places, I'm still getting used > to them!) In any case, then I changed my createEnemies to look like > this: > > def createEnemies(screen, speed, level): > enemyship_sprites = EnemySprites(speed) > for rows in xrange(5): > for cols in xrange(8): > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) > enemyship_sprites.draw(screen) > return enemyship_sprites > > Since the part that changes each level actually matters when the Enemy > function gets called (because that's where the bmps are loaded), I > made Enemy need 'level': > > class Enemy(pygame.sprite.Sprite): > def __init__(self, startx, starty, level): > pygame.sprite.Sprite.__init__(self) > if level == 1: > self.image, self.rect = load_image('salad_ship.bmp', -1) > elif level == 2: > (.................etc) > self.rect.centerx = startx > self.rect.centery = starty > (...............etc) > > > Now I know this email is getting hard to read ;) > > At this point I was thinking I'd have one createEnemies, called in the > mainloop, which would take the level and, when it called Enemy to > create the ships, use that level argument to determine which bmp to > use for the ship itself. One createEnemies(), one Enemy(), there you > go. > > But now it's giving me an error when createEnemies is called, for the > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) line, > saying __init__() (and this would be Enemy's init, correct?) takes > exactly 4 arguments (3 given): and Enemy's init, as you can see, > takes (self, startx, starty, level). But the first argument is just > 'self'! I don't have to pass that in.... I never *did*, anyway, in > all my Enemy1, Enemy2, Enemy3 code...? > > I can send the full code for anybody who thinks that would be > clearer to look at (ha ha) - I was going to attach it here but it > would make the message too big for the list. I know that going > through such a messy > problem like this is a pain, and questions like this don't always get > a lot of responses on the list. My code worked, it was just messy, > and so I suppose I could just leave it alone. But I want to clean it > up: I want to make it more Pythonic, more organized, more efficient, > and would really love any advice anyone could offer. > > Heck, for all I know, I could just be needing to add a "self.___" > somewhere, heaven knows that has tripped me up before! > > Would love to hear from you guys, and thanks again, > Denise > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050701/bf538316/attachment-0001.htm From denise.hartley at gmail.com Fri Jul 1 02:13:19 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 30 Jun 2005 17:13:19 -0700 Subject: [Tutor] A more Pythonic way to do this In-Reply-To: References: <8daabe5605063015111d32477a@mail.gmail.com> Message-ID: <8daabe560506301713350ab2c9@mail.gmail.com> ..... it was a paren. I was so worried that I just wasn't figuring it all out, that I had tried to write elegant code and wasnt understanding the fundamentals, and the only reason it didnt work was because I left out a paren. I actually laughed until I cried. Thanks for that. And yes, it works now ;) it's lovely. ~Denise On 6/30/05, Adam Bark wrote: > Here's the problem --> > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), > level) > > 1,2 1 2 > 1 0 > you've put a braket after +30 which ends the Enemy call. The numbering is +1 > for opening braket -1 for closing so 0 is the end of the Enemy call if you > understand this. > > > On 6/30/05, D. Hartley wrote: > > > > Hey guys! > > > > I have a 'quest,' and at first glance this email looks long, but the > > problem is probably not as complex as the length implies. Please bear > > with me, if I could get some advice on this particular problem, it > > would go along way toward helping me be a better Python programmer. > > > > Some of you might remember, a few months ago, I was working on a space > > invaders game for a birthday present. One of the functions I really > > wanted to add to the game was to change the enemy "ships" at each new > > level. Because of my deadline and my newness to Python, I did this in > > an extremely ugly way. To give you an idea: > > > > the original main loop called: > > enemyship_sprites = createEnemies(screen, enemy_speed) > > > > createEnemies looks like this: > > > > def createEnemies(screen, speed): > > enemyship_sprites = EnemySprites(speed) > > for rows in xrange(5): > > for cols in xrange(8): > > enemyship_sprites.add(Enemy((cols*60)+20, > (rows*40)+30), level) > > enemyship_sprites.draw(screen) > > return enemyship_sprites > > > > It creates an instance of EnemySprites (my holder class) which > > contains code for when the ships hit bottom, when to update them, etc. > > It also calls "Enemy()", which looks like this: > > > > class Enemy(pygame.sprite.Sprite): > > def __init__(self, startx, starty): > > pygame.sprite.Sprite.__init__(self) > > if level == 1: > > self.image, self.rect = load_image('salad_ship.bmp', -1) > > self.rect.centerx = startx > > self.rect.centery = starty > > def update(self, direction, go_down): > > jump = 40 # how much the enemies move to the right/left on > > each jump > > if go_down: > > # if a ship is moving down on this round, > > # it doesn't move on the x-axys > > self.rect.move_ip((0, 5)) > > else: > > # move a ship in the x-axys. > > # if direction=1, it moves to the right; -1 to the left > > self.rect.move_ip((jump * direction, 0)) > > # maybe it's time for a shot? :) > > # the chances are 1/30 > > dice = random.randint (0,30) > > global enemy_shot_sprites > > if dice == 1: > > shot = EnemyShot(self.rect.midtop) > > enemy_shot_sprites.add(shot) > > > > > > Now, get ready for one of the uglier things you've probably seen lately > (!!): > > > > Since I can only access the variable "level" from within the main > > loop, for some reason I thought I couldnt use it in my class > > definitions (which of course come before and are outside of the > > mainloop). So within the main loop, I did: > > > > if level == 1: > > enemyship_sprites = createEnemies1(screen, > enemy_speed) > > elif level == 2: > > enemyship_sprites = createEnemies2(screen, > enemy_speed) > > elif level == 3: > > enemyship_sprites = createEnemies3(screen, > enemy_speed) > > elif level == 4: > > enemyship_sprites = createEnemies4(screen, > enemy_speed) > > elif level == 5: > > enemyship_sprites = createEnemies5(screen, > enemy_speed) > > elif level == 6: > > enemyship_sprites = createEnemies6(screen, > enemy_speed) > > elif level == 7: > > enemyship_sprites = createEnemies7(screen, > enemy_speed) > > elif level == 8: > > enemyship_sprites = createEnemies8(screen, > enemy_speed) > > else: > > enemyship_sprites = createEnemies9(screen, > enemy_speed) > > > > And yes, I created 9 different createEnemies, all pretty much carbon > > copies of each other except that they called Enemy1, Enemy2, Enemy3, > > etc. And then (you guessed it), I created 9 different Enemy > > functions, too, so that each one could have its own (different) > > bitmap. > > > > Now... this is just ridiculous. > > > > To my credit, I did actually know that at the time. But the day before > > the birthday, I figured if I could make it work somehow, I would, and > > I'd make it prettier later. Now just happens to be that later ;) > > > > So now that I've got a little more Python experience under my belt > > (not much, but a little), it occurred to me that when I call > > createEnemies in the mainloop, I could pass in an argument 'level'. > > > > mainloop now starting off with: > > enemyship_sprites = createEnemies(screen, enemy_speed, level) > > > > level is one of my main loop variables, so it'll know what i'm talking > > about and can take that variable and pass it in when it calls > > createEnemies. (Btw, please forgive me if I mix up terms like argument > > and variable or use them in the wrong places, I'm still getting used > > to them!) In any case, then I changed my createEnemies to look like > > this: > > > > def createEnemies(screen, speed, level): > > enemyship_sprites = EnemySprites(speed) > > for rows in xrange(5): > > for cols in xrange(8): > > enemyship_sprites.add(Enemy((cols*60)+20, > (rows*40)+30), level) > > enemyship_sprites.draw(screen) > > return enemyship_sprites > > > > Since the part that changes each level actually matters when the Enemy > > function gets called (because that's where the bmps are loaded), I > > made Enemy need 'level': > > > > class Enemy(pygame.sprite.Sprite): > > def __init__(self, startx, starty, level): > > pygame.sprite.Sprite.__init__(self) > > if level == 1: > > self.image, self.rect = load_image('salad_ship.bmp', -1) > > elif level == 2: > > (.................etc) > > self.rect.centerx = startx > > self.rect.centery = starty > > (...............etc) > > > > > > Now I know this email is getting hard to read ;) > > > > At this point I was thinking I'd have one createEnemies, called in the > > mainloop, which would take the level and, when it called Enemy to > > create the ships, use that level argument to determine which bmp to > > use for the ship itself. One createEnemies(), one Enemy(), there you > > go. > > > > But now it's giving me an error when createEnemies is called, for the > > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), > level) line, > > saying __init__() (and this would be Enemy's init, correct?) takes > > exactly 4 arguments (3 given): and Enemy's init, as you can see, > > takes (self, startx, starty, level). But the first argument is just > > 'self'! I don't have to pass that in.... I never *did*, anyway, in > > all my Enemy1, Enemy2, Enemy3 code...? > > > > I can send the full code for anybody who thinks that would be > > clearer to look at (ha ha) - I was going to attach it here but it > > would make the message too big for the list. I know that going > > through such a messy > > problem like this is a pain, and questions like this don't always get > > a lot of responses on the list. My code worked, it was just messy, > > and so I suppose I could just leave it alone. But I want to clean it > > up: I want to make it more Pythonic, more organized, more efficient, > > and would really love any advice anyone could offer. > > > > Heck, for all I know, I could just be needing to add a "self.___" > > somewhere, heaven knows that has tripped me up before! > > > > Would love to hear from you guys, and thanks again, > > Denise > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > From kent37 at tds.net Fri Jul 1 03:16:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Jun 2005 21:16:53 -0400 Subject: [Tutor] Need help new to Programming In-Reply-To: <200506292002.j5TK1xw5008247@mwr.mwr.is> References: <200506292002.j5TK1xw5008247@mwr.mwr.is> Message-ID: <42C49985.4050009@tds.net> Jimmy wrote: > My project right now is ?Write another program that reads 100 numbers > from the user and prints out the sum? Now I can get the program to do > these functions, but it won?t stop even using the break statement. Any > help or guidance would be great. Can you show us what you have done so far? Kent From adam.jtm30 at gmail.com Fri Jul 1 03:26:24 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Fri, 1 Jul 2005 02:26:24 +0100 Subject: [Tutor] A more Pythonic way to do this In-Reply-To: <8daabe560506301713350ab2c9@mail.gmail.com> References: <8daabe5605063015111d32477a@mail.gmail.com> <8daabe560506301713350ab2c9@mail.gmail.com> Message-ID: Good, good. I probably wouldn't have been able to help you if it was something so simple but that screws up your program and makes it hard to find out just what is going on. Anyway good look with anymore tidying on that you might be doing. Any chance of a copy? Adam On 7/1/05, D. Hartley wrote: > > ..... it was a paren. > > I was so worried that I just wasn't figuring it all out, that I had > tried to write elegant code and wasnt understanding the fundamentals, > and the only reason it didnt work was because I left out a paren. > > I actually laughed until I cried. > > Thanks for that. And yes, it works now ;) it's lovely. > > ~Denise > > On 6/30/05, Adam Bark wrote: > > Here's the problem --> > > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), > > level) > > > > 1,2 1 2 > > 1 0 > > you've put a braket after +30 which ends the Enemy call. The numbering > is +1 > > for opening braket -1 for closing so 0 is the end of the Enemy call if > you > > understand this. > > > > > > On 6/30/05, D. Hartley wrote: > > > > > > Hey guys! > > > > > > I have a 'quest,' and at first glance this email looks long, but the > > > problem is probably not as complex as the length implies. Please bear > > > with me, if I could get some advice on this particular problem, it > > > would go along way toward helping me be a better Python programmer. > > > > > > Some of you might remember, a few months ago, I was working on a space > > > invaders game for a birthday present. One of the functions I really > > > wanted to add to the game was to change the enemy "ships" at each new > > > level. Because of my deadline and my newness to Python, I did this in > > > an extremely ugly way. To give you an idea: > > > > > > the original main loop called: > > > enemyship_sprites = createEnemies(screen, enemy_speed) > > > > > > createEnemies looks like this: > > > > > > def createEnemies(screen, speed): > > > enemyship_sprites = EnemySprites(speed) > > > for rows in xrange(5): > > > for cols in xrange(8): > > > enemyship_sprites.add(Enemy((cols*60)+20, > > (rows*40)+30), level) > > > enemyship_sprites.draw(screen) > > > return enemyship_sprites > > > > > > It creates an instance of EnemySprites (my holder class) which > > > contains code for when the ships hit bottom, when to update them, etc. > > > It also calls "Enemy()", which looks like this: > > > > > > class Enemy(pygame.sprite.Sprite): > > > def __init__(self, startx, starty): > > > pygame.sprite.Sprite.__init__(self) > > > if level == 1: > > > self.image, self.rect = load_image('salad_ship.bmp', -1) > > > self.rect.centerx = startx > > > self.rect.centery = starty > > > def update(self, direction, go_down): > > > jump = 40 # how much the enemies move to the right/left on > > > each jump > > > if go_down: > > > # if a ship is moving down on this round, > > > # it doesn't move on the x-axys > > > self.rect.move_ip((0, 5)) > > > else: > > > # move a ship in the x-axys. > > > # if direction=1, it moves to the right; -1 to the left > > > self.rect.move_ip((jump * direction, 0)) > > > # maybe it's time for a shot? :) > > > # the chances are 1/30 > > > dice = random.randint (0,30) > > > global enemy_shot_sprites > > > if dice == 1: > > > shot = EnemyShot(self.rect.midtop) > > > enemy_shot_sprites.add(shot) > > > > > > > > > Now, get ready for one of the uglier things you've probably seen > lately > > (!!): > > > > > > Since I can only access the variable "level" from within the main > > > loop, for some reason I thought I couldnt use it in my class > > > definitions (which of course come before and are outside of the > > > mainloop). So within the main loop, I did: > > > > > > if level == 1: > > > enemyship_sprites = createEnemies1(screen, > > enemy_speed) > > > elif level == 2: > > > enemyship_sprites = createEnemies2(screen, > > enemy_speed) > > > elif level == 3: > > > enemyship_sprites = createEnemies3(screen, > > enemy_speed) > > > elif level == 4: > > > enemyship_sprites = createEnemies4(screen, > > enemy_speed) > > > elif level == 5: > > > enemyship_sprites = createEnemies5(screen, > > enemy_speed) > > > elif level == 6: > > > enemyship_sprites = createEnemies6(screen, > > enemy_speed) > > > elif level == 7: > > > enemyship_sprites = createEnemies7(screen, > > enemy_speed) > > > elif level == 8: > > > enemyship_sprites = createEnemies8(screen, > > enemy_speed) > > > else: > > > enemyship_sprites = createEnemies9(screen, > > enemy_speed) > > > > > > And yes, I created 9 different createEnemies, all pretty much carbon > > > copies of each other except that they called Enemy1, Enemy2, Enemy3, > > > etc. And then (you guessed it), I created 9 different Enemy > > > functions, too, so that each one could have its own (different) > > > bitmap. > > > > > > Now... this is just ridiculous. > > > > > > To my credit, I did actually know that at the time. But the day before > > > the birthday, I figured if I could make it work somehow, I would, and > > > I'd make it prettier later. Now just happens to be that later ;) > > > > > > So now that I've got a little more Python experience under my belt > > > (not much, but a little), it occurred to me that when I call > > > createEnemies in the mainloop, I could pass in an argument 'level'. > > > > > > mainloop now starting off with: > > > enemyship_sprites = createEnemies(screen, enemy_speed, level) > > > > > > level is one of my main loop variables, so it'll know what i'm talking > > > about and can take that variable and pass it in when it calls > > > createEnemies. (Btw, please forgive me if I mix up terms like argument > > > and variable or use them in the wrong places, I'm still getting used > > > to them!) In any case, then I changed my createEnemies to look like > > > this: > > > > > > def createEnemies(screen, speed, level): > > > enemyship_sprites = EnemySprites(speed) > > > for rows in xrange(5): > > > for cols in xrange(8): > > > enemyship_sprites.add(Enemy((cols*60)+20, > > (rows*40)+30), level) > > > enemyship_sprites.draw(screen) > > > return enemyship_sprites > > > > > > Since the part that changes each level actually matters when the Enemy > > > function gets called (because that's where the bmps are loaded), I > > > made Enemy need 'level': > > > > > > class Enemy(pygame.sprite.Sprite): > > > def __init__(self, startx, starty, level): > > > pygame.sprite.Sprite.__init__(self) > > > if level == 1: > > > self.image, self.rect = load_image('salad_ship.bmp', -1) > > > elif level == 2: > > > (.................etc) > > > self.rect.centerx = startx > > > self.rect.centery = starty > > > (...............etc) > > > > > > > > > Now I know this email is getting hard to read ;) > > > > > > At this point I was thinking I'd have one createEnemies, called in the > > > mainloop, which would take the level and, when it called Enemy to > > > create the ships, use that level argument to determine which bmp to > > > use for the ship itself. One createEnemies(), one Enemy(), there you > > > go. > > > > > > But now it's giving me an error when createEnemies is called, for the > > > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), > > level) line, > > > saying __init__() (and this would be Enemy's init, correct?) takes > > > exactly 4 arguments (3 given): and Enemy's init, as you can see, > > > takes (self, startx, starty, level). But the first argument is just > > > 'self'! I don't have to pass that in.... I never *did*, anyway, in > > > all my Enemy1, Enemy2, Enemy3 code...? > > > > > > I can send the full code for anybody who thinks that would be > > > clearer to look at (ha ha) - I was going to attach it here but it > > > would make the message too big for the list. I know that going > > > through such a messy > > > problem like this is a pain, and questions like this don't always get > > > a lot of responses on the list. My code worked, it was just messy, > > > and so I suppose I could just leave it alone. But I want to clean it > > > up: I want to make it more Pythonic, more organized, more efficient, > > > and would really love any advice anyone could offer. > > > > > > Heck, for all I know, I could just be needing to add a "self.___" > > > somewhere, heaven knows that has tripped me up before! > > > > > > Would love to hear from you guys, and thanks again, > > > Denise > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050701/03723b31/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Fri Jul 1 03:30:46 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 30 Jun 2005 18:30:46 -0700 (PDT) Subject: [Tutor] would pickle or cpickle help? In-Reply-To: Message-ID: > Could I use something like cpickle to store the dictionary once it is > made so I would not have to make it each time? I have never tried to > use pickle so I am bit fuzzy on what it can store and what it can't. > Also would it really buy me anything...it only takes a second or two to > make the dictionary? Hi John, For a dictionary of about ten-thousand elements, I'm not sure if it will buy you much. There's a complexity cost in adding a cache, in the sense that the cache and the real data might get out of sync if we're not careful. (As a concrete example, Python itself caches bytecode-compiled modules, and in there, there is quite a bit of complexity that can cause grief every so often due to unexpected things like file permission problems.) Building dictionaries from scratch might be fast enough, depending on the application. For example, given something like /usr/share/dict/words, ###### [dyoo at shoebox dyoo]$ ls -l /usr/share/dict/words -rw-r--r-- 2 root root 2486824 Jul 11 2004 /usr/share/dict/words [dyoo at shoebox dyoo]$ wc /usr/share/dict/words 234937 234937 2486824 /usr/share/dict/words ###### building the dictionary that holds all those words on a Pentium 4 2.8Ghz system takes about: ###### >>> timeit.Timer("import sets; " "s = sets.Set(open('/usr/share/dict/words'))" ).timeit(number=5) 1.6103701591491699 ###### and two seconds might not be too long if it's a one-time cost per program run. > There is a chance the file that I use to make the dictionary will > eventually grow to be 10,000 lines or more. I wouldn't optimize this portion of the code yet, until it's known that it'll really be a significant part of the runtime. I've seen lots of applications that have made things complex by using indices and caching, (like BLAST), and in industrial applications, it's worth it. But we can't discount that it does make things more complex. For simple applications, it's probably not worth it. Best of wishes! From alan.gauld at freenet.co.uk Fri Jul 1 09:08:28 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 1 Jul 2005 08:08:28 +0100 Subject: [Tutor] A more Pythonic way to do this References: <8daabe5605063015111d32477a@mail.gmail.com> Message-ID: <006001c57e0b$aee1a290$e8a08851@xp> > enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level) Check your parens... The closing one after 30 closes the constructor list. level is outside so you effectively have sprites.add(Enemy(X,Y), level) HTH, Alan G. From johan at accesstel.co.za Fri Jul 1 15:18:32 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Fri, 01 Jul 2005 15:18:32 +0200 Subject: [Tutor] compiling python files Message-ID: <1120223912.4664.60.camel@KMA.accesstel> Hi all, I have python .py files that I want to compile into .pyc files. Is there a easy way of doing this? Thanks, Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050701/3e0c73d6/attachment.htm From 3dbernard at gmail.com Fri Jul 1 15:36:51 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 1 Jul 2005 08:36:51 -0500 Subject: [Tutor] compiling python files In-Reply-To: <1120223912.4664.60.camel@KMA.accesstel> References: <1120223912.4664.60.camel@KMA.accesstel> Message-ID: <61d0e2b405070106361750c3b9@mail.gmail.com> That would be the compileall utility: http://www.python.org/doc/2.4.1/lib/module-compileall.html Cheers Bernard On 7/1/05, Johan Geldenhuys wrote: > Hi all, > I have python .py files that I want to compile into .pyc files. > Is there a easy way of doing this? > > Thanks, > > Johan > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From keridee at jayco.net Fri Jul 1 19:00:14 2005 From: keridee at jayco.net (Jacob S.) Date: Fri, 1 Jul 2005 12:00:14 -0500 Subject: [Tutor] A more Pythonic way to do this References: <8daabe5605063015111d32477a@mail.gmail.com><8daabe560506301713350ab2c9@mail.gmail.com> Message-ID: <002b01c57e5e$609fd400$8f5328cf@JSLAPTOP> >Good, good. I probably wouldn't have been able to help you if it was something so simple but that >screws up your program and makes it hard to find out just what is going on. Anyway good look with >anymore tidying on that you might be doing. Any chance of a copy? > >Adam Denise, Can I have a copy, too? Jacob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050701/ef24c707/attachment.htm From keridee at jayco.net Fri Jul 1 19:09:03 2005 From: keridee at jayco.net (Jacob S.) Date: Fri, 1 Jul 2005 12:09:03 -0500 Subject: [Tutor] Alternative File I/O for Tuples (fwd) References: <42BF10C8.4070003@tds.net><20050628010920.62cf8f6d@luke.matheteuo.rel><42C11D7E.8010605@tds.net><20050628122638.146f772c@luke.matheteuo.rel><42C27A2C.4050801@tds.net><20050629122441.4cfc92f1@luke.matheteuo.rel><42C2CE59.3040703@tds.net><20050629133103.5116a3b7@luke.matheteuo.rel><42C2E3E5.3070200@tds.net> <20050630012327.31d47cda@luke.matheteuo.rel> Message-ID: <011d01c57e5f$9a7d4120$8f5328cf@JSLAPTOP> ----- Original Message ----- From: "Don Parris" To: Sent: Thursday, June 30, 2005 12:23 AM Subject: Re: [Tutor] Alternative File I/O for Tuples (fwd) > On Wed, 29 Jun 2005 14:09:41 -0400 > Kent Johnson wrote: > >> Don Parris wrote: >> > ### playing with wrapfunc (all other args are the same) ### >> > wrapfunc=lambda x:wrap_onspace(str(rows), x)) >> > >> > also >> > wrapfunc=lambda x:str(wrap_onspace(rows, x))) >> >> This is way off base. wrap_onspace takes two arguments - the string to >> wrap, and the width to wrap to. You are passing it two arguments - the >> tuple of tuples to print, and the string to wrap. >> >> > > > Success!!! > > mbrPhone = open('mbrPhone.txt', 'w') > mbrPhone.write(indent(Results, hasHeader=False, separateRows=False, > prefix='', postfix='', justify='left', wrapfunc=lambda x:str(x))) > mbrPhone.close() Just a point. You don't need the extra lambda at wrapfunc. Writing it as... mbrPhone.write(indent(Results, hasHeader=False, separateRows=False, prefix='', postfix='',justify='left',wrapfunc=str)) will work fine. A lambda definition is simple, and you already grasp most of the concept, but the above shows a little needed tweaking. def a(b,c=d): return somefunc(e) is equivalent to a = lambda b,c=d: somefunc(e) However, def wrapfunc(x): return str(x) can be shortened to wrapfunc = lambda x:str(x) which can be shortened even further to wrapfunc = str I guess the moral of the story is--why bother making wrapfunc a function when you can set it equal to a function -- str -- and it's still the same? Okay, I'm done. Jacob From panard at inzenet.org Fri Jul 1 19:39:44 2005 From: panard at inzenet.org (Panard) Date: Fri, 1 Jul 2005 19:39:44 +0200 Subject: [Tutor] xml, external entity and non-ascii paths Message-ID: <200507011939.53604.panard@inzenet.org> Hi, Here is my problem : My local encoding is iso-8859-15, I use utf8 encoded xml files, which use dtd, which use a common dtd : == sample.xml == == sample.dtd %COMMON_DTD; == == common.dtd == I put them in a non-ascii directory : /home/panard/tests/y?y?/ for exemple. And now, I want to parse sample.xml using its absolute path name : == test1.py import codecs import locale import os import xml.sax import xml.sax.handler def locale_from_unicode( s ) : return codecs.getencoder( locale.getpreferredencoding() )( s, 'replace' )[ 0 ] class EntityResolver : def resolveEntity( self, publicId, systemId ) : return locale_from_unicode( systemId ) parser = xml.sax.make_parser() er = EntityResolver() parser.setEntityResolver( er ) parser.parse( os.path.join( os.getcwd(), "sample.xml" ) ) == which results to : Traceback (most recent call last): File "test1.py", line 18, in ? parser.parse( os.path.join( os.getcwd(), "sample.xml" ) ) File "/usr/lib/python2.4/xml/sax/expatreader.py", line 107, in parse xmlreader.IncrementalParser.parse(self, source) File "/usr/lib/python2.4/xml/sax/xmlreader.py", line 123, in parse self.feed(buffer) File "/usr/lib/python2.4/xml/sax/expatreader.py", line 211, in feed self._err_handler.fatalError(exc) File "/usr/lib/python2.4/xml/sax/handler.py", line 38, in fatalError raise exception xml.sax._exceptions.SAXParseException: /home/panard/tests/y?y?/sample.dtd:2:0: error in processing external entity reference I've tried to change the ExternalEntityRefHandler to know where the problem really appends : == test.py import codecs import locale import os import traceback import xml.sax from xml.sax import saxutils, xmlreader import xml.sax.handler def locale_from_unicode( s ) : return codecs.getencoder( locale.getpreferredencoding() )( s, 'replace' )[ 0 ] class EntityResolver : def resolveEntity( self, publicId, systemId ) : return locale_from_unicode( systemId ) # from /usr/lib/python2.4/xml/sax/expatreader.py line 373 def external_entity_ref( context, base, sysid, pubid): print [ sysid ] ## modified self = parser ## modified if not self._external_ges: return 1 source = self._ent_handler.resolveEntity(pubid, sysid) source = saxutils.prepare_input_source(source, self._source.getSystemId() or "") self._entity_stack.append((self._parser, self._source)) self._parser = self._parser.ExternalEntityParserCreate(context) self._source = source try: xmlreader.IncrementalParser.parse(self, source) except: traceback.print_exc() ## modified return 0 # FIXME: save error info here? (self._parser, self._source) = self._entity_stack[-1] del self._entity_stack[-1] return 1 parser = xml.sax.make_parser() er = EntityResolver() parser.setEntityResolver( er ) parser.external_entity_ref = external_entity_ref parser.parse( os.path.join( os.getcwd(), "sample.xml" ) ) == the backtrace is now : panard at sylvebarbe ~/tests/y?y? $ python test.py [u'sample.dtd'] Traceback (most recent call last): File "test.py", line 35, in external_entity_ref xmlreader.IncrementalParser.parse(self, source) File "/usr/lib/python2.4/xml/sax/xmlreader.py", line 123, in parse self.feed(buffer) File "/usr/lib/python2.4/xml/sax/expatreader.py", line 207, in feed self._parser.Parse(data, isFinal) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 20-22: invalid data ... and the preceding backtrace ... So my question is : is there a nice way to resolve my problem ? For now, I've disabled external_entity_ref feature :( Thanks, Panard -- HomePage : http://dev.inzenet.org/~panard Qomics : http://qomics.inzenet.org YZis editor - http://www.yzis.org Smileys: http://smileys.inzenet.org -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050701/dcbcf6a8/attachment.pgp From denise.hartley at gmail.com Fri Jul 1 19:58:54 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 1 Jul 2005 10:58:54 -0700 Subject: [Tutor] A more Pythonic way to do this In-Reply-To: <002b01c57e5e$609fd400$8f5328cf@JSLAPTOP> References: <8daabe5605063015111d32477a@mail.gmail.com> <8daabe560506301713350ab2c9@mail.gmail.com> <002b01c57e5e$609fd400$8f5328cf@JSLAPTOP> Message-ID: <8daabe560507011058b30809b@mail.gmail.com> Just catching up on a few replies: Alan - yes, Adam pointed out my silly error, and it solved what I thought was a much bigger problem. Very funny how these things go sometimes. And to anyone who's interested: If you'd like a copy, just shoot me an email and I can zip it up and send it to you. I was trying to get it on the web so that I could just give out a url, but my friend that was going to host it is having some technical difficulties. Jacob and Adam, I'll send yours out today. Also, I'm working on version "2.0" - more enemies, special shots, more silly arcade features (requested by my friends who played the game). So if you want an update later, just let me know ;) Thanks for all the support and encouragement, guys - it's just a silly little arcade game, but I still feel an enormous sense of accomplishment for having come this far, and couldnt have done it without you! You'll notice there's a nod to the python tutor mailing list in my opening comments for that very reason, ha ha! ~Denise On 7/1/05, Jacob S. wrote: > >Good, good. I probably wouldn't have been able to help you if it was > something so simple but that >screws up your program and makes it hard to > find out just what is going on. Anyway good look with >anymore tidying on > that you might be doing. Any chance of a copy? > > > >Adam > > Denise, Can I have a copy, too? > > Jacob > > From denise.hartley at gmail.com Sat Jul 2 00:58:29 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 1 Jul 2005 15:58:29 -0700 Subject: [Tutor] I sure do love cookies. Message-ID: <8daabe56050701155814df1832@mail.gmail.com> Anyone have a good (*simple*) tutorial on making/sending cookies via python? (i.e., not receiving/messing with them). Thanks :) ~Denise From bvande at po-box.mcgill.ca Sat Jul 2 01:43:56 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 01 Jul 2005 19:43:56 -0400 Subject: [Tutor] OT self-implementation? Message-ID: <42C5D53C.9070007@po-box.mcgill.ca> Hi all, a bit off topic for Python Tutor, but I am think there are decent odds that folks here both know good resources and have an idea of what level would be appropriate for me. So, I hope no one minds. A recent thread on comp.lang.python has touched on to what extent C was written in C. I know PyPy aims to implement Python in Python. I believe I've heard that many lisp fans think you don't have a language unless you can write the language's interpreter in the language itself. (Perhaps one or more of these claims is a bit inaccurate, but the substance seems right.) This sounds, to the untutored, rather like magic. (It reminds me of a line from the German mathematician and philosopher, Gottlob Frege, who, in a book on the foundations of arithmetic, characterized an opposing position as akin to "trying to pull yourself out of the swamp by your own top-knot" -- which, I can only assume, is even funnier in the original 19th c. German ;-) Naively, one thinks that to write anything in C, you'd have to *have* C to write in, etc. Now's not the time in my life to start a comp. sci. degree. So, my questions are: 1) What would be good terms to google for to find an explanation of how the seeming magic doesn't violate all reason? 2) Much harder, so please pass unless you've a link you know of off-hand: any recommendations of particular things that I could read? Thanks and best, Brian vdB From shaleh at speakeasy.net Sat Jul 2 03:10:05 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri, 01 Jul 2005 18:10:05 -0700 Subject: [Tutor] OT self-implementation? In-Reply-To: <42C5D53C.9070007@po-box.mcgill.ca> References: <42C5D53C.9070007@po-box.mcgill.ca> Message-ID: <42C5E96D.4050103@speakeasy.net> Brian van den Broek wrote: > Now's not the time in my life to start a comp. sci. degree. So, my > questions are: > > 1) What would be good terms to google for to find an explanation of > how the seeming magic doesn't violate all reason? > > 2) Much harder, so please pass unless you've a link you know of > off-hand: any recommendations of particular things that I could read? > try a book on compiler design. If you have programmed for any length of time, the ideas will be easy enough to follow even if you do not follow the data structures and algorithms side. As for the lisp people, they insist everyone has been reimplementing lisp - badly. That is the advantage of being one of the first languages. To directly answer them, the lisp language was originally a mathematics theory. It was not meant to be run, you were supposed to apply logic to the thing. Then someone noticed that if you ran (eval myprog) suddenly your script could execute itself and the interpreter was born. How do you build tools without tools? That is the basis of your question. Ponder that. If you wanted to start your own blacksmith shop a thousand years or so ago, how would you do it? How do you make a framing square actually be square without using another square? From kent37 at tds.net Sat Jul 2 03:16:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Jul 2005 21:16:25 -0400 Subject: [Tutor] I sure do love cookies. Message-ID: <200507020116.j621GPuT021806@outbound1.mail.tds.net> D. Hartley wrote: > Anyone have a good (*simple*) tutorial on making/sending cookies via > python? (i.e., not receiving/messing with them). The problem is, what you have to do is not a usual use of cookies. From the client side you usually just get the cookies from the host and echo them back in a new request. What I did was, - create a new cookielib.Cookie - add the cookie to the CookieJar - make a request the same way as when I was collecting cookies To create the new Cookie it might help to look at the source for cookielib (Lib\cookielib.py), the Cookie constructor doesn't seem to be documented anywhere. To figure out the values for the Cookie constructor it might help to look at one of the cookies you already have. Kent From maxnoel_fr at yahoo.fr Sat Jul 2 03:40:18 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 2 Jul 2005 03:40:18 +0200 Subject: [Tutor] OT self-implementation? In-Reply-To: <42C5D53C.9070007@po-box.mcgill.ca> References: <42C5D53C.9070007@po-box.mcgill.ca> Message-ID: <337B2FC3-8D86-4F88-9BE1-249C577D5C91@yahoo.fr> On Jul 2, 2005, at 01:43, Brian van den Broek wrote: > This sounds, to the untutored, rather like magic. (It reminds me of a > line from the German mathematician and philosopher, Gottlob Frege, > who, in a book on the foundations of arithmetic, characterized an > opposing position as akin to "trying to pull yourself out of the swamp > by your own top-knot" -- which, I can only assume, is even funnier in > the original 19th c. German ;-) Naively, one thinks that to write > anything in C, you'd have to *have* C to write in, etc. Actually, there's not much to it that's magic. The idea is that before being able to self-implement a language, you implement it in another language first (usually, but not always, ASM). Before C was written in C, it was written in assembly language. To get a C compiler that's itself written in C, here's what you do: 1. Obtain a C compiler. Any C compiler, let's call it "fooCC". It doesn't matter as long as it compiles correctly. 2. Your C compiler will be called "barCC". Write its source code in C. Not hard to do as C code is just ASCII text. 3. Compile barCC's source code with fooCC. The resulting compiler (let's call it "bazCC") is not barCC yet. It produces the same output as barCC, but the process is not complete as it was itself produced using a compiler that wasn't written in C. 4. Compile barCC's source code with bazCC. Since bazCC and barCC produce the same output, what you get is equivalent to barCC compiled with barCC itself: it *is* barCC. You have your compiler. 5. (optional) Make sure the previous statement is true: recompile barCC with barCC, and assert that the output is identical to the compiler produced in 4. The whole process is called "bootstrappping" (from the Adventures of Baron Munchausen, as you mentioned), and exists for all compiled languages (including assembly). In fact, every language except microcode was at some point either bootstrapped or cross- compiled. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___________________________________________________________________________ Appel audio GRATUIT partout dans le monde avec le nouveau Yahoo! Messenger Téléchargez cette version sur http://fr.messenger.yahoo.com From arcege at gmail.com Sat Jul 2 04:18:24 2005 From: arcege at gmail.com (Michael P. Reilly) Date: Fri, 1 Jul 2005 22:18:24 -0400 Subject: [Tutor] OT self-implementation? In-Reply-To: <42C5D53C.9070007@po-box.mcgill.ca> References: <42C5D53C.9070007@po-box.mcgill.ca> Message-ID: <7e5ba9220507011918180ca1be@mail.gmail.com> On 7/1/05, Brian van den Broek wrote: > > Hi all, > > a bit off topic for Python Tutor, but I am think there are decent odds > that folks here both know good resources and have an idea of what > level would be appropriate for me. So, I hope no one minds. > > A recent thread on comp.lang.python has touched on to what extent C > was written in C. I know PyPy aims to implement Python in Python. I > believe I've heard that many lisp fans think you don't have a language > unless you can write the language's interpreter in the language > itself. (Perhaps one or more of these claims is a bit inaccurate, but > the substance seems right.) > > This sounds, to the untutored, rather like magic. (It reminds me of a > line from the German mathematician and philosopher, Gottlob Frege, > who, in a book on the foundations of arithmetic, characterized an > opposing position as akin to "trying to pull yourself out of the swamp > by your own top-knot" -- which, I can only assume, is even funnier in > the original 19th c. German ;-) Naively, one thinks that to write > anything in C, you'd have to *have* C to write in, etc. > > Now's not the time in my life to start a comp. sci. degree. So, my > questions are: > > 1) What would be good terms to google for to find an explanation of > how the seeming magic doesn't violate all reason? > > 2) Much harder, so please pass unless you've a link you know of > off-hand: any recommendations of particular things that I could read? > If you are interested in a more abstract explanation on this, you can read up on one reason why lisp programmers are such fans of writting lisp interpreters in lisp: Turing Machines (TM). Abstract computer constructs that, arguably, are equivalent to your desktop computer in terms of programming. They are really for theoretical research, especially good for algorithm creation. But one of the early algorithms was to create a TM with a TM. http://en.wikipedia.org/wiki/Turing_machine http://plato.stanford.edu/entries/turing-machine/ You'll be able to find a lot more hits on any web search. -Arcege -- There's so many different worlds, So many different suns. And we have just one world, But we live in different ones. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050701/80765350/attachment.htm From bowman at mazirian.com Sat Jul 2 05:20:37 2005 From: bowman at mazirian.com (Bradford R. Bowman) Date: Fri, 01 Jul 2005 23:20:37 -0400 Subject: [Tutor] Avoiding clear text passwords; advice for learning projects. Message-ID: <1120274437.19171.27.camel@phandaal> I'm new to the list, new to python, and new to programming, so I'll try not to waste too much of everyone's time here. I just wrote a little script to detect changes in my dynamic IP address and, in case of a change, update the DNS records maintained my registrar, enom. The update process requires that I send a regular http GET request containing my domain name and a password to enom's name server. Ideally, the script should be automated and quiet unless it detects a problem. The program works rather well, but I have written the required password in clear text right in the code. I am leery of storing passwords in clear text. Does anyone have any advice for hiding the passwords, but keeping them accessible to the script when it is invoked automatically (as a cron job)? I suspect I am overlooking something obvious here. Also, in addition to the above program, I wrote something that converts a certain format of playlist file to another such format. That was fun, but I am running out of useful ideas for further projects that are within my grasp. Any suggestions for some other simple projects that would facilitate developing a good base of python skills? -- Bradford R. Bowman From bvande at po-box.mcgill.ca Sat Jul 2 06:11:00 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 02 Jul 2005 00:11:00 -0400 Subject: [Tutor] OT self-implementation? In-Reply-To: <7e5ba9220507011918180ca1be@mail.gmail.com> References: <42C5D53C.9070007@po-box.mcgill.ca> <7e5ba9220507011918180ca1be@mail.gmail.com> Message-ID: <42C613D4.4010908@po-box.mcgill.ca> Michael P. Reilly said unto the world upon 01/07/2005 22:18: > On 7/1/05, Brian van den Broek wrote: >>A recent thread on comp.lang.python has touched on to what extent C >>was written in C. I know PyPy aims to implement Python in Python. I >>believe I've heard that many lisp fans think you don't have a language >>unless you can write the language's interpreter in the language >>itself. (Perhaps one or more of these claims is a bit inaccurate, but >>the substance seems right.) >> >>This sounds, to the untutored, rather like magic. >>Naively, one thinks that to write >>anything in C, you'd have to *have* C to write in, etc. > If you are interested in a more abstract explanation on this, you can read > up on one reason why lisp programmers are such fans of writting lisp > interpreters in lisp: Turing Machines (TM). Abstract computer constructs > that, arguably, are equivalent to your desktop computer in terms of > programming. They are really for theoretical research, especially good for > algorithm creation. But one of the early algorithms was to create a TM with > a TM. > > http://en.wikipedia.org/wiki/Turing_machine > http://plato.stanford.edu/entries/turing-machine/ Thanks to Max, Michael, and Sean for the replies. Max's stepwise explanation, which I will distort in summary by simplifying to "Write a complier in a lower level language and use that to compile your C compiler written in C" was very helpful. Seeing it on screen makes me wonder how I didn't work it out for myself, but there you go :-) Max's and Sean's pointing toward compiler design gives me something to start looking for. Having a search term is key to good googling! Once we get down to Turing Machines and away from real-world messiness, I'm much more happy. I have often found that there is, for me, quite a gap between the abstract mathematical foundations of recursion theory, formal logic, etc. that I have a good handle on, and the real world use and applications of the theory. A prime motive for tackling Python was to try to close that gap. A fun point about Turing machines: The Church-Turing Thesis (roughly, the claim that any intuitively computable function is computable by a Turing machine has, as far as I know, the distinction of being the first mathematically significant claim widely accepted yet know to be insusceptible of proof. (Goedel had earlier shown that any formalism based on a language adequate for arithmetic could formulate propositions not decidable by the formalism, but it wasn't until much later that any natural examples of independent mathematical interest arose. Early on in my graduate career, I spent an excited few days thinking I'd found a refutation of the Thesis employing something similar to the Godel construction. What a let down when I found the fallacy :-( ) The Thesis has, however, much empirical confirmation in that every well defined abstract notion of computability put forth has been proven to be co-extensive with Turing Machine computability. The entry of empirical methods into mathematical argument in this way has made many mathematicians and philosophers of math quite uncomfortable. And, that's more than enough ramble :-) Thanks again. Brian vdB From webdev at matheteuo.org Sat Jul 2 08:39:18 2005 From: webdev at matheteuo.org (Don Parris) Date: Sat, 2 Jul 2005 02:39:18 -0400 Subject: [Tutor] Alternative File I/O for Tuples (fwd) In-Reply-To: <011d01c57e5f$9a7d4120$8f5328cf@JSLAPTOP> References: <42BF10C8.4070003@tds.net> <20050628010920.62cf8f6d@luke.matheteuo.rel> <42C11D7E.8010605@tds.net> <20050628122638.146f772c@luke.matheteuo.rel> <42C27A2C.4050801@tds.net> <20050629122441.4cfc92f1@luke.matheteuo.rel> <42C2CE59.3040703@tds.net> <20050629133103.5116a3b7@luke.matheteuo.rel> <42C2E3E5.3070200@tds.net> <20050630012327.31d47cda@luke.matheteuo.rel> <011d01c57e5f$9a7d4120$8f5328cf@JSLAPTOP> Message-ID: <20050702023918.5212b681@luke.matheteuo.rel> On Fri, 1 Jul 2005 12:09:03 -0500 "Jacob S." wrote: > > ----- Original Message ----- > From: "Don Parris" > To: > Sent: Thursday, June 30, 2005 12:23 AM > Subject: Re: [Tutor] Alternative File I/O for Tuples (fwd) > > > > On Wed, 29 Jun 2005 14:09:41 -0400 > > Kent Johnson wrote: > > > >> Don Parris wrote: > >> > ### playing with wrapfunc (all other args are the same) ### > >> > wrapfunc=lambda x:wrap_onspace(str(rows), x)) > >> > > >> > also > >> > wrapfunc=lambda x:str(wrap_onspace(rows, x))) > >> > >> This is way off base. wrap_onspace takes two arguments - the string to > >> wrap, and the width to wrap to. You are passing it two arguments - the > >> tuple of tuples to print, and the string to wrap. > >> > >> > > > > > Success!!! > > > > mbrPhone = open('mbrPhone.txt', 'w') > > mbrPhone.write(indent(Results, hasHeader=False, separateRows=False, > > prefix='', postfix='', justify='left', wrapfunc=lambda x:str(x))) > > mbrPhone.close() > > Just a point. > > You don't need the extra lambda at wrapfunc. > > Writing it as... > > mbrPhone.write(indent(Results, hasHeader=False, separateRows=False, > prefix='', postfix='',justify='left',wrapfunc=str)) > > will work fine. > > A lambda definition is simple, and you already grasp most of the concept, > but the above shows a little needed tweaking. > I haven't lambdas very closely yet, but I understand them to be something of a mini-function (single statement) with no name. Here, I was simply sticking to what I saw in the example. > def a(b,c=d): > return somefunc(e) > > is equivalent to > > a = lambda b,c=d: somefunc(e) > > However, > > def wrapfunc(x): > return str(x) > > can be shortened to > > wrapfunc = lambda x:str(x) > > which can be shortened even further to > > wrapfunc = str > > I guess the moral of the story is--why bother making wrapfunc a function > when you can set it equal to a function -- str -- and it's still the > same? > Thanks for showing me that - the program still works fine. When you say the statement needs tweaking, is this just a matter of style, or does it affect run-time speed? I'm not timing the program, but didn't happen to notice any difference. Here's screenshots of the old and the new output (if you're interested): http://matheteuo.org/chaddb/screenshots.html The old one is using XFce's terminal, the new is Konsole (easier copy/paste ops). But it's a huge improvement! Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From kent37 at tds.net Sat Jul 2 03:25:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 1 Jul 2005 21:25:51 -0400 Subject: [Tutor] OT self-implementation? Message-ID: <200507020125.j621PpXv007629@outbound4.mail.tds.net> It is called bootstrapping. Some hints on this page: http://en.wikipedia.org/wiki/Bootstrap Kent From alan.gauld at freenet.co.uk Sat Jul 2 09:53:06 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 2 Jul 2005 08:53:06 +0100 Subject: [Tutor] OT self-implementation? References: <42C5D53C.9070007@po-box.mcgill.ca> Message-ID: <004401c57edb$15350120$a6bc8851@xp> > the original 19th c. German ;-) Naively, one thinks that to write > anything in C, you'd have to *have* C to write in, etc. You are correct. Or at least you need the subset of C needed for a minimal compiler. So you figure out your minimal comiler in C. Then you write a basic assembler program to compile that one program. This is much easier than writing a general purpose C compiler, it only needs to deal with a single program - the compiler. Then once your compiler has been compiled, you use it to recompile itself(*). >From there in you can extend the original program and recompile it. Provided each new feature that you sadd doesn't use any new features then it will be compile by the previous version. ONce you've built the new feature you can use it to add the next new feature, and so on... > Now's not the time in my life to start a comp. sci. degree. So, my > questions are: > > 1) What would be good terms to google for to find an explanation of > how the seeming magic doesn't violate all reason? Compiler, Computer Language, Programming, History of C, etc... > 2) Much harder, so please pass unless you've a link you know of > off-hand: any recommendations of particular things that I could read? There are lots of CS books on language design and most will cover this process in detail, usually including staged excercises so you wind up building your own compiler for your own language! A more general CS intro will usually have a chapter on language design and comiler construction. You might find books on Lex and Yacc (Or GNUs Flex and Bison) useful too. (*)One of the hardest malicious bugs I've seen was by a disgruntled employee who deliberately inserted a bug into the C source of the companies compiler. He then recompiled the compiler (using the working compiler) to produce a faulty compiler. He then removed his bugs in the source code so it was back to the correct version. He then recompiled the good source with the faulty compiler to produce a new faulty compiler. He then left the company... It took a long time to figure out what was wrong and why... HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tegmine at gmail.com Sat Jul 2 13:45:53 2005 From: tegmine at gmail.com (Luis N) Date: Sat, 2 Jul 2005 04:45:53 -0700 Subject: [Tutor] slicing nested lists/dicts/tuples In-Reply-To: <42C1AF8D.6070701@po-box.mcgill.ca> References: <77bfa81a05062812253d94b102@mail.gmail.com> <42C1AF8D.6070701@po-box.mcgill.ca> Message-ID: <77bfa81a0507020445c49864e@mail.gmail.com> Hi, Yes, sorry I haven't posted to the list in a while. I should have been more specific. I'm writing a simple contact database, using metakit as the backend. Thank you for pointing out that what I was trying to do was easier than I believed. Here's some code. db = metakit.storage('c:/addy.mk',1) vw = db.getas('contacts[first:S,last:S,phone:S,email:S,notes:S]') desc = ('first', 'last', 'phone', 'email', 'notes') def listItems(): l= [] d = {} for r in range(len(vw)): d = {'first':vw[r].first, 'last':vw[r].last, 'phone':vw[r].phone, 'email':vw[r].email, 'notes':vw[r].notes} l.append(d) return l At the moment I would like to generate the listItems dynamically, from the desc variable, so new databases can be added without changing the code. I thought that if: def listItems(): l= [] d = {} lt = len(desc) for r in range(len(vw)): for x in range(len(lt)): d[desc[x]] = exec("""'vw'+[r]+'.'+desc[x]""") l.append(d) return l Whereby the vw metakit object behaves like a dictionary, and the exec statement isn't usable in the way I would wish for. Luis N. On 6/28/05, Brian van den Broek wrote: > > Luis N said unto the world upon 28/06/2005 15:25: > > Hi, > > > > > >>>>l > > > > [{'last': 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}, > {'last': > > 'Bar', 'first': 'Foo'}, {'last': 'Bar', 'first': 'Foo'}] > > > > > > This is how I imagine it: > > > > for i in l: > > for j in l[i]: > > for k in l[i][j]: > > print k.get('first') > > print k.get('last') > > > > Is there a short and sweet way of doing this (that actually works). > > > > Luis. > > Hi Luis, > > I'm not certain I see what you are wanting from your description. > (You've got more nesting in your loops than in l.) But does this do > what is wanted? > > >>> a_list = [ {'last': 'Bar', 'first': 'Foo'}, > {'last': 'Bar', 'first': 'Foo'}, > {'last': 'Bar', 'first': 'Foo'}, > {'last': 'Bar', 'first': 'Foo'} ] > >>> for a_dict in a_list: > print a_dict['first'] > print a_dict['last'] > > > Foo > Bar > Foo > Bar > Foo > Bar > Foo > Bar > >>> > > > If it does, why are you doing this? Is it to figure out how to > manipulate data structures with Python? If so, good. If you are trying > to do real work this way, there is surely a better way. Maybe if you > said what you are trying to accomplish, someone could help you find a > good way to do it. > > Best, > > Brian vdB > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050702/f2cc0b0d/attachment.htm From tegmine at gmail.com Sat Jul 2 13:51:06 2005 From: tegmine at gmail.com (Luis N) Date: Sat, 2 Jul 2005 04:51:06 -0700 Subject: [Tutor] slicing nested lists/dicts/tuples In-Reply-To: <77bfa81a0507020445c49864e@mail.gmail.com> References: <77bfa81a05062812253d94b102@mail.gmail.com> <42C1AF8D.6070701@po-box.mcgill.ca> <77bfa81a0507020445c49864e@mail.gmail.com> Message-ID: <77bfa81a050702045134b075e6@mail.gmail.com> On 7/2/05, Luis N wrote: Umm, sorry, I meant: d[desc[x]] = exec("""'vw[%s].desc[%s]'""" % (r,x )) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050702/1650220b/attachment.htm From billburns at pennswoods.net Sat Jul 2 14:17:03 2005 From: billburns at pennswoods.net (Bill Burns) Date: Sat, 2 Jul 2005 08:17:03 -0400 Subject: [Tutor] OT self-implementation? In-Reply-To: <42C5D53C.9070007@po-box.mcgill.ca> References: <42C5D53C.9070007@po-box.mcgill.ca> Message-ID: <200507020817.03616.billburns@pennswoods.net> Brian, If you've never read this before, you may find it interesting: http://cm.bell-labs.com/who/ken/trust.html Bill From falcon3166 at hotmail.com Sat Jul 2 19:56:56 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 2 Jul 2005 11:56:56 -0600 Subject: [Tutor] How do I make Python calculate square roots? Message-ID: Hi all, Does anyone know how to make Python calculate square roots? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050702/9d41d54d/attachment.htm From reed at intersiege.com Sat Jul 2 20:04:56 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Sat, 02 Jul 2005 14:04:56 -0400 Subject: [Tutor] How do I make Python calculate square roots? In-Reply-To: References: Message-ID: <42C6D748.1000200@intersiege.com> Nathan Pinno wrote: > Hi all, > > Does anyone know how to make Python calculate square roots? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > Raise to the 1/2 power. >>> 4**.5 2.0 >>> 16**.5 4.0 >>> 81**.5 9.0 ~r From tegmine at gmail.com Sat Jul 2 21:04:29 2005 From: tegmine at gmail.com (Luis N) Date: Sat, 2 Jul 2005 12:04:29 -0700 Subject: [Tutor] Iterating over nested lists part2 Message-ID: <77bfa81a0507021204f9246ea@mail.gmail.com> Okay, This works great now: def listItems(): l= [] d = {} for r in range(len(vw)): for x in range(lt): ed = desc[x] exec("d['%s']=vw[%d].%s" % (ed,r,ed)) l.append(d) print l But, it multiplies all of the records from vw by 5. How can I have: for each record in the database: for each column in the record: do stuff. Without multiplying the result i.e len(vw) * lt Thanks. Luis N. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050702/d0c84c84/attachment.htm From bvande at po-box.mcgill.ca Sat Jul 2 21:28:53 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 02 Jul 2005 15:28:53 -0400 Subject: [Tutor] OT self-implementation? In-Reply-To: <004401c57edb$15350120$a6bc8851@xp> References: <42C5D53C.9070007@po-box.mcgill.ca> <004401c57edb$15350120$a6bc8851@xp> Message-ID: <42C6EAF5.6030302@po-box.mcgill.ca> Alan G said unto the world upon 02/07/2005 03:53: >>the original 19th c. German ;-) Naively, one thinks that to write >>anything in C, you'd have to *have* C to write in, etc. > > > You are correct. Or at least you need the subset of C needed for a > minimal compiler. > > So you figure out your minimal comiler in C. > Then you write a basic assembler program to compile that one program. > This is much easier than writing a general purpose C compiler, it > only needs to deal with a single program - the compiler. > (*)One of the hardest malicious bugs I've seen was by a > disgruntled employee who deliberately inserted a bug into the C > source of the companies compiler. He then recompiled the compiler > (using the working compiler) to produce a faulty compiler. He then > removed his bugs in the source code so it was back to the correct > version. He then recompiled the good source with the faulty > compiler to produce a new faulty compiler. He then left the > company... > > It took a long time to figure out what was wrong and why... > > HTH, > > Alan G Hi all, good lord, but if that fellow could only have harnessed that ingeniousness for the forces of good! Thanks to Alan for the additional explanation and head-hurting tale of malice, and to both Kent and Bill for additional references. Best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Jul 2 22:36:15 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 02 Jul 2005 16:36:15 -0400 Subject: [Tutor] code for expressing rationals in arbitrarty bases Message-ID: <42C6FABF.2010600@po-box.mcgill.ca> Hi all, In a private exchange about floating point representation error spun off of c.l.p., I'd sent someone some code to express rationals (subject to some constraints) in arbitrary bases, 1 < base < 37. The aim was to illustrate my claim that whether a rational had a repeating expansion[*] or not was a function of base of representation. Well, he went and posted it back to c.l.p. :-( So, it is out there, even though it isn't so good that I'd have chosen to put it in a public space (other than Tutor). It is also long, as it includes some tests and sanity checks on the input. *If* anyone has the time and interest, I'd appreciate comments: . If not, no worries. :-) To my embarrassment, I see that I'd commented out, but not removed, debug print statements. etc. [*] Does anyone know a term for a non-fractional representation of a rational in arbitrary base? For particular bases, decimal expansion, binary expansion, etc. But is there a term for the general case, other than base-n expansion? Best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Jul 2 23:53:04 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 02 Jul 2005 17:53:04 -0400 Subject: [Tutor] slicing nested lists/dicts/tuples In-Reply-To: <77bfa81a050702045134b075e6@mail.gmail.com> References: <77bfa81a05062812253d94b102@mail.gmail.com> <42C1AF8D.6070701@po-box.mcgill.ca> <77bfa81a0507020445c49864e@mail.gmail.com> <77bfa81a050702045134b075e6@mail.gmail.com> Message-ID: <42C70CC0.8050401@po-box.mcgill.ca> Luis N said unto the world upon 02/07/2005 07:51: > On 7/2/05, Luis N wrote: > > Umm, sorry, I meant: > > d[desc[x]] = exec("""'vw[%s].desc[%s]'""" % (r,x )) > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Hi Luis, I don't know anything about metakit, and thus I don't know anything about the details of the data structure from: > vw = db.getas('contacts[first:S,last:S,phone:S,email:S,notes:S]') So, I can't manifest exactly how it would work, but unless there is some odd constraint imposed by metakit, you don't need to (and probably shouldn't) use exec or eval. It *looks* to me like you are trying to take some object returned by a metakit method and use it to build a Python dict. I'm sure I don't have the details of your task right, but here is some code that does a similar thing without eval or exec: >>> desc = ('first', 'last', 'email') >>> class Person(object): ... def __init__(self, first, last, email): ... self.first = first ... self.last = last ... self.email = email ... >>> bob = Person('Bob', 'Jones', 'bob at theinternet.org') >>> jane = Person('Jane', 'Best', 'jane at earth.org') >>> persons = (jane, bob) >>> # persons is intended to serve a similar role as your vw. It is a >>> # sequence of objects, from which I will build a dict, without >>> # eval or exec. >>> >>> persons_dict = {} >>> def update(target_dict, object_tuple, attribs): ... for o in object_tuple: ... temp = {} ... for a in attribs: ... temp[a] = o.__getattribute__(a) ... target_dict[o.__getattribute__(attribs[0])] = temp ... return target_dict ... >>> persons_dict = update(persons_dict, persons, desc) >>> persons_dict {'Jane': {'last': 'Best', 'email': 'jane at earth.org', 'first': 'Jane'}, 'Bob': {'last': 'Jones', 'email': 'bob at theinternet.org', 'first': 'Bob'}} >>> Obviously this won't be exactly what you need, but I hope it can give you an idea of how to make what you *do* need. Why am I down on eval and exec? Well, >>> exec("print 6") 6 >>> is harmless. But, running: exec(some_string_with_commands_to_delete_your_hard_drive) would suck :-) Similar nastiness can happen with eval: >>> def f(): print 6 ... >>> eval('f()') 6 >>> Make f() an evil function, and it'll all end in tears :-) So, they are considered a security risk. You may well trust your data drawn from metakit in this instance. But, I think it is a good habit to avoid them when they can be avoided. I hope I've helped at least some. Best, Brian vdB From alan.gauld at freenet.co.uk Sun Jul 3 01:20:27 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 3 Jul 2005 00:20:27 +0100 Subject: [Tutor] OT self-implementation? References: <42C5D53C.9070007@po-box.mcgill.ca><004401c57edb$15350120$a6bc8851@xp> <42C6EAF5.6030302@po-box.mcgill.ca> Message-ID: <008d01c57f5c$a21cc380$a6bc8851@xp> > > (*)One of the hardest malicious bugs I've seen was by a > > disgruntled employee who deliberately inserted a bug into the C > > source of the companies compiler. ... He then left the > > company... > good lord, but if that fellow could only have harnessed that > ingeniousness for the forces of good! He had been, he was a very talented programmer who had worked for us on many big technical projects. In fact he was one of the few people I've met who could debug an octal core dump and genuinely understand what he was reading! Unfortunately deep technical skill is not always recognised by big corporations and he was not as well rewarded as he thought he should be... (and in truth as he probably deserved to be!) Alan G. From nephish at xit.net Sun Jul 3 05:41:09 2005 From: nephish at xit.net (nephish) Date: Sat, 02 Jul 2005 20:41:09 -0700 Subject: [Tutor] search through a list Message-ID: <42C75E55.5090803@xit.net> hey there i have a file that i want to read. each line in the file is the name of a file. the next line is how many lines are in that file. example of loglist.txt log1.txt 232 log2.txt 332 log3.txt 223 so log1 is a text file that has 232 lines in it. ok, so what i want to do is read this file, see if the file i am looking for is in it and if so, i need to know how many lines are in the file. here is what i have so far. import os #get a list of Logs in logs folder LogFiles = os.listdir('/home/nephish/Projects/Piv_GCI/logs') #open the loglist file and read the lines LogList = open('home/nephish/Projects/Piv/logs/LogList.txt', 'r') LogsRead = LogList.readlines() #see if there is a new log file. for i in LogFiles: if LogFiles[i] not in LogList: #if there is a new log, open it and read the lines StrName=(LogFiles[i]) NewLog = open('/home/nephish/Projects/Piv_CGI/logs'+StrName,'r') NewLogRead=NewLog.readlines() #print the lines (testing only) for x in NewLogRead: print x print '\n' print '\n' #end for loop else: #if the log file is not new, um this is where i am stuck. i need search the LogList for the name of the name of the file in LogFiles and get the line number back so i can use it to compare with how many lines are in the log file so i can only process the data in the new lines ... does this make sense ? i need to find the item in a list, and when found, return the next line. any takers? thanks From kent37 at tds.net Sun Jul 3 04:49:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 2 Jul 2005 22:49:53 -0400 Subject: [Tutor] Iterating over nested lists part2 Message-ID: <200507030249.j632nr17025565@outbound4.mail.tds.net> Luis N wrote: > def listItems(): > l= [] > d = {} > for r in range(len(vw)): > for x in range(lt): > ed = desc[x] > exec("d['%s']=vw[%d].%s" % (ed,r,ed)) > l.append(d) > print l If I understand correctly, you want to take all the rows of the view and turn them into dicts, and build a list of all the dicts. If so, the code above is way too complex. First, you can iterate over a list such as vw directly, you don't have to iterate the indices. Instead of for r in range(len(vw)): do something with vw[r] you just say for vwitem in vw: do something with vw Next, instead of exec you should use getattr(). To put the value into d you don't need either; you can assign to d[ed] directly. To get the 'ed' attribute from vwitem, use getattr(vwitem, ed). I also moved the assignment to d inside the loop so you start each row with a fresh dictionary. Here is the result: def listItems(): l= [] for vwitem in vw: d = {} for ed in desc: d[ed] = getattr(vwitem, ed) l.append(d) print l Kent From chinook.nr at tds.net Sun Jul 3 05:45:28 2005 From: chinook.nr at tds.net (Chinook) Date: Sat, 02 Jul 2005 23:45:28 -0400 Subject: [Tutor] String to List and back? Message-ID: I'm missing something simple again. The simplified issue is: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) >>> mystr = 'abc' # I can create a list of the string characters # with list comprehension >>> [c for c in mystr] ['a', 'b', 'c'] # Or just a simple builtin conversion function >>> list(mystr) ['a', 'b', 'c'] # But a conversion back to a string simply makes the # the list a string (I know there would have to be # special handling, but I noted it for illustration) >>> str(['a', 'b', 'c']) "['a', 'b', 'c']" # I know I could get the original string back by # rebuilding it with "for" loop >>> bts = '' >>> for c in strlist: ... bts += c ... >>> bts 'abc' # or even a function or class method which implemented # the "for" loop # I could also build a new string directly from the # original with a "for" loop Is there a one-liner like a builtin conversion function or list comprehension technique for the reverse (i.e. a list of strings back to a single string)? Thank you, Lee C From light_zls at 163.com Sun Jul 3 06:06:19 2005 From: light_zls at 163.com (Light) Date: Sun, 3 Jul 2005 12:06:19 +0800 Subject: [Tutor] String to List and back? Message-ID: <20050703040626.940271E4004@bag.python.org> Hi, Lee. You could using: >>> bts = ''.join(strlist) Then you would get: >>> bts 'abc' Light -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050703/0e01ff1b/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: FOX.GIF Type: image/gif Size: 9519 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050703/0e01ff1b/FOX.gif From chuck at freshsources.com Sun Jul 3 06:06:28 2005 From: chuck at freshsources.com (Chuck Allison) Date: Sat, 2 Jul 2005 22:06:28 -0600 Subject: [Tutor] String to List and back? In-Reply-To: References: Message-ID: <917380675.20050702220628@freshsources.com> Hello Chinook, How about join(), as in ''.join(strlist) ? Saturday, July 2, 2005, 9:45:28 PM, you wrote: C> I'm missing something simple again. The simplified issue is: C> Python 2.4.1 (#2, Mar 31 2005, 00:05:10) C> >>> mystr = 'abc' C> # I can create a list of the string characters C> # with list comprehension C> >>> [c for c in mystr] C> ['a', 'b', 'c'] C> # Or just a simple builtin conversion function C> >>> list(mystr) C> ['a', 'b', 'c'] C> # But a conversion back to a string simply makes the C> # the list a string (I know there would have to be C> # special handling, but I noted it for illustration) C> >>> str(['a', 'b', 'c']) C> "['a', 'b', 'c']" C> # I know I could get the original string back by C> # rebuilding it with "for" loop C> >>> bts = '' C> >>> for c in strlist: C> ... bts += c C> ... C> >>> bts C> 'abc' C> # or even a function or class method which implemented C> # the "for" loop C> # I could also build a new string directly from the C> # original with a "for" loop C> Is there a one-liner like a builtin conversion function or list C> comprehension technique for the reverse (i.e. a list of strings back to C> a single string)? C> Thank you, C> Lee C C> _______________________________________________ C> Tutor maillist - Tutor at python.org C> http://mail.python.org/mailman/listinfo/tutor -- Best regards, Chuck From chinook.nr at tds.net Sun Jul 3 06:43:03 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 03 Jul 2005 00:43:03 -0400 Subject: [Tutor] String to List and back? In-Reply-To: <917380675.20050702220628@freshsources.com> References: <917380675.20050702220628@freshsources.com> Message-ID: Just the thing Light and Chuck - I thought there might be something simple (and I've used the join method before duh). Thanks, Lee C From falcon3166 at hotmail.com Sun Jul 3 08:52:02 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 3 Jul 2005 00:52:02 -0600 Subject: [Tutor] How to get 4 numbers from the user in one line for easy comparision? Message-ID: I saw that great idea from Steven, and I appreciate it. I think it will work. Just need to figure out how to get 4 numbers from the player on one line for easy comparison, e.g. telling whether the number is correct position and number, incorrect position and correct number, or both are incorrect. If anyone has any advice in how to code this, I will gladly appreciate the help. Sorry if I seem like a newbie, but I am! :) Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050703/c639dfe0/attachment.htm From bvande at po-box.mcgill.ca Sun Jul 3 08:59:46 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 03 Jul 2005 02:59:46 -0400 Subject: [Tutor] search through a list In-Reply-To: <42C75E55.5090803@xit.net> References: <42C75E55.5090803@xit.net> Message-ID: <42C78CE2.4090703@po-box.mcgill.ca> nephish said unto the world upon 02/07/2005 23:41: > hey there > i have a file that i want to read. > each line in the file is the name of a file. > the next line is how many lines are in that file. > > example of loglist.txt > > log1.txt > 232 > log2.txt > 332 > log3.txt > 223 > > so log1 is a text file that has 232 lines in it. > > ok, so what i want to do is read this file, see if the file i am looking > for is in it > and if so, i need to know how many lines are in the file. > > here is what i have so far. > > import os > > #get a list of Logs in logs folder > LogFiles = os.listdir('/home/nephish/Projects/Piv_GCI/logs') > > #open the loglist file and read the lines > LogList = open('home/nephish/Projects/Piv/logs/LogList.txt', 'r') > LogsRead = LogList.readlines() > > #see if there is a new log file. > for i in LogFiles: > if LogFiles[i] not in LogList: > #if there is a new log, open it and read the lines > StrName=(LogFiles[i]) > NewLog = open('/home/nephish/Projects/Piv_CGI/logs'+StrName,'r') > NewLogRead=NewLog.readlines() > #print the lines (testing only) > for x in NewLogRead: > print x > print '\n' > print '\n' #end for loop > else: #if the log file is not new, > > um this is where i am stuck. i need search the LogList for the name of > the name of the file in LogFiles and get the line number back so i can > use it to compare with how many lines are in the log file so i can only > process the data in the new lines ... does this make sense ? > > i need to find the item in a list, and when found, return the next line. > > any takers? > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor It's late and I might not have completely understood the task. Warning given: So, you have a list of strings, and each is a line from your text file described at the top, right? If so, maybe this will meet your needs: >>> l_list = ['these are\n', 'just some lines\n', 'to test with\n', 'nothing to see\n'] >>> def line_finder(line_list, flag): flag = flag.strip() return_next = False for line in line_list: if return_next: return line.strip() else: if line.strip() == flag: return_next = True >>> line_finder(l_list, 'just some lines') 'to test with' >>> (If the line isn't found, the function returns None.) HTH, Brian vdB From ypaami at gmail.com Sun Jul 3 09:10:24 2005 From: ypaami at gmail.com (Xinyue Ye) Date: Sun, 3 Jul 2005 03:10:24 -0400 Subject: [Tutor] a question Message-ID: when I type sys.ps2 after import sys, I got the message like: Traceback (most recent call last): File "", line 1, in -toplevel- sys.ps2 AttributeError: 'module' object has no attribute 'ps2' why does it happen? From tegmine at gmail.com Sun Jul 3 09:29:03 2005 From: tegmine at gmail.com (Luis N) Date: Sun, 3 Jul 2005 00:29:03 -0700 Subject: [Tutor] Iterating over nested lists part2 In-Reply-To: <200507030249.j632nr17025565@outbound4.mail.tds.net> References: <200507030249.j632nr17025565@outbound4.mail.tds.net> Message-ID: <77bfa81a05070300291a8b16b4@mail.gmail.com> On 7/2/05, Kent Johnson wrote: > > Luis N wrote: > > def listItems(): > > l= [] > > d = {} > > for r in range(len(vw)): > > for x in range(lt): > > ed = desc[x] > > exec("d['%s']=vw[%d].%s" % (ed,r,ed)) > > l.append(d) > > print l > > If I understand correctly, you want to take all the rows of the view and > turn them into dicts, and build a list of all the dicts. If so, the code > above is way too complex. > > First, you can iterate over a list such as vw directly, you don't have to > iterate the indices. Instead of > for r in range(len(vw)): > do something with vw[r] > > you just say > for vwitem in vw: > do something with vw > > Next, instead of exec you should use getattr(). To put the value into d > you don't need either; you can assign to d[ed] directly. To get the 'ed' > attribute from vwitem, use getattr(vwitem, ed). > > I also moved the assignment to d inside the loop so you start each row > with a fresh dictionary. Here is the result: > > def listItems(): > l= [] > for vwitem in vw: > d = {} > for ed in desc: > d[ed] = getattr(vwitem, ed) > l.append(d) > print l > > Kent That's beautiful. I'm really grokking getattr, and I notice that it has some close relations in the family of built-in functions. Luis N. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050703/9e3762c6/attachment.htm From light_zls at 163.com Sun Jul 3 09:59:51 2005 From: light_zls at 163.com (Light) Date: Sun, 3 Jul 2005 15:59:51 +0800 Subject: [Tutor] search through a list In-Reply-To: <42C75E55.5090803@xit.net> References: <42C75E55.5090803@xit.net> Message-ID: <200507031559.51450.light_zls@163.com> > import os > > #get a list of Logs in logs folder > LogFiles = os.listdir('/home/nephish/Projects/Piv_GCI/logs') > > #open the loglist file and read the lines > LogList = open('home/nephish/Projects/Piv/logs/LogList.txt', 'r') > LogsRead = LogList.readlines() > > #see if there is ?a new log file. > for i in LogFiles: > ? ? if LogFiles[i] not in LogList: > ? ? ? ? #if there is a new log, open it and read the lines > ? ? ? ? ? ? StrName=(LogFiles[i]) > ? ? ? ? ? ? NewLog = > open('/home/nephish/Projects/Piv_CGI/logs'+StrName,'r') > NewLogRead=NewLog.readlines() > ? ? ? ? ? ? #print the lines (testing only) > ? ? ? ? ? ? for x in NewLogRead: > ? ? ? ? ? ? ? ? print x > ? ? ? ? ? ? ? ? print '\n' > ? ? ? ? ? ? print '\n' #end for loop > ? ? ? ? else: #if the log file is not new, ? ? Hi, nephish. I've read Brian's letter. He has given a solution for this problem. And below is another solution for it. StrLog = " ".join([LogsRead[LogsRead.index(line)+1].strip() for line in LogsRead if line.strip() == i]) And I think 'LogFiles[i]' should be replaced by 'i', for 'i' is not an index but a string. Light From sandip at lug-delhi.org Sun Jul 3 11:18:39 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sun, 03 Jul 2005 14:48:39 +0530 Subject: [Tutor] search through a list In-Reply-To: <42C75E55.5090803@xit.net> References: <42C75E55.5090803@xit.net> Message-ID: <42C7AD6F.7080806@lug-delhi.org> nephish wrote: > LogList = open('home/nephish/Projects/Piv/logs/LogList.txt', 'r') > LogsRead = LogList.readlines() > > #see if there is a new log file. > for i in LogFiles: > if LogFiles[i] not in LogList: Don't you mean "if LogFiles[i] not in LogsRead" ? - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip at puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From kent37 at tds.net Sun Jul 3 14:06:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Jul 2005 8:06:44 -0400 Subject: [Tutor] a question Message-ID: <200507031206.j63C6irV019073@outbound4.mail.tds.net> Xinyue Ye wrote: > when I type sys.ps2 after import sys, > I got the message like: > Traceback (most recent call last): > File "", line 1, in -toplevel- > sys.ps2 > AttributeError: 'module' object has no attribute 'ps2' > why does it happen? >From the docs: ps1 ps2 Strings specifying the primary and secondary prompt of the interpreter. These are only defined if the interpreter is in interactive mode. When you are running in IDLE, the command shell is provided by IDLE, not Python, so ps1 and ps2 are not defined. Kent From alan.gauld at freenet.co.uk Sun Jul 3 16:00:58 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 3 Jul 2005 15:00:58 +0100 Subject: [Tutor] a question References: Message-ID: <01d701c57fd7$a3a03950$a6bc8851@xp> It works Ok for me, can you cut and paste the full session so we can see exactly what is happening. Also, what environment are you running it in? Windows/Linux/MacOS? IDLE, Pythonwin, Pycrust? All of that might be relevant. Alan G. ----- Original Message ----- From: "Xinyue Ye" To: Sent: Sunday, July 03, 2005 8:10 AM Subject: [Tutor] a question when I type sys.ps2 after import sys, I got the message like: Traceback (most recent call last): File "", line 1, in -toplevel- sys.ps2 AttributeError: 'module' object has no attribute 'ps2' why does it happen? From alan.gauld at freenet.co.uk Sun Jul 3 16:03:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 3 Jul 2005 15:03:52 +0100 Subject: [Tutor] How to get 4 numbers from the user in one line for easycomparision? References: Message-ID: <01e501c57fd8$0b99cee0$a6bc8851@xp> > I .... Just need to figure out how to get 4 numbers from > the player on one line for easy comparison, Unless there is a set of batteries somewhere that I don't know about I think you have to rely on reading the line as a string and then splitting it. line = raw_input('Type 4 numbers separated by spaces: ') numbers = [int(n) for n in line.split(' ')] HTH, Alan G. From nephish at xit.net Mon Jul 4 00:06:50 2005 From: nephish at xit.net (nephish) Date: Sun, 03 Jul 2005 15:06:50 -0700 Subject: [Tutor] search through a list Message-ID: <42C8617A.7060409@xit.net> Hey there thanks, quote: /try num_of_lines = line_find(LogsRead, "PV050614.LOG") I am binding num_of_lines to the return value. In an interactive session, without the binding, a non-None return value will display on screen. But both interactively and in a program binding it makes it easier to use later. Indeed, in a program, no binding -> no later use. /this is what worked out for me. i am trying to get as familliar as i can in idle because it lets me know as-it-happens when i have something messed up. this put my pieces together. thanks again shawn <>< From dyoo at hkn.eecs.berkeley.edu Mon Jul 4 00:55:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 3 Jul 2005 15:55:18 -0700 (PDT) Subject: [Tutor] OT self-implementation? In-Reply-To: <42C6EAF5.6030302@po-box.mcgill.ca> Message-ID: > > (*)One of the hardest malicious bugs I've seen was by a disgruntled > > employee who deliberately inserted a bug into the C source of the > > companies compiler. He then recompiled the compiler (using the working > > compiler) to produce a faulty compiler. He then removed his bugs in > > the source code so it was back to the correct version. He then > > recompiled the good source with the faulty compiler to produce a new > > faulty compiler. He then left the company... > > > > It took a long time to figure out what was wrong and why... > > good lord, but if that fellow could only have harnessed that > ingeniousness for the forces of good! Hi Brian, You may find the following paper by Ken Thompson an interesting one on this topic: "Reflections on Trusting Trust": http://www.acm.org/classics/sep95/ It follows the exact stuation that Alan mentioned. From cyresse at gmail.com Mon Jul 4 00:55:50 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 4 Jul 2005 10:55:50 +1200 Subject: [Tutor] wxPython shaped window In-Reply-To: References: Message-ID: To totally not answer your question, check out - pythoncard.sourceforge.net It's the Visual Basic Userform IDE of wxPython. :) On 7/1/05, Adam Bark wrote: > > On 6/26/05, Adam Cripps wrote: > > > > On 6/25/05, Adam Bark wrote: > > > Thanks for the info Adam I just seem to be having a problem with the > > panel > > > size it greys out nearly all the image. Ideally I would like to make > > the > > > panel transparent but I can't work out how to do that. > > > > > > > > > On 6/25/05, Adam Cripps < kabads at gmail.com> wrote: > > > > On 6/25/05, Adam Bark < adam.jtm30 at gmail.com > wrote: > > > > > Is it possible to put controls into a shaped window in wxPython. I > > have > > > > > tried putting a button on the demo and it becomes the exact size > > and > > > shape > > > > > of the window. Also when I tried to bind it to an action it > > wouldn't > > > even > > > > > start. > > > > > > > > > > Adam > > > > > > > > > > > > > I'm working through something similar myself at the moment. > > > > > > > > Try adding a wx.Panel to the frame and then the button to the panel. > > > > You can position them through pos parameter, but it should default > > to > > > > the top left of the panel and have a good size if you use > > > > button.SetSize(button.GetBestSize()) > > > > > > > > HTH > > > > > > > > Adam > > > > Adam - how much code do you have? Why not post it either here or the > > wxpython-users list (to which I'm also subscribed) and we can take a > > look. > > > > Adam > > > > -- > > http://www.monkeez.org > > PGP key: 0x7111B833 > > > I tried posting to the wxpython-users list but I'm not sure it worked > nobody replied anyway. > Here's my test script: > > import wx > > class Frame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, -1, "Shaped Window", > style = > wx.FRAME_SHAPED > | wx.SIMPLE_BORDER > | wx.FRAME_NO_TASKBAR > | wx.STAY_ON_TOP > ) > self.hasShape = False > self.delta = (0,0) > > self.Bind(wx.EVT_PAINT, self.OnPaint) > self.Bind(wx.EVT_MOTION, self.OnMouseMove) > > self.bkground = wx.Bitmap("/home/adam/bkgrnd.gif", wx.BITMAP_TYPE_GIF) > w, h = self.bkground.GetWidth(), self.bkground.GetHeight() > self.SetClientSize((w, h)) > self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape) > panel = Panel(self, w, h) > panel.Show() > dc = wx.ClientDC(self) > dc.DrawBitmap(self.bkground, 0,0, True) > > def SetWindowShape(self, evt): > # Use the bitmap's mask to determine the region > r = wx.RegionFromBitmap(self.bkground) > self.hasShape = self.SetShape(r) > > def OnPaint(self, event): > dc = wx.PaintDC(self) > dc.DrawBitmap(self.bkground, 0,0, True) > > def OnMouseMove(self, evt): > if evt.Dragging() and evt.LeftIsDown(): > x, y = self.ClientToScreen(evt.GetPosition()) > fp = (x - self.delta[0], y - self.delta[1]) > self.Move(fp) > > class Panel(wx.Panel): > def __init__(self, parent, width, height): > wx.Panel.__init__(self, parent, -1, size=(width, height)) > > button = wx.Button(self, -1, "hello") > button.SetSize(button.GetBestSize()) > self.SetSize((width, height)) > #print dir(self) > > if __name__ == "__main__": > app = wx.PySimpleApp() > frame = Frame() > frame.Show() > app.MainLoop() > > Thanks. > Adam. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050704/4efb2e05/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon Jul 4 00:59:32 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 3 Jul 2005 15:59:32 -0700 (PDT) Subject: [Tutor] OT self-implementation? In-Reply-To: <7e5ba9220507011918180ca1be@mail.gmail.com> Message-ID: > > Now's not the time in my life to start a comp. sci. degree. So, my > > questions are: > > > > 1) What would be good terms to google for to find an explanation of > > how the seeming magic doesn't violate all reason? Hi Michael, The idea is that we can use _ourselves_ as the initial compiler for a simplified version of the language that we're trying to compile. We know, for example, that something like: ###### print "hello world" ###### should produce something machine-like, like: 1. Put the bytes "hello world" somewhere where the system can see things. 2. Invoke whatever the underlying system provides us to print those bytes. and if we knew what the hardware looked like, we could write out the exact low-level instructions that produces the words "hello world" on screen. Just as a sample of what these lower-level instructions might look like, here's a sample using Python's bytecode disassembler: ###### >>> import dis >>> def say_hello(): ... print "hello world" ... >>> dis.dis(say_hello) 2 0 LOAD_CONST 1 ('hello world') 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE ###### It's a lot more lines for doing something simple, but that's exactly why we write programs in higher-level languages now. Anyway, if we know what the underlying low-level language looks like we can take something written in a higher level language, and manually transcribe those high-level constructs into the lower-level language. So the base case is ourselves and the hardware. *grin* This is usually very tedious work, though, so many metacircular implementations will use a limited subset of the language, one that is really easy to translate down to primitive actions. That's what the PyPy folks are doing: they're writing Python in Python, with the caveat that the kind of Python that they're writing is a "restricted" one that uses less features than full-on Python: http://codespeak.net/svn/pypy/dist/pypy/documentation/coding-guide.txt They're doing this to make the translation to the lower machine language easier: I think their plan is to take their PyPy interpreter, and mechanically translate it down into C. This implies that they're planning to use tools to do the translation, but in a pinch, they could always use themselves and do the translation by hand. Such a process would be very bug prone and painful, but it's possible. *grin* > > 2) Much harder, so please pass unless you've a link you know of > > off-hand: any recommendations of particular things that I could read? The classic textbook "Structure and Interpretation of Computer Programs" might interest you: http://mitpress.mit.edu/sicp/ Chapter 4 goes into writing a Scheme interpreter in Scheme, and the chapter right after that talks about how to take that interpreter and mechanically rewrite it into low-level instructions. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Mon Jul 4 01:02:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 3 Jul 2005 16:02:56 -0700 (PDT) Subject: [Tutor] How do I make Python calculate square roots? In-Reply-To: <42C6D748.1000200@intersiege.com> Message-ID: On Sat, 2 Jul 2005, Reed L. O'Brien wrote: > > Does anyone know how to make Python calculate square roots? > > > Raise to the 1/2 power. > > >>> 4**.5 > 2.0 > >>> 16**.5 > 4.0 > >>> 81**.5 > 9.0 By the way, if you need to take the square roots of negative numbers, then the 'sqrt' function in the cmath module should do the trick: ###### >>> (-1)**0.5 Traceback (most recent call last): File "", line 1, in ? ValueError: negative number cannot be raised to a fractional power >>> >>> import cmath >>> cmath.sqrt(-1) 1j ###### Best of wishes! From alan.gauld at freenet.co.uk Mon Jul 4 01:20:54 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 4 Jul 2005 00:20:54 +0100 Subject: [Tutor] OT self-implementation? References: Message-ID: <020601c58025$dcca2df0$a6bc8851@xp> > You may find the following paper by Ken Thompson an interesting one on > this topic: "Reflections on Trusting Trust": > > http://www.acm.org/classics/sep95/ > > It follows the exact stuation that Alan mentioned. Yes, I hadn't seen the Thompson paper before but I notice it was dated 1989 and the guy I'm discussing left in 1991. I know he read the ACM papers so now I guess I know where he got the idea! Mind you even though I know how he did it I'm still not sure I could replicate the feat even now! Alan G. From cyresse at gmail.com Mon Jul 4 01:39:37 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 4 Jul 2005 11:39:37 +1200 Subject: [Tutor] Sudoku puzzle implementation Message-ID: Hi all, If you aren't aware of Sudoku, this is it - http://www.sudoku.com/ Big craze at my office, and I've just been wracking my brains to try and think of how to model it in Python (in order to solve.) What I'm not sure of is how to implement it. Basic rundown of a Sudoku puzzle is - Generally composed of 9 x 9 squares, with the box divided further into nine 3 x 3 mini-squares. Certain numbers are given at the start. Sudoku puzzles follow these rules - Each column, row and mini-square must contain the complete set of numbers 1 - 9. The numbers do not have to be sequential. Each column, row, and mini-square can only contain each number once So that's it. So, to implement... I was thinking, a list of lists of lists.... [grid[0], grid[1], grid[2], grid[3], grid[4], grid[5], grid[6], grid[7], grid[8] ] [ [ [a,b,c], [d,e,f,], [g,h,i] ], [ [j,k,l], [m,n,o], [p,q,r].... So forth. This approach gets a little confusing in terms of array arithmetic but it's livable. Now each variable can be [1-9].... Variable a (grid[0][0][0]) can be 1 unless grid - any member of grid[0] is 1 row - any member of grid[1][0] or grid[2][0] is 1 column - grid[3][x][0] or grid[6][x][0] is 1 (where x is an index of 0 to 2) My current approach is to start with each variable as a list of numbers [1-9] and to pop numbers based on the above rules, but I got thinking about sets and what not, and wondered if they would work better, unions and intersections and whatnot. Problem is, I don't know the first thing about set mathematics. Any pointers in the right direction would be gratefully appreciated. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050704/1e7afdb6/attachment.htm From nephish at xit.net Mon Jul 4 05:12:36 2005 From: nephish at xit.net (nephish) Date: Sun, 03 Jul 2005 20:12:36 -0700 Subject: [Tutor] search through a list Message-ID: <42C8A924.2090002@xit.net> Hey there, sorry to bother you again about this same problem but i have a line of code in this same issue that works in idle but it does not work in a regular script. that same thing i am trying to do, reading the directory, comparing the list of files to a list ..... just want to catch the newest lines of a log file to process later. here is what i have ( kinda long ) ____________________________________________________________ #!/usr/bin/python # Update Database import os print ' ' print ' ' #get a list of log files in the directory LogsInDir=os.listdir('/home/nephish/Projects/Piv_CGI/logs') print LogsInDir #testing only, remove later #read the contents of the log list LogList = open('/home/nephish/Projects/Piv_CGI/LogList.txt', 'r') LogsRead=LogList.readlines() LogList.close() print 'Lines of LogList.txt' for i in LogsRead: print i #testing only, remove later #this function returns the number of lines on record for each log file. def line_finder(LogsInDir, flag): flag=flag.strip() return_next=False for line in LogsInDir: if return_next: return line.strip() else: if line.strip() == flag: return_next = True NumLogsInDir = len(LogsInDir) NextLog = 0 while NextLog < NumLogsInDir: print 'opening file '+LogsInDir[NextLog] print ' ' Count_in_Log = open('/home/nephish/Projects/Piv_CGI/logs/'+LogsInDir[NextLog], "r") Defer = Count_in_Log.readlines() Count_in_Log.close() CountEmUp = len(Defer) print 'number is ' print CountEmUp NumLinesOnFile=line_finder(LogsRead, LogsInDir[NextLog]) print NumLinesOnFile if CountEmUp > int(NumLinesOnFile): print " "+LogsInDir[NextLog]+" is longer than on record" XtraLines = int(NumLinesOnFile) - CountEmUp print XtraLines else: print ' '+LogsInDir[NextLog]+" is not greater than on record" XtraLines=0 print XtraLines NextLog=NextLog+1 print 'done' ______________________________________________________________________ the line in question is this one: NumLinesOnFile=line_finder(LogsRead, LogsInDir[NextLog]) print NumLinesOnFile if i run this in idle printing NumLinesOnFile gives me a string 14 when run in a terminal it returns "None" dont get it. is it because it is in a while loop? any ideas would be awesome here. thanks From chinook.nr at tds.net Mon Jul 4 03:18:33 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 03 Jul 2005 21:18:33 -0400 Subject: [Tutor] Sudoku puzzle implementation In-Reply-To: References: Message-ID: Liam, I couldn't get "into" your approach at the moment, but I was wondering if you have looked at the following: First, the Reverse Puzzle section of: http://cs.gettysburg.edu/~tneller/resources/ai-search/uninformed-java/ and secondly more generally: http://www.gamedev.net/reference/articles/article1374.asp http://www.gamedev.net/reference/articles/article1433.asp http://www.gamedev.net/reference/articles/article2041.asp Just some references I've used for puzzle problems, Lee C Liam Clarke wrote: > Hi all, > > If you aren't aware of Sudoku, this is it - http://www.sudoku.com/ > > Big craze at my office, and I've just been wracking my brains to try and > think of how to model it in Python (in order to solve.) > > What I'm not sure of is how to implement it. > > Basic rundown of a Sudoku puzzle is - > > > Generally composed of 9 x 9 squares, with the box divided further into > nine 3 x 3 mini-squares. Certain numbers are given at the start. > > Sudoku puzzles follow these rules - > > Each column, row and mini-square must contain the complete set of > numbers 1 - 9. > The numbers do not have to be sequential. > Each column, row, and mini-square can only contain each number once > > So that's it. So, to implement... > > I was thinking, a list of lists of lists.... > [grid[0], grid[1], grid[2], > grid[3], grid[4], grid[5], > grid[6], grid[7], grid[8] ] > > [ > [ > [a,b,c], > [d,e,f,], > [g,h,i] > ], > [ > [j,k,l], > [m,n,o], > [p,q,r].... > > So forth. This approach gets a little confusing in terms of array > arithmetic but it's livable. > > Now each variable can be [1-9].... > > Variable a (grid[0][0][0]) can be 1 unless > > grid - any member of grid[0] is 1 > row - any member of grid[1][0] or grid[2][0] is 1 > column - grid[3][x][0] or grid[6][x][0] is 1 (where x is an index of 0 to 2) > > My current approach is to start with each variable as a list of numbers > [1-9] and to pop numbers based on the above rules, > but I got thinking about sets and what not, and wondered if they would > work better, unions and intersections and whatnot. > > Problem is, I don't know the first thing about set mathematics. > > Any pointers in the right direction would be gratefully appreciated. > > Regards, > > > Liam Clarke > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From modern.teenage.cyberpunk at gmail.com Mon Jul 4 03:37:57 2005 From: modern.teenage.cyberpunk at gmail.com (gelsey torres) Date: Sun, 3 Jul 2005 21:37:57 -0400 Subject: [Tutor] Confused about error message Message-ID: I'm new to Python and computer programming in general. Eventually I got sick of just reading my programming books and typing code from them into the interpreter, so I decided to write a script that will grab files from websites and save them to the hard drive, and if they're compressed, unzip them. Here is my code: #! /usr/bin/python # 07/03/2005 # file_downloader.py - Downloads files and unzips them if they are a .zip file from urllib import FancyURLopener import os.path import zlib import fnmatch def get_file(address, filename, url): try: file_content = FancyURLopener() file_content.retrieve(address, filename) print "Finished downloading %s from %s." % (filename, url) except(), error: print "An error has occured:", error def unzip_file(filename): print "Unzipping file.." for file in filename: try: file = os.path.split(filename)[2] file += zlib.decompressobj() def main(): address = raw_input("Enter the address of the site: ") url, filename = os.path.split(address) # remove path and keep the name of the original file get_file(address, filename, url) if fnmatch(filename, "*.zip"): unzip_file(filename) else: pass main() response = raw_input("Do you want to run the program again? (y/n): ") while (response == "y"): main() else: raw_input("\n\nPress enter to quit.") When I ran it to test main(), I got this error: File "file_downloader.py", line 25 def main(): ^ SyntaxError: invalid syntax Although sometimes it takes me awhile, I can usually spot the errors that I've made when they come up. I've stared at this one for two days and I still don't see the syntax error the interpreter is referring to. What am I doing wrong? I'm using Python 2.3 on Mac OS X version 10.3.9, and I run my scripts from Terminal. Thank you for your consideration, Gelsey From kent37 at tds.net Mon Jul 4 03:50:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 3 Jul 2005 21:50:08 -0400 Subject: [Tutor] Confused about error message Message-ID: <200507040150.j641o8Et013545@outbound4.mail.tds.net> gelsey torres wrote: > def unzip_file(filename): > print "Unzipping file.." > for file in filename: > try: > file = os.path.split(filename)[2] > file += zlib.decompressobj() > > def main(): > address = raw_input("Enter the address of the site: ") > url, filename = os.path.split(address) # remove path and keep the > name of the original file > get_file(address, filename, url) > if fnmatch(filename, "*.zip"): > unzip_file(filename) > else: > pass > > main() > response = raw_input("Do you want to run the program again? (y/n): ") > while (response == "y"): > main() > else: > raw_input("\n\nPress enter to quit.") > > When I ran it to test main(), I got this error: > > File "file_downloader.py", line 25 > def main(): > ^ > SyntaxError: invalid syntax You are missing the except: or finally: clause to the try in unzip_file(). Mysterious syntax errors are often incorrect indentation or (as in this case) something missing from the code before. Kent From dyoo at hkn.eecs.berkeley.edu Mon Jul 4 09:34:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 4 Jul 2005 00:34:15 -0700 (PDT) Subject: [Tutor] search through a list In-Reply-To: <42C8A924.2090002@xit.net> Message-ID: > #this function returns the number of lines on record for each log file. > def line_finder(LogsInDir, flag): > flag=flag.strip() > return_next=False > for line in LogsInDir: > if return_next: > return line.strip() > else: > if line.strip() == flag: > return_next = True Hi Nephish, Question: what should the program return if return_next is never True? That is, what happens if the program does not find the flag that you're looking for? The comment of this function also seems a bit weird: it appears to try to return the very next line after the 'flag' line of a file: it's not doing any counting of numbers, as far as I can tell. > the line in question is this one: > > NumLinesOnFile=line_finder(LogsRead, LogsInDir[NextLog]) > print NumLinesOnFile > > if i run this in idle printing NumLinesOnFile gives me a string 14 The function will return None if 'flag' can't be found in the LogsRead list. Otherwise, it'll return one of the lines of the file. So I'd assume for the moment that line_finder can't find what it is trying to find. You may want to test this yourself by adding some kind of debugging statement in line_finder() to make it more clear if t can't find what it's looking for. Does this sound reasonable? Best of wishes to you! From ewald.ertl at hartter.com Mon Jul 4 09:44:13 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Mon, 4 Jul 2005 09:44:13 +0200 Subject: [Tutor] Confused about error message In-Reply-To: References: Message-ID: <20050704094413.000004da@sunray1> Hi! you're missing the except-clause in the exception-handling: on Sun, 3 Jul 2005 21:37:57 -0400 gelsey torres wrote : --------------------------------------------------------------------------------------------- gelsey torres > I'm new to Python and computer programming in general. Eventually I gelsey torres > got sick of just reading my programming books and typing code from gelsey torres > them into the interpreter, so I decided to write a script that will gelsey torres > grab files from websites and save them to the hard drive, and if gelsey torres > they're compressed, unzip them. Here is my code: gelsey torres > gelsey torres > #! /usr/bin/python gelsey torres > # 07/03/2005 gelsey torres > # file_downloader.py - Downloads files and unzips them if they are a .zip file gelsey torres > gelsey torres > from urllib import FancyURLopener gelsey torres > import os.path gelsey torres > import zlib gelsey torres > import fnmatch gelsey torres > gelsey torres > def get_file(address, filename, url): gelsey torres > try: gelsey torres > file_content = FancyURLopener() gelsey torres > file_content.retrieve(address, filename) gelsey torres > print "Finished downloading %s from %s." % (filename, url) gelsey torres > except(), error: gelsey torres > print "An error has occured:", error gelsey torres > gelsey torres > def unzip_file(filename): gelsey torres > print "Unzipping file.." gelsey torres > for file in filename: gelsey torres > try: gelsey torres > file = os.path.split(filename)[2] gelsey torres > file += zlib.decompressobj() gelsey torres > Here is the catch of the Exception missing. gelsey torres > def main(): gelsey torres > address = raw_input("Enter the address of the site: ") gelsey torres > url, filename = os.path.split(address) # remove path and keep the gelsey torres > name of the original file gelsey torres > get_file(address, filename, url) gelsey torres > if fnmatch(filename, "*.zip"): gelsey torres > unzip_file(filename) gelsey torres > else: gelsey torres > pass gelsey torres > gelsey torres > main() gelsey torres > response = raw_input("Do you want to run the program again? (y/n): ") gelsey torres > while (response == "y"): gelsey torres > main() gelsey torres > else: gelsey torres > raw_input("\n\nPress enter to quit.") gelsey torres > gelsey torres > When I ran it to test main(), I got this error: gelsey torres > gelsey torres > File "file_downloader.py", line 25 gelsey torres > def main(): gelsey torres > ^ gelsey torres > SyntaxError: invalid syntax gelsey torres > gelsey torres > Although sometimes it takes me awhile, I can usually spot the errors gelsey torres > that I've made when they come up. I've stared at this one for two days gelsey torres > and I still don't see the syntax error the interpreter is referring gelsey torres > to. What am I doing wrong? I'm using Python 2.3 on Mac OS X version gelsey torres > 10.3.9, and I run my scripts from Terminal. gelsey torres > gelsey torres > Thank you for your consideration, gelsey torres > gelsey torres > Gelsey gelsey torres > _______________________________________________ gelsey torres > Tutor maillist - Tutor at python.org gelsey torres > http://mail.python.org/mailman/listinfo/tutor gelsey torres > ------------------- end ---------------------- The exception catching should solve your problem. HTH Ewald From dyoo at hkn.eecs.berkeley.edu Mon Jul 4 09:57:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 4 Jul 2005 00:57:04 -0700 (PDT) Subject: [Tutor] Confused about error message In-Reply-To: Message-ID: On Sun, 3 Jul 2005, gelsey torres wrote: > I'm new to Python and computer programming in general. Eventually I got > sick of just reading my programming books and typing code from them into > the interpreter, so I decided to write a script that will grab files > from websites and save them to the hard drive, and if they're > compressed, unzip them. Hi Gelsey, [looking at code] Wow, that's pretty impressive as a beginning program! As Kent mentioned, the exception handling code that you've written is slightly misindented with some other syntax errors. But I'd strongly recommend just stripping it out altogether for the moment until you have a need for exception handling. I'm taking a look at the get_file() function now: ###### def get_file(address, filename, url): file_content = FancyURLopener() file_content.retrieve(address, filename) print "Finished downloading %s from %s." % (filename, url) ###### Ok, makes sense so far. unzip_file() looks like it'll need some work, so I'll skip that one for now. Let's concentrate on getting this working for regular files first. The main function has a slightly unusual line here: url, filename = os.path.split(address) I see what you're trying to do: you're trying to take something like: "http://python.org/index.html" and break it down into: ["http://python.org/", "index.html"] The only issue is that os.path.split() works with file paths, not URLs. Some operating systems don't use forward slash as the path separator, so the code is a little fragile. A more reliable way to do this splitting is with the 'urlparse' library: http://www.python.org/doc/lib/module-urlparse.html But in a pinch, you can also just split the string along slashes, since the URL standard says that slashes are special. Here's a quick-and-dirty function to do that: ###### >>> def mysplit(address): ... """Breaks a full URL address into the url and filename ... portions.""" ... pieces = address.split("/") ... url = '/'.join(pieces[:-1]) ... filename = pieces[-1] ... return (url, filename) ... >>> mysplit("http://python.org/index.html") ('http://python.org', 'index.html') ###### > Although sometimes it takes me awhile, I can usually spot the errors > that I've made when they come up. I've stared at this one for two days > and I still don't see the syntax error the interpreter is referring to. Feel free to show us code on Tutor; there's no reason you have to suffer through SyntaxErrors like that. Don't wait for two days. *grin* Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Jul 4 10:11:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 4 Jul 2005 01:11:28 -0700 (PDT) Subject: [Tutor] I sure do love cookies. In-Reply-To: <8daabe56050701155814df1832@mail.gmail.com> Message-ID: On Fri, 1 Jul 2005, D. Hartley wrote: > Anyone have a good (*simple*) tutorial on making/sending cookies via > python? (i.e., not receiving/messing with them). Hi Denise, I did find one tutorial here that might help with the receiving side of things: http://www.voidspace.org.uk/python/articles/cookielib.shtml To make cookies, in the examples of the Cookie module will probably help the most: http://www.python.org/doc/lib/cookie-example.html >From the documentation, it sounds like Cookie.SimpleCookie is what you're looking for: ###### >>> import Cookie >>> mycookie = Cookie.SimpleCookie() >>> mycookie['pop'] = 'tart' >>> >>> mycookie >>> >>> print mycookie Set-Cookie: pop=tart; ###### as the page at the very beginning of the Cookie documentation says that Cookie.SmartCookie is too smart and trusting for its own good. Best of wishes! From nephish at xit.net Mon Jul 4 16:23:04 2005 From: nephish at xit.net (nephish) Date: Mon, 04 Jul 2005 07:23:04 -0700 Subject: [Tutor] search through a list In-Reply-To: References: Message-ID: <42C94648.2090806@xit.net> Danny Yoo wrote: > > >>#this function returns the number of lines on record for each log file. >>def line_finder(LogsInDir, flag): >> flag=flag.strip() >> return_next=False >> for line in LogsInDir: >> if return_next: >> return line.strip() >> else: >> if line.strip() == flag: >> return_next = True >> >> > > >Hi Nephish, > >Question: what should the program return if return_next is never True? >That is, what happens if the program does not find the flag that you're >looking for? > >The comment of this function also seems a bit weird: it appears to try to >return the very next line after the 'flag' line of a file: it's not doing >any counting of numbers, as far as I can tell. > > > > >>the line in question is this one: >> >>NumLinesOnFile=line_finder(LogsRead, LogsInDir[NextLog]) >>print NumLinesOnFile >> >>if i run this in idle printing NumLinesOnFile gives me a string 14 >> >> > >The function will return None if 'flag' can't be found in the LogsRead >list. Otherwise, it'll return one of the lines of the file. > >So I'd assume for the moment that line_finder can't find what it is trying >to find. You may want to test this yourself by adding some kind of >debugging statement in line_finder() to make it more clear if t can't find >what it's looking for. Does this sound reasonable? > > >Best of wishes to you! > > > > Ok, if the return_next is never True, returning None is very useful. If it is true, yes, i do want it to return the next line of the list. this is a list of files. It is a file name, followed by the number of lines in the file, this way i can only process the data that is new. Your suggestion sounds reasonable and i will work with it with a few more print statements to see exactly where it is failing. maybe i had something messed up in my string that it is looking for that wouldn't apply from IDLE. Thanks for your help. -shawn<>< From kent37 at tds.net Mon Jul 4 15:02:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 4 Jul 2005 9:02:49 -0400 Subject: [Tutor] I sure do love cookies. Message-ID: <200507041302.j64D2nof029473@outbound1.mail.tds.net> Danny Yoo wrote: > To make cookies, in the examples of the Cookie module will probably help > the most: > > http://www.python.org/doc/lib/cookie-example.html > >>From the documentation, it sounds like Cookie.SimpleCookie is what you're > looking for: My understanding is that the Cookie module is for server-side cookie handling. cookielib.Cookie integrates with cookielib.CookieJar for client-side cookie handling which is what Denise is looking for. Though possibly I am missing something... Kent From pierre.barbier at cirad.fr Mon Jul 4 16:40:10 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon, 04 Jul 2005 16:40:10 +0200 Subject: [Tutor] How do I make Python calculate square roots? In-Reply-To: References: Message-ID: <42C94A4A.8020701@cirad.fr> Or, you can use: complex(-1)**0.5 However the result is strange ... >>> complex(-1)**0.5 (6.1230317691118863e-17+1j) Pierre Danny Yoo a ?crit : > > On Sat, 2 Jul 2005, Reed L. O'Brien wrote: > > >>> Does anyone know how to make Python calculate square roots? >>> >> >>Raise to the 1/2 power. >> >> >>>>>4**.5 >> >>2.0 >> >>>>>16**.5 >> >>4.0 >> >>>>>81**.5 >> >>9.0 > > > > By the way, if you need to take the square roots of negative numbers, then > the 'sqrt' function in the cmath module should do the trick: > > ###### > >>>>(-1)**0.5 > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: negative number cannot be raised to a fractional power > >>>>import cmath >>>>cmath.sqrt(-1) > > 1j > ###### > > > Best of wishes! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From dyoo at hkn.eecs.berkeley.edu Mon Jul 4 23:10:14 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 4 Jul 2005 14:10:14 -0700 (PDT) Subject: [Tutor] update (fwd) Message-ID: ---------- Forwarded message ---------- Date: Mon, 04 Jul 2005 12:55:45 -0700 From: nephish To: Danny Yoo Subject: update Hey, i did what you said, added print lines to debug my line_finder function, and it was finding everythin ok, just iterating through the loop one too many times. so last time returns None. thanks for the tips, shawn <>< From falcon3166 at hotmail.com Mon Jul 4 23:55:05 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 4 Jul 2005 15:55:05 -0600 Subject: [Tutor] Is there a way to combine a request for numbers and letters? Message-ID: Hi all, Is there a way to combine a request for numbers and letters (e.g. user id and passwords)? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050704/fca86477/attachment.htm From falcon3166 at hotmail.com Tue Jul 5 00:48:49 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 4 Jul 2005 16:48:49 -0600 Subject: [Tutor] Is there a way to combine a request for numbers and letters? References: Message-ID: Sorry, Just remembered that strings can include both letters and numbers. Case closed. Nathan Pinno Crew, McDonalds Restaurant, Camrose, AB Canada http://www.npinnowebsite.ca/ ----- Original Message ----- From: Nathan Pinno To: tutor at python.org Sent: Monday, July 04, 2005 3:55 PM Subject: [Tutor] Is there a way to combine a request for numbers and letters? Hi all, Is there a way to combine a request for numbers and letters (e.g. user id and passwords)? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ ---------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050704/4bb8c9f6/attachment.htm From falcon3166 at hotmail.com Tue Jul 5 02:30:28 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 4 Jul 2005 18:30:28 -0600 Subject: [Tutor] What's wrong with this code? Message-ID: What's wrong with this code? I'm using 2.2.3 if this helps. #This is for a password protected program to store passwords. password = "hello" print "The Password Program" print "Copywrite 2005. All Rights Reserved." print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Save login list" print "6) Open Login list" print "9) Exit" def load_login(site,filename): in_file = open(filename,"r") while 1: in_line = in_file.readline() if len(in_file) == 0: break in_line = in_line[:-1] [site,id,passcard] = string.split(in_line,",") list[site] = id and passcard in_file.close() def save_login(site,filename): out_file = open(filename,"w") for x in site.keys(): out_file.write(x+","+sites[x]+"\n") out_file.close() menu_choice = 0 list = {} print "Welcome to the second half of the program." print main_menu() while menu_choice != 9: menu_choice = input("Choose an option: ") if menu_choice == 1: print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") list[site] = id and passcard elif menu_choice == 2: print "Lookup a login info card" site = raw_input("Site: ") if site.has_key(site): print "The ID is: ",id(site) print "The password is: ",passcard(site) else: print site," was not found." elif menu_choice == 3: print "Remove a login info card" site = raw_input("Site: ") if sites.has_key(site): del numbers[site] else: print site," was not found." elif menu_choice == 4: print "Login Info" for x in site.keys(): print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] print elif menu_choice == 5: filename = raw_input("Filename to save: ") save_login(list,filename) elif menu_choice == 6: filename == raw_input("Filename to load: ") load_login(list,filename) print "Have a nice day!" Thanks, Nathan Pinno Crew, McDonalds Restaurant, Camrose, AB Canada http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050704/d331c3db/attachment-0001.htm From cyresse at gmail.com Tue Jul 5 03:41:52 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 5 Jul 2005 13:41:52 +1200 Subject: [Tutor] I sure do love cookies. In-Reply-To: <200507041302.j64D2nof029473@outbound1.mail.tds.net> References: <200507041302.j64D2nof029473@outbound1.mail.tds.net> Message-ID: Hi, Denise, if you're handling cookies client side, then this is how to do it (code snippets taken from http://www.voidspace.org.uk/python/articles/cookielib.shtml as I'm at work.) import os.path import urllib2 import cookielib COOKIEFILE = 'cookies.lwp' # the path and filename to save your cookies in urlopen = urllib2.urlopen Request = urllib2.Request cj = cookielib.LWPCookieJar() # This is a subclass of FileCookieJar # that has useful load and save methods if os.path.isfile(COOKIEFILE): # if we have a cookie file already saved # then load the cookies into the Cookie Jar cj.load(COOKIEFILE) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) #The above two lines initialise a opener which can handle cookies, and will use our cookie jar theurl = 'http://www.google.co.uk/search?hl=en&ie=UTF-8&q=voidspace&meta=' # an example url that sets a cookie, # try different urls here and see the cookie collection you can make ! txdata = None # if we were making a POST type request, # we could encode a dictionary of values here, # using urllib.urlencode(somedict) txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' } # fake a user agent, some websites (like google) don't like automated exploration try: req = Request(theurl, txdata, txheaders) # create a request object handle = urlopen(req) # and open it to return a handle on the url except IOError, e: print 'We failed to open "%s".' % theurl if hasattr(e, 'code'): print 'We failed with error code - %s.' % e.code elif hasattr(e, 'reason'): print "The error object has the following 'reason' attribute :" print e.reason print "This usually means the server doesn't exist,', print "is down, or we don't have an internet connection." sys.exit() else: print 'Here are the headers of the page :' print handle.info() # handle.read() returns the page # handle.geturl() returns the true url of the page fetched # (in case urlopen has followed any redirects, which it sometimes does) print if cj is None: print "We don't have a cookie library available - sorry." print "I can't show you any cookies." else: print 'These are the cookies we have received so far :' for index, cookie in enumerate(cj): print index, ' : ', cookie cj.save(COOKIEFILE) ----- Phew! A bit of code, but that shows a simple usage(!) of it. Good luck. On 7/5/05, Kent Johnson wrote: > > Danny Yoo wrote: > > To make cookies, in the examples of the Cookie module will probably help > > the most: > > > > http://www.python.org/doc/lib/cookie-example.html > > > >>From the documentation, it sounds like Cookie.SimpleCookie is what > you're > > looking for: > > My understanding is that the Cookie module is for server-side cookie > handling. cookielib.Cookie integrates with cookielib.CookieJar for > client-side cookie handling which is what Denise is looking for. Though > possibly I am missing something... > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050705/d2398db2/attachment.htm From cyresse at gmail.com Tue Jul 5 03:45:11 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 5 Jul 2005 13:45:11 +1200 Subject: [Tutor] What's wrong with this code? In-Reply-To: References: Message-ID: What error messages are you getting? Please post the full message. On 7/5/05, Nathan Pinno wrote: > > What's wrong with this code? I'm using 2.2.3 if this helps. > #This is for a password protected program to store passwords. > password = "hello" > print "The Password Program" > print "Copywrite 2005. All Rights Reserved." > print > answer = raw_input("What is the password? ") > while password != answer: > print "The password is incorrect." > def main_menu(): > print "1) Add a login info card" > print "2) Lookup a login info card" > print "3) Remove a login info card" > print "4) Print Login info list" > print "5) Save login list" > print "6) Open Login list" > print "9) Exit" > def load_login(site,filename): > in_file = open(filename,"r") > while 1: > in_line = in_file.readline() > if len(in_file) == 0: > break > in_line = in_line[:-1] > [site,id,passcard] = string.split(in_line,",") > list[site] = id and passcard > in_file.close() > > def save_login(site,filename): > out_file = open(filename,"w") > for x in site.keys(): > out_file.write(x+","+sites[x]+"\n") > out_file.close() > > menu_choice = 0 > list = {} > print "Welcome to the second half of the program." > print main_menu() > while menu_choice != 9: > menu_choice = input("Choose an option: ") > if menu_choice == 1: > print "Add a login info card" > site = raw_input("Site: ") > id = raw_input("User ID: ") > passcard = raw_input("Password: ") > list[site] = id and passcard > elif menu_choice == 2: > print "Lookup a login info card" > site = raw_input("Site: ") > if site.has_key(site): > print "The ID is: ",id(site) > print "The password is: ",passcard(site) > else: > print site," was not found." > elif menu_choice == 3: > print "Remove a login info card" > site = raw_input("Site: ") > if sites.has_key(site): > del numbers[site] > else: > print site," was not found." > elif menu_choice == 4: > print "Login Info" > for x in site.keys(): > print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] > print > elif menu_choice == 5: > filename = raw_input("Filename to save: ") > save_login(list,filename) > elif menu_choice == 6: > filename == raw_input("Filename to load: ") > load_login(list,filename) > print "Have a nice day!" > Thanks, > Nathan Pinno > Crew, McDonalds Restaurant, Camrose, AB Canada > http://www.npinnowebsite.ca/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050705/596dcee6/attachment.htm From cyresse at gmail.com Tue Jul 5 03:52:46 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 5 Jul 2005 13:52:46 +1200 Subject: [Tutor] What's wrong with this code? In-Reply-To: References: Message-ID: Also - menu_choice = input("Choose an option: ") input() is always bad. Use int(raw_input(""Choose an option: ")) instead. input() evaluates your input as a Python expression - I could select 9 by entering 5+4 or, I could enter sys.exit() and drop to DOS (or whatever it's running on.) or far more malicious code, like deleting everything on C: drive list[site] = id and passcard I'm not sure if that's real or a comment. Possibly you meant list[site] = id + passcard ? ...Or, it could be this - if site.has_key(site): print "The ID is: ",id(site) print "The password is: ",passcard(site) id(site) - if you have functions called id and passcard, I can't see them, if id and passcard are collections (list/dictionary) I can't see them. If they are functions, id() is a builtin Python function. If they are collections, then the correct way to access member items is to use id[site] or passcard[site]. But, now I'm guessing. Please post error message. And, if you need to post code, please post all relevant code, I recommend http://www.rafb.net/paste/to have it formatted nicely and even colour coded. Regards, Liam Clarke On 7/5/05, Liam Clarke wrote: > > What error messages are you getting? Please post the full message. > > On 7/5/05, Nathan Pinno wrote: > > > What's wrong with this code? I'm using 2.2.3 if this helps. > > #This is for a password protected program to store passwords. > > password = "hello" > > print "The Password Program" > > print "Copywrite 2005. All Rights Reserved." > > print > > answer = raw_input("What is the password? ") > > while password != answer: > > print "The password is incorrect." > > def main_menu(): > > print "1) Add a login info card" > > print "2) Lookup a login info card" > > print "3) Remove a login info card" > > print "4) Print Login info list" > > print "5) Save login list" > > print "6) Open Login list" > > print "9) Exit" > > def load_login(site,filename): > > in_file = open(filename,"r") > > while 1: > > in_line = in_file.readline() > > if len(in_file) == 0: > > break > > in_line = in_line[:-1] > > [site,id,passcard] = string.split(in_line,",") > > list[site] = id and passcard > > in_file.close() > > > > def save_login(site,filename): > > out_file = open(filename,"w") > > for x in site.keys(): > > out_file.write(x+","+sites[x]+"\n") > > out_file.close() > > > > menu_choice = 0 > > list = {} > > print "Welcome to the second half of the program." > > print main_menu() > > while menu_choice != 9: > > menu_choice = input("Choose an option: ") > > if menu_choice == 1: > > print "Add a login info card" > > site = raw_input("Site: ") > > id = raw_input("User ID: ") > > passcard = raw_input("Password: ") > > list[site] = id and passcard > > elif menu_choice == 2: > > print "Lookup a login info card" > > site = raw_input("Site: ") > > if site.has_key(site): > > print "The ID is: ",id(site) > > print "The password is: ",passcard(site) > > else: > > print site," was not found." > > elif menu_choice == 3: > > print "Remove a login info card" > > site = raw_input("Site: ") > > if sites.has_key(site): > > del numbers[site] > > else: > > print site," was not found." > > elif menu_choice == 4: > > print "Login Info" > > for x in site.keys(): > > print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] > > print > > elif menu_choice == 5: > > filename = raw_input("Filename to save: ") > > save_login(list,filename) > > elif menu_choice == 6: > > filename == raw_input("Filename to load: ") > > load_login(list,filename) > > print "Have a nice day!" > > Thanks, > > Nathan Pinno > > Crew, McDonalds Restaurant, Camrose, AB Canada > > http://www.npinnowebsite.ca/ > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050705/bffd8a95/attachment-0001.htm From andreengels at gmail.com Tue Jul 5 08:44:50 2005 From: andreengels at gmail.com (Andre Engels) Date: Tue, 5 Jul 2005 08:44:50 +0200 Subject: [Tutor] What's wrong with this code? In-Reply-To: <6faf39c905070423445b8d263f@mail.gmail.com> References: <6faf39c905070423445b8d263f@mail.gmail.com> Message-ID: <6faf39c9050704234457994d3f@mail.gmail.com> >From the program:: answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." If the user submits a wrong password, the while-loop will be entered. The program prints "The password is incorrect." then tests whether the password is still not equal to the answer, prints "The password is incorrect." again, etcetera. I think you intended to make it so that the program kept asking for passwords until the right one was given. This is done with: answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") Apart from this, I would like to ask you and anyone else who submits a question: Do NOT just say there's something wrong with your code, say WHAT is going wrong. That is, say "if I run this program (with this-and-that input if that's important), I would expect to get such-and-such, but I get so-and-so instead." Andre Engels On 7/5/05, Nathan Pinno wrote: > > > What's wrong with this code? I'm using 2.2.3 if this helps. > > #This is for a password protected program to store passwords. > password = "hello" > print "The Password Program" > print "Copywrite 2005. All Rights Reserved." > print > answer = raw_input("What is the password? ") > while password != answer: > print "The password is incorrect." > def main_menu(): > print "1) Add a login info card" > print "2) Lookup a login info card" > print "3) Remove a login info card" > print "4) Print Login info list" > print "5) Save login list" > print "6) Open Login list" > print "9) Exit" > > def load_login(site,filename): > in_file = open(filename,"r") > while 1: > in_line = in_file.readline() > if len(in_file) == 0: > break > in_line = in_line[:-1] > [site,id,passcard] = string.split(in_line,",") > list[site] = id and passcard > in_file.close() > > def save_login(site,filename): > out_file = open(filename,"w") > for x in site.keys(): > out_file.write(x+","+sites[x]+"\n") > out_file.close() > > menu_choice = 0 > list = {} > print "Welcome to the second half of the program." > print main_menu() > while menu_choice != 9: > menu_choice = input("Choose an option: ") > if menu_choice == 1: > print "Add a login info card" > site = raw_input("Site: ") > id = raw_input("User ID: ") > passcard = raw_input("Password: ") > list[site] = id and passcard > elif menu_choice == 2: > print "Lookup a login info card" > site = raw_input("Site: ") > if site.has_key(site): > print "The ID is: ",id(site) > print "The password is: ",passcard(site) > else: > print site," was not found." > elif menu_choice == 3: > print "Remove a login info card" > site = raw_input("Site: ") > if sites.has_key(site): > del numbers[site] > else: > print site," was not found." > elif menu_choice == 4: > print "Login Info" > for x in site.keys(): > print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] > print > elif menu_choice == 5: > filename = raw_input("Filename to save: ") > save_login(list,filename) > elif menu_choice == 6: > filename == raw_input("Filename to load: ") > load_login(list,filename) > print "Have a nice day!" > > Thanks, > Nathan Pinno > Crew, McDonalds Restaurant, Camrose, AB Canada > http://www.npinnowebsite.ca/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From flamesrock at gmail.com Tue Jul 5 08:56:43 2005 From: flamesrock at gmail.com (Aaron Elbaz) Date: Tue, 5 Jul 2005 06:56:43 +0000 Subject: [Tutor] HELP: wxPython, adding items to combo box? Message-ID: <2c2812b6050704235658e8acc6@mail.gmail.com> The simplest way I can explain this: I have a settings wxPython settings dialog, which contains a 'servers' combo box. I also have a shelf object that 'remembers' values entered into the ComboBox. The current value is stored as shelf['SERVER'] and the old values are kept in a list at shelf['OLD_SERVERS']. The idea is to keep a history of all servers entered into the combo box. So when you click apply changes: def save_settings(self): d = shelve.open(self.SETTINGS_FILE) if d.has_key('SERVER') and d.has_key('OLD_SERVER') and \ d['SERVER'] != self.server_combo_box.GetValue(): d['OLD_SERVER'].append(d['SERVER']) d['SERVER'] = self.server_combo_box.GetValue() else: d['OLD_SERVER'] = [self.server_combo_box.GetValue()] d['SERVER'] = self.server_combo_box.GetValue() d.close() def on_apply_changes(self, event): self.save_settings() When I load the settings dialog, it should execute: def __set_properties(self): # begin wxGlade: SettingsDialog.__set_properties self.SetTitle("SimNet Settings") self.server_combo_box.SetSelection(0) # end wxGlade if os.path.exists(self.SETTINGS_FILE): d = shelve.open(self.SETTINGS_FILE) self.server_combo_box.SetString(1,d['SERVER']) self.server_combo_box.SetString(2,d['SERVER']) if d.has_key('OLD_SERVER'): counter = 2 for x in d['OLD_SERVER']: if x != d['SERVER']: self.server_combo_box.SetString(counter,x) counter = counter + 1 d.close() Causing the 'history' of old servers to load at position 'counter'. Only, this isn't working! Am I doing something wrong or have I discovered some sort of bug in wxPython (2.6.0)? -thanks -- A man convinced against his will is still of the same opinion -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050705/8fdfc889/attachment.htm From bvande at po-box.mcgill.ca Tue Jul 5 09:03:16 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 05 Jul 2005 03:03:16 -0400 Subject: [Tutor] What's wrong with this code? In-Reply-To: <6faf39c9050704234457994d3f@mail.gmail.com> References: <6faf39c905070423445b8d263f@mail.gmail.com> <6faf39c9050704234457994d3f@mail.gmail.com> Message-ID: <42CA30B4.3070402@po-box.mcgill.ca> Andre Engels said unto the world upon 05/07/2005 02:44: >>From the program:: > > answer = raw_input("What is the password? ") > while password != answer: > print "The password is incorrect." > I think you intended to make it so that > the program kept asking for passwords until the right one was given. > This is done with: > answer = raw_input("What is the password? ") > while password != answer: > print "The password is incorrect." > answer = raw_input("What is the password? ") A small thing, but I think that is better as: while True: answer = raw_input("What is the password? ") if password == answer: break print "The password is incorrect." It probably runs a bit slower, but who cares, as the bottleneck is in the chair, not the chip. The advantage is that there is only one statement of the prompt to alter if you wanted to change it later. But, I think this will be one where reasonable people can differ. Andre's version does make the semantics of the loop somewhat more obvious. Best to all, Brian vdB > Andre Engels From gordnjen at rogers.com Tue Jul 5 04:24:43 2005 From: gordnjen at rogers.com (gordnjen) Date: Mon, 4 Jul 2005 22:24:43 -0400 Subject: [Tutor] "And" function Message-ID: <008301c58108$b492acc0$a471c545@JennineGord> I need to write a program that will do the following: Ask the user's age. If their age is below 1 yr old, it prints "you are old enought to eat baby food" If they are over 16, it prints "You are old enough to drive" If they are over 65, it prints "You are old enough to drive" and "You are old enough to retire" If they are between the ages of 16 and 25, it prints "you are old enough to get a student discount". So far, I have this: age =int(raw_input("How old are you?")) if age>16: print "You are old enough to drive!" if age>65: print "You are old enough to retire!" if age<1: print "You are old enough to eat baby food!" I get stuck with the old enough to get a student discount part. I have tried if age>16 and age<25: print "You are old enough to get a student discount" But it doesn't seem to work. Any help would be great. Thanks! Jennine -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.8.9/39 - Release Date: 04/07/2005 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050704/9462b1d1/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 9749 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050704/9462b1d1/attachment-0001.gif -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 17147 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050704/9462b1d1/attachment-0001.jpeg From bvande at po-box.mcgill.ca Tue Jul 5 10:11:03 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 05 Jul 2005 04:11:03 -0400 Subject: [Tutor] "And" function In-Reply-To: <008301c58108$b492acc0$a471c545@JennineGord> References: <008301c58108$b492acc0$a471c545@JennineGord> Message-ID: <42CA4097.8090401@po-box.mcgill.ca> gordnjen said unto the world upon 04/07/2005 22:24: > I need to write a program that will do the following: > > Ask the user's age. > If their age is below 1 yr old, it prints "you are old enought to eat baby > food" > If they are over 16, it prints "You are old enough to drive" > If they are over 65, it prints "You are old enough to drive" and "You are > old enough to retire" > > If they are between the ages of 16 and 25, it prints "you are old enough to > get a student discount". Hi Jennine, > So far, I have this: > > age =int(raw_input("How old are you?")) > if age>16: > print "You are old enough to drive!" > if age>65: > print "You are old enough to retire!" > if age<1: > print "You are old enough to eat baby food!" And this works? Is it your actual code? I ask as it seems to me as though if age = 0.5, age > 16 will evaluate as False, and the flow will never get to if age < 1. > I get stuck with the old enough to get a student discount part. I have tried > > if age>16 and age<25: > print "You are old enough to get a student discount" > > But it doesn't seem to work. Can you define "doesn't work"? Did you get a syntax error? Or just not the behaviour you expected? Unless your fancy html mail (please don't do that when posting here, by the way) stripped the indents, the problem is you didn't indent your print statement into the if block. Witness: >>> num = 97 >>> if num > 10 and num < 30: ... print "In the range" ... >>> num = 20 >>> if num > 10 and num < 30: ... print "In the range" ... In the range >>> Even better is: >>> if 10 < num < 30: ... print "Still there" ... Still there >>> HTH, Brian vdB From geon at post.cz Tue Jul 5 10:21:35 2005 From: geon at post.cz (geon) Date: Tue, 05 Jul 2005 10:21:35 +0200 Subject: [Tutor] "And" function In-Reply-To: <008301c58108$b492acc0$a471c545@JennineGord> References: <008301c58108$b492acc0$a471c545@JennineGord> Message-ID: <42CA430F.70400@post.cz> gordnjen napsal(a): > I need to write a program that will do the following: > > Ask the user's age. > If their age is below 1 yr old, it prints "you are old enought to eat > baby food" > If they are over 16, it prints "You are old enough to drive" > If they are over 65, it prints "You are old enough to drive" and "You > are old enough to retire" > > If they are between the ages of 16 and 25, it prints "you are old > enough to get a student discount". > > So far, I have this: what about this: > > age =input("How old are you?") > if age>16: > print "You are old enough to drive!" > if age>65: > print "You are old enough to retire!" > if age<1: > print "You are old enough to eat baby food!" > > If's those are on the same logical level should be also on the same vertical level :-) Pavel -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050705/1852ec04/attachment.htm From max_russell2000 at yahoo.co.uk Tue Jul 5 13:05:45 2005 From: max_russell2000 at yahoo.co.uk (Max Russell) Date: Tue, 5 Jul 2005 12:05:45 +0100 (BST) Subject: [Tutor] Initialising attributes with random values Message-ID: <20050705110545.94735.qmail@web25403.mail.ukl.yahoo.com> Hello there; If I have a class and want to initalise it, with random values assigned to the attributes, what is the best way of doing this? For example: def __init__(self, name, size = 0, strength = 0): self.name = name self.size = size self.strength = strength starts with values of 0. But how can I neatly say, start with a random value from (for example) 1 - 5? thanks Max ___________________________________________________________ How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com From ajikoe at gmail.com Tue Jul 5 13:54:14 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 5 Jul 2005 13:54:14 +0200 Subject: [Tutor] Initialising attributes with random values In-Reply-To: <20050705110545.94735.qmail@web25403.mail.ukl.yahoo.com> References: <20050705110545.94735.qmail@web25403.mail.ukl.yahoo.com> Message-ID: use : random.randint(1,5) so complete code will be: class something: def __init__(self, name): self.name = name self.size = random.randint(1,5) self.strength = random.randint(1,5) pujo On 7/5/05, Max Russell wrote: > Hello there; > > If I have a class and want to initalise it, with > random values assigned to the attributes, what is the > best way of doing this? > > For example: > > def __init__(self, name, size = 0, strength = 0): > self.name = name > self.size = size > self.strength = strength > > starts with values of 0. But how can I neatly say, > start with a random value from (for example) 1 - 5? > > thanks > Max > > > > ___________________________________________________________ > How much free photo storage do you get? Store your holiday > snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From johan at accesstel.co.za Tue Jul 5 15:30:33 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue, 05 Jul 2005 15:30:33 +0200 Subject: [Tutor] more() method of asynchat Message-ID: <1120570233.4788.68.camel@KMA.accesstel> Hi all, I am trying to use the asynchat and asyncore modules in the documentation it says that one must create the producers (connection) own more() method. What does this do and do I need to have it? Thanks, Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050705/54b4c0b0/attachment.htm From mac at Wireless.Com Tue Jul 5 12:38:03 2005 From: mac at Wireless.Com (Mike Cheponis) Date: Tue, 5 Jul 2005 03:38:03 -0700 (PDT) Subject: [Tutor] Case ? Message-ID: Why does Python not have a "case" statement, like C? Thanks! -Mike From dyoo at hkn.eecs.berkeley.edu Tue Jul 5 19:38:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 5 Jul 2005 10:38:44 -0700 (PDT) Subject: [Tutor] Case ? In-Reply-To: Message-ID: On Tue, 5 Jul 2005, Mike Cheponis wrote: > Why does Python not have a "case" statement, like C? Hi Mike, It's a proposed enhancement: http://www.python.org/peps/pep-0275.html That being said, a dispatch-table approach, using a dictionary, works well in Python because it's not hard to use functions as values --- most people haven't really missed case/switch statements in Python because dispatch tables can be very effective. For example, something like this: ### C ### switch(state) { case STATE_1: doStateOneStuff(); break; case STATE_2: doStateTwoStuff(); break; case STATE_3: doStateThreeStuff(); break; default: doDefaultAction(); ###### has a natural translation into Python as: ### Python ### dispatchTable = { STATE_1: doStateOneStuff, STATE_2: doStateTwoStuff, STATE_3: doStateThreeStuff } command = dispatchTable.get(state, doDefaultAction) command() ###### where we're essentially mimicking the jump table that a case/switch statement produces underneath the surface. One other consideration about C's case/switch statement is its bug-proneness: it's all too easy to programmers to accidently forget to put 'break' in appropriate places in there. Hope this helps! From denise.hartley at gmail.com Tue Jul 5 21:07:37 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 5 Jul 2005 12:07:37 -0700 Subject: [Tutor] I sure do love cookies. In-Reply-To: References: <200507041302.j64D2nof029473@outbound1.mail.tds.net> Message-ID: <8daabe56050705120720987b46@mail.gmail.com> Thank you for the code, everyone. I actually have a piece of information (something like "this+is+a+cookie") that I am trying to *send* (not receive), and I'm not sure how to do it. I looked at the Cookie examples a little bit, but am having trouble applying what I see there to my present situation, since there is so much that either a). doesnt apply or b). is over my head (usually c). all of the above!). Although the client-side illustration you provided was very clear and I'll archive that for future use, too. So, for *sending* cookies, it seems that I would want to create one this way: ###### >>> import Cookie >>> mycookie = Cookie.SimpleCookie() >>> mycookie['value'] = 'this+is+a+cookie' >>> >>> mycookie >>> >>> print mycookie Set-Cookie: value=this+is+a+cookie; ###### But then what? How do I send this anywhere? Right now it seems to be just a thing sitting in my python screen, and not something that actually does anything. If I have correctly created a cookie (have I?), what do I do with it now? Thanks, Denise On 7/4/05, Liam Clarke wrote: > Hi, > > Denise, if you're handling cookies client side, then this is how to do it > (code snippets taken from > http://www.voidspace.org.uk/python/articles/cookielib.shtml > as I'm at work.) > > import os.path > import urllib2 > import cookielib > > > COOKIEFILE = 'cookies.lwp' > # the path and filename to save your cookies in > > urlopen = urllib2.urlopen > Request = urllib2.Request > cj = cookielib.LWPCookieJar( ) > # This is a subclass of FileCookieJar > # that has useful load and save methods > > if os.path.isfile (COOKIEFILE): > # if we have a cookie file already saved > # then load the cookies into the Cookie Jar > cj .load(COOKIEFILE) > > opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > #The above two lines initialise a opener which can handle cookies, and will > use our cookie jar > > theurl = > 'http://www.google.co.uk/search?hl=en&ie=UTF-8&q=voidspace&meta= > ' > # an example url that sets a cookie, > # try different urls here and see the cookie collection you can make ! > > txdata = None > # if we were making a POST type request, > # we could encode a dictionary of values here, > # using urllib.urlencode(somedict) > > txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows > NT)'} > # fake a user agent, some websites (like google) don't like automated > exploration > > try: > req = Request(theurl, txdata, txheaders) > # create a request object > > handle = urlopen(req) > # and open it to return a handle on the url > > except IOError, e: > print 'We failed to open "%s".' % theurl > if hasattr(e, 'code' ): > print 'We failed with error code - %s.' % e. code > elif hasattr(e, 'reason' ): > print "The error object has the following 'reason' attribute :" > print e.reason > print "This usually means the server doesn't exist,', > print "is down, or we don't have an internet connection." > sys.exit() > > else: > print 'Here are the headers of the page :' > print handle.info() > # handle.read() returns the page > # handle.geturl() returns the true url of the page fetched > # (in case urlopen has followed any redirects, which it sometimes does) > > print > if cj is None: > print "We don't have a cookie library available - sorry." > print "I can't show you any cookies." > else: > print 'These are the cookies we have received so far :' > for index, cookie in enumerate (cj): > print index, ' : ', cookie > cj.save(COOKIEFILE) > > > > ----- > > Phew! A bit of code, but that shows a simple usage(!) of it. > > Good luck. > > > On 7/5/05, Kent Johnson wrote: > > Danny Yoo wrote: > > > To make cookies, in the examples of the Cookie module will probably help > > > the most: > > > > > > http://www.python.org/doc/lib/cookie-example.html > > > > > >>From the documentation, it sounds like Cookie.SimpleCookie is what > you're > > > looking for: > > > > My understanding is that the Cookie module is for server-side cookie > handling. cookielib.Cookie integrates with cookielib.CookieJar for > client-side cookie handling which is what Denise is looking for. Though > possibly I am missing something... > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From gnumathetes at gmail.com Tue Jul 5 23:10:03 2005 From: gnumathetes at gmail.com (Don Parris) Date: Tue, 5 Jul 2005 17:10:03 -0400 Subject: [Tutor] Handling Unpickled Data Message-ID: <66926144050705141064b33ab1@mail.gmail.com> Greetings, I have a script that gets a little info from the user, using a dictionary, which I then store in a file via cPickle. This pickle concept must be good for something, but I haven't figured out exactly what just yet. At any rate, I would like to now get the code and be able to display only one value for the user. I thought I could do this by specifying a key in orginfo. However, the function throws all the data to stdout, not just the desired key. How can I limit the output to just the value of the key I want to reference? Do I need to create a for or while loop, or an if statement to say, "extract this key:value pair only"? I can also get this from a SQL query, but since I couldn't do it with a file, I wanted to try and figure it out. The book, "Learning Python" is very helpful, now that I have it, but it kind of breezed past this kind of thing. I really would like to understand how to work with the data in the text file. ### function def ### def org_Get_Info(): orgGdata = open('orgdata.txt', 'r') orginfo = cPickle.load(orgGdata), orgGdata.close() print orginfo['Name'] # this is really all I want. ### Output at DOS prompt ### Organization Name: ocf # Begin input Address: 6123 City: char State: nc Zip: 282 City : char # Begin output from org_Get_Info() State : nc Name : ocf Zip : 282 Address : 6123 ocf # this is all I want - not the rest. Thanks, Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com Free software is like God's love - you can share it with anyone anywhere anytime! From gnumathetes at gmail.com Wed Jul 6 00:17:31 2005 From: gnumathetes at gmail.com (Don Parris) Date: Tue, 5 Jul 2005 18:17:31 -0400 Subject: [Tutor] Handling Unpickled Data In-Reply-To: <66926144050705141064b33ab1@mail.gmail.com> References: <66926144050705141064b33ab1@mail.gmail.com> Message-ID: <6692614405070515173e068452@mail.gmail.com> On 7/5/05, Don Parris wrote: > Greetings, > > I have a script that gets a little info from the user, using a > dictionary, which I then store in a file via cPickle. This pickle > concept must be good for something, but I haven't figured out exactly > what just yet. At any rate, I would like to now get the code and be > able to display only one value for the user. > Never mind. I had set a print statement in the other function way back when, and did not think about that as I looked at my code. Duh! Yes, I'm a newbie. :) Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com Free software is like God's love - you can share it with anyone anywhere anytime! From kent37 at tds.net Wed Jul 6 01:21:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 5 Jul 2005 19:21:37 -0400 Subject: [Tutor] I sure do love cookies. Message-ID: <200507052321.j65NLb5H016498@outbound3.mail.tds.net> D. Hartley wrote: > Thank you for the code, everyone. > > I actually have a piece of information (something like > "this+is+a+cookie") that I am trying to *send* (not receive), and I'm > not sure how to do it. I looked at the Cookie examples a little bit, > but am having trouble applying what I see there to my present > situation, since there is so much that either a). doesnt apply or b). > is over my head (usually c). all of the above!). Although the > client-side illustration you provided was very clear and I'll archive > that for future use, too. Did you see the hint I posted a few days ago? I'll repeat it, if you want more detail then ask but after all it's supposed to be a challenge :-) What I did was, - create a new cookielib.Cookie - add the cookie to the CookieJar - make a request the same way as when I was collecting cookies To create the new Cookie it might help to look at the source for cookielib (Lib\cookielib.py), the Cookie constructor doesn't seem to be documented anywhere. To figure out the values for the Cookie constructor it might help to look at one of the cookies you already have. I could be wrong but I don't think Cookie.SimpleCookie is going to get you there. Kent From denise.hartley at gmail.com Wed Jul 6 01:35:58 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Tue, 5 Jul 2005 16:35:58 -0700 Subject: [Tutor] Fwd: A more Pythonic way to do this In-Reply-To: References: <8daabe5605063015111d32477a@mail.gmail.com> <002b01c57e5e$609fd400$8f5328cf@JSLAPTOP> <8daabe560507011058b30809b@mail.gmail.com> <42C5B888.6000708@po-box.mcgill.ca> <8daabe5605070115567afb6c39@mail.gmail.com> <42C5CC7D.4070705@po-box.mcgill.ca> <8daabe5605070117216b20c08a@mail.gmail.com> <8daabe56050705115964075b58@mail.gmail.com> Message-ID: <8daabe5605070516351857d85e@mail.gmail.com> This question began on the tutor mailing list, but I am now seeing that it is pygame-specific, so I am forwarding it here as well. I apologize if anyone gets a duplicate post. As it turns out, my "holder" classes are all subclasses of type RenderClear (which it says is "basic Group class you will want to use." My "group" was "enemyship_sprites," which I discovered could not be iterated over. However, if I used "enemyship_sprites.sprites()" instead, I *can* iterate over that - it creates a list of all the sprites in my group (according to the docs), so I could use this in len(enemyship_sprites.sprites()) to count the number of enemy ships I had on the screen and so on. So what I am trying to do is take all of the enemy ships left on the screen that have not been killed in this particular level (i.e., when one of them drops too low on the screen and kills the hero - a space invaders-style game), and reset it to its own starting position for that level. So I created variables in my Enemy class called initialx and initialy (given default values of 0 and then updated when the Enemy is actually drawn on screen), and when the bad guys drop down too low, I inserted this for loop: for each in (enemyship_sprites.sprites()): each.rect.centerx = Enemy.initialx each.rect.centery = Enemy.initialy Then I draw the enemyship_sprites like I always did. (Before, it just redrew ALL the enemies for that level, effectively restarting the level with a full screen of baddies. I want to take just the ones that havent been killed yet and return them to their original position). My problem at first was I was just doing for each in (enemyship_sprites): - which would not work because I can't iterate over it. Now apparently I *am* iterating over the list of sprites I have at this point (I think, if I am doing it correctly, it should be the list of enemies which has not yet been killed on this level), and should be returning each to its original starting position. Since I create initialx/initialy for each enemy when the screen full of enemies is drawn (and I know I do create a new initialx/initialy for each one - because I had it print the initialx, initialy when the screen was drawn and I get 40 sets of values printed for the 40 enemies on the screen), wouldnt each instance of the Enemy class store its own initialx initialy so that when I called each.rect.centerx = Enemy.initialx each.rect.centery = Enemy.initialy .. it would return each to its own starting position? Right now, it seems to be printing them all right on top of the other, in one enemy position. At first I thought I was redrawing only one enemy, but I shot it, and there seems to be another underneath it. A lot of others, actually. So I can't even see if it is drawing just the ones that havent been killed yet or a whole new batch. And, obviously, it's not relocating them correctly :P Am I understanding this wrong? Is it only storing the last-computed initialx/initialy and restoring all enemies there? Should I be using something other than pygame.sprite.RenderClear as my 'super group'? Am I going about this in the totally wrong way? Any pointers/suggestions/things to try would be appreciated! Thanks, Denise ---------- Forwarded message ---------- From: Adam Bark Date: Jul 5, 2005 3:58 PM Subject: Re: [Tutor] A more Pythonic way to do this To: "D. Hartley" I mean an actual group from pygame.sprite either Group or AbstractGroup. http://www.pygame.org/docs/ref/pygame_sprite.html#Group Check out the sprite tutorial for more info. On 7/5/05, D. Hartley wrote: > Actually, I *have* a holder superclass: but idle is telling me I cant > iterate over it. Is this a different kind of group? > Thanks, > Denise > > ---------- Forwarded message ---------- > From: Adam Bark < adam.jtm30 at gmail.com> > Date: Jul 2, 2005 6:39 AM > Subject: Re: [Tutor] A more Pythonic way to do this > To: "D. Hartley" > > > I haven't actually used this myself but if you check the pygame docs > you should be able to make a group and put all of the sprites in to > the group. It effectively creates a list of sprites which you will be > able to iterate over. > > > On 7/2/05, D. Hartley wrote: > > Also, I'm trying to figure out a way to do the following: > > > > If the enemies drop too low, right now it just takes away a life and > > redraws a screen full of enemies (effectively restarting the level). > > > > I'd like to make it so that if they drop too low and you die, it just > > takes those ones that you havent killed already and puts them back up > > in their original starting positions. I can figure out how to store > > that "initial position" data, but I dont know how to move the > > havent-yet-been-killed sprites back there: > > > > what i WANT to do is: > > > > for each in enemyship_sprites: > > each.rect.centerx = Enemy.initialx > > each.rect.centery = Enemy.initialy > > > > (I created initialx in the init of enemy and update it when i > > createEnemies at the beginning of the level) > > > > But I cant iterate over enemyship_sprites. > > > > Any ideas would be appreciated! > > > > ~Denise > > > > On 7/1/05, Brian van den Broek wrote: > > > D. Hartley said unto the world upon 01/07/2005 18:56: > > > > Ok, this copy should work! Let me know if it doesnt. > > > > ~Denise > > > > > > > > > > > > > > I had nothing attached nor in body other than the above. > > > > > > Best, > > > > > > Brian vdB > > > > > > > > > > > > From amonroe at columbus.rr.com Wed Jul 6 04:47:12 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 5 Jul 2005 22:47:12 -0400 Subject: [Tutor] [pygame] Fwd: A more Pythonic way to do this In-Reply-To: <8daabe5605070516351857d85e@mail.gmail.com> References: <8daabe5605063015111d32477a@mail.gmail.com> <002b01c57e5e$609fd400$8f5328cf@JSLAPTOP> <8daabe560507011058b30809b@mail.gmail.com> <42C5B888.6000708@po-box.mcgill.ca> <8daabe5605070115567afb6c39@mail.gmail.com> <42C5CC7D.4070705@po-box.mcgill.ca> <8daabe5605070117216b20c08a@mail.gmail.com> <8daabe56050705115964075b58@mail.gmail.com> <8daabe5605070516351857d85e@mail.gmail.com> Message-ID: <82118811491.20050705224712@columbus.rr.com> > should be returning each to its original starting position. Since I > create initialx/initialy for each enemy when the screen full of > enemies is drawn (and I know I do create a new initialx/initialy for > each one - because I had it print the initialx, initialy when the > screen was drawn and I get 40 sets of values printed for the 40 > enemies on the screen), wouldnt each instance of the Enemy class store > its own initialx initialy so that when I called > each.rect.centerx = Enemy.initialx > each.rect.centery = Enemy.initialy > .. it would return each to its own starting position? > Right now, it seems to be printing them all right on top of the other, > in one enemy position. At first I thought I was redrawing only one > enemy, but I shot it, and there seems to be another underneath it. A > lot of others, actually. So I can't even see if it is drawing just > the ones that havent been killed yet or a whole new batch. And, > obviously, it's not relocating them correctly :P Did you inadvertently set the initialx & initialy on a class-wide basis (within the class's definition), when you meant to set it on a per-instance basis (within each enemy one at a time)? Alan From cyresse at gmail.com Wed Jul 6 06:41:55 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 6 Jul 2005 16:41:55 +1200 Subject: [Tutor] I sure do love cookies. In-Reply-To: <200507052321.j65NLb5H016498@outbound3.mail.tds.net> References: <200507052321.j65NLb5H016498@outbound3.mail.tds.net> Message-ID: Denise - Create a cookie, save it, load it as a cookie jar (using cookielib), create an URLopener using urllib2 that uses the cookiejar, do your thing. Remember that sending a cookie/receiving a cookie client side is initiated by the server, so you just have to have the cookie present. The technical steps you'll have to puzzle out by reading docs for the two above mentioned libraries, but it shouldn't take you too long with the interactive prompt and an open web-browser to get the hang of it. Good luck. On 7/6/05, Kent Johnson wrote: > > D. Hartley wrote: > > Thank you for the code, everyone. > > > > I actually have a piece of information (something like > > "this+is+a+cookie") that I am trying to *send* (not receive), and I'm > > not sure how to do it. I looked at the Cookie examples a little bit, > > but am having trouble applying what I see there to my present > > situation, since there is so much that either a). doesnt apply or b). > > is over my head (usually c). all of the above!). Although the > > client-side illustration you provided was very clear and I'll archive > > that for future use, too. > > Did you see the hint I posted a few days ago? I'll repeat it, if you want > more detail then ask but after all it's supposed to be a challenge :-) > > What I did was, > - create a new cookielib.Cookie > - add the cookie to the CookieJar > - make a request the same way as when I was collecting cookies > > To create the new Cookie it might help to look at the source for cookielib > (Lib\cookielib.py), the Cookie constructor doesn't seem to be documented > anywhere. > > To figure out the values for the Cookie constructor it might help to look > at one of the cookies you already have. > > I could be wrong but I don't think Cookie.SimpleCookie is going to get you > there. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050706/bf9651f6/attachment.htm From cyresse at gmail.com Wed Jul 6 06:43:11 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed, 6 Jul 2005 16:43:11 +1200 Subject: [Tutor] Case ? In-Reply-To: References: Message-ID: Ah, the cascading broken case statement of doom. On 7/6/05, Danny Yoo wrote: > > > > On Tue, 5 Jul 2005, Mike Cheponis wrote: > > > Why does Python not have a "case" statement, like C? > > > Hi Mike, > > It's a proposed enhancement: > > http://www.python.org/peps/pep-0275.html > > > That being said, a dispatch-table approach, using a dictionary, works well > in Python because it's not hard to use functions as values --- most people > haven't really missed case/switch statements in Python because dispatch > tables can be very effective. > > > For example, something like this: > > ### C ### > switch(state) { > case STATE_1: doStateOneStuff(); > break; > case STATE_2: doStateTwoStuff(); > break; > case STATE_3: doStateThreeStuff(); > break; > default: doDefaultAction(); > ###### > > > has a natural translation into Python as: > > ### Python ### > dispatchTable = { STATE_1: doStateOneStuff, > STATE_2: doStateTwoStuff, > STATE_3: doStateThreeStuff } > command = dispatchTable.get(state, doDefaultAction) > command() > ###### > > where we're essentially mimicking the jump table that a case/switch > statement produces underneath the surface. > > > One other consideration about C's case/switch statement is its > bug-proneness: it's all too easy to programmers to accidently forget to > put 'break' in appropriate places in there. > > > Hope this helps! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050706/10b552c7/attachment.htm From ceplm at seznam.cz Wed Jul 6 10:04:26 2005 From: ceplm at seznam.cz (Matej Cepl) Date: Wed, 06 Jul 2005 10:04:26 +0200 Subject: [Tutor] Uncertain about exceptions Message-ID: Hi, I have here two Python modules (see attached), where newsparser.py defines (among other things) an object SoupReader and an exception PageNotAvailable. This object (or its children) is then periodically created in a loop in reprocess.py. Now, my question is concerned with the use of exception in SoupReader.suck. The idea is that when the page is not available for download, whole object goes up in flames, the rest of SoapReader.__init__ is skipped over, and the exception is then caught in reprocess.py cycle, which makes a note in some errorlog, that this particular page has not been downloaded, but otherwise the script continues for other pages. Is it what I am doing here or did I missed the idea of exceptions at all? Thanks for any answer, Matej -- Matej Cepl, http://www.ceplovi.cz/matej/blog/ GPG Finger: 89EF 4BC6 288A BF43 1BAB 25C3 E09F EF25 D964 84AC I used to date a woman who did PR and marketing for MS, so you can imagine we had some in-depth and sometimes heated discussions about MS vs. Linux and Macs. Well, one day we were going hiking, and she presented me with a really nice backback. The only issue with it was that it had the MS logo emblazoned all over it. Of course, she knew I wouldn't refuse it. Anyway, she said to me, "Isn't that nice? See? What'd RedHat ever give you for free?" I replied, "An operating system." That was one long, quiet hike. -- disserto on Slashdot http://slashdot.org/comments.pl\ ?sid=138492&tid=109&mode=thread&cid=11590292 -------------- next part -------------- A non-text attachment was scrubbed... Name: newsparser.py Type: application/x-python Size: 13349 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050706/765acc21/newsparser.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: reprocess.py Type: application/x-python Size: 2031 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050706/765acc21/reprocess.bin From kent37 at tds.net Wed Jul 6 14:27:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 6 Jul 2005 8:27:07 -0400 Subject: [Tutor] Uncertain about exceptions Message-ID: <200507061227.j66CR7WQ029343@outbound3.mail.tds.net> Matej Cepl wrote: > Now, my question is concerned with the use of exception in SoupReader.suck. > The idea is that when the page is not available for download, whole object > goes up in flames, the rest of SoapReader.__init__ is skipped over, and the > exception is then caught in reprocess.py cycle, which makes a note in some > errorlog, that this particular page has not been downloaded, but otherwise > the script continues for other pages. Is it what I am doing here or did I > missed the idea of exceptions at all? After a quick look I think you have it right. You could define PageNotAvailable as class PageNotAvailable(Exception): pass because the behavior you give it is the default behaviour for Exception. Kent From mumke at xs4all.nl Wed Jul 6 15:20:37 2005 From: mumke at xs4all.nl (christinA) Date: Wed, 06 Jul 2005 15:20:37 +0200 Subject: [Tutor] Is there a way to combine a request for numbers and letters? In-Reply-To: Message-ID: <42CBF6C5.11012.133314B@localhost> Please will you find out why the score on your mails are that high? My ISP is sending them directly to my spambox. For your convenience I copied the headers. Especially 0.8 MSGID_FROM_MTA_HEADER Message-Id was added by a relay 2.2 RCVD_IN_BL_SPAMCOP_NET Received via a relay in bl.spamcop.net seems to ring the bell. christinA Return-Path: Received: from smtp-vbr12.xs4all.nl (smtp-vbr12.xs4all.nl [194.109.24.32]) by mxdrop3.xs4all.nl (8.13.3/8.13.3) with ESMTP id j64Mnm3T005860 for ; Tue, 5 Jul 2005 00:49:48 +0200 (CEST) (envelope-from tutor-bounces+mumke=xs4all.nl at python.org) Received: from bag.python.org (bag.python.org [194.109.207.14]) by smtp-vbr12.xs4all.nl (8.13.3/8.13.3) with ESMTP id j64MnlLQ079469 for ; Tue, 5 Jul 2005 00:49:47 +0200 (CEST) (envelope-from tutor-bounces+mumke=xs4all.nl at python.org) Received: from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with ESMTP id 4D96F1E4006 for ; Tue, 5 Jul 2005 00:49:50 +0200 (CEST) X-Original-To: tutor at python.org Delivered-To: tutor at bag.python.org Received: from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with ESMTP id 9DB211E4004 for ; Tue, 5 Jul 2005 00:49:00 +0200 (CEST) X-Spam-Status: OK 0.000 Received: from bag (HELO bag.python.org) (127.0.0.1) by bag.python.org with SMTP; 05 Jul 2005 00:49:00 +0200 Received: from hotmail.com (unknown [65.54.161.89]) by bag.python.org (Postfix) with ESMTP for ; Tue, 5 Jul 2005 00:48:59 +0200 (CEST) Received: from mail pickup service by hotmail.com with Microsoft SMTPSVC; Mon, 4 Jul 2005 15:48:56 -0700 Message-ID: Received: from 65.54.161.201 by BAY106-DAV17.phx.gbl with DAV; Mon, 04 Jul 2005 22:48:55 +0000 X-Originating-IP: [65.54.161.201] X-Originating-Email: [falcon3166 at hotmail.com] X-Sender: falcon3166 at hotmail.com From: "Nathan Pinno" To: References: Date: Mon, 4 Jul 2005 16:48:49 -0600 MIME-Version: 1.0 X-Priority: 3 X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook Express 6.00.2900.2180 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2180 X-OriginalArrivalTime: 04 Jul 2005 22:48:56.0232 (UTC) FILETIME=[8F26E280:01C580EA] Subject: Re: [Tutor] Is there a way to combine a request for numbers and letters? X-BeenThere: tutor at python.org X-Mailman-Version: 2.1.6 Precedence: list List-Id: Discussion for learning programming with Python List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Content-Type: multipart/mixed; boundary="===============1425094626==" Sender: tutor-bounces+mumke=xs4all.nl at python.org Errors-To: tutor-bounces+mumke=xs4all.nl at python.org X-Virus-Scanned: by XS4ALL Virus Scanner X-XS4ALL-Spam-Score: 5.904 (*****) FORGED_MUA_OUTLOOK,FROM_ENDS_IN_NUMS,HTML_30_40,HTML_MESSAGE,MAILTO_TO _SPAM_ADDR,MSGID_FROM_MTA_HEADER,RCVD_IN_BL_SPAMCOP_NET X-XS4ALL-Spam: YES Envelope-To: mumkspam at xs4all.nl This is a multi-part message in MIME format. --===============1425094626== Content-Type: multipart/alternative; boundary="----=_NextPart_000_0038_01C580B8.4099DB90" This is a multi-part message in MIME format. ------=_NextPart_000_0038_01C580B8.4099DB90 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Sorry, Just remembered that strings can include both letters and numbers. = Case closed. Nathan Pinno Crew, McDonalds Restaurant, Camrose, AB Canada http://www.npinnowebsite.ca/ ----- Original Message -----=20 From: Nathan Pinno=20 To: tutor at python.org=20 Sent: Monday, July 04, 2005 3:55 PM Subject: [Tutor] Is there a way to combine a request for numbers and = letters? Hi all, Is there a way to combine a request for numbers and letters (e.g. = user id and passwords)? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ ---------------------------------------------------------------------- ---= --- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ------=_NextPart_000_0038_01C580B8.4099DB90 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Sorry,
 
Just remembered that strings can include both letters and = numbers. Case=20 closed.
 
Nathan Pinno
Crew, McDonalds Restaurant, Camrose, AB = Canada
http://www.npinnowebsite.ca/
----- Original Message -----
From:=20 Nathan=20 Pinno
Sent: Monday, July 04, 2005 = 3:55=20 PM
Subject: [Tutor] Is there a = way to=20 combine a request for numbers and letters?

Hi all,
 
Is there a way to combine a request for numbers and letters = (e.g. user=20 id and passwords)?
 
Thanks,
Nathan Pinno
http://www.npinnowebsite.ca/


_______________________________________________
Tutor=20 maillist  -  Tutor at python.org
http://mail.pyt hon= org/mailman/listinfo/tutor

------=_NextPart_000_0038_01C580B8.4099DB90-- --===============1425094626== Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: inline _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --===============1425094626==-- From mhuster at simpsonuniversity.edu Wed Jul 6 17:21:49 2005 From: mhuster at simpsonuniversity.edu (Michael Huster) Date: Wed, 6 Jul 2005 08:21:49 -0700 Subject: [Tutor] (no subject) Message-ID: In python under windows, how can I create and access a file on the Desktop? The following do NOT work: fp = open(r'Desktop\myFile','r') fp = open(r'\Desktop\myFile','r') fp = open(r'c:\Desktop\myFile','r') fp = open(r'c:\Windows\Desktop\myFile','r') I don't want to drill into c:\Documents and Setting\... because the user name is often obscure AND not all desktop files appear in the same subdir. of that. For example some are in 'All Users" or 'Default User'. Michael Huster, Simpson University From mhuster at simpsonuniversity.edu Wed Jul 6 17:24:14 2005 From: mhuster at simpsonuniversity.edu (Michael Huster) Date: Wed, 6 Jul 2005 08:24:14 -0700 Subject: [Tutor] Finding Desktop Files Message-ID: Repost - I forgot a subject In python under windows, how can I create and access a file on the Desktop? The following do NOT work: fp = open(r'Desktop\myFile','r') fp = open(r'\Desktop\myFile','r') fp = open(r'c:\Desktop\myFile','r') fp = open(r'c:\Windows\Desktop\myFile','r') I don't want to drill into c:\Documents and Setting\... because the user name is often obscure AND not all desktop files appear in the same subdir. of that. For example some are in 'All Users" or 'Default User'. Michael Huster, Simpson University From light_zls at 163.com Wed Jul 6 17:52:44 2005 From: light_zls at 163.com (Light) Date: Wed, 6 Jul 2005 23:52:44 +0800 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <200507062352.44169.light_zls@163.com> You could use this: import os fp = open(os.path.expanduser('~')+r'\Desktop\myFile', 'r') Light > In python under windows, how can I create and access a file on the > Desktop? The following do NOT work: fp = open(r'Desktop\myFile','r') > fp = open(r'\Desktop\myFile','r') > fp = open(r'c:\Desktop\myFile','r') > fp = open(r'c:\Windows\Desktop\myFile','r') > > I don't want to drill into c:\Documents and Setting\... because the > user name is often obscure AND not all desktop files appear in the > same subdir. of that. For example some are in 'All Users" or 'Default > User'. > > Michael Huster, > Simpson University > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Wed Jul 6 20:16:16 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 6 Jul 2005 11:16:16 -0700 (PDT) Subject: [Tutor] Case ? (fwd) Message-ID: ---------- Forwarded message ---------- Date: Wed, 6 Jul 2005 00:01:52 -0700 (PDT) From: Mike Cheponis To: Danny Yoo Subject: Re: [Tutor] Case ? On Tue, 5 Jul 2005, Danny Yoo wrote: > On Tue, 5 Jul 2005, Mike Cheponis wrote: > >> Why does Python not have a "case" statement, like C? > Hi Mike, > > It's a proposed enhancement: > > http://www.python.org/peps/pep-0275.html Thanks, comments below. Since this didn't come out in Python 2.4, is it "automatically" re-considered for 2.5 ? > That being said, a dispatch-table approach, using a dictionary, works well > in Python because it's not hard to use functions as values --- most people > haven't really missed case/switch statements in Python because dispatch > tables can be very effective. > > > For example, something like this: > > ### C ### > switch(state) { > case STATE_1: doStateOneStuff(); > break; > case STATE_2: doStateTwoStuff(); > break; > case STATE_3: doStateThreeStuff(); > break; > default: doDefaultAction(); > ###### > > has a natural translation into Python as: > > ### Python ### > dispatchTable = { STATE_1: doStateOneStuff, > STATE_2: doStateTwoStuff, > STATE_3: doStateThreeStuff } > command = dispatchTable.get(state, doDefaultAction) > command() > ###### > > where we're essentially mimicking the jump table that a case/switch > statement produces underneath the surface. Sure, this is nice. It does require one to "functionalize" each case, tho, rather than "doing the work" in the body of the case. > One other consideration about C's case/switch statement is its > bug-proneness: it's all too easy to programmers to accidently forget to > put 'break' in appropriate places in there. Years ago, I did this: #define is :{ #define esac break;} So above becomes: switch(state) { case STATE_1 is doStateOneStuff(); esac case STATE_2 is doStateTwoStuff(); esac case STATE_3 is doStateThreeStuff(); esac default is doDefaultAction(); esac } I worked with one C programmer who said that's "not C" and refused to use this simple technique to reduce bugginess. He was from Russia, and seemed pretty convinced about a lot of things ;-) but I don't work with him anymore. > Hope this helps! yes, greatly! Thanks -Mike From thomas.s.mark at gmail.com Wed Jul 6 20:51:36 2005 From: thomas.s.mark at gmail.com (Mark Thomas) Date: Wed, 6 Jul 2005 14:51:36 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <7b969903050706115150c5e4bd@mail.gmail.com> On 7/6/05, Michael Huster wrote: > In python under windows, how can I create and access a file on the Desktop? The following do NOT work: How about... >>> userp = os.getenv('USERPROFILE') + '\\Desktop\\MyFile.txt' >>> fo = file(userp, 'w') -- _ ( ) Mark Thomas ASCII ribbon campaign X www.theswamp.org - against HTML email / \ From klappnase at freenet.de Wed Jul 6 21:05:09 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed, 6 Jul 2005 21:05:09 +0200 Subject: [Tutor] Adding attributes to imported class Message-ID: <20050706210509.64809a6a.klappnase@freenet.de> Hello list, I'm trying to write a python wrapper for the tkDnD Tk extension to add drag and drop support to Tkinter. Looking for a way to give all widgets access to the newly defined dnd methods I came to create a subclass of Tkinter.Tk() and pass the dnd methods to Tkinter.BaseWidget() (all Tkinter widgets except Tk() inherit from BaseWidget()), like this: ###### file TkinterDnD.py ######################### import Tkinter class Tk(Tkinter.Tk): def __init__(self, *args, **kw): Tkinter.Tk.__init__(self, *args, **kw) self.tk.eval('package require tkdnd') def dnd_clearsource(self): '''Unregister widget as drag source.''' return self.tk.call('dnd', 'clearsource', self) Tkinter.BaseWidget.dnd_clearsource = dnd_clearsource < etc. > ################################################### This is nice, because now I can simply do: from Tkinter import * import TkinterDnD root = TkinterDnD.Tk() to magically add dnd methods to all Tkinter widgets. However, I can't help that this trick somehow reminds me of a do-it-yourself lobotomy, so now my question, is this a common way to add new attributes to existing classes or is it possible that this causes problems that I don't see at the moment? Thanks in advance Michael From sallyfes4real at yahoo.com Wed Jul 6 17:36:06 2005 From: sallyfes4real at yahoo.com (festus freeborn) Date: Wed, 6 Jul 2005 08:36:06 -0700 (PDT) Subject: [Tutor] Problem with data storage Message-ID: <20050706153606.38330.qmail@web60520.mail.yahoo.com> plz I need infor About "Problem with data storage" Thanks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050706/08b6f0be/attachment.htm From magoldfish at gmail.com Wed Jul 6 22:12:59 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Wed, 6 Jul 2005 16:12:59 -0400 Subject: [Tutor] file io: reading an int32 at the end of a file? Message-ID: <5e183f3d0507061312782620ed@mail.gmail.com> Hi, I have a file format that ends in a 4-byte (int32) number. I would like to read this value in python on a WinXP machine with something like: fname = 'somefile' f = open(fname, 'rb') f.seek(-4,2) offset = f.read() ... but this doesn't seem to work. The value that Python returns is: '@\x19\x01\x00' but I know from similar code in Matlab that the correct sequence is: 64 25 1 0 Can someone point out my error? Thanks! Marcus From dyoo at hkn.eecs.berkeley.edu Wed Jul 6 22:15:32 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 6 Jul 2005 13:15:32 -0700 (PDT) Subject: [Tutor] (no subject) In-Reply-To: Message-ID: On Wed, 6 Jul 2005, Michael Huster wrote: > In python under windows, how can I create and access a file on the > Desktop? The following do NOT work: fp = open(r'Desktop\myFile','r') fp > = open(r'\Desktop\myFile','r') fp = open(r'c:\Desktop\myFile','r') fp = > open(r'c:\Windows\Desktop\myFile','r') > > I don't want to drill into c:\Documents and Setting\... because the user > name is often obscure AND not all desktop files appear in the same > subdir. of that. For example some are in 'All Users" or 'Default User'. Hi Michael, One issue that might be relevant is that it appears you're asking Python to open a file in read mode ('r'). Are you sure that you don't meant to open a file in write mode ('w') instead? > The following do NOT work: fp = open(r'Desktop\myFile','r') fp = > open(r'\Desktop\myFile','r') fp = open(r'c:\Desktop\myFile','r') fp = > open(r'c:\Windows\Desktop\myFile','r') For the problem that you're running into now, it does seem like you need to open the file in write mode to get it to create new files. Next time, it might be helpful to show how they don't work. What kind of error message do you see when you execute those statements? The reason we ask this is because, in some cases, an error has less to do with what you're doing, and more with an external situation outside of Python. One general principle for error reporting is to make sure to provide enough information that someone else can try it, and enough output that we know that the person will recognize that they're seeing the same error that you're seeing. It also helps because if we see an error message, we can also help explain what the error message means. That way, next time you see a similar error message, you have a better chance to understand what the silly system is really trying to say. *grin* Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed Jul 6 22:29:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 6 Jul 2005 13:29:05 -0700 (PDT) Subject: [Tutor] Case ? (fwd) In-Reply-To: Message-ID: > > It's a proposed enhancement: > > > > http://www.python.org/peps/pep-0275.html > > Since this didn't come out in Python 2.4, is it "automatically" > re-considered for 2.5 ? Hello! It's still in the "open" set of peps: http://www.python.org/peps/ so there's no guarantee that PEP 275 go in. I think there's still quite a bit of revision and discussion ahead before it's ready for the community. The PEP system is described here: http://www.python.org/peps/pep-0001.html > > in Python because it's not hard to use functions as values --- most > > people haven't really missed case/switch statements in Python because > > dispatch tables can be very effective. [code cut] > > where we're essentially mimicking the jump table that a case/switch > > statement produces underneath the surface. > > Sure, this is nice. > > It does require one to "functionalize" each case, tho, rather than > "doing the work" in the body of the case. Yes --- although that restriction might be a good thing, to force programmers to break their code into smaller functions. *grin* Certain syntactic constraints in Python do put a cap on how complicated or long our programs can be; I personally rationalize this as an attempt to keep Python programs readable. > > One other consideration about C's case/switch statement is its > > bug-proneness: it's all too easy to programmers to accidently forget > > to put 'break' in appropriate places in there. > > Years ago, I did this: > > #define is :{ > #define esac break;} [code example cut] Cute. *grin* Aside: I'm not against the idea of that style of case analysis; I'm starting to get infatuated with the more general idea of "pattern matching" that other programming languages --- for example, PLT Scheme and OCaml --- provide. But, unfortunately, I don't see anything like pattern matching hitting Python anytime soon. I just don't like how C does it, because it's so close to how the underlying hardware works that it seems designed to be easy for the C compiler writer to implement, rather than for the casual programmer to use. From rudy.schockaert at gmail.com Wed Jul 6 22:33:43 2005 From: rudy.schockaert at gmail.com (Rudy Schockaert) Date: Wed, 6 Jul 2005 22:33:43 +0200 Subject: [Tutor] (no subject) In-Reply-To: <7b969903050706115150c5e4bd@mail.gmail.com> References: <7b969903050706115150c5e4bd@mail.gmail.com> Message-ID: <60987dac050706133313e38e29@mail.gmail.com> This will work, but only on an English version of the OS. E.g. in Dutch the desktop is called 'Bureaublad'. On 7/6/05, Mark Thomas wrote: > > On 7/6/05, Michael Huster wrote: > > In python under windows, how can I create and access a file on the > Desktop? The following do NOT work: > > How about... > > >>> userp = os.getenv('USERPROFILE') + '\\Desktop\\MyFile.txt' > >>> fo = file(userp, 'w') > -- > _ > ( ) Mark Thomas ASCII ribbon campaign > X www.theswamp.org - against HTML email > / \ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- "A little nonsense now and then, is cherished by the wisest men." -- Roald Dahl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050706/44a262b1/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Wed Jul 6 22:35:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 6 Jul 2005 13:35:52 -0700 (PDT) Subject: [Tutor] file io: reading an int32 at the end of a file? In-Reply-To: <5e183f3d0507061312782620ed@mail.gmail.com> Message-ID: On Wed, 6 Jul 2005, Marcus Goldfish wrote: > I have a file format that ends in a 4-byte (int32) number. I would like > to read this value in python on a WinXP machine with something like: > > fname = 'somefile' > f = open(fname, 'rb') > f.seek(-4,2) > offset = f.read() > > ... but this doesn't seem to work. The value that Python returns is: > > '@\x19\x01\x00' Hi Marcus, You are very close. It looks like you're getting the right bytes back as a single string, so you may need to manually destructure the bytes back into numbers. Let's try something: ###### >>> text = '@\x19\x01\x00' >>> ord(text[0]) 64 >>> ord(text[1]) 25 >>> ord(text[2]) 1 >>> ord(text[3]) 0 ###### So you are getting the right values: you just need to do a little bit more work to unpack them. Using ord() will do the trick, although there is a better way to do it, which we'll talk about below: > but I know from similar code in Matlab that the correct sequence is: > > 64 25 1 0 In that case, it sounds like Matlab is taking those four bytes and treating each bytes as a 'byte' integer. Python has a nice facility for doing this with the 'struct' module: http://www.python.org/doc/lib/module-struct.html ###### >>> import struct >>> struct.unpack('bbbb', '@\x19\x01\x00') (64, 25, 1, 0) ###### I'm not sure if Matlab is treating each byte as an unsigned or signed char, so I'm guessing a signed interpretation at the moment. If you have more questions, please feel free to ask. From jsmith at medplus.com Wed Jul 6 23:24:25 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Wed, 6 Jul 2005 17:24:25 -0400 Subject: [Tutor] Case ? (fwd) Message-ID: If you like the switch statement (which I do) and believe Python should have one (which I do) then you might take a look at this which someone posted when I asked this same question a few months ago: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410692 Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Danny Yoo Sent: Wednesday, July 06, 2005 4:29 PM To: Tutor Cc: mac at Wireless.Com Subject: Re: [Tutor] Case ? (fwd) > > It's a proposed enhancement: > > > > http://www.python.org/peps/pep-0275.html > > Since this didn't come out in Python 2.4, is it "automatically" > re-considered for 2.5 ? Hello! It's still in the "open" set of peps: http://www.python.org/peps/ so there's no guarantee that PEP 275 go in. I think there's still quite a bit of revision and discussion ahead before it's ready for the community. The PEP system is described here: http://www.python.org/peps/pep-0001.html > > in Python because it's not hard to use functions as values --- most > > people haven't really missed case/switch statements in Python > > because dispatch tables can be very effective. [code cut] > > where we're essentially mimicking the jump table that a case/switch > > statement produces underneath the surface. > > Sure, this is nice. > > It does require one to "functionalize" each case, tho, rather than > "doing the work" in the body of the case. Yes --- although that restriction might be a good thing, to force programmers to break their code into smaller functions. *grin* Certain syntactic constraints in Python do put a cap on how complicated or long our programs can be; I personally rationalize this as an attempt to keep Python programs readable. > > One other consideration about C's case/switch statement is its > > bug-proneness: it's all too easy to programmers to accidently forget > > to put 'break' in appropriate places in there. > > Years ago, I did this: > > #define is :{ > #define esac break;} [code example cut] Cute. *grin* Aside: I'm not against the idea of that style of case analysis; I'm starting to get infatuated with the more general idea of "pattern matching" that other programming languages --- for example, PLT Scheme and OCaml --- provide. But, unfortunately, I don't see anything like pattern matching hitting Python anytime soon. I just don't like how C does it, because it's so close to how the underlying hardware works that it seems designed to be easy for the C compiler writer to implement, rather than for the casual programmer to use. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bgailer at sbcglobal.net Wed Jul 6 23:12:39 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Wed, 06 Jul 2005 14:12:39 -0700 Subject: [Tutor] Problem with data storage In-Reply-To: <20050706153606.38330.qmail@web60520.mail.yahoo.com> References: <20050706153606.38330.qmail@web60520.mail.yahoo.com> Message-ID: <6.1.2.0.0.20050706141140.03adbf28@pop.sbcglobal.yahoo.com> At 08:36 AM 7/6/2005, festus freeborn wrote: >plz I need infor About "Problem with data storage" We need more information. How does this question relate to Python? What is the problem you are having? Why do you need to know? Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050706/c53d6228/attachment.htm From bgailer at sbcglobal.net Wed Jul 6 23:17:53 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Wed, 06 Jul 2005 14:17:53 -0700 Subject: [Tutor] file io: reading an int32 at the end of a file? In-Reply-To: <5e183f3d0507061312782620ed@mail.gmail.com> References: <5e183f3d0507061312782620ed@mail.gmail.com> Message-ID: <6.1.2.0.0.20050706141328.03adc1b8@pop.sbcglobal.yahoo.com> At 01:12 PM 7/6/2005, Marcus Goldfish wrote: >Hi, > >I have a file format that ends in a 4-byte (int32) number. I would >like to read this value in python on a WinXP machine with something >like: > >fname = 'somefile' >f = open(fname, 'rb') >f.seek(-4,2) >offset = f.read() > >... but this doesn't seem to work. The value that Python returns is: > > '@\x19\x01\x00' > >but I know from similar code in Matlab that the correct sequence is: > > 64 25 1 0 > >Can someone point out my error? A file is a sequence of characters. That is what Python is showing you. Since 3 of them are not "graphic characters" Python displays their hexadecimal equivalents.. x19 translated to base 10 is 25. To ask Python to (in essence) cast a character to an integer you use the ord function. Ord('\x19') will give you integer 25. >Thanks! >Marcus >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer at alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050706/9cb1ce93/attachment.htm From jfouhy at paradise.net.nz Thu Jul 7 01:03:00 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 07 Jul 2005 11:03:00 +1200 (NZST) Subject: [Tutor] Adding attributes to imported class In-Reply-To: <20050706210509.64809a6a.klappnase@freenet.de> References: <20050706210509.64809a6a.klappnase@freenet.de> Message-ID: <1120690980.42cc63248aab7@www.paradise.net.nz> Quoting Michael Lange : > I'm trying to write a python wrapper for the tkDnD Tk extension to add > drag and drop support Hi Michael, Just a side issue --- tkDnD seems to be broken in python 2.4: see bug 1164742, http://sourceforge.net/tracker/index.php?func=detail&aid=1164742&group_id=5470&atid=105470 -- John. From alan.gauld at freenet.co.uk Thu Jul 7 02:15:16 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 7 Jul 2005 01:15:16 +0100 Subject: [Tutor] Case ? (fwd) References: Message-ID: <007101c58288$f41d6f20$f6b58651@xp> The reason why Python doresn't have a case statement is simply because Guido didn't put one in. Why he didn't I don't know, you'd need to ask him. But I guess that since case stateents are simply syntactic sugar (well nearly), that providing one might have seemed like going against Python's ethos of explicit being better than implicit. The reason why it doesn't have C style case statements is more likely to be due to the fact that C case statements are notoriously bug prone. Pascal or VB style case statements might have been acceptable... But ultimately they are only a minor performance tweak over an if/elif chain saving the cost of one boolean comparison and possibly an assembler jump per case. Long case constructs are better done as dispatch tables - and yes you have to wrap them in functions, but thats definitely a good thing and should be done in well written case statements too IMHO. Short case statements are usually fine in if/elif chains. And type based case statements should be eliminated by using objects and polymorphism. But see a long thread in the archives between Jeff Smith (advocating cases) and myself playing devils advocate for the status quo (about a year ago?) for much more discussion :-) HTH, Alan G. From alan.gauld at freenet.co.uk Thu Jul 7 02:18:40 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 7 Jul 2005 01:18:40 +0100 Subject: [Tutor] Problem with data storage References: <20050706153606.38330.qmail@web60520.mail.yahoo.com> Message-ID: <008701c58289$6da99d50$f6b58651@xp> From: "festus freeborn" > plz I need infor About "Problem with data storage" You might need to give us a clue here. What kind of problem? What kind of data? What kind of storage? - for how long? how quickly retrieved? And if its a homework exercise, which it looks like it might be, how far have you got yourself? What have you tried to do to find the answer - actually thats a good thing to tell us even if its not homework! Personally for long lived data I tend to use a filing cabinet... Alan G. From alan.gauld at freenet.co.uk Thu Jul 7 02:21:40 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 7 Jul 2005 01:21:40 +0100 Subject: [Tutor] file io: reading an int32 at the end of a file? References: <5e183f3d0507061312782620ed@mail.gmail.com> Message-ID: <008c01c58289$d8cb74f0$f6b58651@xp> ------------------------------------------ ... but this doesn't seem to work. The value that Python returns is: '@\x19\x01\x00' but I know from similar code in Matlab that the correct sequence is: 64 25 1 0 Can someone point out my error? ------------------------------------------ That looks like the same thing to me. The ascii code for '@' is 64... hex 19 = decimal 25 Why do you think there is a problem? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From gordnjen at rogers.com Thu Jul 7 02:54:27 2005 From: gordnjen at rogers.com (gordnjen) Date: Wed, 6 Jul 2005 20:54:27 -0400 Subject: [Tutor] Doctype declaration Message-ID: <004e01c5828e$6d0ef1b0$a471c545@JennineGord> Thanks to everyone who helped me with the problem I had with my "age" program. I now have it working properly (yay). So, now I need to know how to insert a doctype declaration into my python script so that a) the python script runs properly and b)the page validates as valid XHTML. Here is my code below. It runs fine as a python script, but won't validate: import time print "Content-type: text/html" print print "" print "Current Time" print "" print "

Current Time

" print "

The current time is" print "", time.asctime(), "

" print "" Any help would be greatly appreciated! Thanks! Regards, Jennine -----Original Message----- From: gordnjen [mailto:gordnjen at rogers.com] Sent: July 4, 2005 10:25 PM To: 'tutor at python.org' Subject: "And" function I need to write a program that will do the following: Ask the user's age. If their age is below 1 yr old, it prints "you are old enought to eat baby food" If they are over 16, it prints "You are old enough to drive" If they are over 65, it prints "You are old enough to drive" and "You are old enough to retire" If they are between the ages of 16 and 25, it prints "you are old enough to get a student discount". So far, I have this: age =int(raw_input("How old are you?")) if age>16: print "You are old enough to drive!" if age>65: print "You are old enough to retire!" if age<1: print "You are old enough to eat baby food!" I get stuck with the old enough to get a student discount part. I have tried if age>16 and age<25: print "You are old enough to get a student discount" But it doesn't seem to work. Any help would be great. Thanks! Jennine -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.8.9/41 - Release Date: 05/07/2005 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050706/7b3dcbe4/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 17147 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050706/7b3dcbe4/attachment-0001.jpeg From kent37 at tds.net Thu Jul 7 03:37:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 6 Jul 2005 21:37:14 -0400 Subject: [Tutor] Doctype declaration Message-ID: <200507070137.j671bEUQ013804@outbound4.mail.tds.net> gordnjen wrote: > So, now I need to know how to insert a doctype declaration into my > python script so that a) the python script runs properly and b)the page > validates as valid XHTML. > > Here is my code below. It runs fine as a python script, but won't validate: > > import time > print "Content-type: text/html" > print print '' print '''''' print '' > print "" > print "Current Time" > print "" > print "

Current Time

" > print "

The current time is" > print "", time.asctime(), "

" > print "" By the way, triple-quoted strings are very handy for this, you can just say print ''' Current Time

Current Time

The current time is''' Kent From falcon3166 at hotmail.com Thu Jul 7 08:44:18 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 00:44:18 -0600 Subject: [Tutor] What's wrong with this code? References: <6faf39c905070423445b8d263f@mail.gmail.com><6faf39c9050704234457994d3f@mail.gmail.com> <42CA30B4.3070402@po-box.mcgill.ca> Message-ID: Hi all, I meant to ask why the main part after the password is not working right. No one has answered that yet. When I run the code and try to load a file that has been saved, a TypeError appears. How do I fix the code so no more errors will show up. Here is the newest code so far: # This is the code for a password protected program to store passwords. password = "hello" print "The Password Program" print "Copywrite 2005. All Rights Reserved." print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Save login list" print "6) Open Login list" print "9) Exit" def load_login(site,filename): in_file = open(filename,"r") while 1: in_line = in_file.readline() if len(in_file) == 0: break in_line = in_line[:-1] [site,id,passcard] = string.split(in_line,",") list[site] = id and passcard in_file.close() def save_login(site,filename): out_file = open(filename,"w") for x in site.keys(): out_file.write(x+","+sites[x]+"\n") out_file.close() menu_choice = 0 list = {} print "Welcome to the second half of the program." print main_menu() while menu_choice != 9: menu_choice = input("Choose an option: ") if menu_choice == 1: print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") list[site] = id and passcard menu_choice = input("Choose an option: ") elif menu_choice == 2: print "Lookup a login info card" site = raw_input("Site: ") if site.has_key(site): print "The ID is: ",id(site) print "The password is: ",passcard(site) else: print site," was not found." menu_choice = input("Choose an option: ") elif menu_choice == 3: print "Remove a login info card" site = raw_input("Site: ") if sites.has_key(site): del numbers[site] else: print site," was not found." menu_choice = input("Choose an option: ") elif menu_choice == 4: print "Login Info" for x in site.keys(): print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] print menu_choice = input("Choose an option: ") elif menu_choice == 5: filename = raw_input("Filename to save: ") save_login(list,filename) menu_choice = input("Choose an option: ") elif menu_choice == 6: filename == raw_input("Filename to load: ") load_login(list,filename) menu_choice = input("Choose an option: ") print "Have a nice day!" Thanks for the input so far, Nathan Pinno ----- Original Message ----- From: "Brian van den Broek" Cc: Sent: Tuesday, July 05, 2005 1:03 AM Subject: Re: [Tutor] What's wrong with this code? > Andre Engels said unto the world upon 05/07/2005 02:44: >>>From the program:: >> >> answer = raw_input("What is the password? ") >> while password != answer: >> print "The password is incorrect." > > > >> I think you intended to make it so that >> the program kept asking for passwords until the right one was given. >> This is done with: >> answer = raw_input("What is the password? ") >> while password != answer: >> print "The password is incorrect." >> answer = raw_input("What is the password? ") > > > A small thing, but I think that is better as: > > while True: > answer = raw_input("What is the password? ") > if password == answer: > break > print "The password is incorrect." > > It probably runs a bit slower, but who cares, as the bottleneck is in > the chair, not the chip. The advantage is that there is only one > statement of the prompt to alter if you wanted to change it later. > > But, I think this will be one where reasonable people can differ. > Andre's version does make the semantics of the loop somewhat more obvious. > > Best to all, > > Brian vdB > > > >> Andre Engels > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Thu Jul 7 08:54:56 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 00:54:56 -0600 Subject: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. Message-ID: Hi all, Here's one of the messages that pops up: Traceback (most recent call last): File "D:\password.py", line 77, in ? filename == raw_input("Filename to load: ") NameError: name 'filename' is not defined Why is it popping up whenever I try to load a file? Here's the latest code: # This is the code for a password protected program to store passwords. password = "hello" print "The Password Program" print "Copyright 2005 Nathan Pinno." print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") def main_menu(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Save login list" print "6) Open Login list" print "9) Exit" def load_login(site,filename): in_file = open(filename,"r") while 1: in_line = in_file.readline() if len(in_file) == 0: break in_line = in_line[:-1] [site,id,passcard] = string.split(in_line,",") list[site] = id and passcard in_file.close() def save_login(site,filename): out_file = open(filename,"w") for x in site.keys(): out_file.write(x+","+sites[x]+"\n") out_file.close() menu_choice = "0" list = {} print "Welcome to the second half of the program." print main_menu() while menu_choice != "9": menu_choice = raw_input("Choose an option: ") if menu_choice == "1": print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") list[site] = id and passcard menu_choice = raw_input("Choose an option: ") elif menu_choice == "2": print "Lookup a login info card" site = raw_input("Site: ") if site.has_key(site): print "The ID is: ",id(site) print "The password is: ",passcard(site) else: print site," was not found." menu_choice = raw_input("Choose an option: ") elif menu_choice == "3": print "Remove a login info card" site = raw_input("Site: ") if sites.has_key(site): del numbers[site] else: print site," was not found." menu_choice = raw_input("Choose an option: ") elif menu_choice == "4": print "Login Info" for x in site.keys(): print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] print menu_choice = raw_input("Choose an option: ") elif menu_choice == "5": filename = raw_input("Filename to save: ") save_login(list,filename) menu_choice = raw_input("Choose an option: ") elif menu_choice == "6": filename == raw_input("Filename to load: ") load_login(list,filename) menu_choice = raw_input("Choose an option: ") print "Have a nice day!" Anything else that needs addressing? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050707/82370141/attachment.htm From kraus at hagen-partner.de Thu Jul 7 09:02:06 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 07 Jul 2005 09:02:06 +0200 Subject: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. In-Reply-To: References: Message-ID: You wrote filename == raw_input("Filename to load: ") instead of filename = raw_input("Filename to load: ") HTH, Wolfram Nathan Pinno wrote: > Hi all, > > Here's one of the messages that pops up: > > Traceback (most recent call last): > File "D:\password.py", line 77, in ? > filename == raw_input("Filename to load: ") > NameError: name 'filename' is not defined > > Why is it popping up whenever I try to load a file? > > Here's the latest code: > > # This is the code for a password protected program to store passwords. > password = "hello" > print "The Password Program" > print "Copyright 2005 Nathan Pinno." > print > answer = raw_input("What is the password? ") > while password != answer: > print "The password is incorrect." > answer = raw_input("What is the password? ") > def main_menu(): > print "1) Add a login info card" > print "2) Lookup a login info card" > print "3) Remove a login info card" > print "4) Print Login info list" > print "5) Save login list" > print "6) Open Login list" > print "9) Exit" > > def load_login(site,filename): > in_file = open(filename,"r") > while 1: > in_line = in_file.readline() > if len(in_file) == 0: > break > in_line = in_line[:-1] > [site,id,passcard] = string.split(in_line,",") > list[site] = id and passcard > in_file.close() > > def save_login(site,filename): > out_file = open(filename,"w") > for x in site.keys(): > out_file.write(x+","+sites[x]+"\n") > out_file.close() > > menu_choice = "0" > list = {} > print "Welcome to the second half of the program." > print main_menu() > while menu_choice != "9": > menu_choice = raw_input("Choose an option: ") > if menu_choice == "1": > print "Add a login info card" > site = raw_input("Site: ") > id = raw_input("User ID: ") > passcard = raw_input("Password: ") > list[site] = id and passcard > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "2": > print "Lookup a login info card" > site = raw_input("Site: ") > if site.has_key(site): > print "The ID is: ",id(site) > print "The password is: ",passcard(site) > else: > print site," was not found." > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "3": > print "Remove a login info card" > site = raw_input("Site: ") > if sites.has_key(site): > del numbers[site] > else: > print site," was not found." > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "4": > print "Login Info" > for x in site.keys(): > print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] > print > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "5": > filename = raw_input("Filename to save: ") > save_login(list,filename) > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "6": > filename == raw_input("Filename to load: ") > load_login(list,filename) > menu_choice = raw_input("Choose an option: ") > print "Have a nice day!" > > Anything else that needs addressing? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > From falcon3166 at hotmail.com Thu Jul 7 09:13:48 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 01:13:48 -0600 Subject: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. References: Message-ID: Thanks Wolfram for help with that error. Here's another that popped up: Traceback (most recent call last): File "D:\password.py", line 68, in ? for x in site.keys(): AttributeError: 'str' object has no attribute 'keys' How to fix it? Thanks, Nathan Pinno ----- Original Message ----- From: "Wolfram Kraus" To: Sent: Thursday, July 07, 2005 1:02 AM Subject: Re: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. > You wrote filename == raw_input("Filename to load: ") instead of > filename = raw_input("Filename to load: ") > > HTH, > Wolfram > > Nathan Pinno wrote: >> Hi all, >> >> Here's one of the messages that pops up: >> >> Traceback (most recent call last): >> File "D:\password.py", line 77, in ? >> filename == raw_input("Filename to load: ") >> NameError: name 'filename' is not defined >> >> Why is it popping up whenever I try to load a file? >> >> Here's the latest code: >> >> # This is the code for a password protected program to store passwords. >> password = "hello" >> print "The Password Program" >> print "Copyright 2005 Nathan Pinno." >> print >> answer = raw_input("What is the password? ") >> while password != answer: >> print "The password is incorrect." >> answer = raw_input("What is the password? ") >> def main_menu(): >> print "1) Add a login info card" >> print "2) Lookup a login info card" >> print "3) Remove a login info card" >> print "4) Print Login info list" >> print "5) Save login list" >> print "6) Open Login list" >> print "9) Exit" >> >> def load_login(site,filename): >> in_file = open(filename,"r") >> while 1: >> in_line = in_file.readline() >> if len(in_file) == 0: >> break >> in_line = in_line[:-1] >> [site,id,passcard] = string.split(in_line,",") >> list[site] = id and passcard >> in_file.close() >> >> def save_login(site,filename): >> out_file = open(filename,"w") >> for x in site.keys(): >> out_file.write(x+","+sites[x]+"\n") >> out_file.close() >> >> menu_choice = "0" >> list = {} >> print "Welcome to the second half of the program." >> print main_menu() >> while menu_choice != "9": >> menu_choice = raw_input("Choose an option: ") >> if menu_choice == "1": >> print "Add a login info card" >> site = raw_input("Site: ") >> id = raw_input("User ID: ") >> passcard = raw_input("Password: ") >> list[site] = id and passcard >> menu_choice = raw_input("Choose an option: ") >> elif menu_choice == "2": >> print "Lookup a login info card" >> site = raw_input("Site: ") >> if site.has_key(site): >> print "The ID is: ",id(site) >> print "The password is: ",passcard(site) >> else: >> print site," was not found." >> menu_choice = raw_input("Choose an option: ") >> elif menu_choice == "3": >> print "Remove a login info card" >> site = raw_input("Site: ") >> if sites.has_key(site): >> del numbers[site] >> else: >> print site," was not found." >> menu_choice = raw_input("Choose an option: ") >> elif menu_choice == "4": >> print "Login Info" >> for x in site.keys(): >> print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] >> print >> menu_choice = raw_input("Choose an option: ") >> elif menu_choice == "5": >> filename = raw_input("Filename to save: ") >> save_login(list,filename) >> menu_choice = raw_input("Choose an option: ") >> elif menu_choice == "6": >> filename == raw_input("Filename to load: ") >> load_login(list,filename) >> menu_choice = raw_input("Choose an option: ") >> print "Have a nice day!" >> >> Anything else that needs addressing? >> >> Thanks, >> Nathan Pinno >> http://www.npinnowebsite.ca/ >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ewald.ertl at hartter.com Thu Jul 7 09:36:53 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 7 Jul 2005 09:36:53 +0200 Subject: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. In-Reply-To: References: Message-ID: <20050707093653.0000416b@sunray1> Hi! on Thu, 7 Jul 2005 01:13:48 -0600 "Nathan Pinno" wrote : --------------------------------------------------------------------------------------------- Nathan Pinno > Thanks Wolfram for help with that error. Nathan Pinno > Nathan Pinno > Here's another that popped up: Nathan Pinno > Nathan Pinno > Traceback (most recent call last): Nathan Pinno > File "D:\password.py", line 68, in ? Nathan Pinno > for x in site.keys(): Nathan Pinno > AttributeError: 'str' object has no attribute 'keys' Nathan Pinno > The Traceback tells you on which line the error is. site comes from your input : site = raw_input("Site: ") which is a string and not a dictionary. Nathan Pinno > How to fix it? Nathan Pinno > Nathan Pinno > Thanks, Nathan Pinno > Nathan Pinno Nathan Pinno > ----- Original Message ----- Nathan Pinno > From: "Wolfram Kraus" Nathan Pinno > To: Nathan Pinno > Sent: Thursday, July 07, 2005 1:02 AM Nathan Pinno > Subject: Re: [Tutor] Why is this error showing up? (Original Message: Nathan Pinno > (Tutor) What's wrong with this code?) Ignore previous post. Nathan Pinno > Nathan Pinno > Nathan Pinno > > You wrote filename == raw_input("Filename to load: ") instead of Nathan Pinno > > filename = raw_input("Filename to load: ") Nathan Pinno > > Nathan Pinno > > HTH, Nathan Pinno > > Wolfram Nathan Pinno > > Nathan Pinno > > Nathan Pinno wrote: Nathan Pinno > >> Hi all, Nathan Pinno > >> Nathan Pinno > >> Here's one of the messages that pops up: Nathan Pinno > >> Nathan Pinno > >> Traceback (most recent call last): Nathan Pinno > >> File "D:\password.py", line 77, in ? Nathan Pinno > >> filename == raw_input("Filename to load: ") Nathan Pinno > >> NameError: name 'filename' is not defined Nathan Pinno > >> Nathan Pinno > >> Why is it popping up whenever I try to load a file? Nathan Pinno > >> Nathan Pinno > >> Here's the latest code: Nathan Pinno > >> Nathan Pinno > >> # This is the code for a password protected program to store passwords. Nathan Pinno > >> password = "hello" Nathan Pinno > >> print "The Password Program" Nathan Pinno > >> print "Copyright 2005 Nathan Pinno." Nathan Pinno > >> print Nathan Pinno > >> answer = raw_input("What is the password? ") Nathan Pinno > >> while password != answer: Nathan Pinno > >> print "The password is incorrect." Nathan Pinno > >> answer = raw_input("What is the password? ") Nathan Pinno > >> def main_menu(): Nathan Pinno > >> print "1) Add a login info card" Nathan Pinno > >> print "2) Lookup a login info card" Nathan Pinno > >> print "3) Remove a login info card" Nathan Pinno > >> print "4) Print Login info list" Nathan Pinno > >> print "5) Save login list" Nathan Pinno > >> print "6) Open Login list" Nathan Pinno > >> print "9) Exit" Nathan Pinno > >> Nathan Pinno > >> def load_login(site,filename): Nathan Pinno > >> in_file = open(filename,"r") Nathan Pinno > >> while 1: Nathan Pinno > >> in_line = in_file.readline() Nathan Pinno > >> if len(in_file) == 0: Nathan Pinno > >> break Nathan Pinno > >> in_line = in_line[:-1] Nathan Pinno > >> [site,id,passcard] = string.split(in_line,",") Nathan Pinno > >> list[site] = id and passcard Nathan Pinno > >> in_file.close() Nathan Pinno > >> Nathan Pinno > >> def save_login(site,filename): Nathan Pinno > >> out_file = open(filename,"w") Nathan Pinno > >> for x in site.keys(): site comes form your input : site = raw_input("Site: ") and is a string and not a dictionary. Perhaps you will use here "sites", but there are no items added to sites?? Nathan Pinno > >> out_file.write(x+","+sites[x]+"\n") Nathan Pinno > >> out_file.close() Nathan Pinno > >> Nathan Pinno > >> menu_choice = "0" Nathan Pinno > >> list = {} Nathan Pinno > >> print "Welcome to the second half of the program." Nathan Pinno > >> print main_menu() Nathan Pinno > >> while menu_choice != "9": Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") Nathan Pinno > >> if menu_choice == "1": Nathan Pinno > >> print "Add a login info card" Nathan Pinno > >> site = raw_input("Site: ") Nathan Pinno > >> id = raw_input("User ID: ") Nathan Pinno > >> passcard = raw_input("Password: ") Nathan Pinno > >> list[site] = id and passcard Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") Nathan Pinno > >> elif menu_choice == "2": Nathan Pinno > >> print "Lookup a login info card" Nathan Pinno > >> site = raw_input("Site: ") Nathan Pinno > >> if site.has_key(site): Nathan Pinno > >> print "The ID is: ",id(site) Nathan Pinno > >> print "The password is: ",passcard(site) Nathan Pinno > >> else: Nathan Pinno > >> print site," was not found." Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") Nathan Pinno > >> elif menu_choice == "3": Nathan Pinno > >> print "Remove a login info card" Nathan Pinno > >> site = raw_input("Site: ") Nathan Pinno > >> if sites.has_key(site): Nathan Pinno > >> del numbers[site] Nathan Pinno > >> else: Nathan Pinno > >> print site," was not found." Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") Nathan Pinno > >> elif menu_choice == "4": Nathan Pinno > >> print "Login Info" Nathan Pinno > >> for x in site.keys(): Here's the next use of the input-String "site" as a dictionary which will fail. Nathan Pinno > >> print "Site: ",x," \tID: ",numbers[x]," \tPassword: Nathan Pinno > ",numbers[x] Nathan Pinno > >> print Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") Nathan Pinno > >> elif menu_choice == "5": Nathan Pinno > >> filename = raw_input("Filename to save: ") Nathan Pinno > >> save_login(list,filename) Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") Nathan Pinno > >> elif menu_choice == "6": Nathan Pinno > >> filename == raw_input("Filename to load: ") Nathan Pinno > >> load_login(list,filename) Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") Nathan Pinno > >> print "Have a nice day!" Nathan Pinno > >> Nathan Pinno > >> Anything else that needs addressing? Nathan Pinno > >> Nathan Pinno > >> Thanks, Nathan Pinno > >> Nathan Pinno Nathan Pinno > >> http://www.npinnowebsite.ca/ Nathan Pinno > >> Nathan Pinno > > Nathan Pinno > > _______________________________________________ Nathan Pinno > > Tutor maillist - Tutor at python.org Nathan Pinno > > http://mail.python.org/mailman/listinfo/tutor Nathan Pinno > > Nathan Pinno > _______________________________________________ Nathan Pinno > Tutor maillist - Tutor at python.org Nathan Pinno > http://mail.python.org/mailman/listinfo/tutor Nathan Pinno > ------------------- end ---------------------- HTH Ewald From falcon3166 at hotmail.com Thu Jul 7 09:40:51 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 01:40:51 -0600 Subject: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. References: <20050707093653.0000416b@sunray1> Message-ID: How do I change it to a dictionary, then? Or do I have to delete it, and just code it in the main part of the code? ----- Original Message ----- From: "Ewald Ertl" To: Sent: Thursday, July 07, 2005 1:36 AM Subject: Re: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. > Hi! > > > on Thu, 7 Jul 2005 01:13:48 -0600 "Nathan Pinno" wrote : > --------------------------------------------------------------------------------------------- > > Nathan Pinno > Thanks Wolfram for help with that error. > Nathan Pinno > > Nathan Pinno > Here's another that popped up: > Nathan Pinno > > Nathan Pinno > Traceback (most recent call last): > Nathan Pinno > File "D:\password.py", line 68, in ? > Nathan Pinno > for x in site.keys(): > Nathan Pinno > AttributeError: 'str' object has no attribute 'keys' > Nathan Pinno > > > The Traceback tells you on which line the error is. > site comes from your input : site = raw_input("Site: ") > which is a string and not a dictionary. > > > > Nathan Pinno > How to fix it? > Nathan Pinno > > Nathan Pinno > Thanks, > Nathan Pinno > Nathan Pinno > Nathan Pinno > ----- Original Message ----- > Nathan Pinno > From: "Wolfram Kraus" > Nathan Pinno > To: > Nathan Pinno > Sent: Thursday, July 07, 2005 1:02 AM > Nathan Pinno > Subject: Re: [Tutor] Why is this error showing up? (Original Message: > Nathan Pinno > (Tutor) What's wrong with this code?) Ignore previous post. > Nathan Pinno > > Nathan Pinno > > Nathan Pinno > > You wrote filename == raw_input("Filename to load: ") instead of > Nathan Pinno > > filename = raw_input("Filename to load: ") > Nathan Pinno > > > Nathan Pinno > > HTH, > Nathan Pinno > > Wolfram > Nathan Pinno > > > Nathan Pinno > > Nathan Pinno wrote: > Nathan Pinno > >> Hi all, > Nathan Pinno > >> > Nathan Pinno > >> Here's one of the messages that pops up: > Nathan Pinno > >> > Nathan Pinno > >> Traceback (most recent call last): > Nathan Pinno > >> File "D:\password.py", line 77, in ? > Nathan Pinno > >> filename == raw_input("Filename to load: ") > Nathan Pinno > >> NameError: name 'filename' is not defined > Nathan Pinno > >> > Nathan Pinno > >> Why is it popping up whenever I try to load a file? > Nathan Pinno > >> > Nathan Pinno > >> Here's the latest code: > Nathan Pinno > >> > Nathan Pinno > >> # This is the code for a password protected program to store passwords. > Nathan Pinno > >> password = "hello" > Nathan Pinno > >> print "The Password Program" > Nathan Pinno > >> print "Copyright 2005 Nathan Pinno." > Nathan Pinno > >> print > Nathan Pinno > >> answer = raw_input("What is the password? ") > Nathan Pinno > >> while password != answer: > Nathan Pinno > >> print "The password is incorrect." > Nathan Pinno > >> answer = raw_input("What is the password? ") > Nathan Pinno > >> def main_menu(): > Nathan Pinno > >> print "1) Add a login info card" > Nathan Pinno > >> print "2) Lookup a login info card" > Nathan Pinno > >> print "3) Remove a login info card" > Nathan Pinno > >> print "4) Print Login info list" > Nathan Pinno > >> print "5) Save login list" > Nathan Pinno > >> print "6) Open Login list" > Nathan Pinno > >> print "9) Exit" > Nathan Pinno > >> > Nathan Pinno > >> def load_login(site,filename): > Nathan Pinno > >> in_file = open(filename,"r") > Nathan Pinno > >> while 1: > Nathan Pinno > >> in_line = in_file.readline() > Nathan Pinno > >> if len(in_file) == 0: > Nathan Pinno > >> break > Nathan Pinno > >> in_line = in_line[:-1] > Nathan Pinno > >> [site,id,passcard] = string.split(in_line,",") > Nathan Pinno > >> list[site] = id and passcard > Nathan Pinno > >> in_file.close() > Nathan Pinno > >> > Nathan Pinno > >> def save_login(site,filename): > Nathan Pinno > >> out_file = open(filename,"w") > Nathan Pinno > >> for x in site.keys(): > > site comes form your input : site = raw_input("Site: ") > and is a string and not a dictionary. > Perhaps you will use here "sites", but there are no items added to > sites?? > > > Nathan Pinno > >> out_file.write(x+","+sites[x]+"\n") > Nathan Pinno > >> out_file.close() > Nathan Pinno > >> > Nathan Pinno > >> menu_choice = "0" > Nathan Pinno > >> list = {} > Nathan Pinno > >> print "Welcome to the second half of the program." > Nathan Pinno > >> print main_menu() > Nathan Pinno > >> while menu_choice != "9": > Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") > Nathan Pinno > >> if menu_choice == "1": > Nathan Pinno > >> print "Add a login info card" > Nathan Pinno > >> site = raw_input("Site: ") > Nathan Pinno > >> id = raw_input("User ID: ") > Nathan Pinno > >> passcard = raw_input("Password: ") > Nathan Pinno > >> list[site] = id and passcard > Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") > Nathan Pinno > >> elif menu_choice == "2": > Nathan Pinno > >> print "Lookup a login info card" > Nathan Pinno > >> site = raw_input("Site: ") > Nathan Pinno > >> if site.has_key(site): > Nathan Pinno > >> print "The ID is: ",id(site) > Nathan Pinno > >> print "The password is: ",passcard(site) > Nathan Pinno > >> else: > Nathan Pinno > >> print site," was not found." > Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") > Nathan Pinno > >> elif menu_choice == "3": > Nathan Pinno > >> print "Remove a login info card" > Nathan Pinno > >> site = raw_input("Site: ") > Nathan Pinno > >> if sites.has_key(site): > Nathan Pinno > >> del numbers[site] > Nathan Pinno > >> else: > Nathan Pinno > >> print site," was not found." > Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") > Nathan Pinno > >> elif menu_choice == "4": > Nathan Pinno > >> print "Login Info" > Nathan Pinno > >> for x in site.keys(): > > Here's the next use of the input-String "site" as a dictionary which will fail. > > > > Nathan Pinno > >> print "Site: ",x," \tID: ",numbers[x]," \tPassword: > Nathan Pinno > ",numbers[x] > Nathan Pinno > >> print > Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") > Nathan Pinno > >> elif menu_choice == "5": > Nathan Pinno > >> filename = raw_input("Filename to save: ") > Nathan Pinno > >> save_login(list,filename) > Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") > Nathan Pinno > >> elif menu_choice == "6": > Nathan Pinno > >> filename == raw_input("Filename to load: ") > Nathan Pinno > >> load_login(list,filename) > Nathan Pinno > >> menu_choice = raw_input("Choose an option: ") > Nathan Pinno > >> print "Have a nice day!" > Nathan Pinno > >> > Nathan Pinno > >> Anything else that needs addressing? > Nathan Pinno > >> > Nathan Pinno > >> Thanks, > Nathan Pinno > >> Nathan Pinno > Nathan Pinno > >> http://www.npinnowebsite.ca/ > Nathan Pinno > >> > Nathan Pinno > > > Nathan Pinno > > _______________________________________________ > Nathan Pinno > > Tutor maillist - Tutor at python.org > Nathan Pinno > > http://mail.python.org/mailman/listinfo/tutor > Nathan Pinno > > > Nathan Pinno > _______________________________________________ > Nathan Pinno > Tutor maillist - Tutor at python.org > Nathan Pinno > http://mail.python.org/mailman/listinfo/tutor > Nathan Pinno > > > > ------------------- end ---------------------- > > HTH Ewald > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From negroup at gmail.com Thu Jul 7 10:25:16 2005 From: negroup at gmail.com (Negroup -) Date: Thu, 7 Jul 2005 10:25:16 +0200 Subject: [Tutor] Create zip files on the fly. Message-ID: <2fdabf19050707012539e6a49f@mail.gmail.com> Hi, in my application I need to generate a zip file (via the great zipfile module) and pass it from function A to function B. One way to do it is create the object from function A and write it on filesystem via close(). Then, function B will obtain the object reading the file from disk. After this operation, the file must be deleted from the filesystem. Now I'd like to know if it is possible to accomplish this task working in memory directly without pass for the filesystem. I know that a class StringIO.StringIO (memory files) exists, but I need something valid for zipfiles. As a final solution I have also considered to use tempfile module to generate files that will be automatically removed. Sorry for the simple question but I'm just trying to learn.. Do you have some way to enlighten me? Thanks! From dyoo at hkn.eecs.berkeley.edu Thu Jul 7 10:31:43 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 7 Jul 2005 01:31:43 -0700 (PDT) Subject: [Tutor] What's wrong with this code? In-Reply-To: Message-ID: Hi Nathan, Other folks are pointing out why you're getting certain error messages. You may also want to consider breaking up the long second-half of the program into into its own set of functions. I believe that the second half could look something like this: ###### while menu_choice != 9: menu_choice = input("Choose an option:") if menu_choice == 1: add_login_command() elif menu_choice == 2: lookup_login_command() elif menu_choice == 3: remove_login_command() elif menu_choice == 4: display_login_command() elif menu_choice == 5: save_login_command() elif menu_choice == 6: load_login_command() ###### The idea behind the break-up here is to make it a little easier to see, at a high level, how the program works. As a side benefit, it should help to avoid wacky things like certain menu choices munging up the variables used by other menu choices. Finally, by physcially shortening that loop, it's easier to see that we'll always ask for a menu_choice whenever we hit the start of the loop. In contrast, the original code is so long that we may have forgotten, which is why each menu command appears to repeat the "Choose an option:" question. (When you learn a little more about Python, we can talk about the concept of "dispatch tables" to further dissolve that code, but let's talk about that later.) I guess I'm trying to say: style can mattes because it can help you fix your program's bugs faster. *grin* Best of wishes to you! From zamb at saudi.net.sa Thu Jul 7 10:56:02 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Thu, 07 Jul 2005 11:56:02 +0300 Subject: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. In-Reply-To: References: Message-ID: <1120726562.16067.6.camel@localhost.localdomain> On Thu, 2005-07-07 at 00:54 -0600, Nathan Pinno wrote: > Hi all, > > Here's one of the messages that pops up: > > Traceback (most recent call last): > File "D:\password.py", line 77, in ? > filename == raw_input("Filename to load: ") > NameError: name 'filename' is not defined > > Why is it popping up whenever I try to load a file? > > Here's the latest code: > > # This is the code for a password protected program to store passwords. > password = "hello" > print "The Password Program" > print "Copyright 2005 Nathan Pinno." > print > answer = raw_input("What is the password? ") > while password != answer: > print "The password is incorrect." > answer = raw_input("What is the password? ") > def main_menu(): > print "1) Add a login info card" > print "2) Lookup a login info card" > print "3) Remove a login info card" > print "4) Print Login info list" > print "5) Save login list" > print "6) Open Login list" > print "9) Exit" > > def load_login(site,filename): > in_file = open(filename,"r") > while 1: > in_line = in_file.readline() > if len(in_file) == 0: > break > in_line = in_line[:-1] > [site,id,passcard] = string.split(in_line,",") > list[site] = id and passcard > in_file.close() > > def save_login(site,filename): > out_file = open(filename,"w") > for x in site.keys(): > out_file.write(x+","+sites[x]+"\n") > out_file.close() > > menu_choice = "0" > list = {} > print "Welcome to the second half of the program." > print main_menu() Above, you mean: main_menu() instead of "print main_menu()" which is wrong (not technically wrong, but you what you really want to do). > while menu_choice != "9": > menu_choice = raw_input("Choose an option: ") > if menu_choice == "1": > print "Add a login info card" > site = raw_input("Site: ") > id = raw_input("User ID: ") > passcard = raw_input("Password: ") > list[site] = id and passcard > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "2": > print "Lookup a login info card" > site = raw_input("Site: ") > if site.has_key(site): > print "The ID is: ",id(site) > print "The password is: ",passcard(site) > else: > print site," was not found." > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "3": > print "Remove a login info card" > site = raw_input("Site: ") > if sites.has_key(site): > del numbers[site] > else: > print site," was not found." > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "4": > print "Login Info" > for x in site.keys(): > print "Site: ",x," \tID: ",numbers[x]," \tPassword: ",numbers[x] > print > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "5": > filename = raw_input("Filename to save: ") > save_login(list,filename) > menu_choice = raw_input("Choose an option: ") > elif menu_choice == "6": > filename == raw_input("Filename to load: ") ^^ filename = raw_input("Filename to load: ") You used '==' instead of '='. > load_login(list,filename) > menu_choice = raw_input("Choose an option: ") > print "Have a nice day!" > > Anything else that needs addressing? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ Ziyad. From cyresse at gmail.com Thu Jul 7 12:15:09 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 7 Jul 2005 22:15:09 +1200 Subject: [Tutor] What's wrong with this code? In-Reply-To: References: Message-ID: And please, please, post the whole error message, as it specifies where the error occurred. Oh, yes, and I think I answered this - " I meant to ask why the main part after the password is not working right. No one has answered that yet. When I run the code and try to load a file that has been saved, a TypeError appears. " Try id[site] and passcard[site] not id(site) and passcard(site). It'll make a world of difference, honest. On 7/7/05, Danny Yoo wrote: > > > Hi Nathan, > > Other folks are pointing out why you're getting certain error messages. > You may also want to consider breaking up the long second-half of the > program into into its own set of functions. I believe that the second > half could look something like this: > > ###### > while menu_choice != 9: > menu_choice = input("Choose an option:") > if menu_choice == 1: > add_login_command() > elif menu_choice == 2: > lookup_login_command() > elif menu_choice == 3: > remove_login_command() > elif menu_choice == 4: > display_login_command() > elif menu_choice == 5: > save_login_command() > elif menu_choice == 6: > load_login_command() > ###### > > The idea behind the break-up here is to make it a little easier to see, at > a high level, how the program works. As a side benefit, it should help to > avoid wacky things like certain menu choices munging up the variables used > by other menu choices. > > Finally, by physcially shortening that loop, it's easier to see that we'll > always ask for a menu_choice whenever we hit the start of the loop. In > contrast, the original code is so long that we may have forgotten, which > is why each menu command appears to repeat the "Choose an option:" > question. > > (When you learn a little more about Python, we can talk about the concept > of "dispatch tables" to further dissolve that code, but let's talk about > that later.) > > I guess I'm trying to say: style can mattes because it can help you fix > your program's bugs faster. *grin* > > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050707/f23b2f4c/attachment.htm From klappnase at freenet.de Thu Jul 7 12:27:03 2005 From: klappnase at freenet.de (Michael Lange) Date: Thu, 7 Jul 2005 12:27:03 +0200 Subject: [Tutor] Adding attributes to imported class In-Reply-To: <1120690980.42cc63248aab7@www.paradise.net.nz> References: <20050706210509.64809a6a.klappnase@freenet.de> <1120690980.42cc63248aab7@www.paradise.net.nz> Message-ID: <20050707122703.52d9158a.klappnase@freenet.de> On Thu, 07 Jul 2005 11:03:00 +1200 (NZST) jfouhy at paradise.net.nz wrote: > Quoting Michael Lange : > > > I'm trying to write a python wrapper for the tkDnD Tk extension to add > > drag and drop support > > Hi Michael, > > Just a side issue --- tkDnD seems to be broken in python 2.4: see bug 1164742, > http://sourceforge.net/tracker/index.php?func=detail&aid=1164742&group_id=5470&atid=105470 > > -- Hi John, thanks for the pointer , but of course I did not mean the python module but the Tk extension library ( http://sourceforge.net/projects/tkdnd ), which adds "real" dnd support to Tk. As far as I have tested (not very much however) it seems to work now, but I'm still not sure if the on-the-fly adding of attributes to classes of an imported module is proper programming style or "do-it-yourself lobotomy" . It is the first time for me to try wrapping a Tk extension for python, so I am not sure of the way to go. Anyway, it's a cool new feature for Tkinter, so I thought I should share it with the community; anyone who is interested can find it at http://www.8ung.at/klappnase/TkinterDnD/TkinterDnD.html . Any feedback is much appreciated. Best regards Michael From m.moghimi at gmail.com Thu Jul 7 12:24:16 2005 From: m.moghimi at gmail.com (Mohammad Moghimi) Date: Thu, 7 Jul 2005 14:54:16 +0430 Subject: [Tutor] maximum recursion depth exceeded ! Message-ID: Hi there I wrote a recursive function a got this error how can I increase maximum recursion depth. And what is its default value? -- Mohammad do you Python?!! From ewald.ertl at hartter.com Thu Jul 7 12:51:58 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 7 Jul 2005 12:51:58 +0200 Subject: [Tutor] Why is this error showing up? (Original Message: (Tutor) What's wrong with this code?) Ignore previous post. In-Reply-To: References: <20050707093653.0000416b@sunray1> Message-ID: <20050707125158.0000786e@sunray1> Hello! I just looked a little over the code, what it is perhaps ment to do now. As allready mentioned by Ziyad in your former post: just call "main_menu()" don't print main_menu() This calls the funciton main_men(), which prints it menu and after this the print-Command in this line print's the return-Value of the function : e.g. in the python-shell: >>> def main_menu(): ... print "here in main_menu" ... >>> print main_menu() here in main_menu None The next thing is to move main_menu() into the while-Loop, so you see the menu every time the loop runs, otherwise it would after some inputs disappear from the screen. In every if/elif-branch you can delete the last raw_input() requesting for an option, because the while-Loop has it's own request at the start of the loop. Here's a snap of the first 2 Options in the menu, I've changed: --------- while menu_choice != "9": main_menu() menu_choice = raw_input("Choose an option: ") if menu_choice == "1": print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") sitelist[site] = [id,passcard] !!!! Here I asign the data to the dictionary sitelist with the key "site" !!!! an list with the value of id as the first entry and the value of passcard !!!! as the second entry !!!! I've renamed list to sitelist, because list itself is a builtin creating !!!! a list . !!!! e.g.: !!!! >>> a="hallo" !!!! >>> list(a) !!!! ['h', 'a', 'l', 'l', 'o'] !!!! elif menu_choice == "2": print "Lookup a login info card" site = raw_input("Site: ") !!!! as the "list" is a dictionary we can lookup if the site is !!!! available in the sitelist. if sitelist.has_key(site): print "The ID is: ",sitelist[site][0] !!!! the 0 Element of the list at sitelist[site] is the id and the first !!!! one is the password. print "The password is: ",sitelist[site][1] else: print site," was not found." --------- I've used a list for storing the elements of id and passcard, but you could also use an other dictionary with the keys id and passcard if you like. The next problem is in the part of menu_choice =="3" and "4": There is no dictionary named "numbers". Here you can also use the sitelist[site], ... I hope that help's you to change the rest of your code. Ewald From kraus at hagen-partner.de Thu Jul 7 12:55:48 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 07 Jul 2005 12:55:48 +0200 Subject: [Tutor] maximum recursion depth exceeded ! In-Reply-To: References: Message-ID: Mohammad Moghimi wrote: > Hi there > I wrote a recursive function a got this error how can I increase > maximum recursion depth. And what is its default value? > -- Mohammad > do you Python?!! Start your python interpreter and: >>> import sys >>> sys.getrecursionlimit() 1000 >>> help(sys.setrecursionlimit) HTH, Wolfram From andreengels at gmail.com Thu Jul 7 12:57:43 2005 From: andreengels at gmail.com (Andre Engels) Date: Thu, 7 Jul 2005 12:57:43 +0200 Subject: [Tutor] What's wrong with this code? In-Reply-To: References: <6faf39c905070423445b8d263f@mail.gmail.com> <6faf39c9050704234457994d3f@mail.gmail.com> <42CA30B4.3070402@po-box.mcgill.ca> Message-ID: <6faf39c905070703576dd92ea2@mail.gmail.com> On 7/7/05, Nathan Pinno wrote: > Hi all, > > I meant to ask why the main part after the password is not working right. > No one has answered that yet. When I run the code and try to load a file > that has been saved, a TypeError appears. How do I fix the code so no more > errors will show up. Here is the newest code so far: I don't get a TypeError, but a NameError. Reason is the line: filename == raw_input("Filename to load: ") which should be: filename = raw_input("Filename to load: ") After correcting this, I get the TypeError. And the error clearly says what is wrong: in_file is a file object, and those do not have the value "len". I think what you mean is done by replacing: if len(in_file) == 0: by: if len(in_line) == 0: In general, in such cases, check the error message. In this case it said "len() of an unsized object". There is only one len() in the line given, so that must be it, and thus in_file must be that 'unsized object'. Andre Engels From ewald.ertl at hartter.com Thu Jul 7 12:58:34 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu, 7 Jul 2005 12:58:34 +0200 Subject: [Tutor] maximum recursion depth exceeded ! In-Reply-To: References: Message-ID: <20050707125834.00005f58@sunray1> Hi Mohammad! I've never use a recursive function in python, but the error has the same meaning as e.g in java. Your function get's called and called without the end-criteria for the recursive call is ever met. I would suggest to check if the end-criteria of the recursive call is correct. I don't know if there is something like a "default" value for the maximum of a recursive call depth. I just looked into the sys-Module and found the following on my Solaris 9 box: >>> help(sys.setrecursionlimit) Help on built-in function setrecursionlimit: setrecursionlimit(...) setrecursionlimit(n) Set the maximum depth of the Python interpreter stack to n. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform- dependent. >>> sys.getrecursionlimit() 1000 >>> HTH Ewald on Thu, 7 Jul 2005 14:54:16 +0430 Mohammad Moghimi wrote : --------------------------------------------------------------------------------------------- Mohammad Moghimi > Hi there Mohammad Moghimi > I wrote a recursive function a got this error how can I increase Mohammad Moghimi > maximum recursion depth. And what is its default value? Mohammad Moghimi > -- Mohammad Mohammad Moghimi > do you Python?!! Mohammad Moghimi > _______________________________________________ Mohammad Moghimi > Tutor maillist - Tutor at python.org Mohammad Moghimi > http://mail.python.org/mailman/listinfo/tutor Mohammad Moghimi > ------------------- end ---------------------- -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl at trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl at hartter.com From m.moghimi at gmail.com Thu Jul 7 13:17:18 2005 From: m.moghimi at gmail.com (Mohammad Moghimi) Date: Thu, 7 Jul 2005 15:47:18 +0430 Subject: [Tutor] a problem wiht struct module Message-ID: Hi there can you describe why last two lines print different numbers --------------------------------------------------------------- import struct struct.calcsize("lH") struct.calcsize("Hl") --------------------------------------------------------------- -- Mohammad do you Python?!! From kent37 at tds.net Thu Jul 7 13:46:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 7 Jul 2005 7:46:41 -0400 Subject: [Tutor] Create zip files on the fly. Message-ID: <200507071146.j67BkfJm008734@outbound4.mail.tds.net> Negroup - wrote: > Hi, in my application I need to generate a zip file (via the great > zipfile module) and pass it from function A to function B. One way to > do it is create the object from function A and write it on filesystem > via close(). Then, function B will obtain the object reading the file > from disk. After this operation, the file must be deleted from the > filesystem. > > Now I'd like to know if it is possible to accomplish this task working > in memory directly without pass for the filesystem. I know that a > class StringIO.StringIO (memory files) exists, but I need something > valid for zipfiles. The ZipFile constructor accepts a "file-like object"; that is, any object that supports the same interface as a file. An instance of cStringIO.StringIO should work fine here. Something like out = cStringIO.StringIO() zip = zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) Kent From kent37 at tds.net Thu Jul 7 13:55:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 7 Jul 2005 7:55:59 -0400 Subject: [Tutor] a problem wiht struct module Message-ID: <200507071155.j67BtxaB002628@outbound3.mail.tds.net> Mohammad Moghimi wrote: > Hi there > can you describe why last two lines print different numbers > > --------------------------------------------------------------- > import struct > struct.calcsize("lH") > struct.calcsize("Hl") > --------------------------------------------------------------- Because by default struct uses "native" alignment. Your processor presumably aligns longs on long boundaries so two pad bytes are inserted in the Hl case. You can force no alignment by using "standard" alignment. For example on Windows: >>> from struct import calcsize >>> calcsize('Hl') 8 >>> calcsize('lH') 6 >>> calcsize('=Hl') 6 >>> calcsize('=lH') 6 Kent From work at infomaniak.ch Thu Jul 7 15:19:16 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Thu, 07 Jul 2005 15:19:16 +0200 Subject: [Tutor] python and database Message-ID: <20050707131916.GG31365@obs.unige.ch> Hi, I've read this: http://www.python.org/workshops/1997-10/proceedings/shprentz.html and some points look good: - no hand coded SQL queries - provide a cache - objects insert and updates - ... but quite old too. So the question is : what are the best practice to use python with a pgsql. Ced. -- Cedric BRINER From mhansen at cso.atmel.com Thu Jul 7 16:06:25 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 07 Jul 2005 08:06:25 -0600 Subject: [Tutor] generating documentation for a module Message-ID: <42CD36E1.8030401@cso.atmel.com> Is there a utility that generates documentation for your python modules/scripts/programs based on their doc strings that looks similar to the library documentation on the python web site? What do you use to generate documentation for your python modules/scripts/programs? Mike From kraus at hagen-partner.de Thu Jul 7 16:17:11 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 07 Jul 2005 16:17:11 +0200 Subject: [Tutor] generating documentation for a module In-Reply-To: <42CD36E1.8030401@cso.atmel.com> References: <42CD36E1.8030401@cso.atmel.com> Message-ID: Mike Hansen wrote: > Is there a utility that generates documentation for your python > modules/scripts/programs based on their doc strings that looks similar to the > library documentation on the python web site? > > What do you use to generate documentation for your python modules/scripts/programs? > > Mike Never used it, but this should do what you want: http://docs.python.org/lib/module-pydoc.html Batteries included ;-) HTH, Wolfram From count0.djd at gmail.com Thu Jul 7 17:33:52 2005 From: count0.djd at gmail.com (David Driver) Date: Thu, 7 Jul 2005 10:33:52 -0500 Subject: [Tutor] Dict operation question. Message-ID: <22803ae20507070833b5f7cc@mail.gmail.com> I have a function def updateit(self,**mydict): which is intended to update a dictionary self.somedict. If there are keys in mydict that are not in self.somedict I want them returned in a new dict. here is what i am doing now: errdict = dict([(a,b) for a,b in mydict.items() if not a in self.somedict]) I then test (if errdict) and raise an exception that contains errdict as an attribute. Else i update self.somedict. Is there something other than a list comprehension in a dict function that can do this? Thanks! -- *********************************** See there, that wasn't so bad. *********************************** From ja_roush at mminternet.com Thu Jul 7 18:42:47 2005 From: ja_roush at mminternet.com (Jim Roush) Date: Thu, 07 Jul 2005 09:42:47 -0700 Subject: [Tutor] Can't figure out AttributeError message Message-ID: <42CD5B87.9020209@mminternet.com> I'm getting the following error message: AttributeError: 'tuple' object has no attribute 'seek' below is the code that produced the error. The line in question is marked with arrow in the left margin. Any help would be appreciated. def build_sp500_rand(): sp500_csv = open('c:/indices/sp500.csv', 'r') sp500_csv_recs = sp500_csv.readlines() sp500_csv.close() sp_rand = ('c:/indices/sp500.rnd', 'w+b') record_size = struct.calcsize('Lf') record_number = 0 for rec in sp500_csv_recs: rec.strip('\n') sp500_csv_fields = rec.split(',') sp500_csv_date = sp500_csv_fields[0] sp500_csv_open = sp500_csv_fields[1] sp500_csv_high = sp500_csv_fields[2] sp500_csv_low = sp500_csv_fields[3] sp500_csv_close = sp500_csv_fields[4] sp500_csv_volume = sp500_csv_fields[5] print 'build:', sp500_csv_date buffer = struct.pack('Lf', long(sp500_csv_date), float(sp500_csv_close)) ====> sp_rand.seek(record_number * record_size) sp_rand.write(buffer) record_number = record_number + 1 sp_rand.close() -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.8.10/43 - Release Date: 7/6/2005 From reed at intersiege.com Thu Jul 7 19:09:27 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Thu, 07 Jul 2005 13:09:27 -0400 Subject: [Tutor] Can't figure out AttributeError message In-Reply-To: <42CD5B87.9020209@mminternet.com> References: <42CD5B87.9020209@mminternet.com> Message-ID: <42CD61C7.6000901@intersiege.com> Jim Roush wrote: >I'm getting the following error message: > > AttributeError: 'tuple' object has no attribute 'seek' > >below is the code that produced the error. The line in question is >marked with arrow in the left margin. Any help would be appreciated. > >def build_sp500_rand(): > sp500_csv = open('c:/indices/sp500.csv', 'r') > sp500_csv_recs = sp500_csv.readlines() > sp500_csv.close() > > sp_rand = ('c:/indices/sp500.rnd', 'w+b') > record_size = struct.calcsize('Lf') > > record_number = 0 > for rec in sp500_csv_recs: > rec.strip('\n') > sp500_csv_fields = rec.split(',') > > > sp500_csv_date = sp500_csv_fields[0] > sp500_csv_open = sp500_csv_fields[1] > sp500_csv_high = sp500_csv_fields[2] > sp500_csv_low = sp500_csv_fields[3] > sp500_csv_close = sp500_csv_fields[4] > sp500_csv_volume = sp500_csv_fields[5] > > print 'build:', sp500_csv_date > > buffer = struct.pack('Lf', long(sp500_csv_date), >float(sp500_csv_close)) >====> sp_rand.seek(record_number * record_size) > sp_rand.write(buffer) > > record_number = record_number + 1 > > sp_rand.close() > > > > > > >>> sp_rand = ('c:/indices/sp500.rnd', 'w+b') >>> type(sp_rand) you aren't opening sp_500.rnd you are assigning tuple values. >>> sp_rand = open('c:/indices/sp500.rnd', 'w+b') >>> type(sp_rand) but you still need to read in values (sp_rand.readlines()) assuming that's what you want. ~r -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 keyID: 0x0FA09FCE From bvande at po-box.mcgill.ca Thu Jul 7 19:11:33 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 07 Jul 2005 13:11:33 -0400 Subject: [Tutor] Can't figure out AttributeError message In-Reply-To: <42CD5B87.9020209@mminternet.com> References: <42CD5B87.9020209@mminternet.com> Message-ID: <42CD6245.7070500@po-box.mcgill.ca> Jim Roush said unto the world upon 07/07/2005 12:42: > I'm getting the following error message: > > AttributeError: 'tuple' object has no attribute 'seek' > > below is the code that produced the error. The line in question is > marked with arrow in the left margin. Any help would be appreciated. > > def build_sp500_rand(): > sp500_csv = open('c:/indices/sp500.csv', 'r') > sp500_csv_recs = sp500_csv.readlines() > sp500_csv.close() > > sp_rand = ('c:/indices/sp500.rnd', 'w+b') Here is the problem. sp_rand is a tuple of 2 strings, not a file object. Try sp_rand = open('c:/indices/sp500.rnd', 'w+b') or sp_rand = file('c:/indices/sp500.rnd', 'w+b') > record_size = struct.calcsize('Lf') > > record_number = 0 > for rec in sp500_csv_recs: > buffer = struct.pack('Lf', long(sp500_csv_date), > float(sp500_csv_close)) > ====> sp_rand.seek(record_number * record_size) > sp_rand.write(buffer) > > record_number = record_number + 1 > > sp_rand.close() HTH, Brian vdB From falcon3166 at hotmail.com Thu Jul 7 19:43:05 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 11:43:05 -0600 Subject: [Tutor] Why does invalid syntax pop up? Message-ID: Hi all, Why does invalid syntax popup? Here is the latest code: # This is the code for a password protected program to store passwords. password = "hello" print "The Password Program" print "Copyright 2005 Nathan Pinno." print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") def main_menu_command(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Save login list" print "6) Open Login list" print "9) Exit" def load_login_command(site,filename): in_file = open(filename,"r") while 1: in_line = in_file.readline() if len(in_file) == 0: break in_line = in_line[:-1] [site,id,passcard] = string.split(in_line,",") list[site] = id and passcard in_file.close() def save_login_command(site,filename): out_file = open(filename,"w") for x in site.keys(): out_file.write(x+","+sites[x]+"\n") out_file.close() def add_login_command(site,filename): print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") sitelist[site] = [id,passcard] def lookup_login_command(site,filename): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitelist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." def remove_login_command(site,filename): print "Remove a login info card" site = raw_input("Site: ") if sites.has_key(site): del sitelist[site] else: print site," was not found." def display_login_command(site,filename): print "Login Info" for x in site.keys(): print "Site: ",sitelist," \tID: ",sitelist[site]," \tPassword: ",sitelist[site] print menu_choice = "0" list = {} print "Welcome to the second half of the program." main_menu() while menu_choice != "9": menu_choice = raw_input("Choose an option: ") if menu_choice == "1": add_login_command() elif menu_choice == "2": lookup_login_command() elif menu_choice == "3": remove_login_command() elif menu_choice == "4": display_login_command() elif menu_choice == "5": filename = raw_input("Filename to save: ") save_login_command() elif menu_choice == "6": filename = raw_input("Filename to load: ") load_login_command() print "Have a nice day!" Thanks, Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050707/56fa251d/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Thu Jul 7 19:53:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 7 Jul 2005 10:53:54 -0700 (PDT) Subject: [Tutor] Why does invalid syntax pop up? In-Reply-To: Message-ID: On Thu, 7 Jul 2005, Nathan Pinno wrote: > Why does invalid syntax popup? [text cut] Hi Nathan, What does the SyntaxError look like? Copy-and-paste that error message and bring it to the Tutor list. One thing we want to help you do is recognize what the SyntaxError is really trying to say, so that the next time you see a SyntaxError, you have ways to fix it. Best of wishes! From falcon3166 at hotmail.com Thu Jul 7 21:04:46 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 13:04:46 -0600 Subject: [Tutor] Why does invalid syntax pop up? References: Message-ID: Here is the error: File "D:\password.py", line 45 site = raw_input("Site: ") ^ SyntaxError: invalid syntax HTH, Nathan Pinno ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: Sent: Thursday, July 07, 2005 11:53 AM Subject: Re: [Tutor] Why does invalid syntax pop up? > > > On Thu, 7 Jul 2005, Nathan Pinno wrote: > >> Why does invalid syntax popup? > > [text cut] > > Hi Nathan, > > What does the SyntaxError look like? Copy-and-paste that error message > and bring it to the Tutor list. One thing we want to help you do is > recognize what the SyntaxError is really trying to say, so that the next > time you see a SyntaxError, you have ways to fix it. > > Best of wishes! > > From falcon3166 at hotmail.com Thu Jul 7 21:09:04 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 13:09:04 -0600 Subject: [Tutor] Why does invalid syntax pop up? References: Message-ID: Here is another error message: Traceback (most recent call last): File "D:\password.py", line 69, in ? main_menu() NameError: name 'main_menu' is not defined Thanks. ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: Sent: Thursday, July 07, 2005 1:04 PM Subject: Re: [Tutor] Why does invalid syntax pop up? > Here is the error: > > File "D:\password.py", line 45 > site = raw_input("Site: ") > ^ > SyntaxError: invalid syntax > > HTH, > Nathan Pinno > ----- Original Message ----- > From: "Danny Yoo" > To: "Nathan Pinno" > Cc: > Sent: Thursday, July 07, 2005 11:53 AM > Subject: Re: [Tutor] Why does invalid syntax pop up? > > > > > > > > On Thu, 7 Jul 2005, Nathan Pinno wrote: > > > >> Why does invalid syntax popup? > > > > [text cut] > > > > Hi Nathan, > > > > What does the SyntaxError look like? Copy-and-paste that error message > > and bring it to the Tutor list. One thing we want to help you do is > > recognize what the SyntaxError is really trying to say, so that the next > > time you see a SyntaxError, you have ways to fix it. > > > > Best of wishes! > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Thu Jul 7 21:12:38 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 7 Jul 2005 13:12:38 -0600 Subject: [Tutor] Why does invalid syntax pop up? References: Message-ID: Here is the latest code, in case you need it: # This is the code for a password protected program to store passwords. password = "hello" print "The Password Program" print "Copyright 2005 Nathan Pinno." print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") def main_menu_command(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Save login list" print "6) Open Login list" print "9) Exit" def load_login_command(site,filename): in_file = open(filename,"r") while 1: in_line = in_file.readline() if len(in_file) == 0: break in_line = in_line[:-1] [site,id,passcard] = string.split(in_line,",") list[site] = id and passcard in_file.close() def save_login_command(site,filename): out_file = open(filename,"w") for x in site.keys(): out_file.write(x+","+sites[x]+"\n") out_file.close() def add_login_command(site,filename): print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") sitelist[site] = [id,passcard] def lookup_login_command(site,filename): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitelist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." def remove_login_command(site,filename): print "Remove a login info card" site = raw_input("Site: ") if sites.has_key(site): del sitelist[site] else: print site," was not found." def display_login_command(site,filename): print "Login Info" for x in site.keys(): print "Site: ",sitelist," \tID: ",sitelist[site]," \tPassword: ",sitelist[site] print menu_choice = "0" list = {} print "Welcome to the second half of the program." main_menu() while menu_choice != "9": menu_choice = raw_input("Choose an option: ") if menu_choice == "1": add_login_command() elif menu_choice == "2": lookup_login_command() elif menu_choice == "3": remove_login_command() elif menu_choice == "4": display_login_command() elif menu_choice == "5": filename = raw_input("Filename to save: ") save_login_command() elif menu_choice == "6": filename = raw_input("Filename to load: ") load_login_command() print "Have a nice day!" HTH, Nathan Pinno. ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: Sent: Thursday, July 07, 2005 1:09 PM Subject: Re: [Tutor] Why does invalid syntax pop up? > Here is another error message: > > Traceback (most recent call last): > File "D:\password.py", line 69, in ? > main_menu() > NameError: name 'main_menu' is not defined > > Thanks. > ----- Original Message ----- > From: "Nathan Pinno" > To: "Danny Yoo" > Cc: > Sent: Thursday, July 07, 2005 1:04 PM > Subject: Re: [Tutor] Why does invalid syntax pop up? > > > > Here is the error: > > > > File "D:\password.py", line 45 > > site = raw_input("Site: ") > > ^ > > SyntaxError: invalid syntax > > > > HTH, > > Nathan Pinno > > ----- Original Message ----- > > From: "Danny Yoo" > > To: "Nathan Pinno" > > Cc: > > Sent: Thursday, July 07, 2005 11:53 AM > > Subject: Re: [Tutor] Why does invalid syntax pop up? > > > > > > > > > > > > > On Thu, 7 Jul 2005, Nathan Pinno wrote: > > > > > >> Why does invalid syntax popup? > > > > > > [text cut] > > > > > > Hi Nathan, > > > > > > What does the SyntaxError look like? Copy-and-paste that error > message > > > and bring it to the Tutor list. One thing we want to help you do is > > > recognize what the SyntaxError is really trying to say, so that the > next > > > time you see a SyntaxError, you have ways to fix it. > > > > > > Best of wishes! > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mhansen at cso.atmel.com Thu Jul 7 21:33:26 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu, 07 Jul 2005 13:33:26 -0600 Subject: [Tutor] generating documentation for a module In-Reply-To: References: Message-ID: <42CD8386.80304@cso.atmel.com> > Subject: > Re: [Tutor] generating documentation for a module > From: > Wolfram Kraus > Date: > Thu, 07 Jul 2005 16:17:11 +0200 > To: > tutor at python.org > > To: > tutor at python.org > > > Mike Hansen wrote: > >> Is there a utility that generates documentation for your python >> modules/scripts/programs based on their doc strings that looks similar >> to the library documentation on the python web site? >> >> What do you use to generate documentation for your python >> modules/scripts/programs? >> >> Mike > > > Never used it, but this should do what you want: > > http://docs.python.org/lib/module-pydoc.html > > Batteries included ;-) > HTH, > Wolfram > Duh... I should have noticed that. The html output is pretty good. Thanks, Mike From fant at pobox.com Thu Jul 7 22:01:03 2005 From: fant at pobox.com (Andrew D. Fant) Date: Thu, 07 Jul 2005 16:01:03 -0400 Subject: [Tutor] Getting started in jython Message-ID: <42CD89FF.4090400@pobox.com> I'm a semi-competent python user who has discovered that all the toolkits I really have use of are bound up in java classes. I can cope with this, because there is Python, but I was wondering if anyone who has spent more time around it than I have could spare any advice that will make the adjustment a little less painful. Thanks, Andy From alan.gauld at freenet.co.uk Thu Jul 7 22:50:47 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 7 Jul 2005 21:50:47 +0100 Subject: [Tutor] maximum recursion depth exceeded ! References: Message-ID: <002d01c58335$8d5fac50$c4a88751@xp> > I wrote a recursive function a got this error how can > I increase maximum recursion depth. You have to go into the Python source code and change a value then rebuild Python. > And what is its default value? 1000 last time I looked. But beware that increasing it too far can result in significant memory usage, which is why there is a limit in the first place. Recursion is a powerful tool but can quickly run away with your PC resources. Although with modern machines you can probably increase the limit to 10000 without serious problems - but I've never tried! Maybe someday someone will convert Python to implement tail-end recursion... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Jul 7 22:52:43 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 7 Jul 2005 21:52:43 +0100 Subject: [Tutor] maximum recursion depth exceeded ! References: Message-ID: <003201c58335$d2973f40$c4a88751@xp> > Start your python interpreter and: > > >>> import sys > >>> sys.getrecursionlimit() > 1000 > >>> help(sys.setrecursionlimit) Ooh, that's nice. When did the ability to tweak it programmatically appear? Or has it always been there and I've just never noticed? Looks like a good candidate for use inside an exception handler... Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Jul 7 22:58:46 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 7 Jul 2005 13:58:46 -0700 (PDT) Subject: [Tutor] Why does invalid syntax pop up? In-Reply-To: Message-ID: On Thu, 7 Jul 2005, Nathan Pinno wrote: > Here is another error message: > > Traceback (most recent call last): > File "D:\password.py", line 69, in ? > main_menu() > NameError: name 'main_menu' is not defined Hi Nathan, The error message is correct: there is no "main_menu()" function. There is, however, a "main_menu_command()" function that's defined right at the top. Did you mean that instead? And just out of curiosity, when did you get this NameError message? Before the SyntaxError, or after? The reason I ask is because if you're still hitting SyntaxError, there should no be possible way for the program to even get to NameError --- a SyntaxError is a show-stopper. Is the SyntaxError still showing up? As far as I could tell, your code looked fine from a syntactic point of view. Best of wishes to you! From alan.gauld at freenet.co.uk Thu Jul 7 23:02:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 7 Jul 2005 22:02:38 +0100 Subject: [Tutor] Why does invalid syntax pop up? References: Message-ID: <005801c58337$36354d70$c4a88751@xp> > Why does invalid syntax popup? If you show us the error message it will probably tell us. Thats what the error messages are for. They may look cryptic when you start out but they generally give you a clue as to roughly the right bit of the program and the reason. Can you repost with the error to save us reading and analysing all of your code. Thanks, Now a quick scan through shows up some strangely indented print statements, is it those that are being complained about: def lookup_login_command(site,filename): print "Lookup a login info card" there is an indentation mismatch between these lines. site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitelist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Jul 8 00:11:42 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 7 Jul 2005 23:11:42 +0100 Subject: [Tutor] Getting started in jython References: <42CD89FF.4090400@pobox.com> Message-ID: <002201c58340$dbc6c670$fe338651@xp> > I'm a semi-competent python user who has discovered that all the > toolkits I really have use of are bound up in java classes. I can cope > with this, because there is Python, but I was wondering if anyone who > has spent more time around it than I have could spare any advice that > will make the adjustment a little less painful. Just go through the Jython tutorial. I found the O'Reilly book useful too but it does cover a lot of basic Python stuff if you already know standard Python. But since I have a Safari subscription it didn't cost me anything! Alan G. From denise.hartley at gmail.com Fri Jul 8 00:15:32 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Thu, 7 Jul 2005 15:15:32 -0700 Subject: [Tutor] Getting started in jython In-Reply-To: <002201c58340$dbc6c670$fe338651@xp> References: <42CD89FF.4090400@pobox.com> <002201c58340$dbc6c670$fe338651@xp> Message-ID: <8daabe56050707151534d7edcf@mail.gmail.com> I don't know if this will be useful to everyone, but I found the O'Reilly book wasn't so helpful to those starting with Python and moving to Jython (i.e., rather than starting with Java and not knowing Python). I have yet to find Jython materials that are very good for beginners - most everything I come across is directed at Java programmers who need to learn enough Python to make Jython work. ~Denise On 7/7/05, Alan G wrote: > > > I'm a semi-competent python user who has discovered that all the > > toolkits I really have use of are bound up in java classes. I can > cope > > with this, because there is Python, but I was wondering if anyone > who > > has spent more time around it than I have could spare any advice > that > > will make the adjustment a little less painful. > > Just go through the Jython tutorial. > > I found the O'Reilly book useful too but it does cover a lot of basic > Python stuff if you already know standard Python. But since I have a > Safari > subscription it didn't cost me anything! > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From javier at ruere.com.ar Fri Jul 8 02:36:12 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Thu, 07 Jul 2005 21:36:12 -0300 Subject: [Tutor] Dict operation question. In-Reply-To: <22803ae20507070833b5f7cc@mail.gmail.com> References: <22803ae20507070833b5f7cc@mail.gmail.com> Message-ID: David Driver wrote: > I have a function > > def updateit(self,**mydict): > > which is intended to update a dictionary self.somedict. > > If there are keys in mydict that are not in self.somedict I want them > returned in a new dict. > > here is what i am doing now: > > errdict = dict([(a,b) for a,b in mydict.items() if not a in self.somedict]) > > I then test (if errdict) and raise an exception that contains errdict > as an attribute. Else i update self.somedict. > > Is there something other than a list comprehension in a dict function > that can do this? > > Thanks! Hi, You could have posted the code but anyway, this is your algorithm as I understood it: class Test: def __init__(self, dict): self.somedict = dict def updateit(self, **mydict): errdict = dict([(a,b) for a,b in mydict.items() if not a in self.somedict]) if (not errdict): raise Exception(errdict) self.somedict.update(errdict) The following implementation uses Sets to find the new keys and is slower (twice as slow). from sets import Set class Test: def __init__(self, dict): self.somedict = dict def updateit(self, **mydict): new = Set(mydict.iterkeys()) cur = Set(self.somedict.iterkeys()) diff = new - cur for k in diff: self.somedict[k] = mydict[k] if (not diff): raise Exception(errdict) The last one uses dicts and is a bit faster than the original. class Test: def __init__(self, dict): self.somedict = dict def updateit(self, **mydict): aux = mydict.copy() aux.update(self.somedict) size = len(self.somedict) self.somedict.update(aux) if (len(self.somedict) == size): raise Exception({}) # It would be empty. Javier From javier at ruere.com.ar Fri Jul 8 04:08:47 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Thu, 07 Jul 2005 23:08:47 -0300 Subject: [Tutor] Dict operation question. In-Reply-To: References: <22803ae20507070833b5f7cc@mail.gmail.com> Message-ID: I should also add the most simple and obvious implementation which is also the fastest: class Test: def __init__(self, dict): self.somedict = dict def updateit(self, **mydict): errdict = {} for k, v in mydict.iteritems(): if k not in self.somedict: self.somedict[k] = v errdict[k] = v if (not errdict): raise Exception(errdict) From carroll at tjc.com Fri Jul 8 08:33:29 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu, 7 Jul 2005 23:33:29 -0700 (PDT) Subject: [Tutor] Why does invalid syntax pop up? In-Reply-To: Message-ID: On Thu, 7 Jul 2005, Nathan Pinno wrote: > Why does invalid syntax popup? > def lookup_login_command(site,filename): > print "Lookup a login info card" > site = raw_input("Site: ") > if sitelist.has_key(site): > print "The ID is: ",sitelist[site][0] > print "The password is: ",sitelist[site][1] > else: > print site," was not found." Bad indentation. Try this instead: def lookup_login_command(site,filename): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitelist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." From kraus at hagen-partner.de Fri Jul 8 08:35:43 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Fri, 08 Jul 2005 08:35:43 +0200 Subject: [Tutor] maximum recursion depth exceeded ! In-Reply-To: <003201c58335$d2973f40$c4a88751@xp> References: <003201c58335$d2973f40$c4a88751@xp> Message-ID: Alan G wrote: >> Start your python interpreter and: >> >>>>> import sys sys.getrecursionlimit() >> 1000 >>>>> help(sys.setrecursionlimit) > > > Ooh, that's nice. When did the ability to tweak it programmatically > appear? Or has it always been there and I've just never noticed? It isn't in the 1.5.2 documentation but in the 2.0 documentation, so it has been there for some time ;-) > Looks like a good candidate for use inside an exception handler... > > Alan G. > From kent37 at tds.net Fri Jul 8 15:37:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jul 2005 9:37:38 -0400 Subject: [Tutor] Dict operation question. Message-ID: <200507081337.j68DbcoV021221@outbound2.mail.tds.net> David Driver wrote: > I have a function > > def updateit(self,**mydict): > > which is intended to update a dictionary self.somedict. > > If there are keys in mydict that are not in self.somedict I want them > returned in a new dict. > > here is what i am doing now: > > errdict = dict([(a,b) for a,b in mydict.items() if not a in self.somedict]) > > I then test (if errdict) and raise an exception that contains errdict > as an attribute. Else i update self.somedict. > > Is there something other than a list comprehension in a dict function > that can do this? What's wrong with using the list comprehension? It is terse and readable. If speed is a concern, you can use mydict.iteritems() instead of mydict.items() and in Python 2.4 you can use a generator comprehension instead of a list comprehension: errdict = dict((a,b) for a,b in mydict.iteritems() if not a in self.somedict) Both of these changes eliminate creation of intermediate lists. Kent From kent37 at tds.net Fri Jul 8 15:39:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 8 Jul 2005 9:39:33 -0400 Subject: [Tutor] Dict operation question. Message-ID: <200507081339.j68DdX5u000643@outbound4.mail.tds.net> Javier Ruere wrote: > I should also add the most simple and obvious implementation which is also the fastest: > > > class Test: > def __init__(self, dict): > self.somedict = dict > > def updateit(self, **mydict): > errdict = {} > for k, v in mydict.iteritems(): > if k not in self.somedict: > self.somedict[k] = v > errdict[k] = v > > if (not errdict): > raise Exception(errdict) My understanding of the OP is that he wants an exception if there are items in errdict. Also this solution will change self.somedict even in the error case which may not be desirable. Kent From alex_brollo at yahoo.it Fri Jul 8 15:57:53 2005 From: alex_brollo at yahoo.it (Alessandro Brollo) Date: Fri, 8 Jul 2005 15:57:53 +0200 (CEST) Subject: [Tutor] New entry in the Tutor list - Question: Python and dbf files Message-ID: <20050708135753.18979.qmail@web26705.mail.ukl.yahoo.com> I'm using Python 2.3 in Win32/WinXP context. I'm new at all to newsgroups and discussion lists; the first help I need, is how to learn "good-manner" use of such very effective, but time-consuming tools. My approach will be a "try-and-error" one; I encourage all of you to send me any suggestion/observation/remark about. I'm a (low-level) user of both Python 2.3 and Dbase IV (yes, I'm far from young). 1. Does a Python dbf reader/writer module exist somewhere? 2. Does a dBase IV - like (or a Python-based dBase IV emulator) free database program exist? Alex ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it From 3dbernard at gmail.com Fri Jul 8 16:11:00 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 8 Jul 2005 10:11:00 -0400 Subject: [Tutor] __init__.py not working? Message-ID: <61d0e2b40507080711516b11de@mail.gmail.com> Hello, In my script library, one directory is named "rendering". When I try to import a module from this directory, I always get this error: #ImportError: dynamic module does not define init function (initrendering) However, there is an __init__.py file in there, and also the pyc version. All other directories of the library seem to be working fine. Any suggestion? Thanks Bernard From alan.gauld at freenet.co.uk Fri Jul 8 18:32:26 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Fri, 8 Jul 2005 17:32:26 +0100 Subject: [Tutor] maximum recursion depth exceeded ! References: <003201c58335$d2973f40$c4a88751@xp> Message-ID: <001301c583da$a1398de0$b4ad8851@xp> >> Ooh, that's nice. When did the ability to tweak it programmatically >> appear? Or has it always been there and I've just never noticed? > > It isn't in the 1.5.2 documentation but in the 2.0 documentation, so > it has been there for some time ;-) I did most of my deep digging in Python on 1.5.1 so that explains it. >From Version 2 onwards I've just read the top level 'what's new' stuff and I doubt if this would have made the headlines! :-) Thanks for the research. Alan G. From carroll at tjc.com Fri Jul 8 19:39:51 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri, 8 Jul 2005 10:39:51 -0700 (PDT) Subject: [Tutor] New entry in the Tutor list - Question: Python and dbf files In-Reply-To: <20050708135753.18979.qmail@web26705.mail.ukl.yahoo.com> Message-ID: On Fri, 8 Jul 2005, Alessandro Brollo wrote: > 1. Does a Python dbf reader/writer module exist > somewhere? A google on "python dbf" led me to a few promising leads: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 http://www.fiby.at/dbfpy/ http://www.garshol.priv.no/download/software/python/ (see "dbfreader") From falcon3166 at hotmail.com Fri Jul 8 22:14:04 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Fri, 8 Jul 2005 14:14:04 -0600 Subject: [Tutor] Why does invalid syntax pop up? References: Message-ID: Thanks, Danny and all. Adjusted the code, here is the newest code and error: # This is the code for a password protected program to store passwords. password = "hello" print "The Password Program" print "Copyright 2005 Nathan Pinno." print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") def main_menu_command(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Save login list" print "6) Open Login list" print "9) Exit" def load_login_command(site,filename): in_file = open(filename,"r") while 1: in_line = in_file.readline() if len(in_file) == 0: break in_line = in_line[:-1] [site,id,passcard] = string.split(in_line,",") list[site] = id and passcard in_file.close() def save_login_command(site,filename): out_file = open(filename,"w") for x in site.keys(): out_file.write(x+","+sites[x]+"\n") out_file.close() def add_login_command(site,filename): print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") sitelist[site] = [id,passcard] def lookup_login_command(site,filename): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitelist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." def remove_login_command(site,filename): print "Remove a login info card" site = raw_input("Site: ") if sites.has_key(site): del sitelist[site] else: print site," was not found." def display_login_command(site,filename): print "Login Info" for x in site.keys(): print "Site: ",sitelist," \tID: ",sitelist[site]," \tPassword: ",sitelist[site] print menu_choice = "0" list = {} print "Welcome to the second half of the program." main_menu_command() while menu_choice != "9": menu_choice = raw_input("Choose an option: ") if menu_choice == "1": add_login_command() elif menu_choice == "2": lookup_login_command() elif menu_choice == "3": remove_login_command() elif menu_choice == "4": display_login_command() elif menu_choice == "5": filename = raw_input("Filename to save: ") save_login_command() elif menu_choice == "6": filename = raw_input("Filename to load: ") load_login_command() print "Have a nice day!" Error Message: Traceback (most recent call last): File "D:\password.py", line 73, in ? add_login_command() TypeError: add_login_command() takes exactly 2 arguments (0 given) How do I fix it so that it runs properly, and any other errors that have to be fixed? ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: Sent: Thursday, July 07, 2005 2:58 PM Subject: Re: [Tutor] Why does invalid syntax pop up? > > > On Thu, 7 Jul 2005, Nathan Pinno wrote: > >> Here is another error message: >> >> Traceback (most recent call last): >> File "D:\password.py", line 69, in ? >> main_menu() >> NameError: name 'main_menu' is not defined > > > Hi Nathan, > > The error message is correct: there is no "main_menu()" function. There > is, however, a "main_menu_command()" function that's defined right at the > top. Did you mean that instead? > > And just out of curiosity, when did you get this NameError message? > Before the SyntaxError, or after? The reason I ask is because if you're > still hitting SyntaxError, there should no be possible way for the program > to even get to NameError --- a SyntaxError is a show-stopper. > > Is the SyntaxError still showing up? As far as I could tell, your code > looked fine from a syntactic point of view. > > > > Best of wishes to you! > > From dyoo at hkn.eecs.berkeley.edu Fri Jul 8 22:48:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 8 Jul 2005 13:48:35 -0700 (PDT) Subject: [Tutor] Why does invalid syntax pop up? In-Reply-To: Message-ID: > Error Message: > Traceback (most recent call last): > File "D:\password.py", line 73, in ? > add_login_command() > TypeError: add_login_command() takes exactly 2 arguments (0 given) > > How do I fix it so that it runs properly, and any other errors that have > to be fixed? Hi Nathan, Ok, so the error message is saying "I'm trying to call the add_login_command, but as add_login_command is defined, it needs two arguments. Isn't this weird?" Let's look at the definition of add_login_command(): ###### def add_login_command(site,filename): print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") sitelist[site] = [id,passcard] ###### It's not clear to me why 'site' and 'filename' are in the argument list, as neither are being used as arguments, and no matter what we pass into add_login_command, it looks like the function just ignores whatever it sees. There are two possible ways of fixing this: 1. When calling add_login_command(), just pass random garbage for those two parameters: add_login_command("foo", "bar") 2. Correct add_login_command() so that it doesn't take in two parameters. I do not like option one. *grin* I strongly recommend fixing the parameter list for add_login_command() so that it doesn't ask for parameters that it never uses. Best of wishes! From bvande at po-box.mcgill.ca Fri Jul 8 23:16:17 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 08 Jul 2005 17:16:17 -0400 Subject: [Tutor] Why does invalid syntax pop up? In-Reply-To: References: Message-ID: <42CEED21.7060601@po-box.mcgill.ca> Nathan Pinno said unto the world upon 08/07/2005 16:14: > Thanks, Danny and all. > > Adjusted the code, here is the newest code and error: > def add_login_command(site,filename): > print "Add a login info card" > site = raw_input("Site: ") > id = raw_input("User ID: ") > passcard = raw_input("Password: ") > sitelist[site] = [id,passcard] > while menu_choice != "9": > menu_choice = raw_input("Choose an option: ") > if menu_choice == "1": > add_login_command() > Error Message: > Traceback (most recent call last): > File "D:\password.py", line 73, in ? > add_login_command() > TypeError: add_login_command() takes exactly 2 arguments (0 given) > > How do I fix it so that it runs properly, and any other errors that have > to be fixed? Hi Nathan, (Having just finished this long email up, I see that Danny is quicker, terser, and more to the point than I am. But I hate to waste the effort, so I'm sending anyway. In case of conflict, go with what Danny said :-) First, I mean what I am about to say as a constructive comment. It seems like you have been getting an error message and then posting the error msg and entire generating code to the list. It is good you are giving the exact error msg now, but posting the entire code isn't really the best idea. It would be much better if you instead tried to post a smaller chunk of the code that still exhibits the behaviour you'd like help with. (My snips don't leave it running but that is the general idea.) This is good for 2 reasons: 1) It makes it less time-consuming for those who want to help you, and 2) It is a great way of helping yourself. Trimming things down is a valuable way for you to gain general understanding *and* will often result in your determining the answer to your own question. No one on the list minds helping, that's what its for (and goodness knows, I'm grateful for the hours and hours of effort list members have put into helping me). But, the ultimate point is to learn to help yourself, right? :-) So, to your particular problem: Look at the code that remains above. The error msg is complaining that the function add_login_command takes 2 arguments and that it was called with none. And sure enough, if you look at your def block for the function: def add_login_command(site,filename): # code goes here and the block causing the error: if menu_choice == "1": add_login_command() you've called it with no arguments at all. Hence the poor Python interpreter is confused. So, minimally, to fix it, you need to either pass arguments to the function call or to remove the arguments from the function definition. I'm not sure what your overall intent is, so it is hard to say. I also wonder if you understand the role of the arguments in function definitions. Several functions you defined take site as one of their arguments, but do nothing with it other than rebind the name to the result of a raw_input() call. In that case, it isn't clear why you should have the argument. Compare these: IDLE 1.1.1 >>> def very_silly_print_function(the_argument): the_argument = raw_input('What should I print?') print the_argument >>> def slightly_less_silly_print_function_no_arg(): the_value = raw_input('What should I print?') print the_value >>> def slightly_less_silly_print_function_arg(the_argument): print the_argument >>> very_silly_print_function('This will not be printed') What should I print?This will be printed instead This will be printed instead >>> slightly_less_silly_print_function_no_arg() What should I print?This will be printed This will be printed >>> slightly_less_silly_print_function_arg('As will this') As will this >>> So, your functions that take site in as an argument and only reference it by site = raw_input(some_prompt_here) are kind of like the very_silly_print_function above. But, it is a bit worse than that. The very_silly_print_function reassigns the name and then does something with it. You only reassign. Then, when your function ends, you drop the name on the floor :-) Take a look at this: >>> def name_dropper(): name_inside_function = raw_input('What is your moniker?') >>> name_dropper() What is your moniker?Brian >>> name_inside_function Traceback (most recent call last): File "", line 1, in -toplevel- name_inside_function NameError: name 'name_inside_function' is not defined >>> The name name_inside_function only exists (so to speak) inside the function. To make it meaningful in your top-level (i.e. not inside a function of class) code, you've got to bind it in the top-level: >>> name_inside_function = 'Misleadingly named string that exists at top-level' >>> name_inside_function 'Misleadingly named string that exists at top-level' >>> name_dropper() What is your moniker?Brian >>> name_inside_function 'Misleadingly named string that exists at top-level' >>> But now there are two names name_inside_function. One in your function scope, one in the top-level or global scope. To make the assignment to the name inside the function affect your top-level name, you've got to do something like: >>> def name_keeper(): name_inside_function = raw_input('What is your moniker?') return name_inside_function >>> top_level_name = name_keeper() What is your moniker?Brian >>> top_level_name 'Brian' >>> (There are other ways, but that's enough for now.) I hope that there is some help in all that :-) Best, brian vdB From dyoo at hkn.eecs.berkeley.edu Sat Jul 9 00:14:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 8 Jul 2005 15:14:44 -0700 (PDT) Subject: [Tutor] Why does invalid syntax pop up? (fwd) Message-ID: [Nathan, please don't send only to me: make sure you're using "Reply to All" and that tutor at python.org is also being replied to. I'm actually going slightly crazy with work right now, but there are other people on the mailing list who can help. I'm forwarding your message to the rest of the mailing list now. Good luck!] ---------- Forwarded message ---------- Date: Fri, 8 Jul 2005 16:08:53 -0600 From: Nathan Pinno To: Danny Yoo Subject: Re: [Tutor] Why does invalid syntax pop up? Here's another: Traceback (most recent call last): File "D:\password.py", line 73, in ? add_login_command() File "D:\password.py", line 41, in add_login_command sitelist[site] = [id,passcard] NameError: global name 'sitelist' is not defined And current code: # This is the code for a password protected program to store passwords. password = "hello" print "The Password Program" print "Copyright 2005 Nathan Pinno." print answer = raw_input("What is the password? ") while password != answer: print "The password is incorrect." answer = raw_input("What is the password? ") def main_menu_command(): print "1) Add a login info card" print "2) Lookup a login info card" print "3) Remove a login info card" print "4) Print Login info list" print "5) Save login list" print "6) Open Login list" print "9) Exit" def load_login_command(site,filename): in_file = open(filename,"r") while 1: in_line = in_file.readline() if len(in_file) == 0: break in_line = in_line[:-1] [site,id,passcard] = string.split(in_line,",") list[site] = id and passcard in_file.close() def save_login_command(site,filename): out_file = open(filename,"w") for x in site.keys(): out_file.write(x+","+sites[x]+"\n") out_file.close() def add_login_command(): print "Add a login info card" site = raw_input("Site: ") id = raw_input("User ID: ") passcard = raw_input("Password: ") sitelist[site] = [id,passcard] def lookup_login_command(): print "Lookup a login info card" site = raw_input("Site: ") if sitelist.has_key(site): print "The ID is: ",sitelist[site][0] print "The password is: ",sitelist[site][1] else: print site," was not found." def remove_login_command(): print "Remove a login info card" site = raw_input("Site: ") if sites.has_key(site): del sitelist[site] else: print site," was not found." def display_login_command(): print "Login Info" for x in site.keys(): print "Site: ",sitelist," \tID: ",sitelist[site]," \tPassword: ",sitelist[site] print menu_choice = "0" list = {} print "Welcome to the second half of the program." main_menu_command() while menu_choice != "9": menu_choice = raw_input("Choose an option: ") if menu_choice == "1": add_login_command() elif menu_choice == "2": lookup_login_command() elif menu_choice == "3": remove_login_command() elif menu_choice == "4": display_login_command() elif menu_choice == "5": filename = raw_input("Filename to save: ") save_login_command() elif menu_choice == "6": filename = raw_input("Filename to load: ") load_login_command() print "Have a nice day!" Thanks for the input so far, Nathan ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor" Sent: Friday, July 08, 2005 2:48 PM Subject: Re: [Tutor] Why does invalid syntax pop up? > >> Error Message: >> Traceback (most recent call last): >> File "D:\password.py", line 73, in ? >> add_login_command() >> TypeError: add_login_command() takes exactly 2 arguments (0 given) >> >> How do I fix it so that it runs properly, and any other errors that have >> to be fixed? > > > Hi Nathan, > > Ok, so the error message is saying "I'm trying to call the > add_login_command, but as add_login_command is defined, it needs two > arguments. Isn't this weird?" > > > Let's look at the definition of add_login_command(): > > ###### > def add_login_command(site,filename): > print "Add a login info card" > site = raw_input("Site: ") > id = raw_input("User ID: ") > passcard = raw_input("Password: ") > sitelist[site] = [id,passcard] > ###### > > It's not clear to me why 'site' and 'filename' are in the argument list, > as neither are being used as arguments, and no matter what we pass into > add_login_command, it looks like the function just ignores whatever it > sees. > > > There are two possible ways of fixing this: > > 1. When calling add_login_command(), just pass random garbage for > those two parameters: > > add_login_command("foo", "bar") > > 2. Correct add_login_command() so that it doesn't take in two > parameters. > > > I do not like option one. *grin* I strongly recommend fixing the > parameter list for add_login_command() so that it doesn't ask for > parameters that it never uses. > > > Best of wishes! > > From count0.djd at gmail.com Sat Jul 9 00:29:05 2005 From: count0.djd at gmail.com (David Driver) Date: Fri, 8 Jul 2005 17:29:05 -0500 Subject: [Tutor] Dict operation question. In-Reply-To: <22803ae20507070833b5f7cc@mail.gmail.com> References: <22803ae20507070833b5f7cc@mail.gmail.com> Message-ID: <22803ae20507081529508cddd@mail.gmail.com> Really I was just wondering if this was a bad practice or if there was some way to get the same result. So if the list comprehension isn't a bad way to to it then I will stick with it. I am at the point where I have used python for simple stuff for a few years and I am attempting to get past a novice's understanding. Thanks for the suggestions! I do appreciate the input. the python community is probably the best on the Internet. On 7/7/05, David Driver wrote: > I have a function > ... From javier at ruere.com.ar Sat Jul 9 01:33:21 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Fri, 08 Jul 2005 20:33:21 -0300 Subject: [Tutor] Dict operation question. In-Reply-To: <200507081339.j68DdX5u000643@outbound4.mail.tds.net> References: <200507081339.j68DdX5u000643@outbound4.mail.tds.net> Message-ID: Kent Johnson wrote: > My understanding of the OP is that he wants an exception if there are items in errdict. Also this solution will change self.somedict even in the error case which may not be desirable. I understood what the OP said but think he expressed himself incorrectly or the algorithm is wrong. If the exception is thrown when errdict contains elements and somedict is not updated, then somedict will never have any new keys, making the update pointless. On the other hand, if my interpretation was correct there is no point in putting errdict in the exception since it will always be empty. Who knows... Javier From bvande at po-box.mcgill.ca Sat Jul 9 01:16:21 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 08 Jul 2005 19:16:21 -0400 Subject: [Tutor] Why does invalid syntax pop up? (fwd) In-Reply-To: References: Message-ID: <42CF0945.7050005@po-box.mcgill.ca> Danny Yoo said unto the world upon 08/07/2005 18:14: > [Nathan, please don't send only to me: make sure you're using "Reply to > All" and that tutor at python.org is also being replied to. I'm actually > going slightly crazy with work right now, but there are other people on > the mailing list who can help. > > I'm forwarding your message to the rest of the mailing list now. Good > luck!] > > > ---------- Forwarded message ---------- > Date: Fri, 8 Jul 2005 16:08:53 -0600 > From: Nathan Pinno > To: Danny Yoo > Subject: Re: [Tutor] Why does invalid syntax pop up? > > Here's another: > > Traceback (most recent call last): > File "D:\password.py", line 73, in ? > add_login_command() > File "D:\password.py", line 41, in add_login_command > sitelist[site] = [id,passcard] > NameError: global name 'sitelist' is not defined Nathan, if you take a look at my examples with the function I called name_dropper() that might help you understand this. The problem here is that you have only ever assigned anything to sitelist within the body of your various functions. So, the name doesn't 'have meaning' at the global level. I see from the code I sniped that you dealt with the last problem by removing the spurious arguments from the function definition. But I also notice you left them in in other functions with exactly the same problem. I suggest you go through your functions and verify, for each of your arguments, that you are actually using them. Once done that, go through and check that any assignments made within functions are propagated out of them if they are needed in body code. (That was the point of the top_level_name = name_keeper() example I gave. Best, Brian vdB From rabidpoobear at gmail.com Sat Jul 9 01:40:18 2005 From: rabidpoobear at gmail.com (luke p) Date: Fri, 8 Jul 2005 18:40:18 -0500 Subject: [Tutor] dictionary values Message-ID: just assume all the below code is correct. I am not having a problem with it, it is all for example only. I have a dictionary like this: alpha = {'a':0,'b':0, ... 'z':0} and the following code f = file("hamlet.txt","r") text = f.readlines() f.close() for line in text: for char in line: try: alpha[char] += 1 so at the end of the loop I have a dictionary eg. {'a':14000,'b':12000 ... 'z':100} what I want to do is find out which value in my dictionary is lowest. is there a dictionary function for this, like alpha.min() that will return a key:value pair of the lowest? I cannot find one and I wondered if there was a quick fix to this. what I will do instead to find the lowest is just use a list instead... alphalist = ['a','b' ... 'z'] alphavalues = [0,0 ... 0] lowest = alphavalues[0] lowestlocation = 0 and just do for x in range(26):#or is it 25? can't remember if value is included if alphavalues[x] < lowest: lowest = alphavalues[x] lowestlocation = x but for future reference I just wondered about the dictionary thing. thanks in advance. -Luke From gnumathetes at gmail.com Sat Jul 9 02:09:17 2005 From: gnumathetes at gmail.com (Don Parris) Date: Fri, 8 Jul 2005 20:09:17 -0400 Subject: [Tutor] dictionary values In-Reply-To: References: Message-ID: <6692614405070817094b4a4c6d@mail.gmail.com> On 7/8/05, luke p wrote: > just assume all the below code is correct. > I am not having a problem with it, it is all for example only. > > I have a dictionary like this: > alpha = {'a':0,'b':0, ... 'z':0} > and the following code > f = file("hamlet.txt","r") > text = f.readlines() > f.close() > for line in text: > for char in line: > try: > alpha[char] += 1 > > so at the end of the loop I have a dictionary eg. > {'a':14000,'b':12000 ... 'z':100} > > what I want to do is find out which value in my dictionary is lowest. > is there a dictionary function for this, like alpha.min() that will > return a key:value pair of the lowest? I cannot find one and I > wondered if there was a quick fix to this. > > what I will do instead to find the lowest is just use a list instead... > > alphalist = ['a','b' ... 'z'] > alphavalues = [0,0 ... 0] > lowest = alphavalues[0] > lowestlocation = 0 > and just do > for x in range(26):#or is it 25? can't remember if value is included > if alphavalues[x] < lowest: > lowest = alphavalues[x] > lowestlocation = x > > but for future reference I just wondered about the dictionary thing. > thanks in advance. > -Luke > _______________________________________________ I'm new at this, but thought I would throw my $0.02 in the ring for the learning experience. I know that sequence operations won't work on dictionaries. I wonder if you could get away with a lambda here? I'm probably in way over my head, but would something like this work: min = (lambda x, y: x < y) min(1, 9) Could min() take the dictionary values, as in min(dict[0], dict[9])? Again, I'm no expert, but having my input picked apart will be a good thing. ;) Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com Free software is like God's love - you can share it with anyone anywhere anytime! From denise.hartley at gmail.com Sat Jul 9 02:19:22 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Fri, 8 Jul 2005 17:19:22 -0700 Subject: [Tutor] py2exe Message-ID: <8daabe56050708171978d585dd@mail.gmail.com> Hello everyone, and I apologize in advance if anyone gets this message twice. I am trying to figure out how to use py2exe. I've created a game and sent it to friends before, and had to have them install python, pygame, and livewires in order to play it, which, as you can imagine, is a royal pain. So the idea of a windows executable sounds just peachy. I downloaded the package and read through some of the samples. They didnt make a *whole* lot of sense, and I couldn't get them to work, so I googled for some more beginner-friendly tutorials, and found one basic sort of 'overview' here http://www.free2code.net/plugins/articles/read.php?id=395 and another tutorial by Pete Shinners here: http://www.pygame.org/docs/tut/Executable.html . I was very excited to see the later, since the chimp pygame tutorial actually made sense to me as a beginner, and I hoped I'd be able to follow this one as easily. Ah, but alas... I modified the setup.py file to match the details of my game (as best I can imagine: I don't know what "optimize = 2 #0, 1, or 2; like -O and -OO" means, so I just left it as his sample had it, and I'm not sure if I put in all of the module names it will need specified, but it looks as if its supposed to give me an error if it can't find them). But then the tutorial says "simply run this script and it will do all the work. The final executable and DLLs will be placed inside a project directory, which will be inside a directory named "dist". " I tried running it by doubleclicking, and it just closed out, so I tried it with IDLE open and it gave me the following error message: Traceback (most recent call last): File "Z:\misc\surprise\1\setup.py", line 49, in ? setup(name=project_name, scripts=[script]) File "Z:\misc\python\lib\distutils\core.py", line 137, in setup raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: option --force not recognized ..... which has me stymied. The "Z:\misc\python\lib\distutils\core.py" file is not even the setup.py file I'm running (which most of you probably already deduced, but which still confuses me a little), and I have no idea what that error is trying to tell me. I do know, however, that no "dist" directory was created (unless it was put in some really strange place I don't know about). Was there something wonky with my py2exe install, since it's giving me an error from a file in my lib? Or am I just trying to use py2exe incorrectly? If you know why this isnt working, or know of any very-beginner-friendly tutorials other than the ones I found on google, I would surely appreciate it! Thanks, Denise From bvande at po-box.mcgill.ca Sat Jul 9 02:56:45 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 08 Jul 2005 20:56:45 -0400 Subject: [Tutor] dictionary values In-Reply-To: <6692614405070817094b4a4c6d@mail.gmail.com> References: <6692614405070817094b4a4c6d@mail.gmail.com> Message-ID: <42CF20CD.6040708@po-box.mcgill.ca> Don Parris said unto the world upon 08/07/2005 20:09: > On 7/8/05, luke p wrote: >>what I want to do is find out which value in my dictionary is lowest. >>is there a dictionary function for this, like alpha.min() that will >>return a key:value pair of the lowest? I cannot find one and I >>wondered if there was a quick fix to this. >>thanks in advance. >>-Luke > > > > I'm new at this, but thought I would throw my $0.02 in the ring for > the learning experience. I know that sequence operations won't work > on dictionaries. I wonder if you could get away with a lambda here? > I'm probably in way over my head, but would something like this work: > > min = (lambda x, y: x < y) > min(1, 9) > > Could min() take the dictionary values, as in min(dict[0], dict[9])? > > Again, I'm no expert, but having my input picked apart will be a good thing. ;) > > Don Hi Don, try it out at the prompt :-) >>> min = (lambda x, y: x < y) >>> min(1, 9) True >>> So, that's just a complicated way of saying x < y. ;-) There is also a bit of a consensus (though not unanimous) that using lambda to get a function bound to a name is to obscure a def. (See ) Best, Brian vdB From bvande at po-box.mcgill.ca Sat Jul 9 02:34:26 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 08 Jul 2005 20:34:26 -0400 Subject: [Tutor] dictionary values In-Reply-To: References: Message-ID: <42CF1B92.70100@po-box.mcgill.ca> luke p said unto the world upon 08/07/2005 19:40: > just assume all the below code is correct. > I am not having a problem with it, it is all for example only. > > I have a dictionary like this: > alpha = {'a':0,'b':0, ... 'z':0} > and the following code > f = file("hamlet.txt","r") > text = f.readlines() > f.close() > for line in text: > for char in line: > try: > alpha[char] += 1 > > so at the end of the loop I have a dictionary eg. > {'a':14000,'b':12000 ... 'z':100} > > what I want to do is find out which value in my dictionary is lowest. > is there a dictionary function for this, like alpha.min() that will > return a key:value pair of the lowest? I cannot find one and I > wondered if there was a quick fix to this. > > what I will do instead to find the lowest is just use a list instead... > > alphalist = ['a','b' ... 'z'] > alphavalues = [0,0 ... 0] > lowest = alphavalues[0] > lowestlocation = 0 > and just do > for x in range(26):#or is it 25? can't remember if value is included > if alphavalues[x] < lowest: > lowest = alphavalues[x] > lowestlocation = x > > but for future reference I just wondered about the dictionary thing. > thanks in advance. > -Luke Hi Luke, if you care about the possibility that there is no unique key with the lowest value, I'd do: >>> def get_low_keys(a_dict): ... '''-> list of keys in a_dict with lowest value''' ... min_val = min(a_dict.values()) ... low_keys = [] ... for k,v in a_dict.items(): ... if v == min_val: ... low_keys.append(k) ... return low_keys ... >>> lows = get_low_keys(my_dict) >>> lows ['another one', 'one'] >>> If you don't care abut duplicate values, then: >>> def get_low_key(a_dict): ... '''a key in a_dict with lowest value''' ... min_val = min(a_dict.values()) ... for k,v in a_dict.items(): ... if v == min_val: ... return k ... >>> low = get_low_key(my_dict) >>> low 'another one' HTH, Brian vdB From kent37 at tds.net Sat Jul 9 03:03:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Jul 2005 21:03:25 -0400 Subject: [Tutor] dictionary values In-Reply-To: References: Message-ID: <42CF225D.8030804@tds.net> luke p wrote: > just assume all the below code is correct. > I am not having a problem with it, it is all for example only. > > I have a dictionary like this: > alpha = {'a':0,'b':0, ... 'z':0} > and the following code > f = file("hamlet.txt","r") > text = f.readlines() > f.close() > for line in text: > for char in line: > try: > alpha[char] += 1 > > so at the end of the loop I have a dictionary eg. > {'a':14000,'b':12000 ... 'z':100} > > what I want to do is find out which value in my dictionary is lowest. > is there a dictionary function for this, like alpha.min() that will > return a key:value pair of the lowest? I cannot find one and I > wondered if there was a quick fix to this. It's easy enough to convert the dictionary to a list of (count, letter) pairs and find the min of the list: >>> alpha = {'a':14000,'b':12000, 'z':100} >>> alpha.items() [('a', 14000), ('b', 12000), ('z', 100)] >>> [(v,k) for k,v in alpha.items()] [(14000, 'a'), (12000, 'b'), (100, 'z')] >>> min([(v,k) for k,v in alpha.items()]) (100, 'z') or in Python 2.4, without creating the intermediate lists: >>> min((v,k) for k,v in alpha.iteritems()) (100, 'z') Kent From kent37 at tds.net Sat Jul 9 03:09:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Jul 2005 21:09:04 -0400 Subject: [Tutor] dictionary values In-Reply-To: <42CF1B92.70100@po-box.mcgill.ca> References: <42CF1B92.70100@po-box.mcgill.ca> Message-ID: <42CF23B0.4030804@tds.net> Brian van den Broek wrote: > if you care about the possibility that there is no unique key with the > lowest value, I'd do: > > >>> def get_low_keys(a_dict): > ... '''-> list of keys in a_dict with lowest value''' > ... min_val = min(a_dict.values()) > ... low_keys = [] > ... for k,v in a_dict.items(): > ... if v == min_val: > ... low_keys.append(k) > ... return low_keys Hmm, list comprehension is your friend... how about min_val = min(a_dict.values()) low_keys = [ k for k,v in a_dict.items() if v == min_val ] More concise and IMO much more readable. Kent From bvande at po-box.mcgill.ca Sat Jul 9 03:18:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 08 Jul 2005 21:18:25 -0400 Subject: [Tutor] dictionary values In-Reply-To: <42CF23B0.4030804@tds.net> References: <42CF1B92.70100@po-box.mcgill.ca> <42CF23B0.4030804@tds.net> Message-ID: <42CF25E1.101@po-box.mcgill.ca> Kent Johnson said unto the world upon 08/07/2005 21:09: > Brian van den Broek wrote: > >>if you care about the possibility that there is no unique key with the >>lowest value, I'd do: >> >> >>> def get_low_keys(a_dict): >>... '''-> list of keys in a_dict with lowest value''' >>... min_val = min(a_dict.values()) >>... low_keys = [] >>... for k,v in a_dict.items(): >>... if v == min_val: >>... low_keys.append(k) >>... return low_keys > > > Hmm, list comprehension is your friend... how about > min_val = min(a_dict.values()) > low_keys = [ k for k,v in a_dict.items() if v == min_val ] > > More concise and IMO much more readable. > > Kent Yep, I saw your answer after I sent mine. Mine is the second-place solution :-) Best, Brian vdB From reed at intersiege.com Sat Jul 9 05:03:37 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Fri, 08 Jul 2005 23:03:37 -0400 Subject: [Tutor] py2exe In-Reply-To: <8daabe56050708171978d585dd@mail.gmail.com> References: <8daabe56050708171978d585dd@mail.gmail.com> Message-ID: <42CF3E89.4090600@intersiege.com> D. Hartley wrote: >Hello everyone, and I apologize in advance if anyone gets this message twice. > >I am trying to figure out how to use py2exe. I've created a game and >sent it to friends before, and had to have them install python, >pygame, and livewires in order to play it, which, as you can imagine, >is a royal pain. So the idea of a windows executable sounds just >peachy. > >I downloaded the package and read through some of the samples. They >didnt make a *whole* lot of sense, and I couldn't get them to work, so >I googled for some more beginner-friendly tutorials, and found one >basic sort of 'overview' here >http://www.free2code.net/plugins/articles/read.php?id=395 and another >tutorial by Pete Shinners here: >http://www.pygame.org/docs/tut/Executable.html . > >I was very excited to see the later, since the chimp pygame tutorial >actually made sense to me as a beginner, and I hoped I'd be able to >follow this one as easily. > >Ah, but alas... > >I modified the setup.py file to match the details of my game (as best >I can imagine: I don't know what "optimize = 2 #0, >1, or 2; like -O and -OO" means, so I just left it as his sample had >it, and I'm not sure if I put in all of the module names it will need >specified, but it looks as if its supposed to give me an error if it >can't find them). But then the tutorial says "simply run this script >and it will do all the work. The final executable and DLLs will be >placed inside a project directory, which will be inside a directory >named "dist". " I tried running it by doubleclicking, and it just >closed out, so I tried it with IDLE open and it gave me the following >error message: > >Traceback (most recent call last): > File "Z:\misc\surprise\1\setup.py", line 49, in ? > setup(name=project_name, scripts=[script]) > File "Z:\misc\python\lib\distutils\core.py", line 137, in setup > raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg >SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 >[cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > >error: option --force not recognized > >..... which has me stymied. The >"Z:\misc\python\lib\distutils\core.py" file is not even the setup.py >file I'm running (which most of you probably already deduced, but >which still confuses me a little), and I have no idea what that error >is trying to tell me. I do know, however, that no "dist" directory >was created (unless it was put in some really strange place I don't >know about). Was there something wonky with my py2exe install, since >it's giving me an error from a file in my lib? Or am I just trying to >use py2exe incorrectly? > >If you know why this isnt working, or know of any >very-beginner-friendly tutorials other than the ones I found on >google, I would surely appreciate it! > >Thanks, > >Denise >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > If memory serves you don't run it by clicking. you call it from commandline, something like: C:\Python24\python.exe script.py py2exe luck, ~r -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 keyID: 0x0FA09FCE From falcon3166 at hotmail.com Sat Jul 9 09:26:17 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 01:26:17 -0600 Subject: [Tutor] Why does invalid syntax pop up? (fwd) In-Reply-To: <42CF0945.7050005@po-box.mcgill.ca> Message-ID: Hey all, Just a notice, I'm quitting work on this program, too complicated for me to work out, I'm getting lost now and can't figure out the bugs anymore. I think for know I'll work on my Giant Calculator application, which I'll show the code when it's done. If anyone is interested in finishing it, just give me a shout, and I'll send it to you as a ZIP file. Thanks, Nathan Pinno Crew, McDonalds Restaurant, Camrose, AB, Canada http://www.npinnowebsite.ca -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Brian van den Broek Sent: July 8, 2005 5:16 PM Cc: Tutor Subject: Re: [Tutor] Why does invalid syntax pop up? (fwd) Danny Yoo said unto the world upon 08/07/2005 18:14: > [Nathan, please don't send only to me: make sure you're using "Reply > to All" and that tutor at python.org is also being replied to. I'm > actually going slightly crazy with work right now, but there are other > people on the mailing list who can help. > > I'm forwarding your message to the rest of the mailing list now. Good > luck!] > > > ---------- Forwarded message ---------- > Date: Fri, 8 Jul 2005 16:08:53 -0600 > From: Nathan Pinno > To: Danny Yoo > Subject: Re: [Tutor] Why does invalid syntax pop up? > > Here's another: > > Traceback (most recent call last): > File "D:\password.py", line 73, in ? > add_login_command() > File "D:\password.py", line 41, in add_login_command > sitelist[site] = [id,passcard] > NameError: global name 'sitelist' is not defined Nathan, if you take a look at my examples with the function I called name_dropper() that might help you understand this. The problem here is that you have only ever assigned anything to sitelist within the body of your various functions. So, the name doesn't 'have meaning' at the global level. I see from the code I sniped that you dealt with the last problem by removing the spurious arguments from the function definition. But I also notice you left them in in other functions with exactly the same problem. I suggest you go through your functions and verify, for each of your arguments, that you are actually using them. Once done that, go through and check that any assignments made within functions are propagated out of them if they are needed in body code. (That was the point of the top_level_name = name_keeper() example I gave. Best, Brian vdB _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From gnumathetes at gmail.com Sat Jul 9 11:17:15 2005 From: gnumathetes at gmail.com (Don Parris) Date: Sat, 9 Jul 2005 05:17:15 -0400 Subject: [Tutor] Passing Arguments Message-ID: <66926144050709021764f31393@mail.gmail.com> For some reason, everytime I think I finally understand the passing arguments thing, I prove that I don't. However, I *am* getting a little closer to getting it. # Here I just created a couple of variables to print, and then prt_Name returns g. def prt_Name(): g = 'foo' a = 'bar' print g print a return g # get_Name will get the argument from prt_Name: def get_Name(b): print 'f' print b get_Name(prt_Name) # Calling get_Name with prt_Name as the argument produces this: C:\Python24>python scripts\learning.py f At least it found the function. That's little shy of a miracle for me. :) However, I would like to see 'foo' printed out, since it is the result of the function. How can I correct this? Thanks, Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com Free software is like God's love - you can share it with anyone anywhere anytime! From maxnoel_fr at yahoo.fr Sat Jul 9 11:35:19 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat, 9 Jul 2005 11:35:19 +0200 Subject: [Tutor] Passing Arguments In-Reply-To: <66926144050709021764f31393@mail.gmail.com> References: <66926144050709021764f31393@mail.gmail.com> Message-ID: On Jul 9, 2005, at 11:17, Don Parris wrote: > get_Name(prt_Name) > # Calling get_Name with prt_Name as the argument produces this: > > C:\Python24>python scripts\learning.py > f > > > At least it found the function. That's little shy of a miracle for > me. :) However, I would like to see 'foo' printed out, since it is > the result of the function. How can I correct this? You have to call the function: get_Name(prt_Name()) prt_Name is the function itself. prt_Name() (note the parens) calls (executes) the function and allows you to use its return value. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___________________________________________________________________________ Appel audio GRATUIT partout dans le monde avec le nouveau Yahoo! Messenger Téléchargez cette version sur http://fr.messenger.yahoo.com From severin.kacianka at aon.at Sat Jul 9 11:38:37 2005 From: severin.kacianka at aon.at (Severin Kacianka) Date: Sat, 9 Jul 2005 11:38:37 +0200 Subject: [Tutor] UnicodeDecodeError when copying files with Umlauten Message-ID: <200507091138.38079.severin.kacianka@aon.at> Hello, I am very new to python programming and totally new to GUI-programming. Now I try to write a GUI for a little script I wrote some time ago, and get a Error I cannot explain. As it may be helpful for you to see the whole scripts I put them both online: The CLI-application (and library): http://kacianka.at/python/m3u2iso.py The GUI-code: http://kacianka.at/python/win.py The script essentially copies files listed in a m3u file into a given directory. The essential line in the library is line 95: shutil.copyfile(file,'%s%s'% (self.tmpDir,self.currentFile )) Now there is no problem with "normal" files, but if I try to copy a file with German Umlauten (?,?,?,?) a UnicodeDecodeError is triggered in this GUI-Code: def OnConvert(self,event): """Starts everything""" m2i = m3u2iso.m3uToIso(self.m3uPath,self.tmpDir) if DEBUG: print "m3u2iso::m3uPath: %s" % m2i.m3uPath print "m3u2iso::tmpDir: %s" % m2i.tmpDir m2i.getSongPath() m2i.cpFilesToTmpDir(self.shortFileNames,self.verbose,self.start) If I run the script on the CLI, it always works, no matter if the files contain Umlaute or not. However if I do the same thing with the GUI I get this error: Traceback (most recent call last): File "./win.py", line 132, in OnConvert m2i.cpFilesToTmpDir(self.shortFileNames,self.verbose,self.start) File "/home/severin/python/m3u2iso.py", line 100, in cpFilesToTmpDir print "Unicode Error n trying to copy %s to %s%s" % (file,self.tmpDir,self.currentFile ) UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 23: ordinal not in range(128) This happens when I try to copy a file called "Kettcar - Landungsbr?cken raus.mp3". I cannot explain to myself why this happens in the GUI but not in the CLI version. The code is the same! Is there an obvious error in my code, or do I maybe totally missunderstand the concept of handling files with nonstandard characters in them? Thank you for you time, Severin -- They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety. Benjamin Franklin From jfouhy at paradise.net.nz Sat Jul 9 12:15:44 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Sat, 09 Jul 2005 22:15:44 +1200 (NZST) Subject: [Tutor] py2exe In-Reply-To: <8daabe56050708171978d585dd@mail.gmail.com> References: <8daabe56050708171978d585dd@mail.gmail.com> Message-ID: <1120904144.42cfa3d0d8b4a@www.paradise.net.nz> Quoting "D. Hartley" : > I modified the setup.py file to match the details of my game (as best > I can imagine: I don't know what "optimize = 2 #0, > 1, or 2; like -O and -OO" means, so I just left it as his sample had > it, >From python -h: -O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) -OO : remove doc-strings in addition to the -O optimizations optimize=2 means py2exe will optimize the bytecode and remove doc strings; this is probably OK since you're not going to be running the debugger on your finished executable. > and I'm not sure if I put in all of the module names it will need > specified, but it looks as if its supposed to give me an error if it > can't find them). py2exe will search for all the modules it thinks it needs, but sometimes it will miss some. Generally, the best way to find out if it missed anything is to run your executable and see if it crashes :-) > But then the tutorial says "simply run this script > and it will do all the work. You need to run it from the command line: python setup.py py2exe HTH. -- John. From alan.gauld at freenet.co.uk Sat Jul 9 13:19:24 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sat, 9 Jul 2005 12:19:24 +0100 Subject: [Tutor] Passing Arguments References: <66926144050709021764f31393@mail.gmail.com> Message-ID: <001a01c58478$104311a0$b1458651@xp> > # Here I just created a couple of variables to print, and then > prt_Name returns g. >def prt_Name(): > g = 'foo' > print g > return g > > def get_Name(b): > print 'f' > print b > > get_Name(prt_Name) So you are passing a function object into your get_Name function. Is that what you want? Or do you want to pass the value returned by the function? Either is valid but its hard to know where your misunderstanding is until I know your intent... I'll first assume you actually wanted to pass the return value You should have called it like: get_NAme(prtName()) # notice the parens to invoke the prtName If you did mean to pass the function then your call is OK but you need to call prtName inside getName, like so: def get_Name(b): print 'f' print b() # notice the parens to invoke b (which is the prtName function) Which solution were you trying to achieve? Alan G. From falcon3166 at hotmail.com Sat Jul 9 21:07:22 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 13:07:22 -0600 Subject: [Tutor] Is it possible to... Message-ID: Hi all, I was just wondering if it is possible to use Python as a language to password protect a webpage? If it is possible, I wouldn't mind learning how, it would enable me to add a member-only section to my website. Thanks, Nathan Pinno Crew, McDonalds Restaurant, Camrose, AB Canada http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050709/cd38c48e/attachment.htm From falcon3166 at hotmail.com Sat Jul 9 22:00:24 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 14:00:24 -0600 Subject: [Tutor] What's the invalid syntax? Message-ID: What's the invalid syntax? Here's the code (Part of my Guess the Numbers game): if a0 == x0 and a1 == x1 and a2 == x2 and a3 == x3: print "Congratulations! Way to go?" answer = raw input("Play again: (Y)es or (N)o Type the letter of your choice. ") Thanks, Nathan Pinno Crew, McDonalds Restaurant, Camrose, AB Canada http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050709/9048bc31/attachment.htm From zamb at saudi.net.sa Sat Jul 9 22:50:14 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Sat, 09 Jul 2005 23:50:14 +0300 Subject: [Tutor] What's the invalid syntax? In-Reply-To: References: Message-ID: <1120942214.31083.11.camel@localhost.localdomain> On Sat, 2005-07-09 at 14:00 -0600, Nathan Pinno wrote: > What's the invalid syntax? > > Here's the code (Part of my Guess the Numbers game): > > if a0 == x0 and a1 == x1 and a2 == x2 and a3 == x3: > print "Congratulations! Way to go?" > answer = raw input("Play again: (Y)es or (N)o Type the letter of your choice. ") ^^^^^^^^^ raw_input It's "raw_input()" not "raw input()" > > Thanks, > Nathan Pinno > Crew, McDonalds Restaurant, Camrose, AB Canada > http://www.npinnowebsite.ca/ You're welcome. Ziyad. From falcon3166 at hotmail.com Sun Jul 10 00:43:57 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 16:43:57 -0600 Subject: [Tutor] Is it possible to... References: <1120933950.11834.1.camel@localhost.localdomain> Message-ID: Could you send me the code if possible, or show me the way to go? ----- Original Message ----- From: "nephish" To: "Nathan Pinno" Sent: Saturday, July 09, 2005 12:32 PM Subject: Re: [Tutor] Is it possible to... >i am, with a simple if-then statement. works ok, not the most secure > (like what you would expect with something like pay-pal) but works for > what i need. > i have a dictionary that references the username to a password. > if the username is not in the list, they get kicked to a different page. > > > On Sat, 2005-07-09 at 13:07 -0600, Nathan Pinno wrote: >> Hi all, >> >> I was just wondering if it is possible to use Python as a language to >> password protect a webpage? If it is possible, I wouldn't mind >> learning how, it would enable me to add a member-only section to my >> website. >> >> Thanks, >> Nathan Pinno >> Crew, McDonalds Restaurant, Camrose, AB Canada >> http://www.npinnowebsite.ca/ >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From falcon3166 at hotmail.com Sun Jul 10 01:03:12 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 17:03:12 -0600 Subject: [Tutor] Can I use def without ( ) at the end? Message-ID: Hi all, Is the subject possible without getting an error? Nathan Pinno Crew, McDonalds Restaurant, Camrose, AB Canada http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050709/c100b433/attachment.htm From bvande at po-box.mcgill.ca Sun Jul 10 02:15:54 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 09 Jul 2005 20:15:54 -0400 Subject: [Tutor] Can I use def without ( ) at the end? In-Reply-To: References: Message-ID: <42D068BA.1070002@po-box.mcgill.ca> Nathan Pinno said unto the world upon 09/07/2005 19:03: > Hi all, > > Is the subject possible without getting an error? > > Nathan Pinno > Crew, McDonalds Restaurant, Camrose, AB Canada > http://www.npinnowebsite.ca/ No. Why do you want to do this? If it is to have a function with no arguments: >>> def no_args(): ... print "I've no arguments" ... >>> no_args() I've no arguments >>> Brian vdB From falcon3166 at hotmail.com Sun Jul 10 02:33:54 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 18:33:54 -0600 Subject: [Tutor] Can I use def without ( ) at the end? References: <42D068BA.1070002@po-box.mcgill.ca> Message-ID: Hi all, How do I make Python get a def? Is it the "get" function, or something else? I need to know so that I can get a def for that computer MasterMind(tm) game that I'm writing. BTW, I took your advice, and wrote some definitions for my Giant Calculator program. Might make the code easier to read, but harder to code because I have to keep going to the top to read the menu. Not that fun, but necessary for a smooth program, I guess. Nathan Pinno ----- Original Message ----- From: "Brian van den Broek" To: "Nathan Pinno" Cc: Sent: Saturday, July 09, 2005 6:15 PM Subject: Re: [Tutor] Can I use def without ( ) at the end? > Nathan Pinno said unto the world upon 09/07/2005 19:03: >> Hi all, >> >> Is the subject possible without getting an error? >> >> Nathan Pinno >> Crew, McDonalds Restaurant, Camrose, AB Canada >> http://www.npinnowebsite.ca/ > > No. Why do you want to do this? If it is to have a function with no > arguments: > > >>> def no_args(): > ... print "I've no arguments" > ... > >>> no_args() > I've no arguments > >>> > > Brian vdB > > From falcon3166 at hotmail.com Sun Jul 10 02:36:14 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 18:36:14 -0600 Subject: [Tutor] Can I use def without ( ) at the end? References: <42D068BA.1070002@po-box.mcgill.ca> Message-ID: Also, I just wanted to know because I'm using it in my Giant Computer program for the menus, so I don't have to keep re-typing them. Nathan Pinno ----- Original Message ----- From: "Brian van den Broek" To: "Nathan Pinno" Cc: Sent: Saturday, July 09, 2005 6:15 PM Subject: Re: [Tutor] Can I use def without ( ) at the end? > Nathan Pinno said unto the world upon 09/07/2005 19:03: >> Hi all, >> >> Is the subject possible without getting an error? >> >> Nathan Pinno >> Crew, McDonalds Restaurant, Camrose, AB Canada >> http://www.npinnowebsite.ca/ > > No. Why do you want to do this? If it is to have a function with no > arguments: > > >>> def no_args(): > ... print "I've no arguments" > ... > >>> no_args() > I've no arguments > >>> > > Brian vdB > > From bvande at po-box.mcgill.ca Sun Jul 10 02:54:21 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 09 Jul 2005 20:54:21 -0400 Subject: [Tutor] Can I use def without ( ) at the end? In-Reply-To: References: <42D068BA.1070002@po-box.mcgill.ca> Message-ID: <42D071BD.6040808@po-box.mcgill.ca> Nathan Pinno said unto the world upon 09/07/2005 20:36: > ----- Original Message ----- From: "Brian van den Broek" > > > Nathan Pinno said unto the world upon 09/07/2005 19:03: > >> Hi all, > >> > >> Is the subject possible without getting an error? > >> > >> Nathan Pinno > >> Crew, McDonalds Restaurant, Camrose, AB Canada > >> http://www.npinnowebsite.ca/ > > > > No. Why do you want to do this? If it is to have a function with no > > arguments: > > > > >>> def no_args(): > > ... print "I've no arguments" > > ... > > >>> no_args() > > I've no arguments > > >>> > > > > Brian vdB > > > > Also, I just wanted to know because I'm using it in my Giant Computer > program for the menus, so I don't have to keep re-typing them. > > Nathan Pinno Nathan, I'm afraid I don't know what you meant in your other post by "get a def". I'm also unclear on what it is you feel that you are having to retype. The usual way to have some functions and 'drive' them through a text menu is either a dictionary dispatch (don't worry about that right now) or something simpler like: >>> def function_1(): ... print "I am function 1!" ... >>> def function_2(): ... print "I am function 2!" ... >>> def menu(): ... print "I'm a simple menu system." ... print "Enter 1 for function 1" ... print "Enter 2 for function 2" ... choice = raw_input("Your selection please?\n") ... if choice == '1': ... function_1() ... elif choice == '2': ... function_2() ... else: ... print "Please read more carefully" Try that at the prompt, and then call the menu function -- on a line, type: menu() If that isn't helping, you are going to have to explain more clearly what problem it is that you are trying to avoid. Brian vdB From falcon3166 at hotmail.com Sun Jul 10 03:13:06 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 19:13:06 -0600 Subject: [Tutor] Can I use def without ( ) at the end? References: <42D068BA.1070002@po-box.mcgill.ca> <42D071BD.6040808@po-box.mcgill.ca> Message-ID: Brian, I'll do one better and post the code after I'm done writing it. Then you can decide for yourself what I'm trying to do. Nathan P. ----- Original Message ----- From: "Brian van den Broek" To: "Nathan Pinno" Cc: Sent: Saturday, July 09, 2005 6:54 PM Subject: Re: [Tutor] Can I use def without ( ) at the end? > Nathan Pinno said unto the world upon 09/07/2005 20:36: > > > >> ----- Original Message ----- From: "Brian van den Broek" >> >> > Nathan Pinno said unto the world upon 09/07/2005 19:03: >> >> Hi all, >> >> >> >> Is the subject possible without getting an error? >> >> >> >> Nathan Pinno >> >> Crew, McDonalds Restaurant, Camrose, AB Canada >> >> http://www.npinnowebsite.ca/ >> > >> > No. Why do you want to do this? If it is to have a function with no >> > arguments: >> > >> > >>> def no_args(): >> > ... print "I've no arguments" >> > ... >> > >>> no_args() >> > I've no arguments >> > >>> >> > >> > Brian vdB >> >> >> >> Also, I just wanted to know because I'm using it in my Giant Computer >> program for the menus, so I don't have to keep re-typing them. >> >> Nathan Pinno > > > Nathan, > > I'm afraid I don't know what you meant in your other post by "get a > def". I'm also unclear on what it is you feel that you are having to > retype. > > The usual way to have some functions and 'drive' them through a text > menu is either a dictionary dispatch (don't worry about that right > now) or something simpler like: > > > >>> def function_1(): > ... print "I am function 1!" > ... > >>> def function_2(): > ... print "I am function 2!" > ... > >>> def menu(): > ... print "I'm a simple menu system." > ... print "Enter 1 for function 1" > ... print "Enter 2 for function 2" > ... choice = raw_input("Your selection please?\n") > ... if choice == '1': > ... function_1() > ... elif choice == '2': > ... function_2() > ... else: > ... print "Please read more carefully" > > Try that at the prompt, and then call the menu function -- on a line, > type: > > menu() > > If that isn't helping, you are going to have to explain more clearly > what problem it is that you are trying to avoid. > > Brian vdB > > From falcon3166 at hotmail.com Sun Jul 10 05:07:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 21:07:36 -0600 Subject: [Tutor] What's going on with this code? Error message supplied. Message-ID: Here is the error message: Traceback (most recent call last): File "D:\GC.py", line 67, in ? if option == 1: NameError: name 'option' is not defined And the relevant code: print "The Giant Calculator" print print "Copyright 2005 Written and debugged by Nathan Pinno" print print main_menu() if option == 1: and the dictionary code: def main_menu(): print "OPTIONS MENU" print "1) Calculate" print "2) Shapes" print "3) Temperature" print "4) Formulas" print "5) Quit" option = input("What option would you like:" ) Thanks ahead of time, Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050709/7eb2e904/attachment.htm From falcon3166 at hotmail.com Sun Jul 10 05:16:50 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sat, 9 Jul 2005 21:16:50 -0600 Subject: [Tutor] Looks like Giant Calc is a bust. Message-ID: Hey all, The Giant Calculator runs now, just not as I want it to. I can't seem to get it past the main menu. Here is the code: # This program is designed as a big calculator with functions. # This first bunch of code is for the various menus. I decided to divide the calculations into seperate sub-menus, #so that the main menus would not be that long. option = 0 a = 0 b = 0 temp_option = 0 formula_option = 0 def main_menu(): print "OPTIONS MENU" print "1) Calculate" print "2) Shapes" print "3) Temperature" print "4) Formulas" print "5) Quit" option = input("What option would you like:" ) def cal_menu(): print "CALCULATE MENU" print "1) Add" print "2) Subraction" print "3) Multiplication" print "4) Division w/o remainder" print "5) Division with remaider" print "6) Exponation" print "7) Square roots" print "8) Back to the previous menu." a = input("What option would you like:" ) def shape_menu(): print "SHAPES MENU" print "Important: The figure that is used for pi is 3.14." print "1) Squares" print "2) Circles" print "3) Rectangles" print "4) Triangles" print "5) Cones" print "6) Cylinders" print "7) Semicircles" print "8) Main menu" b = input("What option would you like?" ) def temp_menu(): print "1) Convert degrees Kevins to degrees Celsius" print "2) Contvert Fahrenheit to Celsius" print "3) Convert Celsius to Fahrenheit" print "4) Convert Celsius to Kelvins" print "5) Convert Kelvins to Fahrenheit" print "6) Convert Fahrenheit to Kelvins" print "7) Main Menu" temp_option = input("Choice: ") def formula_menu(): print "1) Interest" print "2) Distance" print "3) Uniform motion" print "4) Momentum" print "5) Uniformly accelerated motion" print "6) Falling bodies" print "7) Weight" print "8) Main menu" fourmula_option = input("Choice: ") #Code for main part of program. print "The Giant Calculator" print print "Copyright 2005 Written and debugged by Nathan Pinno" print print main_menu() if option == 1: print cal_menu() if a == 1: X = input("First number:" ) Y = input("Second number:" ) print X, "+", Y, "= ",X + Y print cal_menu() elif a == 2: X = input("First number:" ) Y = input("Second number:" ) print X, "-", Y, "= ",X - Y print cal_menu() elif a == 3: X = input("First number:" ) Y = input("Second number:" ) print X, "*", Y, "= ",X * Y print cal_menu() elif a == 4: X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y print cal_menu() elif a == 5: X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y," R ", X % Y print cal_menu() elif a == 6: X = input("First number:" ) Y = input("Power:" ) print X, "**", Y, "= ",X**Y print cal_menu() elif a == 7: X = input("Number to be squared:" ) print "The square root of", X, " = ",X**0.5 print cal_menu() elif a == 8: print main_menu() else: print "That's not an option. Try again." a = input("What option would you like:" ) elif option == 2: print shape_menu() if b == 1: print "1) Circumference" print "2) Area" print "3) Shapes Menu" op = input("Choice: ") if op == 1: side = input("Side: ") print "Circumference = ",4*side print shape_menu() elif op == 2: side = input("Side: ") print "Area = ",side**2 print shape_menu() elif op == 3: print shape_menu() else: print "That's not an option." op = input("Choice: ") elif b == 2: print "1) Circumference" print "2) Area" print "3) Shapes Menu" d = input("Choice: ") if d == 1: diameter = input("Diameter: ") print "The circumference of the circle is ",diameter*3.14 print shape_menu() elif d == 2: radius = input("Radius: ") print "The area of the circle is ",3.14*(radius**2) print shape_menu() elif d == 3: print shape_menu() else: print "That's not an option." d = input("Choice: ") elif b == 3: print "1) Area" print "2) Perimeter" print "3) Main menu" g = input("Choice: ") if g == 1: base = input("Base: ") altitude = input("Altitude: ") print "The area of the rectangle is: ",base*altitude print shape_menu() elif g == 2: base = input("Base: ") altitude = input("Altiutude: ") print "The perimeter of the rectangle is: ",(2*base)+(2*altitude) print shape_menu() elif g == 3: print shape_menu() else: print "That's not an option." g = input("Choice: ") elif b == 4: print "1) Right Triangles - Pygathorean Theorum" print "2) Perimeter" print "3) Area" print "4) Shapes Menu" e = input("Choice: ") if e == 1: sidea = input("Side A: ") sideb = input("side B: ") print "The hypotenuse's length is: ",((sidea**2)+(sideb**2))**0.5 print shape_menu() elif e == 2: sidea = input("Side A: ") sideb = input("Side B: ") sidec = input("Side C: ") print "The Perimeter of the triangle is: ",sidea+sideb+sidec print shape_menu() elif e == 3: base = input("Base: ") height = input("Height: ") print "The area of the triangle is: ",1/2*base*height print shape_menu() elif e == 4: print shape_menu() else: print "That's not an option! Try again." e = input("Choice: ") elif b == 5: print "The base and circumference of a cone can be found with the circle formulas, so they aren't found here." print "1) Lateral Area" print "2) Total Area" print "3) Volume" print "4) Shapes Menu" opt = input("Choice: ") if opt == 1: r = input("Radius: ") sl = input("Slant height: ") print "The Lateral Area is: ",1/2*(2*3.14*r)*sl print shape_menu() elif opt == 2: r = input("Radius: ") sl = input("Slant height: ") print "The total area is: ",1/2*(2*3.14*r)*sl+(3.14*(r**2)) print shape_menu() elif opt == 3: height = input("Height: ") r = input("Radius: ") print "The volume is: ",1/4*(3.14*(r**2))*height print shape_menu() elif opt == 4: print shape_menu() else: print "That's not an option" opt = input("Choice: ") elif b == 6: print "1) Lateral Area" print "2) Total Area" print "3) Volume" print "4) Shape Menu" g = input("Choice: ") if g == 1: r = input("Radius: ") height = input("Height: ") print "The Lateral Area is: ",(2*3.14*r)*height print shape_menu() elif g == 2: r = input("Radius: ") height = input("Height: ") print "The Total Area is: ",((2*3.14*r)*height)+(2*(3.14*(r**2))) print shape_menu() elif g == 3: r = input("Radius: ") height = input("Height: ") print "The volume is: ",(3.14*(r**2))*height print shape_menu() elif g == 4: print shape_menu() else: print "That is not an option!" g = input("Choice: ") elif b == 7: print "1) Arc Length" print "2) Area" print "3) Shape Menu" h = input("Choice: ") if h == 1: diam = input("Diameter: ") print "The arc length is: ",(3.14*diam)/2 print shape_menu() elif h == 2: r = input("Radius: ") print "The area is: ",(3.14*(r**2))/2 print shape_menu() elif h == 3: print shape_menu else: print "Sorry, incorrect entry. Please try again." h = input("Choice: ") elif b == 8: print main_menu() else: print "Sorry, not an option." print shape_menu() elif option == 3: print temp_menu() if temp_option == 1: print "Convert degrees Kelvin to degrees Celsius." k = input("Degrees Kelvin: ") print k-273.16," degrees Celsius" print temp_menu() elif temp_option == 2: print "Convert Fahrenheit to Celsius" f = input("Degrees Fahrenheit: ") print 5/9*(f-32)," degrees Celsius" print temp_menu() elif temp_option == 3: print "Convert Celsius to Fahrenheit" c = input("Degrees Celsius: ") print (9/5*C)+32," degrees Fahrenheit" print temp_menu() elif temp_option == 4: print "Convert degrees Celsius to degrees Kelvin" c = input("Degrees Celsius: ") print c+273.16," degrees Kelvin" print temp_menu() elif temp_option == 5: print "Convert degrees Kelvin to Fahrenheit" k = input("Degrees Kelvin: ") print ((k-273.16)*9/5)+32," degrees Fahrenheit" print temp_menu() elif temp_option == 6: print "Convert Fahrenheit to degrees Kelvin" f = input("Degrees Fahrenheit: ") print (5/9*(f-32))+273.16," degrees Kelvin" print temp_menu() elif temp_option == 7: print main_menu() else: print "That's not an option. Please try again" print temp_menu() elif option == 4: print formula_menu() if formula_option == 1: p = input("Principal: ") r = input("Rate as a decimal: ") t = input("Time in years: ") print "Interest: ",p*r*t print formula_menu() elif formula_option == 2: r = input("Rate: ") t = input("Time: ") print "Distance: ",r*t print formula_menu() elif formula_option == 3: v = input("Velocity: ") t = input("Time: ") print "Uniform motion: ",v*t print formula_menu() elif formula_option == 4: m = input("Mass: ") v = input("Velocity: ") print "Momentum: ",m*v print formula_menu() elif formula_option == 5: as = input("Acceleration speed: ") t = input("Time: ") print "Uniformly accelerated motion: ",1/2*as*t print formula_menu() elif formula_option == 6: gravity = input("Constant acceleration due to gravity: ") t = input("Time: ") print "Distance covered by falling body: ",1/2*gravity*(t**2) print formula_menu() elif formula_option == 7: m = input("Mass: ") gravity = input("Gravity: ") print "Weight: ",m*gravity print formula_menu() elif formula_option == 8: print main_menu() else: print "That is not an option." print formula_menu() elif option == 5: print "Goodbye!" else: print "That is not an option. Please choose an option from the menu." print main_menu() print Any help will be appreciated! Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050709/765d7ef0/attachment-0001.htm From forestiero at qwest.net Sun Jul 10 06:26:56 2005 From: forestiero at qwest.net (DogWalker) Date: Sat, 09 Jul 2005 21:26:56 -0700 Subject: [Tutor] Re: Looks like Giant Calc is a bust. In-Reply-To: References: Message-ID: <20050710041822.20327.52541@linux.local> "Nathan Pinno" said: >Hey all, > >The Giant Calculator runs now, just not as I want it to. I can't seem to get it past the main menu. Here is the code: > ># This program is designed as a big calculator with functions. > ># This first bunch of code is for the various menus. I decided to divide the calculations into seperate sub-menus, >#so that the main menus would not be that long. >option = 0 >a = 0 >b = 0 >temp_option = 0 >formula_option = 0 > >def main_menu(): global option # Without this, 'option' is local! <<<----- > print "OPTIONS MENU" > print "1) Calculate" > print "2) Shapes" > print "3) Temperature" > print "4) Formulas" > print "5) Quit" > option = input("What option would you like:" ) > ... and so on in all the other functions. [...] From dyoo at hkn.eecs.berkeley.edu Sun Jul 10 08:29:16 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 9 Jul 2005 23:29:16 -0700 (PDT) Subject: [Tutor] What's the invalid syntax? [What's the error mesaage?] In-Reply-To: Message-ID: On Sat, 9 Jul 2005, Nathan Pinno wrote: > What's the invalid syntax? > > Here's the code (Part of my Guess the Numbers game): > > if a0 == x0 and a1 == x1 and a2 == x2 and a3 == x3: > print "Congratulations! Way to go?" > answer = raw input("Play again: (Y)es or (N)o Type the letter of your choice. ") Hi Nathan, Next time you ask this kind of question, show us the error message. Brian has asked you before on other questions in the past; his recommendation is a good one in general. Error message are not content-less, despite what you might think. They usually have some kind of useful information associated with them, and they they really often provide key clues to what's broken. Let's try an example to demonstrate this idea. Let's say that we write a program like this: ###### def test_syntax_error(): print "hello world" goodbye world ###### When we run this, Python says that there's a problem here. But it actually says more than "it doesn't work"; it gets specific: ###### File "", line 3 goodbye world ^ SyntaxError: invalid syntax ###### Python is saying: "Up to line 2 of the program, things look syntactically ok. I, the Python system, hit a problem on line three. Here, I'll show the line to you; maybe you'll see what's wrong immediately. Look around there for the syntax error. If it helps here's more info: I got confused as soon as I saw the word 'world'; I was not expecting that word there." Of course, if Python really did say something like that in full English, it would be too verbose. So it does take some practice in reading something terse like an error message, and actually understanding what it means. But many of us on the tutor list have that experience. I hope this makes it clear: if you see an error message, include it! It's actually really useful for us when we try to help you with problems. From dyoo at hkn.eecs.berkeley.edu Sun Jul 10 08:34:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 9 Jul 2005 23:34:04 -0700 (PDT) Subject: [Tutor] Can I use def without ( ) at the end? In-Reply-To: Message-ID: On Sat, 9 Jul 2005, Nathan Pinno wrote: > Also, I just wanted to know because I'm using it in my Giant Computer > program for the menus, so I don't have to keep re-typing them. Hi Nathan, Wait; Nathan, are you using the IDLE Python programming environment to edit your programs? I just want to make sure that you're using some kind of text editor. You should NOT be retyping programs by hand: a good text editor will do that for you. I have a quick-and-dirty visual guide to IDLE here that shows the concept of using a programmer-friendly text editor: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html I wrote that tutorial a few years ago, so some of the menu options are different --- in particular, Run Script is now somewhere under the Module menu. (One of these days, I'll fix that...) But most of the material there is still relevant and should help you use IDLE effectively. Best of wishes to you! From alan.gauld at freenet.co.uk Sun Jul 10 09:42:31 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 10 Jul 2005 08:42:31 +0100 Subject: [Tutor] Is it possible to... References: Message-ID: <004f01c58522$eded2090$b1458651@xp> > I was just wondering if it is possible to use Python as a language > to password protect a webpage? Yes it is possible but you will need to have a web server that can run Pyhon and there aren't too many of those on the internet... OTOH if its a privately owned web server then password protection is usually a standard configuration item of the web server, you just edit a file and tell it to password protect a particular file or folder. Certainly Apache and Xitami work like that, no coding needed. Alan G. From alan.gauld at freenet.co.uk Sun Jul 10 10:03:44 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 10 Jul 2005 09:03:44 +0100 Subject: [Tutor] Can I use def without ( ) at the end? References: <42D068BA.1070002@po-box.mcgill.ca> Message-ID: <005f01c58525$e4f039c0$b1458651@xp> Nathan, > How do I make Python get a def? Is it the "get" function, or > something > else? I need to know so that I can get a def for that computer > MasterMind(tm) game that I'm writing. This sounds like you really don't understand what def does. Can I suggest you take time out to read about functions in one of the tutorials, it will likely save a lot of time in the long run. You can try my tutorial "Modules and Functions" is the topic, or the official tutorial, or virtually any other. > BTW, I took your advice, and wrote some definitions for my Giant > Calculator program. def is not a definition in the general sense, it is a function definition. You call functions with parens and get a result back. Your earlier questions showed that you don't really understand that concept yet. > Might make the code easier to read, but harder to code > because I have to keep going to the top to read the menu. Not that > fun, If your editor supports split screens (eg. emacs, vim) then you can simply do that and have the top 'frame' display the menu. Other common tricks include setting a bookmark at the menu and using the goto bookmark feature(if you have one) to jump straight there and then go to bottom to get back to your new code. If you have a folding editor like Scite (or Pythonwin) then you can collapse all definitions except the menu and the one you are working on which is often enough too. Finally you can always open two editor sessions on the same file, one for reading and one for working in. Lots of options depending on your tools. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Jul 10 10:16:23 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 10 Jul 2005 09:16:23 +0100 Subject: [Tutor] What's going on with this code? Error message supplied. References: Message-ID: <007901c58527$a970ae00$b1458651@xp> Nathan, > Subject: [Tutor] What's going on with this code? Error message > supplied. > > Here is the error message: > > Traceback (most recent call last): > File "D:\GC.py", line 67, in ? > if option == 1: > NameError: name 'option' is not defined The error message tells you what is wrong, option is not defined at the point where you are using it. Pythopn starts executing code from the top so when it comes to your line if option == 1 it doesn't know about anything called option, you haven't created it yet. In fact you only ever create it inside the main_menu() function. But names created inside functions are only seen inside the function - they are called "local" because they are localised to the function. You need to create a variable outside the function, then return the value from the function to that variabl;e like this: option = main_menu() # assign the value thus creating option if option == 1: # now you can test it But your program has another problem. > print main_menu() main_menu is a function which prints a menu. You do not need to use print here. There are print commands inside the function. In fact what this says is print the return value of main_menu() and, as it stands, you don't have a return value so Python will print 'None', which you don't want. > def main_menu(): > print "OPTIONS MENU" > print "1) Calculate" > ... > print "5) Quit" > option = input("What option would you like:" ) return option And finally to get my code above to work you need to return the option value as shown above. You might want to rethink using input() too sibnce it has some security issues, option = int(raw_input()) is safer and for youur purposes does the same thing. Take some time to work through a tutorial, that should explain these issues. In the long run it will be faster than writing code and posting every problem here, then waiting for an answer! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Jul 10 10:20:32 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 10 Jul 2005 09:20:32 +0100 Subject: [Tutor] Looks like Giant Calc is a bust. References: Message-ID: <008501c58528$3de87e00$b1458651@xp> > The Giant Calculator runs now, just not as I want it to. > I can't seem to get it past the main menu. See my other post. You are never returning the choice from the function so option is never changed from 0... ------------------ option = 0 def main_menu(): print "OPTIONS MENU" print "1) Calculate" print "2) Shapes" print "3) Temperature" print "4) Formulas" print "5) Quit" option = input("What option would you like:" ) #Code for main part of program. print main_menu() if option == 1: ---------------------- You have created an option variable but you never change it. you need to set option to the return value from main_menu() and modify main_menu() to return the value. One other option, but its bad proctice, is to declare option as global inside main_menu(), but returning the value is much better. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From severin.kacianka at aon.at Sun Jul 10 13:00:42 2005 From: severin.kacianka at aon.at (Severin Kacianka) Date: Sun, 10 Jul 2005 13:00:42 +0200 Subject: [Tutor] UnicodeDecodeError when copying files with Umlauten In-Reply-To: <200507091138.38079.severin.kacianka@aon.at> References: <200507091138.38079.severin.kacianka@aon.at> Message-ID: <200507101300.42581.severin.kacianka@aon.at> Hello, I finally could solve the problem on my own. These two articles helped me a lot: http://www.onlamp.com/pub/a/python/excerpt/pythonckbk_chap1/ http://www.reportlab.com/i18n/python_unicode_tutorial.html I simply had to ensure that all the file names I got from the m3u file were in unicode format. I do that by simply running "unicode" over every filename I extract from the m3u files: self.pathList.append(unicode(eachLine[:-1],"latin-1")) Severin -- They that can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety. Benjamin Franklin From jorge at bcs.org.uk Sun Jul 10 14:01:03 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Sun, 10 Jul 2005 13:01:03 +0100 Subject: [Tutor] Learning Python with a Simple IM Message-ID: Hello, I am a Java Developer that wants to learn Python by doing. I am loving this initial vibe I'm getting out of Python. However, because I feel programmers of a certain languages bring with them certain vices when moving to other languages, I'd like to have feedback from seasoned Python programmers regarding my code. Using some socket examples I've googled here and there I wrote the very simple Instant-Messaging-wannabe program below. I was advised to post the code here and get feedback from this community. In my next iteration with this code I'll be changing the client to include a server thread listening instead of polling the server. Regards jorge THE SIMPLE IM CLIENT import socket, threading, time, msvcrt print "Please enter the following information" _url = raw_input("URL: ") _port = raw_input("Port: ") print "Starting IIM client on port: " + _port socketOut = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socketOut.connect((_url, int(_port))) # clear screen here print "Enter your user details" _from = raw_input("User id: ") _to = raw_input("Buddy id: ") print '\n' print "Connecting to server..." print '\n' # send user details and receive response socketOut.sendall('@@@'+_from+'##'+_to) response = socketOut.recv(8192) def listener(): while 1: time.sleep(5) socketOut.sendall('$$$'+_from) response = socketOut.recv(8192) if response != " ": print "\n" + response if response == 'AUTH_OK': data = "" th = threading.Thread(target=listener) th.setDaemon(1) th.start() print "Background polling thread started" while 1: if msvcrt.kbhit(): ch = msvcrt.getche() else: ch = None if ch: if ch != '\r': data += ch else: print '\n' socketOut.sendall('###'+_from+'##'+data) response = socketOut.recv(8192) if response != " ": print response data = "" else: print "Auhentication failed!" socketOut.close() THE SIMPLE IM SERVER import SocketServer _port = 8881 _clients = {} # a connected client class Client: # queue of messages sent to this client queue = [] def __init__(self, _sock, _src, _dest): print "Creating IM client" self.socket = _sock print "Incoming socket: %s" % self.socket self.user = _src print "Username: " + self.user # buddies should be a list self.buddy = _dest print "Buddy: " + self.buddy print "Created IM client" # the server handling requests class Broker(SocketServer.BaseRequestHandler): def handle(self): print "Connected from", self.client_address while True: receivedData = self.request.recv(8192) if not receivedData: break # if handshake packet, extract client details if receivedData.startswith('@@@',0,3): print "Received handshake packet" # strip handshake code receivedData = receivedData.replace('@@@', '', 1).lstrip() l = receivedData.split('##',1) socket = self.request src = l[0] dest = l[1] c = Client(socket, src, dest) # use username as key on hashmap _clients[src] = c # send success message socket.sendall('AUTH_OK') print "Client " + src + " authenticated" # if polling packet, extract sender details and send messages if receivedData.startswith('$$$',0,3): # strip polling message print "Received polling packet" src = receivedData.replace('$$$', '', 1).lstrip() # only poll if more than 1 user if len(_clients) > 1: # use username as key on hashmap _clients[src] = c if len(c.queue) < 1: c.socket.sendall(" ") else: msgs = "" for q in c.queue: msgs += q + '\n' # send queued messages c.socket.sendall(msgs) c.queue = [] print "Sent all pending messages for " + c.user else: socket.sendall(" ") # if message packet, extract data and append to target queue if receivedData.startswith('###',0,3): print "Received message packet" receivedData = receivedData.replace('###', '', 1).lstrip() l = receivedData.split('##',1) src = l[0] text = l[1] if text.strip != "": print "Message not empty" # extract client clientSrc = _clients[src] # ...and its buddy clientDest = _clients[clientSrc.buddy] msg = src+": "+text print "Appended message to queue of " + clientSrc.buddy clientDest.queue.append(msg) print "Queue of: " + clientDest.user + " = %s" % clientDest.queue clientDest.socket.sendall(" ") else: if len(_clients) < 2: self.request.sendall(receivedData) for c in _clients.values(): if self.request == c.socket: c.socket.close() # remove from hashmap del _clients[c.user] print "Removed " + c.user + " from hashmap" print "Disconnected from", self.client_address srv = SocketServer.ThreadingTCPServer(('',_port),Broker) print "Started IIM server on port %d" % _port srv.serve_forever() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050710/27bd37a2/attachment.htm From byron at christianfreebies.com Sun Jul 10 16:09:14 2005 From: byron at christianfreebies.com (Byron) Date: Sun, 10 Jul 2005 07:09:14 -0700 Subject: [Tutor] Is it possible to... In-Reply-To: References: Message-ID: <42D12C0A.7030600@christianfreebies.com> Alan G wrote: >> I was just wondering if it is possible to use Python as a language to >> password protect a webpage? > > > Yes it is possible but you will need to have a web server that can run > Pyhon and there aren't too many of those on the internet... > > However, there are some hosters that do allow Python scripts. If you search google for "web hosters" + Python, you will find a variety of them. One that looks interesting is: http://www.synergyconnect.com/Linux_Plans/Linux/Linux_Web_Hosting_Plans/ > OTOH if its a privately owned web server then password protection is > usually a standard configuration item of the web server, you just edit > a file and tell it to password protect a particular file or folder. > Certainly Apache and Xitami work like that, no coding needed. > I agree. This is by far, the best option -- however, if Nathan is wanting to learn how to password protect a page using Python technology, I would recommend that he check out the following page: http://www.devshed.com/c/a/Python/Python-on-the-Web/ HTHs, Byron --- -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.8.11/44 - Release Date: 7/8/2005 From byron at christianfreebies.com Sun Jul 10 16:19:25 2005 From: byron at christianfreebies.com (Byron) Date: Sun, 10 Jul 2005 07:19:25 -0700 Subject: [Tutor] What's going on with this code? Error message supplied. In-Reply-To: References: Message-ID: <42D12E6D.1090307@christianfreebies.com> Hi Nathan, It appears that you are just starting to learn the Python programming language. May I suggest that you check out the following FREE resources -- they will help to get you started and running smoothly with Python. Learning With Python http://www.greenteapress.com/thinkpython/ After you have gone though that tutorial, I would then recommend the following advanced materials: http://www.devshed.com/c/b/Python/ HTHs (Hope this helps), Byron --- -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.8.11/44 - Release Date: 7/8/2005 From alan.gauld at freenet.co.uk Sun Jul 10 16:56:39 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 10 Jul 2005 15:56:39 +0100 Subject: [Tutor] Learning Python with a Simple IM References: Message-ID: <00bc01c5855f$941e05b0$b1458651@xp> Hi Jorge, > I am a Java Developer that wants to learn Python by doing. > I am loving this initial vibe I'm getting out of Python. > However, because I feel programmers of a certain languages > bring with them certain vices when moving to other languages, Absolutely right, thats why its good to learn several languages - to see the world from different angles! ;-) > print "Please enter the following information" > _url = raw_input("URL: ") Using an underscore in front of a variable is usually done in a class to make the member "invisible" - a wee bit like private in Java, but much less rigorous. Its not often used for normal variables in a program. > print '\n' > print "Connecting to server..." > print '\n' Using a tripple quioted string might be easier here: print ''' Connecting to seerver ''' >def listener(): > while 1: > time.sleep(5) > socketOut.sendall('$$$'+_from) > response = socketOut.recv(8192) > if response != " ": > print "\n" + response There is no break in this loop so it will run forever. That might be what you want, but usually I'd put some kind of breakout mechanism even on a long running server daemon. > if msvcrt.kbhit(): > ch = msvcrt.getche() I may be wrong but I don;t think you need the kbhit() function, getch[e]() will block and wait for a keypress. > else: > ch = None Which in turn means ch should never be None... Although it might never exist if kbhit is not True since getche will never be called and thus ch will never be created! Alan G. (Recovering from G8 riots 300m from his house!) From falcon3166 at hotmail.com Sun Jul 10 20:28:21 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 10 Jul 2005 12:28:21 -0600 Subject: [Tutor] What's the invalid syntax? [What's the error mesaage?] References: Message-ID: I fixed this bug by myself, I had forgotten to add a print on a line by itself. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: Sent: Sunday, July 10, 2005 12:29 AM Subject: Re: [Tutor] What's the invalid syntax? [What's the error mesaage?] > > > On Sat, 9 Jul 2005, Nathan Pinno wrote: > >> What's the invalid syntax? >> >> Here's the code (Part of my Guess the Numbers game): >> >> if a0 == x0 and a1 == x1 and a2 == x2 and a3 == x3: >> print "Congratulations! Way to go?" >> answer = raw input("Play again: (Y)es or (N)o Type the letter of your choice. ") > > > Hi Nathan, > > Next time you ask this kind of question, show us the error message. > Brian has asked you before on other questions in the past; his > recommendation is a good one in general. > > Error message are not content-less, despite what you might think. They > usually have some kind of useful information associated with them, and > they they really often provide key clues to what's broken. > > > Let's try an example to demonstrate this idea. Let's say that we write a > program like this: > > ###### > def test_syntax_error(): > print "hello world" > goodbye world > ###### > > When we run this, Python says that there's a problem here. But it > actually says more than "it doesn't work"; it gets specific: > > ###### > File "", line 3 > goodbye world > ^ > SyntaxError: invalid syntax > ###### > > Python is saying: "Up to line 2 of the program, things look syntactically > ok. I, the Python system, hit a problem on line three. Here, I'll show > the line to you; maybe you'll see what's wrong immediately. Look around > there for the syntax error. If it helps here's more info: I got confused > as soon as I saw the word 'world'; I was not expecting that word there." > > Of course, if Python really did say something like that in full English, > it would be too verbose. So it does take some practice in reading > something terse like an error message, and actually understanding what it > means. But many of us on the tutor list have that experience. > > I hope this makes it clear: if you see an error message, include it! > It's actually really useful for us when we try to help you with problems. > > From falcon3166 at hotmail.com Sun Jul 10 20:41:04 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 10 Jul 2005 12:41:04 -0600 Subject: [Tutor] Another newbie question from Nathan. Message-ID: Hi all, How do I make Python get a def? Is it the "get" function, or something else? I need to know so that I can get a def for that computer MasterMind(tm) game that I'm writing. BTW, I took your advice, and wrote some definitions for my Giant Calculator program. Might make the code easier to read, but harder to code because I have to keep going to the top to read the menu. Not that fun, but necessary for a smooth program, I guess. Nathan Pinno "Steven D'Aprano" wrote in message news:pan.2005.07.03.02.30.28.82992 at REMOVETHIScyber.com.au... > On Sat, 02 Jul 2005 00:25:00 -0600, Nathan Pinno wrote: >> Hi all. >> How do I make the computer generate 4 random numbers for the guess? I want >> to know because I'm writing a computer program in Python like the game >> MasterMind. > First you get the computer to generate one random number. Then you do it > again three more times. > If you only need to do it once, you could do it this way: > import random # you need this at the top of your program > x0 = random.random() > x1 = random.random() > x2 = random.random() > x3 = random.random() > But if you need to do it more than once, best to create a function that > returns four random numbers in one go. > def four_random(): > """Returns a list of four random numbers.""" > L = [] # start with an empty list > for i in range(4): > L.append(random.random()) > return L > and use it this way: > rand_nums = four_random() > # rand_nums is a list of four numbers > print rand_nums[0] # prints the first random number > print rand_nums[3] # prints the last one > or like this: > alpha, beta, gamma, delta = four_random() > # four names for four separate numbers > Steven. > http://mail.python.org/mailman/listinfo/python-list From falcon3166 at hotmail.com Sun Jul 10 21:19:47 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 10 Jul 2005 13:19:47 -0600 Subject: [Tutor] What's going on with this code? Error message supplied. References: <007901c58527$a970ae00$b1458651@xp> Message-ID: Here's an error message: File "D:\GC.py", line 78 cal_opt = cal_menu() ^ SyntaxError: invalid syntax The relevant code: option = main_menu() if option == 1: cal_menu() cal_opt = cal_menu() if cal_opt == 1: How do I fix this error? Nathan ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; Sent: Sunday, July 10, 2005 2:16 AM Subject: Re: [Tutor] What's going on with this code? Error message supplied. > Nathan, > >> Subject: [Tutor] What's going on with this code? Error message >> supplied. >> > >> Here is the error message: >> >> Traceback (most recent call last): >> File "D:\GC.py", line 67, in ? >> if option == 1: >> NameError: name 'option' is not defined > > The error message tells you what is wrong, option is not defined at > the > point where you are using it. Pythopn starts executing code from the > top > so when it comes to your line > > if option == 1 > > it doesn't know about anything called option, you haven't created it > yet. > In fact you only ever create it inside the main_menu() function. But > names > created inside functions are only seen inside the function - they are > called "local" because they are localised to the function. You need > to create a variable outside the function, then return the value from > the function to that variabl;e like this: > > option = main_menu() # assign the value thus creating option > if option == 1: # now you can test it > > > But your program has another problem. > >> print main_menu() > > main_menu is a function which prints a menu. You do not need to > use print here. There are print commands inside the function. > In fact what this says is print the return value of main_menu() > and, as it stands, you don't have a return value so Python will > print 'None', which you don't want. > >> def main_menu(): >> print "OPTIONS MENU" >> print "1) Calculate" >> ... >> print "5) Quit" >> option = input("What option would you like:" ) > return option > > And finally to get my code above to work you need to return > the option value as shown above. > > You might want to rethink using input() too sibnce it has some > security issues, > > option = int(raw_input()) > > is safer and for youur purposes does the same thing. > > Take some time to work through a tutorial, that should explain these > issues. In the long run it will be faster than writing code and > posting every problem here, then waiting for an answer! > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From falcon3166 at hotmail.com Sun Jul 10 21:43:59 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Sun, 10 Jul 2005 13:43:59 -0600 Subject: [Tutor] Why does my code show this? Message-ID: Hey all, Thought I'd try a mini-calc. Here's the code: # This is a small calculator. print "Mini Calculator" print "By Nathan Pinno" print print "CALCULATE MENU" print "1) Add" print "2) Subraction" print "3) Multiplication" print "4) Division w/o remainder" print "5) Division with remaider" print "6) Exponation" print "7) Square roots" print "8) Exit" cal_opt = int(raw_input("What option would you like: ")) if cal_opt == "1": X = input("First number:" ) Y = input("Second number:" ) print X, "+", Y, "= ",X + Y cal_opt = int(raw_input("Option: ")) elif cal_opt == "2": X = input("First number:" ) Y = input("Second number:" ) print X, "-", Y, "= ",X - Y cal_opt = int(raw_input("Option: ")) elif cal_opt == "3": X = input("First number:" ) Y = input("Second number:" ) print X, "*", Y, "= ",X * Y cal_opt = int(raw_input("Option: ")) elif cal_opt == "4": X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y cal_opt = int(raw_input("Option: ")) elif cal_opt == "5": X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y," R ", X % Y cal_opt = int(raw_input("Option: ")) elif cal_opt == "6": X = input("First number:" ) Y = input("Power:" ) print X, "**", Y, "= ",X**Y cal_opt = int(raw_input("Option: ")) elif cal_opt == "7": X = input("Number to find the square root of:" ) print "The square root of", X, " = ",X**0.5 cal_opt = int(raw_input("Option: ")) elif cal_opt == "8": print "Goodbye!" else: print "That's not an option. Try again." cal_opt = int(raw_input("Option: ")) Here is the screen output: Mini Calculator By Nathan Pinno CALCULATE MENU 1) Add 2) Subraction 3) Multiplication 4) Division w/o remainder 5) Division with remaider 6) Exponation 7) Square roots 8) Exit What option would you like: 7 That's not an option. Try again. Option: 3 3*4 12 >>> Why does it run this way instead of going to the proper equation? Appreciating the help so far, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050710/e8921088/attachment.htm From geon at post.cz Sun Jul 10 22:20:29 2005 From: geon at post.cz (geon) Date: Sun, 10 Jul 2005 22:20:29 +0200 Subject: [Tutor] Why does my code show this? In-Reply-To: References: Message-ID: <42D1830D.3040202@post.cz> Nathan Pinno napsal(a): > cal_opt = int(raw_input("What option would you like: ")) > if cal_opt == "1": > ...... > your problem is in these two lines (and even more, but if you solve this, the others you get for free). try run just these two lines and guess, think about what kind of variable is in cal_opt. > elif cal_opt == "2": > X = input("First number:" ) > Y = input("Second number:" ) > print X, "-", Y, "= ",X - Y > cal_opt = int(raw_input("Option: ")) > the other trouble might be on the last line - note that "if" is not "while". :-) before creating your own program would be better to go through some nice tutorial, to get some experience......... nice pytime geon -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050710/add7a54d/attachment-0001.htm From adam.jtm30 at gmail.com Sun Jul 10 22:54:42 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 10 Jul 2005 21:54:42 +0100 Subject: [Tutor] Another newbie question from Nathan. In-Reply-To: References: Message-ID: If I understand your problem correctly all you need to do is use the name of the function to call it ie: def func(): print "hello world" func() would give the output "hello world" On 7/10/05, Nathan Pinno wrote: > > Hi all, > > How do I make Python get a def? Is it the "get" function, or something > > else? I need to know so that I can get a def for that computer > MasterMind(tm) game that I'm writing. > > BTW, I took your advice, and wrote some definitions for my Giant > Calculator program. Might make the code easier to read, but harder to > code > because I have to keep going to the top to read the menu. Not that fun, > but > necessary for a smooth program, I guess. > > Nathan Pinno > > "Steven D'Aprano" wrote in message > news:pan.2005.07.03.02.30.28.82992 at REMOVETHIScyber.com.au... > > On Sat, 02 Jul 2005 00:25:00 -0600, Nathan Pinno wrote: > >> Hi all. > >> How do I make the computer generate 4 random numbers for the > guess? I > want > >> to know because I'm writing a computer program in Python like the > game > >> MasterMind. > > First you get the computer to generate one random number. Then you > do it > > again three more times. > > If you only need to do it once, you could do it this way: > > import random # you need this at the top of your program > > x0 = random.random() > > x1 = random.random() > > x2 = random.random() > > x3 = random.random() > > But if you need to do it more than once, best to create a function > that > > returns four random numbers in one go. > > def four_random(): > > """Returns a list of four random numbers.""" > > L = [] # start with an empty list > > for i in range(4): > > L.append(random.random()) > > return L > > and use it this way: > > rand_nums = four_random() > > # rand_nums is a list of four numbers > > print rand_nums[0] # prints the first random number > > print rand_nums[3] # prints the last one > > or like this: > > alpha, beta, gamma, delta = four_random() > > # four names for four separate numbers > > Steven. > > http://mail.python.org/mailman/listinfo/python-list > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050710/22b7388f/attachment.htm From rpark69 at hotmail.com Sun Jul 10 23:31:19 2005 From: rpark69 at hotmail.com (Robert) Date: Sun, 10 Jul 2005 16:31:19 -0500 Subject: [Tutor] adding quotation marks around variables Message-ID: Hello all, I am a college student and I am currently working on a two numbers program for our class, The purpose of this program is to take user input and do some math functions. I have figured out how to do the math but I need to display these two variables with quotation marks around them. Also I need to add these two variables together and display the hexadecimal of these two variables??? Also how do you display wheather one variable is greater than or less than or equal to the other variable? Below is an example of the items i need help with? The two numbers were "X" and "Y." The first number was (< > =) the second number. The hexadecimal sum of the two numbers is XXX. Any help with this would be gratly appreciated! Thanks Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050710/b2c10eae/attachment.htm From jfouhy at paradise.net.nz Mon Jul 11 00:35:24 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 11 Jul 2005 10:35:24 +1200 (NZST) Subject: [Tutor] adding quotation marks around variables In-Reply-To: References: Message-ID: <1121034924.42d1a2ac12a0b@www.paradise.net.nz> Quoting Robert : > I have figured out how to do the math but I need to display these two > variables with quotation marks around them. > > Also I need to add these two variables together and display the > hexadecimal of these two variables??? > > Also how do you display wheather one variable is greater than or less > than or equal to the other variable? Hi Robert, I recommend you have a look through the online Python tutorial (http://python.org/doc); in particular, section 3: http://docs.python.org/tut/node5.html -- John. From bvande at po-box.mcgill.ca Mon Jul 11 00:20:08 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 10 Jul 2005 18:20:08 -0400 Subject: [Tutor] adding quotation marks around variables In-Reply-To: References: Message-ID: <42D19F18.4080703@po-box.mcgill.ca> Robert said unto the world upon 10/07/2005 17:31: > Hello all, I am a college student and I am currently working on a > two numbers program for our class, The purpose of this program is > to take user input and do some math functions. > > I have figured out how to do the math but I need to display these > two variables with quotation marks around them. > > Also I need to add these two variables together and display the > hexadecimal of these two variables??? > > Also how do you display wheather one variable is greater than or > less than or equal to the other variable? > > > Below is an example of the items i need help with? > > > > > > > The two numbers were "X" and "Y." > > The first number was (< > =) the second number. > > The hexadecimal sum of the two numbers is XXX. > > Any help with this would be gratly appreciated! Thanks Robert > Hi Robert, for displaying strings with variable content, string formatting is a real boon. See for details. But here is a bit to give you the idea: >>> def silly_example(): name = raw_input('What is your name?\n') if name[0].isalpha(): if name[0].lower() in ('aeiou'): char_type = 'a vowel' else: char_type = 'a consonant' else: char_type = "something other than a letter" print "Hello, %s. Your name begins with %s." %(name, char_type) >>> silly_example() What is your name? Brian Hello, Brian. Your name begins with a consonant. >>> silly_example() What is your name? Alberto Hello, Alberto. Your name begins with a vowel. >>> silly_example() What is your name? 42 Hello, 42. Your name begins with something other than a letter. >>> See if you can get somewhere with these ideas. If you get stuck, post some code, and someone will be glad to help more. Best, Brian vdB From bvande at po-box.mcgill.ca Mon Jul 11 00:47:06 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 10 Jul 2005 18:47:06 -0400 Subject: [Tutor] adding quotation marks around variables In-Reply-To: References: Message-ID: <42D1A56A.1070806@po-box.mcgill.ca> Robert said unto the world upon 10/07/2005 17:31: > Hello all, I am a college student and I am currently working on a two numbers program for our class, The purpose of this program is to take user input and do some math functions. > > I have figured out how to do the math but I need to display these two variables with quotation marks around them. > > Also I need to add these two variables together and display the hexadecimal of these two variables??? > > Also how do you display wheather one variable is greater than or less than or equal to the other variable? > > > Below is an example of the items i need help with? > > > > > The two numbers were "X" and "Y." > > The first number was (< > =) the second number. > > The hexadecimal sum of the two numbers is XXX. > > Any help with this would be gratly appreciated! > Thanks > Robert > Darn, overlooked the desire to embed quotes: >>> print "Formated strings can %s like this ', too" %"include" Formated strings can include like this -too >>> print 'or %s %s"' %('like', 'this') or like this" >>> print '''Or both %s -- ' and " -- if %s''' %('kinds of quotes', 'you use triple-quote strings') Or both kinds of quotes -- ' and " -- if you use triple-quote strings >>> Brian vdB From alan.gauld at freenet.co.uk Mon Jul 11 00:53:44 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Sun, 10 Jul 2005 23:53:44 +0100 Subject: [Tutor] What's going on with this code? Error message supplied. References: <007901c58527$a970ae00$b1458651@xp> Message-ID: <00c601c585a2$39af40b0$b1458651@xp> > Here's an error message: > > File "D:\GC.py", line 78 > cal_opt = cal_menu() > ^ > SyntaxError: invalid syntax > > The relevant code: > > option = main_menu() > if option == 1: > cal_menu() > cal_opt = cal_menu() Consistent indentation is all important in Python Move the linees under the if statement into alignment: if option == 1: cal_menu() cal_opt = cal_menu() My tutor discusses this in the topic on 'Loops' HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jul 11 01:03:28 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 11 Jul 2005 00:03:28 +0100 Subject: [Tutor] Why does my code show this? References: Message-ID: <00eb01c585a3$95972040$b1458651@xp> > cal_opt = int(raw_input("What option would you like: ")) Here you get the input and convert it to a number (int() ) which is fine. > if cal_opt == "1": But here you compare it to a string (see the quotes). So either remove the convertion to int() around raw_input or remove the quotes around the values. The things you compare must be the same type. > That's not an option. Try again. > Option: 3 > 3*4 > 12 I'm not sure how the multiplication appeared though! Alan G. From srini_iyyer_bio at yahoo.com Mon Jul 11 03:30:18 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Sun, 10 Jul 2005 18:30:18 -0700 (PDT) Subject: [Tutor] please help Message-ID: <20050711013018.73428.qmail@web53506.mail.yahoo.com> Hello group, after 4 months my brain became rusty by not solving problems. I need some help to regain my basic skills. my problem: I have a file that looks like this: // AB32456\tTransaction from India \t 43 \t 34 \t 34 \t 65 \t 12 \t 35 // AV32567\tTransaction from Singapore \t 43 \t 34 \t 34 \t 65 \t 12 \t 35 // AK34678\tTransaction from HongKong \t 43 \t 34 \t 34 \t 65 \t 12 \t 35 Characterstics: Every transaction seperated by '//' Column 1 is container name Column 2 - Description of transaction and quantities (in next lines) What I have to do: // AB32456\tTransaction from India AB32456\t 43 \t 34 AB32456\t 34 \t 65 AB32456\t 12 \t 35 // AV32567\tTransaction from Singapore AV32567\t 43 \t 34 AV32567\t 34 \t 65 AV32567\t 12 \t 35 // AK34678\tTransaction from HongKong AK34678\t 43 \t 34 AK34678\t 34 \t 65 AK34678\t 12 \t 35 The line that Ive been writing (of course wrong script): f1 = open('myfile','r') stuff = f1.read().split('\n') for i in stuff: if i != '//': trcode = line.split('\t')[0] trquant = line.split('\t')[1] print trcode+'\t'+trquant This is completely garbage and i am getting no where. Please help me.. thank you ____________________________________________________ Sell on Yahoo! Auctions ? no fees. Bid on great items. http://auctions.yahoo.com/ From reederk at comcast.net Mon Jul 11 05:25:12 2005 From: reederk at comcast.net (Kevin Reeder) Date: Sun, 10 Jul 2005 20:25:12 -0700 Subject: [Tutor] Single Underscore Message-ID: <20050710202512.40757a1f.reederk@comcast.net> What's the significance of naming a variable with a single underscore as its first character? For example, I'm looking at find.py in the standard library and it has variables named _debug and _prune. Kevin From chinook.nr at tds.net Mon Jul 11 05:34:43 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 10 Jul 2005 23:34:43 -0400 Subject: [Tutor] Single Underscore In-Reply-To: <20050710202512.40757a1f.reederk@comcast.net> References: <20050710202512.40757a1f.reederk@comcast.net> Message-ID: Kevin Reeder wrote: >What's the significance of naming a variable with a single >underscore as its first character? For example, I'm looking at >find.py in the standard library and it has variables named _debug >and _prune. > >Kevin >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > Kevin, If it is naming conventions then possibly they mean a private property or method. http://jaynes.colorado.edu/PythonGuidelines.html Lee C From jfouhy at paradise.net.nz Mon Jul 11 05:43:14 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Mon, 11 Jul 2005 15:43:14 +1200 (NZST) Subject: [Tutor] Single Underscore In-Reply-To: <20050710202512.40757a1f.reederk@comcast.net> References: <20050710202512.40757a1f.reederk@comcast.net> Message-ID: <1121053394.42d1ead2e214a@www.paradise.net.nz> Quoting Kevin Reeder : > What's the significance of naming a variable with a single > underscore as its first character? For example, I'm looking at > find.py in the standard library and it has variables named _debug > and _prune. Basically, it means "These variables are internal and not part of the API; please do not use them in your code because they may change without warning". The reference here is PEP-8, the Python style guide: http://www.python.org/peps/pep-0008.html Excerpt: """ In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention): - _single_leading_underscore: weak "internal use" indicator (e.g. "from M import *" does not import objects whose name starts with an underscore). - single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. "Tkinter.Toplevel(master, class_='ClassName')". - __double_leading_underscore: class-private names as of Python 1.4. - __double_leading_and_trailing_underscore__: "magic" objects or attributes that live in user-controlled namespaces, e.g. __init__, __import__ or __file__. Sometimes these are defined by the user to trigger certain magic behavior (e.g. operator overloading); sometimes these are inserted by the infrastructure for its own use or for debugging purposes. Since the infrastructure (loosely defined as the Python interpreter and the standard library) may decide to grow its list of magic attributes in future versions, user code should generally refrain from using this convention for its own use. User code that aspires to become part of the infrastructure could combine this with a short prefix inside the underscores, e.g. __bobo_magic_attr__. """ "class-private" (double leading underscore) basically means extra effort is expended in making the variable hard to see. It's still not enforced, though. This is easiest to explain with an example: >>> class Foo(object): ... __x = 3 ... def p(self): ... print self.__x ... >>> f = Foo() >>> f.__x Traceback (most recent call last): File "", line 1, in ? AttributeError: 'Foo' object has no attribute '__x' >>> f.p() 3 >>> f._Foo__x 3 Google for python name-mangling if you want to know more about this :-) -- John. From dyoo at hkn.eecs.berkeley.edu Mon Jul 11 06:06:14 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 10 Jul 2005 21:06:14 -0700 (PDT) Subject: [Tutor] please help In-Reply-To: <20050711013018.73428.qmail@web53506.mail.yahoo.com> Message-ID: On Sun, 10 Jul 2005, Srinivas Iyyer wrote: > I have a file that looks like this: > > // > AB32456\tTransaction from India > \t 43 \t 34 > \t 34 \t 65 > \t 12 \t 35 > // [some lines cut] > What I have to do: > // > AB32456\tTransaction from India > AB32456\t 43 \t 34 > AB32456\t 34 \t 65 > AB32456\t 12 \t 35 [some lines cut] Ok, so it looks like we want to then remember the first column at the beginning of a transaction, and then have duplicate that value for the rest of the transaction. Let's look at what you have so far. > f1 = open('myfile','r') > stuff = f1.read().split('\n') > for i in stuff: > if i != '//': > trcode = line.split('\t')[0] > trquant = line.split('\t')[1] It might help to simplify the problem a little. I think you might be getting stuck because you're trying to handle the '\\' end of a transaction as well as the column value-trickling stuff, so there's a bit of mixing going on. One way to simplifying a problem is to concentrate on handling a single thing. Let's say that we have a list of lines from a single transaction: ###### sample_data = ["AB32456\tTransaction from India", " \t 43 \t 34", " \t 34 \t 65", " \t 12 \t 35"] ###### Can you transform these lines so that the AB32456 value trickles into the other lines of the transaction? Don't worry about "//" stuff at all in this subproblem. Try handling this first: it's the core of your program anyway, so might as well figure that part out. *grin* If you have more questions, please feel free to ask. Best of wishes to you! From alan.gauld at freenet.co.uk Mon Jul 11 06:09:23 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 11 Jul 2005 05:09:23 +0100 Subject: [Tutor] adding quotation marks around variables References: Message-ID: <012101c585ce$52343ec0$b1458651@xp> > Hello all, I am a college student and I am currently working > on a two numbers program for our class, The purpose of this > program is to take user input and do some math functions. So why not show us what you have come up with so far and we'll work from there? > I have figured out how to do the math but I need to display > these two variables with quotation marks around them. Personally I'd use string formatting for that. Take a look at the Simple Sequences topic ofmy tutorial for examples. > Also I need to add these two variables together and display > the hexadecimal of these two variables??? Again string formatting can help. > Also how do you display wheather one variable is greater > than or less than or equal to the other variable? Use a branch with a boolean expression. The Branching topic of my tutor covers that. Have a go and let us see where you are having problems. You will learn much faster if you try it before asking. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Jul 11 06:14:43 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 11 Jul 2005 05:14:43 +0100 Subject: [Tutor] please help References: <20050711013018.73428.qmail@web53506.mail.yahoo.com> Message-ID: <012f01c585cf$10f36c00$b1458651@xp> > The line that Ive been writing (of course wrong > script): > > f1 = open('myfile','r') > stuff = f1.read().split('\n') > for i in stuff: > if i != '//': > trcode = line.split('\t')[0] > trquant = line.split('\t')[1] > print trcode+'\t'+trquant > You use i in the for loop but line in the code block inside? try for line in file('myfile'): if line != '\\': trcode = line.split('\t')[0] etc... HTH, Alan G. From reederk at comcast.net Mon Jul 11 06:39:26 2005 From: reederk at comcast.net (Kevin Reeder) Date: Sun, 10 Jul 2005 21:39:26 -0700 Subject: [Tutor] Single Underscore In-Reply-To: <20050710202512.40757a1f.reederk@comcast.net> References: <20050710202512.40757a1f.reederk@comcast.net> Message-ID: <20050710213926.64b46961.reederk@comcast.net> Thanks for the info. I'll look into the links provided. > http://jaynes.colorado.edu/PythonGuidelines.html > http://www.python.org/peps/pep-0008.html Kevin From falcon3166 at hotmail.com Mon Jul 11 08:39:19 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 11 Jul 2005 00:39:19 -0600 Subject: [Tutor] Why does my code show this? References: <00eb01c585a3$95972040$b1458651@xp> Message-ID: Thanks to all in the group. Mini_calc is now up and running successfully and is now available to download from my site. Thanks again, Nathan ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; Sent: Sunday, July 10, 2005 5:03 PM Subject: Re: [Tutor] Why does my code show this? >> cal_opt = int(raw_input("What option would you like: ")) > > Here you get the input and convert it to a number (int() ) > which is fine. > >> if cal_opt == "1": > > But here you compare it to a string (see the quotes). > > So either remove the convertion to int() around raw_input or > remove the quotes around the values. The things you compare > must be the same type. > >> That's not an option. Try again. >> Option: 3 >> 3*4 >> 12 > > I'm not sure how the multiplication appeared though! > > Alan G. > From rschroev_nospam_ml at fastmail.fm Mon Jul 11 09:55:51 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 11 Jul 2005 09:55:51 +0200 Subject: [Tutor] What's going on with this code? Error message supplied. In-Reply-To: <00c601c585a2$39af40b0$b1458651@xp> References: <007901c58527$a970ae00$b1458651@xp> <00c601c585a2$39af40b0$b1458651@xp> Message-ID: Alan G wrote: >> Here's an error message: >> >> File "D:\GC.py", line 78 >> cal_opt = cal_menu() >> ^ >> SyntaxError: invalid syntax >> >> The relevant code: >> >> option = main_menu() >> if option == 1: >> cal_menu() >> cal_opt = cal_menu() > > > Consistent indentation is all important in Python > Move the linees under the if statement into alignment: > > if option == 1: > cal_menu() > cal_opt = cal_menu() Apart from the inconsistent indentation, I think you call cal_menu() one time too many. I'm quite sure that you need only need something like this: if option == 1: cal_opt = cal_menu() -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From enas_khalil at yahoo.com Mon Jul 11 12:16:31 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Mon, 11 Jul 2005 03:16:31 -0700 (PDT) Subject: [Tutor] ImportError: No module named numarray In-Reply-To: Message-ID: <20050711101631.87253.qmail@web50301.mail.yahoo.com> when i write a code to import some module like the following : from nltk.probability import ConditionalFreqDist I got the error : Traceback (most recent call last): File "C:\Python24\toky.py", line 1, in -toplevel- from nltk.probability import ConditionalFreqDist File "C:\Python24\Lib\site-packages\nltk\probability.py", line 56, in -toplevel- import types, math, numarray ImportError: No module named numarray can you please tell me the cause --------------------------------- Sell on Yahoo! Auctions - No fees. Bid on great items. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050711/a4e86c92/attachment.htm From kent37 at tds.net Mon Jul 11 13:13:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jul 2005 07:13:25 -0400 Subject: [Tutor] ImportError: No module named numarray In-Reply-To: <20050711101631.87253.qmail@web50301.mail.yahoo.com> References: <20050711101631.87253.qmail@web50301.mail.yahoo.com> Message-ID: <42D25455.3010601@tds.net> enas khalil wrote: > when i write a code to import some module like the following : > > > from nltk.probability import ConditionalFreqDist > > I got the error : > > Traceback (most recent call last): > File "C:\Python24\toky.py", line 1, in -toplevel- > from nltk.probability import ConditionalFreqDist > File "C:\Python24\Lib\site-packages\nltk\probability.py", line 56, in > -toplevel- > import types, math, numarray > ImportError: No module named numarray > > can you please tell me the cause nltk is looking for a module called numarray that is not part of the standard Python distribution. Do you have numarray installed? Look for C:\Python24\Lib\site-packages\numarray. If you don't have it then download numarray from C:\Python24\Lib\site-packages\numarray and install it according to the instructions. Kent From albertito_g at hotmail.com Mon Jul 11 14:59:23 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 11 Jul 2005 12:59:23 +0000 Subject: [Tutor] py2exe In-Reply-To: <1120904144.42cfa3d0d8b4a@www.paradise.net.nz> Message-ID: Hey all I had some problems with this module too but I aas able with your help to make a script that works Here it is: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') ##setup( ## windows = [{'script': "NovusExtension.pyw"}], ##) setup( console = [{'script': "front-end.py"}], ) The commented part is for GUI scripts (Graphic User Interface) The uncommented part is for CLI scripts (Command Line Interface) This works 100% sure. I use this piece in all my scripts to make them executable over Windows. Never tried with pygame though but I think it is the same. The script doesn't need to be run from command line, but if you want to see if there is some error, you'll have to (not mandatory I think you could add a try statement to the code) If you have Pmw, then you have to freeze Pmw first. IIf this is the case reply to me, there is a case opened for that and I'll be glad to forward the answer Best Regards to all Alberto >From: jfouhy at paradise.net.nz >To: Python tutor >Subject: Re: [Tutor] py2exe >Date: Sat, 09 Jul 2005 22:15:44 +1200 (NZST) > >Quoting "D. Hartley" : > > > I modified the setup.py file to match the details of my game (as best > > I can imagine: I don't know what "optimize = 2 #0, > > 1, or 2; like -O and -OO" means, so I just left it as his sample had > > it, > > >From python -h: > >-O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x) >-OO : remove doc-strings in addition to the -O optimizations > >optimize=2 means py2exe will optimize the bytecode and remove doc strings; >this >is probably OK since you're not going to be running the debugger on your >finished executable. > > > and I'm not sure if I put in all of the module names it will need > > specified, but it looks as if its supposed to give me an error if it > > can't find them). > >py2exe will search for all the modules it thinks it needs, but sometimes it >will >miss some. Generally, the best way to find out if it missed anything is to >run >your executable and see if it crashes :-) > > > But then the tutorial says "simply run this script > > and it will do all the work. > >You need to run it from the command line: python setup.py py2exe > >HTH. > >-- >John. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From mhansen at cso.atmel.com Mon Jul 11 18:12:51 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon, 11 Jul 2005 10:12:51 -0600 Subject: [Tutor] Confused "from module import Name" better than "import module"? Message-ID: <42D29A83.3000509@cso.atmel.com> I'm confused. I was just reading the URL below.. http://jaynes.colorado.edu/PythonGuidelines.html and this statement confused me: "Always use from module import Name, Name2, Name3.. syntax instead of import module or from module import *. This is more efficient, reduces typing in the rest of the code, and it makes it much easier to see name collisions and to replace implementations." To me, import module is more explicit. It seems to easier to read CoolModule.niceFunction() than just niceFunction(). You know exactly where niceFunction comes from especially when you've imported many modules. Don't you avoid namespace pollution too by using import module instead of from module import * or from module import Name, Name2, Name3...? What is the preferred/better way to import modules? Mike From kent37 at tds.net Mon Jul 11 18:30:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jul 2005 12:30:16 -0400 Subject: [Tutor] Confused "from module import Name" better than "import module"? In-Reply-To: <42D29A83.3000509@cso.atmel.com> References: <42D29A83.3000509@cso.atmel.com> Message-ID: <42D29E98.2020903@tds.net> Mike Hansen wrote: > I'm confused. I was just reading the URL below.. > > http://jaynes.colorado.edu/PythonGuidelines.html > > and this statement confused me: "Always use from module import Name, Name2, > Name3.. syntax instead of import module or from module import *. This is more > efficient, reduces typing in the rest of the code, and it makes it much easier > to see name collisions and to replace implementations." > > To me, import module is more explicit. > It seems to easier to read CoolModule.niceFunction() than just niceFunction(). > You know exactly where niceFunction comes from especially when you've imported > many modules. Don't you avoid namespace pollution too by using import module > instead of from module import * or from module import Name, Name2, Name3...? from module import * is problematic and discouraged. It causes namespace pollution and makes it harder to find out where a name is defined. Other than that I think it is personal preference. I often use from module import name because it reduces typing at the point of use. It is still easy to find out where a name comes from by searching for the name in the module. This adds a few names to the global namespace but it is just the ones you use, nothing like what you can get with from module import *. I'm not sure what efficiency he is talking about - it might be faster to look up a global name than to look up a name in a module but I would want to test that. Anyway it is clearly a premature optimization and if you have code where the cost of name lookup is hurting you then you will want to convert the name to a local name, not a global. I guess it could be easier to replace the implementation, for example if you split a module you could change from module import Name1, Name1 to from module1 import Name1 from module2 import Name2 and the rest of the client code wouldn't have to change. my two cents Kent From marichar at csusb.edu Mon Jul 11 19:19:13 2005 From: marichar at csusb.edu (Matt Richardson) Date: Mon, 11 Jul 2005 10:19:13 -0700 Subject: [Tutor] Confused "from module import Name" better than "import module"? In-Reply-To: <42D29E98.2020903@tds.net> References: <42D29A83.3000509@cso.atmel.com> <42D29E98.2020903@tds.net> Message-ID: <42D2AA11.6070604@csusb.edu> Kent Johnson wrote: > from module import * is problematic and discouraged. It causes namespace pollution and makes it harder to find out where a name is defined. > > Other than that I think it is personal preference. > I have avoided the 'from module import *' style for the reasons you mentioned, but I have a question about 'import module' versus 'from module import name': is there a performance hit to consider when importing the entire module rather than just getting the specific niceFunction()? Right now,it's more of a curiousity as my programs are fairly small and don't do a whole lot. I would imagine that there would be a penalty, but for now I'm happy with keeping my namespaces distinct and knowing what came from where at a glance. Matt -- Matt Richardson IT Consultant College Of Arts & Letters CSU San Bernardino (909)537-7596 From dyoo at hkn.eecs.berkeley.edu Mon Jul 11 19:42:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 11 Jul 2005 10:42:13 -0700 (PDT) Subject: [Tutor] ImportError: No module named numarray In-Reply-To: <42D25455.3010601@tds.net> Message-ID: > nltk is looking for a module called numarray that is not part of the > standard Python distribution. Do you have numarray installed? Look for > C:\Python24\Lib\site-packages\numarray. If you don't have it then > download numarray from C:\Python24\Lib\site-packages\numarray and > install it according to the instructions. I think Kent meant to link to the Numarray project page: http://www.numpy.org/ From kent37 at tds.net Mon Jul 11 19:44:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jul 2005 13:44:26 -0400 Subject: [Tutor] Confused "from module import Name" better than "import module"? In-Reply-To: <42D2AA11.6070604@csusb.edu> References: <42D29A83.3000509@cso.atmel.com> <42D29E98.2020903@tds.net> <42D2AA11.6070604@csusb.edu> Message-ID: <42D2AFFA.3010007@tds.net> Matt Richardson wrote: > I have a question about 'import module' versus 'from > module import name': is there a performance hit to consider when > importing the entire module rather than just getting the specific > niceFunction()? I can't imagine that there is a performance difference that would matter to any but the most time-critical application. Here is what happens in the two cases: 1. import stuff - loads module 'stuff' if this is the first import - gets a reference to module stuff from sys.modules - binds the name 'stuff' to module stuff in the global namespace of the current module stuff.func() - looks up 'stuff' in the local namespace, if any, which fails - looks up 'stuff' in the global namespace which succeeds and yields module stuff - looks up 'func' in the namespace of module stuff - calls the function 2. from stuff import func - loads module 'stuff' if this is the first import - gets a reference to module stuff from sys.modules - looks up 'func' in the namespace of module stuff which yields function func - binds the name 'func' to function func in the global namespace of the current module func() - looks up 'func' in the local namespace, if any, which fails - looks up 'func' in the global namespace which succeeds and yields function func - calls the function So, at the point of import, plain 'import stuff' will be slightly faster because it doesn't lookup 'func' in the module. At the point of call, 'from stuff import func' will be slightly faster because it has one less lookup. This is good stuff to understand, but really, it isn't going to make an appreciable difference in most applications. Where it does matter, for example if func() is called many times in a loop, the best solution will probably be to bind func to a local variable which is the fastest to access. Pick the style that you find most practical and readable and don't worry about efficiency. Kent From kent37 at tds.net Mon Jul 11 19:55:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jul 2005 13:55:43 -0400 Subject: [Tutor] ImportError: No module named numarray In-Reply-To: References: Message-ID: <42D2B29F.4070608@tds.net> Danny Yoo wrote: >>nltk is looking for a module called numarray that is not part of the >>standard Python distribution. Do you have numarray installed? Look for >>C:\Python24\Lib\site-packages\numarray. If you don't have it then >>download numarray from C:\Python24\Lib\site-packages\numarray and >>install it according to the instructions. > > > I think Kent meant to link to the Numarray project page: > > http://www.numpy.org/ Indeed I did, thank you. This link goes directly to the numarray home page: http://www.stsci.edu/resources/software_hardware/numarray (But this is strange - the url I posted directly above redirects to the url Danny gave, but shows different content than you get if you go to Danny's url directly!) Kent From marichar at csusb.edu Mon Jul 11 19:56:43 2005 From: marichar at csusb.edu (Matt Richardson) Date: Mon, 11 Jul 2005 10:56:43 -0700 Subject: [Tutor] Confused "from module import Name" better than "import module"? In-Reply-To: <42D2AFFA.3010007@tds.net> References: <42D29A83.3000509@cso.atmel.com> <42D29E98.2020903@tds.net> <42D2AA11.6070604@csusb.edu> <42D2AFFA.3010007@tds.net> Message-ID: <42D2B2DB.5000609@csusb.edu> Kent Johnson wrote: > > This is good stuff to understand, but really, it isn't going to make an appreciable difference in most applications. Where it does matter, for example if func() is called many times in a loop, the best solution will probably be to bind func to a local variable which is the fastest to access. > > Pick the style that you find most practical and readable and don't worry about efficiency. > > Kent Thanks for the explanation. It won't make a difference in this really short program I'm putting together, but I was curious about it. Going through the library reference I found a bunch of modules that would replace some ugly (but working) code I had, then started to wonder if importing a bunch of different modules would have much of an effect. In any case, I'm more concerned with readability. Matt -- Matt Richardson IT Consultant College Of Arts & Letters CSU San Bernardino (909)537-7596 From mhansen at cso.atmel.com Mon Jul 11 21:04:21 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Mon, 11 Jul 2005 13:04:21 -0600 Subject: [Tutor] Confused "from module import Name" better than "import module"? In-Reply-To: References: Message-ID: <42D2C2B5.3000306@cso.atmel.com> > Subject: > Re: [Tutor] Confused "from module import Name" better than "import module"? > From: > Kent Johnson > Date: > Mon, 11 Jul 2005 12:30:16 -0400 > > CC: > tutor at python.org > > > Mike Hansen wrote: > >> I'm confused. I was just reading the URL below.. >> >> http://jaynes.colorado.edu/PythonGuidelines.html >> >> and this statement confused me: "Always use from module import Name, >> Name2, Name3.. syntax instead of import module or from module import >> *. This is more efficient, reduces typing in the rest of the code, and >> it makes it much easier to see name collisions and to replace >> implementations." >> >> To me, import module is more explicit. >> It seems to easier to read CoolModule.niceFunction() than just >> niceFunction(). You know exactly where niceFunction comes from >> especially when you've imported many modules. Don't you avoid >> namespace pollution too by using import module instead of from module >> import * or from module import Name, Name2, Name3...? > > > from module import * is problematic and discouraged. It causes namespace > pollution and makes it harder to find out where a name is defined. > > Other than that I think it is personal preference. > > I often use from module import name because it reduces typing at the > point of use. It is still easy to find out where a name comes from by > searching for the name in the module. This adds a few names to the > global namespace but it is just the ones you use, nothing like what you > can get with from module import *. > > I'm not sure what efficiency he is talking about - it might be faster to > look up a global name than to look up a name in a module but I would > want to test that. Anyway it is clearly a premature optimization and if > you have code where the cost of name lookup is hurting you then you will > want to convert the name to a local name, not a global. > > I guess it could be easier to replace the implementation, for example if > you split a module you could change > from module import Name1, Name1 > to > from module1 import Name1 > from module2 import Name2 > and the rest of the client code wouldn't have to change. > > my two cents > Kent > It's interesting. I still like the more explicit import Module. Even if you split the module, it wouldn't be hard to replace all occurrences of module1.sillyfunction with module2.sillyfunction. I'm sure vim and emacs can do this even across multiple files. I suppose if you were only interested in one specific function from a module that you'd use from module import Name1. Like you said, it's personal preference. Thanks, Mike From alan.gauld at freenet.co.uk Mon Jul 11 22:06:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 11 Jul 2005 21:06:52 +0100 Subject: [Tutor] Confused "from module import Name" better than "importmodule"? References: <42D29A83.3000509@cso.atmel.com> Message-ID: <017e01c58654$14566bb0$b1458651@xp> > I'm confused. I was just reading the URL below.. > > http://jaynes.colorado.edu/PythonGuidelines.html Me too. :-) > and this statement confused me: "Always use from module import Name, > Name2, Name3.. syntax instead of import module or from module import > *. This is more efficient, reduces typing in the rest of the code, > and it makes it much easier to see name collisions and to replace > implementations." The efficiency gain is negligible. The typing can be better reduced by using import modulename as m And it definitley doesn't make it easier to see name collisions, they will just silently collide and one or the other name will be hidden with strange results! > To me, import module is more explicit. Undeniably so! > It seems to easier to read CoolModule.niceFunction() than just > niceFunction(). Easier to read but slightly harder to type. Personally I can live with it! Alan G. From alan.gauld at freenet.co.uk Mon Jul 11 22:11:24 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 11 Jul 2005 21:11:24 +0100 Subject: [Tutor] Confused "from module import Name" better than "importmodule"? References: <42D29A83.3000509@cso.atmel.com> <42D29E98.2020903@tds.net> Message-ID: <018201c58654$b6597ce0$b1458651@xp> > I guess it could be easier to replace the implementation, > for example if you split a module you could change > from module import Name1, Name1 > to > from module1 import Name1 > from module2 import Name2 > and the rest of the client code wouldn't have to change. Thats true, but OTOH it's nmuch easier to accidentally create another variable with the same name as an imported one: from module1 import Name1 foo() bar() blah() # and much more Name1 = 42 # oops I've just lost my module1.Name1 !!1 That's why I don't like it. Just look at the number of modules with an open() function, a careless import statement could radically change behaviour but explicit module.function behaviour is reliably consistent. Alan G. From alan.gauld at freenet.co.uk Mon Jul 11 22:14:18 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 11 Jul 2005 21:14:18 +0100 Subject: [Tutor] Confused "from module import Name" better than "importmodule"? References: <42D29A83.3000509@cso.atmel.com> <42D29E98.2020903@tds.net> <42D2AA11.6070604@csusb.edu> Message-ID: <018601c58655$1e965d00$b1458651@xp> > module import name': is there a performance hit to consider when > importing the entire module rather than just getting the specific > niceFunction()? Not significant. Basically import module puts the module name into the local names dictionary. "from m import f" puts f into the dictionary, so it could save a dictionary lookup, but they are pretty fast... Its not like the whole module gets copied, it's only a single name entry in a dictionary, then an extra dictionary access when you use a feature of the imported module. Alan G. From alex_brollo at yahoo.it Mon Jul 11 22:28:00 2005 From: alex_brollo at yahoo.it (Alessandro Brollo) Date: Mon, 11 Jul 2005 22:28:00 +0200 (CEST) Subject: [Tutor] Abnormal \r character in csv text files: csv module error Message-ID: <20050711202800.92725.qmail@web26702.mail.ukl.yahoo.com> Abnormal \r characters inside a .csv text file raise an error when the file is read by csv.reader() (Python 2.3). I'm sending the following files: test.txt : a "csv"-like text file with a \r character; test1.txt : same file, with an x replacing \r; example.txt: the hard copy of my Python shell when testing csv.reader() on former files. I found this error when reading a many-mega, SAS export csv file; I'm a Python beginner, and I found hard to understand such an error and to find the three abnormal \r characters inside! This is a warning to newbies like me and a question for experts: is it a bug into csv module? ___________________________________ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050711/ad332081/test.txt -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test1.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050711/ad332081/test1.txt -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: example.txt Url: http://mail.python.org/pipermail/tutor/attachments/20050711/ad332081/example.txt From count0.djd at gmail.com Mon Jul 11 23:00:56 2005 From: count0.djd at gmail.com (David Driver) Date: Mon, 11 Jul 2005 16:00:56 -0500 Subject: [Tutor] domain logic and avoiding setters and setters. Message-ID: <22803ae2050711140056e07a88@mail.gmail.com> So I have been trying to figure out how to get around doing getters and setters and still have an oo way to inherit and apply business rules. This is what I have some up with so far. Is there any better way? class RuleViolationError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return 'Rule violated in rule object: %s' %self.msg class someObject(object): def __init__(self,a): self._voilatedRules = {} self._rules = [self.aRuleForA] self.a = a def applyRules(self): self._voilatedRules.clear() for rule in self._rules: try: rule() except RuleViolationError, err: self._voilatedRules[rule.__name__] = err.msg if self._voilatedRules: # do something dramatic to deal with all of the # voilated business rules print 'error(s): ' print self._voilatedRules def aRuleForA(self): try: self.a = int(self.a) except ValueError: raise RuleViolationError('a is not an integer') class someObjectChild(someObject): def __init__(self, a,b): someObject.__init__(self,a) self.b = b self._rules.extend((self.aRuleForB, self.anotherRuleForB)) def aRuleForB(self): # apply some business logic for d # check that it starts with b, very silly if not self.b.startswith('b'): raise RuleViolationError('b does not start with b') def anotherRuleForB(self): #test string for length constraints min,max,l=2,15,len(self.b) print min,max,l if not(l>=min and l<=max): raise RuleViolationError('b is out of min or max') class someObjectChild2(someObjectChild): #j ust change one of the rules for b def aRuleForB(self): # apply some business logic for d # check that it starts with d, very silly if not self.b.startswith('d'): raise RuleViolationError('b does not start with d') x = someObjectChild(123,'bob jones') # this should return nothing x.applyRules() x.b = 'obladiobladalifegoesonOOOO' # this should fail twice on b x.applyRules() y = someObjectChild2(123,'bob jones') y.applyRules() z = someObjectChild('happydance','bob jones') z.applyRules() This isn't near complete, but I think it gets the idea across. -- *********************************** See there, that wasn't so bad. *********************************** From kent37 at tds.net Mon Jul 11 23:46:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Jul 2005 17:46:26 -0400 Subject: [Tutor] Abnormal \r character in csv text files: csv module error In-Reply-To: <20050711202800.92725.qmail@web26702.mail.ukl.yahoo.com> References: <20050711202800.92725.qmail@web26702.mail.ukl.yahoo.com> Message-ID: <42D2E8B2.9030706@tds.net> Alessandro Brollo wrote: > Abnormal \r characters inside a .csv text file raise > an error when the file is read by csv.reader() (Python > 2.3). > > This is a warning to newbies like me and a question > for experts: is it a bug into csv module? This has been reported as a bug. http://sourceforge.net/tracker/index.php?func=detail&aid=967934&group_id=5470&atid=105470 Kent From python at jayloden.com Mon Jul 11 04:51:20 2005 From: python at jayloden.com (Jay Loden) Date: Sun, 10 Jul 2005 22:51:20 -0400 Subject: [Tutor] getopt matching incorrect options Message-ID: <200507102251.20271.python@jayloden.com> I have an app that takes a command line argument of -l or --list. It uses the getopt module to parse the arguments, and I just noticed that for some reason, getopt is matching "--lis" or "--li" etc to "--list". (Code pasted in below) Is this normal behavior, and if so, is there any way to avoid this? I just want it to match "--list" to "--list", not "--l" and "--li" and "--lis" etc. -Jay ###### Code chunk below ###### try: options,args = getopt.getopt(sys.argv[1:], "Rf:shvl", ["list", "full-restart=", "full-restart-all", "status-all", "help", "version"]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) if opt in ("-l", "--list"): listServices(svcs) sys.exit() From python at jayloden.com Tue Jul 12 04:30:49 2005 From: python at jayloden.com (Jay Loden) Date: Mon, 11 Jul 2005 22:30:49 -0400 Subject: [Tutor] getopt matching incorrect options Message-ID: <200507112230.49496.python@jayloden.com> I have an app that takes a command line argument of -l or --list. It uses the getopt module to parse the arguments, and I just noticed that for some reason, getopt is matching "--lis" or "--li" etc to "--list". (Code pasted in below) Is this normal behavior, and if so, is there any way to avoid this? I just want it to match "--list" to "--list", not "--l" and "--li" and "--lis" etc. -Jay ###### Code chunk below ###### try: options,args = getopt.getopt(sys.argv[1:], "Rf:shvl", ["list", "full-restart=", "full-restart-all", "status-all", "help", "version"]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) if opt in ("-l", "--list"): listServices(svcs) sys.exit() From david at graniteweb.com Tue Jul 12 05:37:54 2005 From: david at graniteweb.com (David Rock) Date: Mon, 11 Jul 2005 22:37:54 -0500 Subject: [Tutor] getopt matching incorrect options In-Reply-To: <200507112230.49496.python@jayloden.com> References: <200507112230.49496.python@jayloden.com> Message-ID: <20050712033754.GB17101@wdfs.graniteweb.com> * Jay Loden [2005-07-11 22:30]: > I have an app that takes a command line argument of -l or --list. It uses the > getopt module to parse the arguments, and I just noticed that for some > reason, getopt is matching "--lis" or "--li" etc to "--list". (Code pasted in > below) > > Is this normal behavior, and if so, is there any way to avoid this? I just > want it to match "--list" to "--list", not "--l" and "--li" and "--lis" etc. This is normal. From getopt http://docs.python.org/lib/module-getopt.html Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if long_options is ['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised. -- David Rock david at graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050711/844b0343/attachment-0001.pgp From alan.gauld at freenet.co.uk Tue Jul 12 09:11:55 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 12 Jul 2005 08:11:55 +0100 Subject: [Tutor] domain logic and avoiding setters and setters. References: <22803ae2050711140056e07a88@mail.gmail.com> Message-ID: <001901c586b0$fca82050$22a78751@xp> > So I have been trying to figure out how to get around doing getters > and setters and still have an oo way to inherit and apply business > rules. I think you are missing the point a wee bit. The object should not allow you to access its internal data. You should not *need* to access its internal data. The object has responsibilities in the form of behaviours. The internal data is only there to support those behaviours, it should be of no interest to external objects, therefore you do not need setters and getters. Its not the setXXX getXXX thing thats wromg its the very idea that users of the object would want to access the internal data that is wrong. In the words of Peter Coad, "Objects do it to themselves" Now in some applications you do need the internal values, but usually its as a group. For example an Address class might have a method to return the full address content, but rather than provide individuual set/get methods per field it would return the whole address as a string or a tuple.(Note that both of these are immutable types!) In some cases you may actually choose to expose one particular attribute, in which case a get/set pair for that one attribute is OK - they represent a genuine responsibility of the class. (Making it a property might be better still...) Its providing get/set pairs for *every attribute* that breaks good OOP practice. PS. For a more formal description of the above principle look up "The Law of Demeter" on Google. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Tue Jul 12 10:11:47 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 12 Jul 2005 02:11:47 -0600 Subject: [Tutor] Giant Calc runs, but need advice on how to make the menu repopup. Message-ID: It runs but now how do I make it go back to the previous menu (e.g. from Add to Calculate Menu?) Here is the latest screenshot: The Giant Calculator Copyright 2005 Written and debugged by Nathan Pinno OPTIONS MENU 1) Calculate 2) Shapes 3) Temperature 4) Formulas 5) Quit What option would you like:1 CALCULATE MENU 1) Add 2) Subraction 3) Multiplication 4) Division w/o remainder 5) Division with remaider 6) Exponation 7) Square roots 8) Back to the previous menu. What option would you like:3 First number:3 Second number:2 3 * 2 = 6 CALCULATE MENU 1) Add 2) Subraction 3) Multiplication 4) Division w/o remainder 5) Division with remaider 6) Exponation 7) Square roots 8) Back to the previous menu. What option would you like:7 >>> and the current code: # This program is designed as a big calculator with functions. # This first bunch of code is for the various menus. I decided to divide the calculations into seperate sub-menus, #so that the main menus would not be that long. def main_menu(): global option print "OPTIONS MENU" print "1) Calculate" print "2) Shapes" print "3) Temperature" print "4) Formulas" print "5) Quit" option = input("What option would you like:" ) def cal_menu(): global cal_opt print "CALCULATE MENU" print "1) Add" print "2) Subraction" print "3) Multiplication" print "4) Division w/o remainder" print "5) Division with remaider" print "6) Exponation" print "7) Square roots" print "8) Back to the previous menu." cal_opt = input("What option would you like:" ) def shape_menu(): global shape_opt print "SHAPES MENU" print "Important: The figure that is used for pi is 3.14." print "1) Squares" print "2) Circles" print "3) Rectangles" print "4) Triangles" print "5) Cones" print "6) Cylinders" print "7) Semicircles" print "8) Main menu" shape_opt = input("What option would you like?" ) def temp_menu(): global temp_opt print "1) Convert degrees Kevins to degrees Celsius" print "2) Contvert Fahrenheit to Celsius" print "3) Convert Celsius to Fahrenheit" print "4) Convert Celsius to Kelvins" print "5) Convert Kelvins to Fahrenheit" print "6) Convert Fahrenheit to Kelvins" print "7) Main Menu" temp_option = input("Choice: ") def formula_menu(): global formula_opt print "1) Interest" print "2) Distance" print "3) Uniform motion" print "4) Momentum" print "5) Uniformly accelerated motion" print "6) Falling bodies" print "7) Weight" print "8) Main menu" fourmula_option = input("Choice: ") #Code for main part of program. print "The Giant Calculator" print print "Copyright 2005 Written and debugged by Nathan Pinno" print main_menu() if option == 1: cal_menu() if cal_opt == 1: X = input("First number:" ) Y = input("Second number:" ) print X, "+", Y, "= ",X + Y cal_menu() elif cal_opt == 2: X = input("First number:" ) Y = input("Second number:" ) print X, "-", Y, "= ",X - Y cal_menu() elif cal_opt == 3: X = input("First number:" ) Y = input("Second number:" ) print X, "*", Y, "= ",X * Y cal_menu() elif cal_opt == 4: X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y cal_menu() elif cal_opt == 5: X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y," R ", X % Y cal_menu() elif cal_opt == 6: X = input("First number:" ) Y = input("Power:" ) print X, "**", Y, "= ",X**Y cal_menu() elif cal_opt == 7: X = input("Number to be squared:" ) print "The square root of", X, " = ",X**0.5 cal_menu() elif cal_opt == 8: main_menu() else: print "That's not an option. Try again." cal_menu elif option == 2: shape_menu() if shape_opt == 1: print "1) Circumference" print "2) Area" print "3) Shapes Menu" op = input("Choice: ") if op == 1: side = input("Side: ") print "Circumference = ",4*side shape_menu() elif op == 2: side = input("Side: ") print "Area = ",side**2 shape_menu() elif op == 3: shape_menu() else: print "That's not an option." op = input("Choice: ") elif shape_opt == 2: print "1) Circumference" print "2) Area" print "3) Shapes Menu" d = input("Choice: ") if d == 1: diameter = input("Diameter: ") print "The circumference of the circle is ",diameter*3.14 shape_menu() elif d == 2: radius = input("Radius: ") print "The area of the circle is ",3.14*(radius**2) shape_menu() elif d == 3: shape_menu() else: print "That's not an option." d = input("Choice: ") elif shape_opt == 3: print "1) Area" print "2) Perimeter" print "3) Main menu" g = input("Choice: ") if g == 1: base = input("Base: ") altitude = input("Altitude: ") print "The area of the rectangle is: ",base*altitude shape_menu() elif g == 2: base = input("Base: ") altitude = input("Altiutude: ") print "The perimeter of the rectangle is: ",(2*base)+(2*altitude) shape_menu() elif g == 3: shape_menu() else: print "That's not an option." g = input("Choice: ") elif shape_opt == 4: print "1) Right Triangles - Pygathorean Theorum" print "2) Perimeter" print "3) Area" print "4) Shapes Menu" e = input("Choice: ") if e == 1: sidea = input("Side A: ") sideb = input("side B: ") print "The hypotenuse's length is: ",((sidea**2)+(sideb**2))**0.5 shape_menu() elif e == 2: sidea = input("Side A: ") sideb = input("Side B: ") sidec = input("Side C: ") print "The Perimeter of the triangle is: ",sidea+sideb+sidec shape_menu() elif e == 3: base = input("Base: ") height = input("Height: ") print "The area of the triangle is: ",1/2*base*height shape_menu() elif e == 4: shape_menu() else: print "That's not an option! Try again." e = input("Choice: ") elif shape_opt == 5: print "The base and circumference of a cone can be found with the circle formulas, so they aren't found here." print "1) Lateral Area" print "2) Total Area" print "3) Volume" print "4) Shapes Menu" opt = input("Choice: ") if opt == 1: r = input("Radius: ") sl = input("Slant height: ") print "The Lateral Area is: ",1/2*(2*3.14*r)*sl shape_menu() elif opt == 2: r = input("Radius: ") sl = input("Slant height: ") print "The total area is: ",1/2*(2*3.14*r)*sl+(3.14*(r**2)) shape_menu() elif opt == 3: height = input("Height: ") r = input("Radius: ") print "The volume is: ",1/4*(3.14*(r**2))*height shape_menu() elif opt == 4: shape_menu() else: print "That's not an option" opt = input("Choice: ") elif shape_opt == 6: print "1) Lateral Area" print "2) Total Area" print "3) Volume" print "4) Shape Menu" g = input("Choice: ") if g == 1: r = input("Radius: ") height = input("Height: ") print "The Lateral Area is: ",(2*3.14*r)*height shape_menu() elif g == 2: r = input("Radius: ") height = input("Height: ") print "The Total Area is: ",((2*3.14*r)*height)+(2*(3.14*(r**2))) shape_menu() elif g == 3: r = input("Radius: ") height = input("Height: ") print "The volume is: ",(3.14*(r**2))*height shape_menu() elif g == 4: shape_menu() else: print "That is not an option!" g = input("Choice: ") elif shape_opt == 7: print "1) Arc Length" print "2) Area" print "3) Shape Menu" h = input("Choice: ") if h == 1: diam = input("Diameter: ") print "The arc length is: ",(3.14*diam)/2 shape_menu() elif h == 2: r = input("Radius: ") print "The area is: ",(3.14*(r**2))/2 shape_menu() elif h == 3: shape_menu else: print "Sorry, incorrect entry. Please try again." h = input("Choice: ") elif shape_menu == 8: main_menu() else: print "Sorry, not an option." shape_menu() elif option == 3: temp_menu() if temp_option == 1: print "Convert degrees Kelvin to degrees Celsius." k = input("Degrees Kelvin: ") print k-273.16," degrees Celsius" temp_menu() elif temp_option == 2: print "Convert Fahrenheit to Celsius" f = input("Degrees Fahrenheit: ") print 5/9*(f-32)," degrees Celsius" temp_menu() elif temp_option == 3: print "Convert Celsius to Fahrenheit" c = input("Degrees Celsius: ") print (9/5*C)+32," degrees Fahrenheit" temp_menu() elif temp_option == 4: print "Convert degrees Celsius to degrees Kelvin" c = input("Degrees Celsius: ") print c+273.16," degrees Kelvin" temp_menu() elif temp_option == 5: print "Convert degrees Kelvin to Fahrenheit" k = input("Degrees Kelvin: ") print ((k-273.16)*9/5)+32," degrees Fahrenheit" temp_menu() elif temp_option == 6: print "Convert Fahrenheit to degrees Kelvin" f = input("Degrees Fahrenheit: ") print (5/9*(f-32))+273.16," degrees Kelvin" temp_menu() elif temp_option == 7: main_menu() else: print "That's not an option. Please try again" temp_menu() elif option == 4: formula_menu() if formula_option == 1: p = input("Principal: ") r = input("Rate as a decimal: ") t = input("Time in years: ") print "Interest: ",p*r*t formula_menu() elif formula_option == 2: r = input("Rate: ") t = input("Time: ") print "Distance: ",r*t formula_menu() elif formula_option == 3: v = input("Velocity: ") t = input("Time: ") print "Uniform motion: ",v*t formula_menu() elif formula_option == 4: m = input("Mass: ") v = input("Velocity: ") print "Momentum: ",m*v formula_menu() elif formula_option == 5: as = input("Acceleration speed: ") t = input("Time: ") print "Uniformly accelerated motion: ",1/2*as*t formula_menu() elif formula_option == 6: gravity = input("Constant acceleration due to gravity: ") t = input("Time: ") print "Distance covered by falling body: ",1/2*gravity*(t**2) formula_menu() elif formula_option == 7: m = input("Mass: ") gravity = input("Gravity: ") print "Weight: ",m*gravity formula_menu() elif formula_option == 8: main_menu() else: print "That is not an option." formula_menu() elif option == 5: print "Goodbye!" else: print "That is not an option. Please choose an option from the menu." main_menu() print So how do I do it? Nathan Pinno http://www.npinnowebsite.ca/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050712/ae53a43c/attachment-0001.htm From ajikoe at gmail.com Tue Jul 12 10:33:03 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Tue, 12 Jul 2005 10:33:03 +0200 Subject: [Tutor] Giant Calc runs, but need advice on how to make the menu repopup. In-Reply-To: References: Message-ID: you can wrap your code with while statement that check a user input received at the end of every calculation you made whether go back to main menu or not. pujo On 7/12/05, Nathan Pinno wrote: > > It runs but now how do I make it go back to the previous menu (e.g. from Add > to Calculate Menu?) > > Here is the latest screenshot: > > The Giant Calculator > > Copyright 2005 Written and debugged by Nathan Pinno > > OPTIONS MENU > 1) Calculate > 2) Shapes > 3) Temperature > 4) Formulas > 5) Quit > What option would you like:1 > CALCULATE MENU > 1) Add > 2) Subraction > 3) Multiplication > 4) Division w/o remainder > 5) Division with remaider > 6) Exponation > 7) Square roots > 8) Back to the previous menu. > What option would you like:3 > First number:3 > Second number:2 > 3 * 2 = 6 > CALCULATE MENU > 1) Add > 2) Subraction > 3) Multiplication > 4) Division w/o remainder > 5) Division with remaider > 6) Exponation > 7) Square roots > 8) Back to the previous menu. > What option would you like:7 > > > >>> > > and the current code: > > # This program is designed as a big calculator with functions. > > # This first bunch of code is for the various menus. I decided to divide the > calculations into seperate sub-menus, > #so that the main menus would not be that long. > def main_menu(): > global option > print "OPTIONS MENU" > print "1) Calculate" > print "2) Shapes" > print "3) Temperature" > print "4) Formulas" > print "5) Quit" > option = input("What option would you like:" ) > > def cal_menu(): > global cal_opt > print "CALCULATE MENU" > print "1) Add" > print "2) Subraction" > print "3) Multiplication" > print "4) Division w/o remainder" > print "5) Division with remaider" > print "6) Exponation" > print "7) Square roots" > print "8) Back to the previous menu." > cal_opt = input("What option would you like:" ) > > def shape_menu(): > global shape_opt > print "SHAPES MENU" > print "Important: The figure that is used for pi is 3.14." > print "1) Squares" > print "2) Circles" > print "3) Rectangles" > print "4) Triangles" > print "5) Cones" > print "6) Cylinders" > print "7) Semicircles" > print "8) Main menu" > shape_opt = input("What option would you like?" ) > > def temp_menu(): > global temp_opt > print "1) Convert degrees Kevins to degrees Celsius" > print "2) Contvert Fahrenheit to Celsius" > print "3) Convert Celsius to Fahrenheit" > print "4) Convert Celsius to Kelvins" > print "5) Convert Kelvins to Fahrenheit" > print "6) Convert Fahrenheit to Kelvins" > print "7) Main Menu" > temp_option = input("Choice: ") > > def formula_menu(): > global formula_opt > print "1) Interest" > print "2) Distance" > print "3) Uniform motion" > print "4) Momentum" > print "5) Uniformly accelerated motion" > print "6) Falling bodies" > print "7) Weight" > print "8) Main menu" > fourmula_option = input("Choice: ") > > #Code for main part of program. > print "The Giant Calculator" > print > print "Copyright 2005 Written and debugged by Nathan Pinno" > print > main_menu() > if option == 1: > cal_menu() > if cal_opt == 1: > X = input("First number:" ) > Y = input("Second number:" ) > print X, "+", Y, "= ",X + Y > cal_menu() > elif cal_opt == 2: > X = input("First number:" ) > Y = input("Second number:" ) > print X, "-", Y, "= ",X - Y > cal_menu() > elif cal_opt == 3: > X = input("First number:" ) > Y = input("Second number:" ) > print X, "*", Y, "= ",X * Y > cal_menu() > elif cal_opt == 4: > X = input("First number:" ) > Y = input("Second number:" ) > if Y == 0: > print "Division by zero ot allowed!" > Y = input("Second number:" ) > else: > print X, "/", Y, "= ",X / Y > cal_menu() > elif cal_opt == 5: > X = input("First number:" ) > Y = input("Second number:" ) > if Y == 0: > print "Division by zero ot allowed!" > Y = input("Second number:" ) > else: > print X, "/", Y, "= ",X / Y," R ", X % Y > cal_menu() > elif cal_opt == 6: > X = input("First number:" ) > Y = input("Power:" ) > print X, "**", Y, "= ",X**Y > cal_menu() > elif cal_opt == 7: > X = input("Number to be squared:" ) > print "The square root of", X, " = ",X**0.5 > cal_menu() > elif cal_opt == 8: > main_menu() > else: > print "That's not an option. Try again." > cal_menu > elif option == 2: > shape_menu() > if shape_opt == 1: > print "1) Circumference" > print "2) Area" > print "3) Shapes Menu" > op = input("Choice: ") > if op == 1: > side = input("Side: ") > print "Circumference = ",4*side > shape_menu() > elif op == 2: > side = input("Side: ") > print "Area = ",side**2 > shape_menu() > elif op == 3: > shape_menu() > else: > print "That's not an option." > op = input("Choice: ") > elif shape_opt == 2: > print "1) Circumference" > print "2) Area" > print "3) Shapes Menu" > d = input("Choice: ") > if d == 1: > diameter = input("Diameter: ") > print "The circumference of the circle is ",diameter*3.14 > shape_menu() > elif d == 2: > radius = input("Radius: ") > print "The area of the circle is ",3.14*(radius**2) > shape_menu() > elif d == 3: > shape_menu() > else: > print "That's not an option." > d = input("Choice: ") > elif shape_opt == 3: > print "1) Area" > print "2) Perimeter" > print "3) Main menu" > g = input("Choice: ") > if g == 1: > base = input("Base: ") > altitude = input("Altitude: ") > print "The area of the rectangle is: ",base*altitude > shape_menu() > elif g == 2: > base = input("Base: ") > altitude = input("Altiutude: ") > print "The perimeter of the rectangle is: > ",(2*base)+(2*altitude) > shape_menu() > elif g == 3: > shape_menu() > else: > print "That's not an option." > g = input("Choice: ") > elif shape_opt == 4: > print "1) Right Triangles - Pygathorean Theorum" > print "2) Perimeter" > print "3) Area" > print "4) Shapes Menu" > e = input("Choice: ") > if e == 1: > sidea = input("Side A: ") > sideb = input("side B: ") > print "The hypotenuse's length is: > ",((sidea**2)+(sideb**2))**0.5 > shape_menu() > elif e == 2: > sidea = input("Side A: ") > sideb = input("Side B: ") > sidec = input("Side C: ") > print "The Perimeter of the triangle is: ",sidea+sideb+sidec > shape_menu() > elif e == 3: > base = input("Base: ") > height = input("Height: ") > print "The area of the triangle is: ",1/2*base*height > shape_menu() > elif e == 4: > shape_menu() > else: > print "That's not an option! Try again." > e = input("Choice: ") > elif shape_opt == 5: > print "The base and circumference of a cone can be found with the > circle formulas, so they aren't found here." > print "1) Lateral Area" > print "2) Total Area" > print "3) Volume" > print "4) Shapes Menu" > opt = input("Choice: ") > if opt == 1: > r = input("Radius: ") > sl = input("Slant height: ") > print "The Lateral Area is: ",1/2*(2*3.14*r)*sl > shape_menu() > elif opt == 2: > r = input("Radius: ") > sl = input("Slant height: ") > print "The total area is: ",1/2*(2*3.14*r)*sl+(3.14*(r**2)) > shape_menu() > elif opt == 3: > height = input("Height: ") > r = input("Radius: ") > print "The volume is: ",1/4*(3.14*(r**2))*height > shape_menu() > elif opt == 4: > shape_menu() > else: > print "That's not an option" > opt = input("Choice: ") > elif shape_opt == 6: > print "1) Lateral Area" > print "2) Total Area" > print "3) Volume" > print "4) Shape Menu" > g = input("Choice: ") > if g == 1: > r = input("Radius: ") > height = input("Height: ") > print "The Lateral Area is: ",(2*3.14*r)*height > shape_menu() > elif g == 2: > r = input("Radius: ") > height = input("Height: ") > print "The Total Area is: ",((2*3.14*r)*height)+(2*(3.14*(r**2))) > shape_menu() > elif g == 3: > r = input("Radius: ") > height = input("Height: ") > print "The volume is: ",(3.14*(r**2))*height > shape_menu() > elif g == 4: > shape_menu() > else: > print "That is not an option!" > g = input("Choice: ") > elif shape_opt == 7: > print "1) Arc Length" > print "2) Area" > print "3) Shape Menu" > h = input("Choice: ") > if h == 1: > diam = input("Diameter: ") > print "The arc length is: ",(3.14*diam)/2 > shape_menu() > elif h == 2: > r = input("Radius: ") > print "The area is: ",(3.14*(r**2))/2 > shape_menu() > elif h == 3: > shape_menu > else: > print "Sorry, incorrect entry. Please try again." > h = input("Choice: ") > elif shape_menu == 8: > main_menu() > else: > print "Sorry, not an option." > shape_menu() > elif option == 3: > temp_menu() > if temp_option == 1: > print "Convert degrees Kelvin to degrees Celsius." > k = input("Degrees Kelvin: ") > print k-273.16," degrees Celsius" > temp_menu() > elif temp_option == 2: > print "Convert Fahrenheit to Celsius" > f = input("Degrees Fahrenheit: ") > print 5/9*(f-32)," degrees Celsius" > temp_menu() > elif temp_option == 3: > print "Convert Celsius to Fahrenheit" > c = input("Degrees Celsius: ") > print (9/5*C)+32," degrees Fahrenheit" > temp_menu() > elif temp_option == 4: > print "Convert degrees Celsius to degrees Kelvin" > c = input("Degrees Celsius: ") > print c+273.16," degrees Kelvin" > temp_menu() > elif temp_option == 5: > print "Convert degrees Kelvin to Fahrenheit" > k = input("Degrees Kelvin: ") > print ((k-273.16)*9/5)+32," degrees Fahrenheit" > temp_menu() > elif temp_option == 6: > print "Convert Fahrenheit to degrees Kelvin" > f = input("Degrees Fahrenheit: ") > print (5/9*(f-32))+273.16," degrees Kelvin" > temp_menu() > elif temp_option == 7: > main_menu() > else: > print "That's not an option. Please try again" > temp_menu() > elif option == 4: > formula_menu() > if formula_option == 1: > p = input("Principal: ") > r = input("Rate as a decimal: ") > t = input("Time in years: ") > print "Interest: ",p*r*t > formula_menu() > elif formula_option == 2: > r = input("Rate: ") > t = input("Time: ") > print "Distance: ",r*t > formula_menu() > elif formula_option == 3: > v = input("Velocity: ") > t = input("Time: ") > print "Uniform motion: ",v*t > formula_menu() > elif formula_option == 4: > m = input("Mass: ") > v = input("Velocity: ") > print "Momentum: ",m*v > formula_menu() > elif formula_option == 5: > as = input("Acceleration speed: ") > t = input("Time: ") > print "Uniformly accelerated motion: ",1/2*as*t > formula_menu() > elif formula_option == 6: > gravity = input("Constant acceleration due to gravity: ") > t = input("Time: ") > print "Distance covered by falling body: ",1/2*gravity*(t**2) > formula_menu() > elif formula_option == 7: > m = input("Mass: ") > gravity = input("Gravity: ") > print "Weight: ",m*gravity > formula_menu() > elif formula_option == 8: > main_menu() > else: > print "That is not an option." > formula_menu() > elif option == 5: > print "Goodbye!" > else: > print "That is not an option. Please choose an option from the menu." > main_menu() > print > > > So how do I do it? > > Nathan Pinno > http://www.npinnowebsite.ca/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From pythontut at pusspaws.net Tue Jul 12 11:49:22 2005 From: pythontut at pusspaws.net (Dave S) Date: Tue, 12 Jul 2005 10:49:22 +0100 Subject: [Tutor] OT python Licences Message-ID: <42D39222.9040608@pusspaws.net> This is a bit OT but here goes. My work wants me to write a fairly large python script to analyze some technical ASCII data files. Python and its libraries are GPL. That being the case am I right in thinking that my script would also have to be GPL and I would have to inform my employer as I hand it over ? Secondly it would have to run in Windows, The results could pop up on a DOS window. However I was looking at QT until I read the Windows license. Are there any widget libraries that would allow me to program for windows commercially without any license or fees ? Thanks in advance Dave From bvande at po-box.mcgill.ca Tue Jul 12 12:19:05 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 12 Jul 2005 06:19:05 -0400 Subject: [Tutor] OT python Licences In-Reply-To: <42D39222.9040608@pusspaws.net> References: <42D39222.9040608@pusspaws.net> Message-ID: <42D39919.4070009@po-box.mcgill.ca> Dave S said unto the world upon 12/07/2005 05:49: > This is a bit OT but here goes. > > My work wants me to write a fairly large python script to analyze some > technical ASCII data files. Python and its libraries are GPL. > > That being the case am I right in thinking that my script would also > have to be GPL and I would have to inform my employer as I hand it over ? > > Secondly it would have to run in Windows, The results could pop up on a > DOS window. However I was looking at QT until I read the Windows > license. Are there any widget libraries that would allow me to program > for windows commercially without any license or fees ? > > Thanks in advance > Dave > Apologies if this is a dupe; flaky wifi connection on my end. Python's not GPL. It is under the Python license, which allows for non-free (speech sense) uses that the GPL doesn't. It is GPL-compatible. (And, just in case, its use for anything other than Python is strongly discouraged.) Best, Brian vdB From kent37 at tds.net Tue Jul 12 12:44:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Jul 2005 06:44:28 -0400 Subject: [Tutor] OT python Licences In-Reply-To: <42D39222.9040608@pusspaws.net> References: <42D39222.9040608@pusspaws.net> Message-ID: <42D39F0C.5020702@tds.net> Dave S wrote: > This is a bit OT but here goes. > > My work wants me to write a fairly large python script to analyze some > technical ASCII data files. Python and its libraries are GPL. > > That being the case am I right in thinking that my script would also > have to be GPL and I would have to inform my employer as I hand it over ? No, Python is not released under the GPL and there are very few restrictions on redistributing it. See http://www.python.org/doc/faq/general.html#are-there-copyright-restrictions-on-the-use-of-python AFAIK you can license your *scripts* in any way you choose. > Secondly it would have to run in Windows, The results could pop up on a > DOS window. However I was looking at QT until I read the Windows > license. Are there any widget libraries that would allow me to program > for windows commercially without any license or fees ? Tkinter (included with Python) and wxPython are both popular for this. The general consensus seems to be that Tkinter is easier to use for small projects while wxPython is more complete and better at creating apps that match users' expectations of look-and-feel. http://www.wxpython.org Kent From kent37 at tds.net Tue Jul 12 14:19:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 12 Jul 2005 08:19:16 -0400 Subject: [Tutor] domain logic and avoiding setters and setters. In-Reply-To: <22803ae2050711140056e07a88@mail.gmail.com> References: <22803ae2050711140056e07a88@mail.gmail.com> Message-ID: <42D3B544.3040701@tds.net> David Driver wrote: > So I have been trying to figure out how to get around doing getters > and setters and still have an oo way to inherit and apply business > rules. This is what I have some up with so far. Is there any better > way? Hmm. I'm not sure what this has to do with getters and setters...maybe I would have to see the way you *didn't* show us to understand... The only thing that I don't like about the code below is the need for subclasses to add rules to self._rules in the __init__() method. IMO this is fragile - it is too easy to forget to add or remove a rule from the list when the code changes. An alternative is to use some form of auto-discovery of the rules. If you use a naming convention for the rule methods this is pretty easy. You can see an example in the unittest module; it finds all TestCase methods that start with 'test' and runs them. The code to find the tests is in Lib\unittest.py in the function getTestCaseNames(). Kent > > class RuleViolationError(Exception): > def __init__(self, msg): > self.msg = msg > def __str__(self): > return 'Rule violated in rule object: %s' %self.msg > > class someObject(object): > def __init__(self,a): > self._voilatedRules = {} > self._rules = [self.aRuleForA] > self.a = a > > def applyRules(self): > self._voilatedRules.clear() > for rule in self._rules: > try: > rule() > except RuleViolationError, err: > self._voilatedRules[rule.__name__] = err.msg > if self._voilatedRules: > # do something dramatic to deal with all of the > # voilated business rules > print 'error(s): ' > print self._voilatedRules > > def aRuleForA(self): > try: > self.a = int(self.a) > except ValueError: > raise RuleViolationError('a is not an integer') > > class someObjectChild(someObject): > def __init__(self, a,b): > someObject.__init__(self,a) > self.b = b > self._rules.extend((self.aRuleForB, > self.anotherRuleForB)) > > def aRuleForB(self): > # apply some business logic for d > # check that it starts with b, very silly > if not self.b.startswith('b'): > raise RuleViolationError('b does not start with b') > > def anotherRuleForB(self): > #test string for length constraints > min,max,l=2,15,len(self.b) > print min,max,l > if not(l>=min and l<=max): > raise RuleViolationError('b is out of min or max') > > class someObjectChild2(someObjectChild): > #j ust change one of the rules for b > def aRuleForB(self): > # apply some business logic for d > # check that it starts with d, very silly > if not self.b.startswith('d'): > raise RuleViolationError('b does not start with d') > > > x = someObjectChild(123,'bob jones') > > # this should return nothing > x.applyRules() > x.b = 'obladiobladalifegoesonOOOO' > > # this should fail twice on b > x.applyRules() > > y = someObjectChild2(123,'bob jones') > y.applyRules() > > z = someObjectChild('happydance','bob jones') > z.applyRules() > > This isn't near complete, but I think it gets the idea across. From ewald.ertl at hartter.com Tue Jul 12 14:21:14 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue, 12 Jul 2005 14:21:14 +0200 Subject: [Tutor] Giant Calc runs, but need advice on how to make the menu repopup. In-Reply-To: References: Message-ID: <20050712142114.000037ce@sunray2.hartter.com> Hi! As allready shown in your request for the "The Password Program" some day's ago, which has nearly the same problem as here. Wrap your code into loop's: why are you setting the select-Values directly in the functions defining the menu's? Why not just returning the selected value e.g.: def temp_menu(): print "1) Convert degrees Kevins to degrees Celsius" print "2) Contvert Fahrenheit to Celsius" print "3) Convert Celsius to Fahrenheit" print "4) Convert Celsius to Kelvins" print "5) Convert Kelvins to Fahrenheit" print "6) Convert Fahrenheit to Kelvins" print "7) Main Menu" return (input("Choice: ")) and make the assignment in the main-Part: temp_option=temp_menu() So the function does not need to know which option the input should be assigned and it is also useable in other part's of the code. Here's an extract of your calc-Part with while-Loops: there is only one call to the menu-functions necessary and not in all branches, because we return every time in the loop except, when the return-Option is selected. There is simple a "break"-Statement to leave the loop and go on outside the loop. In my opinion, it would als be more readable, when you extract the calculcation-Code somewhere out of the big loop. Create a function for calculation and so on and handle in the functions the code, so it will become more "readable". It would also be somewhat better, to have a unique Number for the "Main Menu"-Option and not everytime a different number to select the "Main Menu". option=1 while option != 5: option=main_menu() if option == 1: cal_opt=1 while cal_opt != 8: cal_opt=cal_menu() if cal_opt == 1: X = input("First number:" ) Y = input("Second number:" ) print X, "+", Y, "= ",X + Y elif cal_opt == 2: X = input("First number:" ) Y = input("Second number:" ) print X, "-", Y, "= ",X - Y elif cal_opt == 3: X = input("First number:" ) Y = input("Second number:" ) print X, "*", Y, "= ",X * Y elif cal_opt == 4: X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y elif cal_opt == 5: X = input("First number:" ) Y = input("Second number:" ) if Y == 0: print "Division by zero ot allowed!" Y = input("Second number:" ) else: print X, "/", Y, "= ",X / Y," R ", X % Y elif cal_opt == 6: X = input("First number:" ) Y = input("Power:" ) print X, "**", Y, "= ",X**Y elif cal_opt == 7: X = input("Number to be squared:" ) print "The square root of", X, " = ",X**0.5 elif cal_opt == 8: break; else: print "That's not an option. Try again." if option == 2: ... One additional step is to make an independent menu-Function def menu( args): count=xrange(len(args)) for mycount,arg in zip( count,args): print "%d) %s" % ( mycount, arg) print "99) Main Menu" return( input("Choice: ")) and just calling with the arguments main_menu=[ "Calculate","Shapes","Temperature","Formulas","Quit" ] calc_menu=["Add","Subraction","Multiplication","Division w/o remainder", "Division with remaider","Exponation","Square roots" ] option=menu(main_menu) ... calc_option=menu(calc_menu) .... HTH Ewald on Tue, 12 Jul 2005 02:11:47 -0600 "Nathan Pinno" wrote : --------------------------------------------------------------------------------------------- Nathan Pinno > It runs but now how do I make it go back to the previous menu (e.g. from Add to Calculate Menu?) Nathan Pinno > Nathan Pinno > Here is the latest screenshot: Nathan Pinno > Nathan Pinno > The Giant Calculator Nathan Pinno > Nathan Pinno > Copyright 2005 Written and debugged by Nathan Pinno Nathan Pinno > Nathan Pinno > OPTIONS MENU Nathan Pinno > 1) Calculate Nathan Pinno > 2) Shapes Nathan Pinno > 3) Temperature Nathan Pinno > 4) Formulas Nathan Pinno > 5) Quit Nathan Pinno > What option would you like:1 Nathan Pinno > CALCULATE MENU Nathan Pinno > 1) Add Nathan Pinno > 2) Subraction Nathan Pinno > 3) Multiplication Nathan Pinno > 4) Division w/o remainder Nathan Pinno > 5) Division with remaider Nathan Pinno > 6) Exponation Nathan Pinno > 7) Square roots Nathan Pinno > 8) Back to the previous menu. Nathan Pinno > What option would you like:3 Nathan Pinno > First number:3 Nathan Pinno > Second number:2 Nathan Pinno > 3 * 2 = 6 Nathan Pinno > CALCULATE MENU Nathan Pinno > 1) Add Nathan Pinno > 2) Subraction Nathan Pinno > 3) Multiplication Nathan Pinno > 4) Division w/o remainder Nathan Pinno > 5) Division with remaider Nathan Pinno > 6) Exponation Nathan Pinno > 7) Square roots Nathan Pinno > 8) Back to the previous menu. Nathan Pinno > What option would you like:7 Nathan Pinno > Nathan Pinno > Nathan Pinno > >>> Nathan Pinno > Nathan Pinno > and the current code: Nathan Pinno > Nathan Pinno > # This program is designed as a big calculator with functions. Nathan Pinno > Nathan Pinno > # This first bunch of code is for the various menus. I decided to divide the calculations into seperate sub-menus, Nathan Pinno > #so that the main menus would not be that long. Nathan Pinno > def main_menu(): Nathan Pinno > global option Nathan Pinno > print "OPTIONS MENU" Nathan Pinno > print "1) Calculate" Nathan Pinno > print "2) Shapes" Nathan Pinno > print "3) Temperature" Nathan Pinno > print "4) Formulas" Nathan Pinno > print "5) Quit" Nathan Pinno > option = input("What option would you like:" ) Nathan Pinno > Nathan Pinno > def cal_menu(): Nathan Pinno > global cal_opt Nathan Pinno > print "CALCULATE MENU" Nathan Pinno > print "1) Add" Nathan Pinno > print "2) Subraction" Nathan Pinno > print "3) Multiplication" Nathan Pinno > print "4) Division w/o remainder" Nathan Pinno > print "5) Division with remaider" Nathan Pinno > print "6) Exponation" Nathan Pinno > print "7) Square roots" Nathan Pinno > print "8) Back to the previous menu." Nathan Pinno > cal_opt = input("What option would you like:" ) Nathan Pinno > Nathan Pinno > def shape_menu(): Nathan Pinno > global shape_opt Nathan Pinno > print "SHAPES MENU" Nathan Pinno > print "Important: The figure that is used for pi is 3.14." Nathan Pinno > print "1) Squares" Nathan Pinno > print "2) Circles" Nathan Pinno > print "3) Rectangles" Nathan Pinno > print "4) Triangles" Nathan Pinno > print "5) Cones" Nathan Pinno > print "6) Cylinders" Nathan Pinno > print "7) Semicircles" Nathan Pinno > print "8) Main menu" Nathan Pinno > shape_opt = input("What option would you like?" ) Nathan Pinno > Nathan Pinno > def temp_menu(): Nathan Pinno > global temp_opt Nathan Pinno > print "1) Convert degrees Kevins to degrees Celsius" Nathan Pinno > print "2) Contvert Fahrenheit to Celsius" Nathan Pinno > print "3) Convert Celsius to Fahrenheit" Nathan Pinno > print "4) Convert Celsius to Kelvins" Nathan Pinno > print "5) Convert Kelvins to Fahrenheit" Nathan Pinno > print "6) Convert Fahrenheit to Kelvins" Nathan Pinno > print "7) Main Menu" Nathan Pinno > temp_option = input("Choice: ") Nathan Pinno > Nathan Pinno > def formula_menu(): Nathan Pinno > global formula_opt Nathan Pinno > print "1) Interest" Nathan Pinno > print "2) Distance" Nathan Pinno > print "3) Uniform motion" Nathan Pinno > print "4) Momentum" Nathan Pinno > print "5) Uniformly accelerated motion" Nathan Pinno > print "6) Falling bodies" Nathan Pinno > print "7) Weight" Nathan Pinno > print "8) Main menu" Nathan Pinno > fourmula_option = input("Choice: ") Nathan Pinno > Nathan Pinno > #Code for main part of program. Nathan Pinno > print "The Giant Calculator" Nathan Pinno > print Nathan Pinno > print "Copyright 2005 Written and debugged by Nathan Pinno" Nathan Pinno > print Nathan Pinno > main_menu() Nathan Pinno > if option == 1: Nathan Pinno > cal_menu() Nathan Pinno > if cal_opt == 1: Nathan Pinno > X = input("First number:" ) Nathan Pinno > Y = input("Second number:" ) Nathan Pinno > print X, "+", Y, "= ",X + Y Nathan Pinno > cal_menu() Nathan Pinno > elif cal_opt == 2: Nathan Pinno > X = input("First number:" ) Nathan Pinno > Y = input("Second number:" ) Nathan Pinno > print X, "-", Y, "= ",X - Y Nathan Pinno > cal_menu() Nathan Pinno > elif cal_opt == 3: Nathan Pinno > X = input("First number:" ) Nathan Pinno > Y = input("Second number:" ) Nathan Pinno > print X, "*", Y, "= ",X * Y Nathan Pinno > cal_menu() Nathan Pinno > elif cal_opt == 4: Nathan Pinno > X = input("First number:" ) Nathan Pinno > Y = input("Second number:" ) Nathan Pinno > if Y == 0: Nathan Pinno > print "Division by zero ot allowed!" Nathan Pinno > Y = input("Second number:" ) Nathan Pinno > else: Nathan Pinno > print X, "/", Y, "= ",X / Y Nathan Pinno > cal_menu() Nathan Pinno > elif cal_opt == 5: Nathan Pinno > X = input("First number:" ) Nathan Pinno > Y = input("Second number:" ) Nathan Pinno > if Y == 0: Nathan Pinno > print "Division by zero ot allowed!" Nathan Pinno > Y = input("Second number:" ) Nathan Pinno > else: Nathan Pinno > print X, "/", Y, "= ",X / Y," R ", X % Y Nathan Pinno > cal_menu() Nathan Pinno > elif cal_opt == 6: Nathan Pinno > X = input("First number:" ) Nathan Pinno > Y = input("Power:" ) Nathan Pinno > print X, "**", Y, "= ",X**Y Nathan Pinno > cal_menu() Nathan Pinno > elif cal_opt == 7: Nathan Pinno > X = input("Number to be squared:" ) Nathan Pinno > print "The square root of", X, " = ",X**0.5 Nathan Pinno > cal_menu() Nathan Pinno > elif cal_opt == 8: Nathan Pinno > main_menu() Nathan Pinno > else: Nathan Pinno > print "That's not an option. Try again." Nathan Pinno > cal_menu Nathan Pinno > elif option == 2: Nathan Pinno > shape_menu() Nathan Pinno > if shape_opt == 1: Nathan Pinno > print "1) Circumference" Nathan Pinno > print "2) Area" Nathan Pinno > print "3) Shapes Menu" Nathan Pinno > op = input("Choice: ") Nathan Pinno > if op == 1: Nathan Pinno > side = input("Side: ") Nathan Pinno > print "Circumference = ",4*side Nathan Pinno > shape_menu() Nathan Pinno > elif op == 2: Nathan Pinno > side = input("Side: ") Nathan Pinno > print "Area = ",side**2 Nathan Pinno > shape_menu() Nathan Pinno > elif op == 3: Nathan Pinno > shape_menu() Nathan Pinno > else: Nathan Pinno > print "That's not an option." Nathan Pinno > op = input("Choice: ") Nathan Pinno > elif shape_opt == 2: Nathan Pinno > print "1) Circumference" Nathan Pinno > print "2) Area" Nathan Pinno > print "3) Shapes Menu" Nathan Pinno > d = input("Choice: ") Nathan Pinno > if d == 1: Nathan Pinno > diameter = input("Diameter: ") Nathan Pinno > print "The circumference of the circle is ",diameter*3.14 Nathan Pinno > shape_menu() Nathan Pinno > elif d == 2: Nathan Pinno > radius = input("Radius: ") Nathan Pinno > print "The area of the circle is ",3.14*(radius**2) Nathan Pinno > shape_menu() Nathan Pinno > elif d == 3: Nathan Pinno > shape_menu() Nathan Pinno > else: Nathan Pinno > print "That's not an option." Nathan Pinno > d = input("Choice: ") Nathan Pinno > elif shape_opt == 3: Nathan Pinno > print "1) Area" Nathan Pinno > print "2) Perimeter" Nathan Pinno > print "3) Main menu" Nathan Pinno > g = input("Choice: ") Nathan Pinno > if g == 1: Nathan Pinno > base = input("Base: ") Nathan Pinno > altitude = input("Altitude: ") Nathan Pinno > print "The area of the rectangle is: ",base*altitude Nathan Pinno > shape_menu() Nathan Pinno > elif g == 2: Nathan Pinno > base = input("Base: ") Nathan Pinno > altitude = input("Altiutude: ") Nathan Pinno > print "The perimeter of the rectangle is: ",(2*base)+(2*altitude) Nathan Pinno > shape_menu() Nathan Pinno > elif g == 3: Nathan Pinno > shape_menu() Nathan Pinno > else: Nathan Pinno > print "That's not an option." Nathan Pinno > g = input("Choice: ") Nathan Pinno > elif shape_opt == 4: Nathan Pinno > print "1) Right Triangles - Pygathorean Theorum" Nathan Pinno > print "2) Perimeter" Nathan Pinno > print "3) Area" Nathan Pinno > print "4) Shapes Menu" Nathan Pinno > e = input("Choice: ") Nathan Pinno > if e == 1: Nathan Pinno > sidea = input("Side A: ") Nathan Pinno > sideb = input("side B: ") Nathan Pinno > print "The hypotenuse's length is: ",((sidea**2)+(sideb**2))**0.5 Nathan Pinno > shape_menu() Nathan Pinno > elif e == 2: Nathan Pinno > sidea = input("Side A: ") Nathan Pinno > sideb = input("Side B: ") Nathan Pinno > sidec = input("Side C: ") Nathan Pinno > print "The Perimeter of the triangle is: ",sidea+sideb+sidec Nathan Pinno > shape_menu() Nathan Pinno > elif e == 3: Nathan Pinno > base = input("Base: ") Nathan Pinno > height = input("Height: ") Nathan Pinno > print "The area of the triangle is: ",1/2*base*height Nathan Pinno > shape_menu() Nathan Pinno > elif e == 4: Nathan Pinno > shape_menu() Nathan Pinno > else: Nathan Pinno > print "That's not an option! Try again." Nathan Pinno > e = input("Choice: ") Nathan Pinno > elif shape_opt == 5: Nathan Pinno > print "The base and circumference of a cone can be found with the circle formulas, so they aren't found here." Nathan Pinno > print "1) Lateral Area" Nathan Pinno > print "2) Total Area" Nathan Pinno > print "3) Volume" Nathan Pinno > print "4) Shapes Menu" Nathan Pinno > opt = input("Choice: ") Nathan Pinno > if opt == 1: Nathan Pinno > r = input("Radius: ") Nathan Pinno > sl = input("Slant height: ") Nathan Pinno > print "The Lateral Area is: ",1/2*(2*3.14*r)*sl Nathan Pinno > shape_menu() Nathan Pinno > elif opt == 2: Nathan Pinno > r = input("Radius: ") Nathan Pinno > sl = input("Slant height: ") Nathan Pinno > print "The total area is: ",1/2*(2*3.14*r)*sl+(3.14*(r**2)) Nathan Pinno > shape_menu() Nathan Pinno > elif opt == 3: Nathan Pinno > height = input("Height: ") Nathan Pinno > r = input("Radius: ") Nathan Pinno > print "The volume is: ",1/4*(3.14*(r**2))*height Nathan Pinno > shape_menu() Nathan Pinno > elif opt == 4: Nathan Pinno > shape_menu() Nathan Pinno > else: Nathan Pinno > print "That's not an option" Nathan Pinno > opt = input("Choice: ") Nathan Pinno > elif shape_opt == 6: Nathan Pinno > print "1) Lateral Area" Nathan Pinno > print "2) Total Area" Nathan Pinno > print "3) Volume" Nathan Pinno > print "4) Shape Menu" Nathan Pinno > g = input("Choice: ") Nathan Pinno > if g == 1: Nathan Pinno > r = input("Radius: ") Nathan Pinno > height = input("Height: ") Nathan Pinno > print "The Lateral Area is: ",(2*3.14*r)*height Nathan Pinno > shape_menu() Nathan Pinno > elif g == 2: Nathan Pinno > r = input("Radius: ") Nathan Pinno > height = input("Height: ") Nathan Pinno > print "The Total Area is: ",((2*3.14*r)*height)+(2*(3.14*(r**2))) Nathan Pinno > shape_menu() Nathan Pinno > elif g == 3: Nathan Pinno > r = input("Radius: ") Nathan Pinno > height = input("Height: ") Nathan Pinno > print "The volume is: ",(3.14*(r**2))*height Nathan Pinno > shape_menu() Nathan Pinno > elif g == 4: Nathan Pinno > shape_menu() Nathan Pinno > else: Nathan Pinno > print "That is not an option!" Nathan Pinno > g = input("Choice: ") Nathan Pinno > elif shape_opt == 7: Nathan Pinno > print "1) Arc Length" Nathan Pinno > print "2) Area" Nathan Pinno > print "3) Shape Menu" Nathan Pinno > h = input("Choice: ") Nathan Pinno > if h == 1: Nathan Pinno > diam = input("Diameter: ") Nathan Pinno > print "The arc length is: ",(3.14*diam)/2 Nathan Pinno > shape_menu() Nathan Pinno > elif h == 2: Nathan Pinno > r = input("Radius: ") Nathan Pinno > print "The area is: ",(3.14*(r**2))/2 Nathan Pinno > shape_menu() Nathan Pinno > elif h == 3: Nathan Pinno > shape_menu Nathan Pinno > else: Nathan Pinno > print "Sorry, incorrect entry. Please try again." Nathan Pinno > h = input("Choice: ") Nathan Pinno > elif shape_menu == 8: Nathan Pinno > main_menu() Nathan Pinno > else: Nathan Pinno > print "Sorry, not an option." Nathan Pinno > shape_menu() Nathan Pinno > elif option == 3: Nathan Pinno > temp_menu() Nathan Pinno > if temp_option == 1: Nathan Pinno > print "Convert degrees Kelvin to degrees Celsius." Nathan Pinno > k = input("Degrees Kelvin: ") Nathan Pinno > print k-273.16," degrees Celsius" Nathan Pinno > temp_menu() Nathan Pinno > elif temp_option == 2: Nathan Pinno > print "Convert Fahrenheit to Celsius" Nathan Pinno > f = input("Degrees Fahrenheit: ") Nathan Pinno > print 5/9*(f-32)," degrees Celsius" Nathan Pinno > temp_menu() Nathan Pinno > elif temp_option == 3: Nathan Pinno > print "Convert Celsius to Fahrenheit" Nathan Pinno > c = input("Degrees Celsius: ") Nathan Pinno > print (9/5*C)+32," degrees Fahrenheit" Nathan Pinno > temp_menu() Nathan Pinno > elif temp_option == 4: Nathan Pinno > print "Convert degrees Celsius to degrees Kelvin" Nathan Pinno > c = input("Degrees Celsius: ") Nathan Pinno > print c+273.16," degrees Kelvin" Nathan Pinno > temp_menu() Nathan Pinno > elif temp_option == 5: Nathan Pinno > print "Convert degrees Kelvin to Fahrenheit" Nathan Pinno > k = input("Degrees Kelvin: ") Nathan Pinno > print ((k-273.16)*9/5)+32," degrees Fahrenheit" Nathan Pinno > temp_menu() Nathan Pinno > elif temp_option == 6: Nathan Pinno > print "Convert Fahrenheit to degrees Kelvin" Nathan Pinno > f = input("Degrees Fahrenheit: ") Nathan Pinno > print (5/9*(f-32))+273.16," degrees Kelvin" Nathan Pinno > temp_menu() Nathan Pinno > elif temp_option == 7: Nathan Pinno > main_menu() Nathan Pinno > else: Nathan Pinno > print "That's not an option. Please try again" Nathan Pinno > temp_menu() Nathan Pinno > elif option == 4: Nathan Pinno > formula_menu() Nathan Pinno > if formula_option == 1: Nathan Pinno > p = input("Principal: ") Nathan Pinno > r = input("Rate as a decimal: ") Nathan Pinno > t = input("Time in years: ") Nathan Pinno > print "Interest: ",p*r*t Nathan Pinno > formula_menu() Nathan Pinno > elif formula_option == 2: Nathan Pinno > r = input("Rate: ") Nathan Pinno > t = input("Time: ") Nathan Pinno > print "Distance: ",r*t Nathan Pinno > formula_menu() Nathan Pinno > elif formula_option == 3: Nathan Pinno > v = input("Velocity: ") Nathan Pinno > t = input("Time: ") Nathan Pinno > print "Uniform motion: ",v*t Nathan Pinno > formula_menu() Nathan Pinno > elif formula_option == 4: Nathan Pinno > m = input("Mass: ") Nathan Pinno > v = input("Velocity: ") Nathan Pinno > print "Momentum: ",m*v Nathan Pinno > formula_menu() Nathan Pinno > elif formula_option == 5: Nathan Pinno > as = input("Acceleration speed: ") Nathan Pinno > t = input("Time: ") Nathan Pinno > print "Uniformly accelerated motion: ",1/2*as*t Nathan Pinno > formula_menu() Nathan Pinno > elif formula_option == 6: Nathan Pinno > gravity = input("Constant acceleration due to gravity: ") Nathan Pinno > t = input("Time: ") Nathan Pinno > print "Distance covered by falling body: ",1/2*gravity*(t**2) Nathan Pinno > formula_menu() Nathan Pinno > elif formula_option == 7: Nathan Pinno > m = input("Mass: ") Nathan Pinno > gravity = input("Gravity: ") Nathan Pinno > print "Weight: ",m*gravity Nathan Pinno > formula_menu() Nathan Pinno > elif formula_option == 8: Nathan Pinno > main_menu() Nathan Pinno > else: Nathan Pinno > print "That is not an option." Nathan Pinno > formula_menu() Nathan Pinno > elif option == 5: Nathan Pinno > print "Goodbye!" Nathan Pinno > else: Nathan Pinno > print "That is not an option. Please choose an option from the menu." Nathan Pinno > main_menu() Nathan Pinno > print Nathan Pinno > Nathan Pinno > Nathan Pinno > So how do I do it? Nathan Pinno > Nathan Pinno > Nathan Pinno Nathan Pinno > http://www.npinnowebsite.ca/ ------------------- end ---------------------- -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl at trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl at hartter.com From cpu.crazy at gmail.com Mon Jul 11 19:22:57 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 11 Jul 2005 17:22:57 +0000 Subject: [Tutor] Tkinter Q's Message-ID: <42D2AAF1.9050400@gmail.com> Hi first off, here's my code: # -*- coding: utf-8 -*- from Tkinter import * import random import time import about import quotes def closeprog(): raise SystemExit class main: root = Tk() frame = Frame() root.title("Quoter %s" % (about.ver)) root.minsize(300, 50) showquote = Label(root, text=random.choice(quotes.quote)) showquote.pack() exit = Button(root, text="Exit", command=closeprog) exit.pack(side=LEFT) aboutprg = Button(root, text="About", command=about.main) aboutprg.pack(side=LEFT) totalq = Label(root, text=quotes.qts) totalq.pack(side=BOTTOM) root.mainloop() (I'd appreciate some suggestions, or notifications on how bad something is) I have a small problem: I don't know how to make a button that would redisplay another quote in the same window, ie I need a button that says: Show Another Quote. (Actually I don't know how to make it show another quote even in a new window!!). I got the interface from Catfood Fortune Cookie. Here's a tid-bit of the quotes module: # Brian Kernighan bk1 = """Controlling complexity is the essence of computer programming. -- Brian Kernighan""" yadayada = """Foo/bar""" quote = [bk1, yadayada] Thanks, Joe -- Unix Love, Linux Pride -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050711/f224c87f/attachment.htm From byron at christianfreebies.com Tue Jul 12 15:47:34 2005 From: byron at christianfreebies.com (Byron) Date: Tue, 12 Jul 2005 06:47:34 -0700 Subject: [Tutor] OT python Licences In-Reply-To: <42D39222.9040608@pusspaws.net> References: <42D39222.9040608@pusspaws.net> Message-ID: <42D3C9F6.9090201@christianfreebies.com> Dave S wrote: >That being the case am I right in thinking that my script would also >have to be GPL and I would have to inform my employer as I hand it over ? > > I don't believe so. Python prefers to encourage its developers to contribute to the general community. However, you can commercially write apps in Python and then sell them -- without having to make them open source or give-awayable to the general community. Hope this helps, Byron --- -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.8.12/46 - Release Date: 7/11/2005 From janos.juhasz at VELUX.com Tue Jul 12 15:56:02 2005 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 12 Jul 2005 15:56:02 +0200 Subject: [Tutor] module with static global In-Reply-To: Message-ID: Dear Guys! I am using a class for connecting to an sql database via odbc. It is like this: import dbi, odbc class scalaDB: def __init__(self): self.cn = odbc.odbc('DSN=scalaDB;UID=query;PWD=query;DATABASE=scalaDB') def closeDB(self): self.cn.close() def Execute(self, sql): cr = self.cn.cursor() cr.execute(sql) cr.close() def Query(self, sql): try: cr = self.cn.cursor() cr.execute(sql) self.colnames = [field_prop[0] for field_prop in cr.description] self.result = cr.fetchall() self.rownum = len(self.result) return self.result except: self.colnames = [None] self.result = [[None]] self.rownum = 0 return [[None]] def QueryValue(self, sql): try: cr = self.cn.cursor() cr.execute(sql) self.colnames = [field_prop[0] for field_prop in cr.description] self.result = cr.fetchall() self.rownum = len(self.result) return self.result[0][0] except: self.colnames = [None] self.result = None self.rownum = 0 return None I also have some other classes represented in this database as records. As the records are in the database, they has to have a scalaDB instance for running any sql statement on it. Currently I send a scalaDB instance to every record-based class in the __init__(): proc. class Component: def __init__(self, scalaDB, StockCode, Qty=1, Parent=None): self.scalaDB = scalaDB self.StockCode = StockCode self.Parent = Parent self.Qty = Qty ## Qty in the BOM self.Components = self.GetComponents() def GetParent(self): return self.Parent def __getattr__(self, name): if 'SC' in name:k value = self.scalaDB.QueryValue("select %s from SC010100 where SC01001 = '%s'" % (name, self.StockCode) ) return value How have I modify this to use my scalaDB class in this way: >>>import scalaDB >>>xy = scalaDB.Query(sql) Best regards, Janos Juhasz From work at infomaniak.ch Tue Jul 12 16:09:27 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Tue, 12 Jul 2005 16:09:27 +0200 Subject: [Tutor] module with static global In-Reply-To: References: Message-ID: <20050712140927.GA23114@obs.unige.ch> give an eyes to sqlobject.org. -- Cedric BRINER From sweetdaddysiki at hotmail.com Tue Jul 12 16:11:55 2005 From: sweetdaddysiki at hotmail.com (Trent Rigsbee) Date: Tue, 12 Jul 2005 14:11:55 +0000 Subject: [Tutor] First Project - Ping Sweeper! Message-ID: Hi! I've completed Learning to Program (off the website) and I've started to play around with code that I've found on Useless Python. I'm ready to start my first project! This may be way over my head, but I want to make a ping sweeper (put a range of IP addresses & ping to see which are vaild). I'm playing around with Mark Kels' Port Scanner off of Useless Python and I wanted to modify this for pinging but I'm stuck. I've ordered Network Programming for Python but I've started to play around with this until the book arrives. Any suggestions? Should I throw in the towel and make something simpler instead? Thanks! Here's the code that I'm tinkering with: #A simple port scanner to scan a range of ports on a single host. #Developers: # 1.Mark Kels (mark.kels at gmail.com) - The basic port scanner #Last updated: # 21.5.2005 #----------Imports---------- from Tkinter import * #Used to make the GUI import tkMessageBox #Used for error display import socket #Used for connecting to ports import threading #Used to make a difrent thread for the scan so it could be stopped #--- Function to start a scan --- def go(): global app result.delete(1.0,END) app=scan() app.start() #start() is definde in threading.Thread #--- Function to stop a scan --- def stop(): app.flag='stop' #--- Function to clear the input and output --- def clear(): host_e.delete(0,END) start_port_e.delete(0,END) end_port_e.delete(0,END) result.delete(1.0,END) #---The scan class which does the port scan itself--- class scan(threading.Thread): def _init_(self): threading.thread._init_(self) def run(self): self.host=host_e.get() self.start_port=int(start_port_e.get()) self.end_port=int(end_port_e.get()) self.open_counter=0 self.flag='scan' start.config(text="Stop",command=stop) root.update() result.insert(END,"Scanning "+str(self.host)+"...\n\n") root.update() while self.start_port<=self.end_port and self.flag=='scan': self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sk.settimeout(0.01) #closed ports take a long time to connect to, so if there is no connection after 0.01 seconds the port is closed try: self.sk.connect((self.host,self.start_port)) except: pass #if connection fails (port is closed) pass and try with another port else: result.insert(END,str(self.start_port)+"\n") root.update() self.open_counter=self.open_counter+1 self.sk.close() self.start_port=self.start_port+1 if self.flag=='scan': result.insert(END,"\nDone !!\nFound "+str(self.open_counter)+" opened ports") root.update() start.config(text="Scan",command=go) root.update() elif self.flag=='stop': result.insert(END,"\n Scan stopped.") start.config(text="Scan",command=go) root.update() #---The GUI--- root=Tk() Label(root,text="Host: ").grid(row=1,column=1,sticky="w") host_e=Entry(root) host_e.grid(row=1,column=2,sticky="WE") Label(root,text="Start port: ").grid(row=2,column=1,sticky="w") start_port_e=Entry(root) start_port_e.grid(row=2,column=2,sticky="WE") Label(root,text="End port: ").grid(row=3,column=1,sticky="w") end_port_e=Entry(root) end_port_e.grid(row=3,column=2,sticky="WE") start=Button(root,text="Scan",command=go) start.grid(row=5,columnspan=3,sticky="WE") clear=Button(root,text="Clear",command=clear) clear.grid(row=6,columnspan=3,sticky="WE") result=Text(root,width=20,height=20) result.grid(row=7,columnspan=3,sticky="WENS") root.wm_maxsize(width='190',height='370') #Set max size root.wm_minsize(width='190',height='370') #Sat min size same as max size (so the window is unresizeable) root.title("PPS 0.1") #Set the title of the window root.mainloop() From webdev at matheteuo.org Tue Jul 12 17:58:27 2005 From: webdev at matheteuo.org (Don Parris) Date: Tue, 12 Jul 2005 11:58:27 -0400 Subject: [Tutor] OT python Licences In-Reply-To: <42D39222.9040608@pusspaws.net> References: <42D39222.9040608@pusspaws.net> Message-ID: <20050712115827.48fc3d4e@luke.matheteuo.rel> On Tue, 12 Jul 2005 10:49:22 +0100 Dave S wrote: > This is a bit OT but here goes. > > My work wants me to write a fairly large python script to analyze some > technical ASCII data files. Python and its libraries are GPL. > > That being the case am I right in thinking that my script would also > have to be GPL and I would have to inform my employer as I hand it over ? > > Secondly it would have to run in Windows, The results could pop up on a > DOS window. However I was looking at QT until I read the Windows > license. Are there any widget libraries that would allow me to program > for windows commercially without any license or fees ? > > Thanks in advance > Dave > > While Python is not GPL'ed, any work you do release under a GPL license can be used in-house without being redistributed. In a sense, that makes it proprietary, but it's still libre for the user - the main point of the GPL. As long as the program is not being redistributed, the GPL does not apply. IOW, your company is not forced to release the code. As soon as your employer distributes the code outside the company (public release), it falls under the terms of the GPL. The GPL FAQ is available at the FSF website, and offers some excellent answers to interesting questions. As stated in another e-mail the current Python license is compatible with the GPL. There were a couple of versions of Python (1.?.?) that the FSF considered incompatible. The GPL is copyleft, the Python License is a non-copyleft license, meaning that the code can be made proprietary. Don, who is preparing for his presentation on FOSS licenses at next month's CharLUG meeting. :-) -- evangelinux GNU Evangelist http://matheteuo.org/ http://www.lulu.com/dcparris "Free software is like God's love - you can share it with anyone anytime anywhere." From sandip at lug-delhi.org Tue Jul 12 18:38:09 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Tue, 12 Jul 2005 22:08:09 +0530 Subject: [Tutor] OT python Licences In-Reply-To: <42D39222.9040608@pusspaws.net> References: <42D39222.9040608@pusspaws.net> Message-ID: <42D3F1F1.8010704@lug-delhi.org> Dave S wrote: > This is a bit OT but here goes. > > My work wants me to write a fairly large python script to analyze some > technical ASCII data files. Python and its libraries are GPL. > > That being the case am I right in thinking that my script would also > have to be GPL and I would have to inform my employer as I hand it over ? > > Secondly it would have to run in Windows, The results could pop up on a > DOS window. However I was looking at QT until I read the Windows > license. Are there any widget libraries that would allow me to program > for windows commercially without any license or fees ? > Avoid QT on Windows in that case. It is prohibitivly expensive for most small applications. You have three choices for widgets programming: 1. Tk. No external libraries to be installed. But limited widgets i.e. not much featureful, but adequate for simple GUIs. 2. Gtk. Simple API. A great RAD GUI builder (Glade). Cons are that you have to have Pygtk installed on windows for your apps to run (I am not sure if py2exe will package them for you as a standalone). Another con is that it lacks a native windows look. On that other hand Gtk2 is quite featureful. 3. wxpython. A bit complex than Gtk. Again external libraries needed to be installed. However, it is very featureful and provides an exact windows app look. There is a wxglade, but i am not sure whether it is as good as gtkglade. But again, if your app just needs to open a dos window, you can simply execute it in a bat file, or execute the "start xxx" command isnt it? About licence, regardless of the compiler or interpretor licence, you are normally never bound to use the same licence ... UNLESS you are *linking* to dev libraries, which happens only when you make a binary. So if you distribute the code (and in the case of scripts like python you probably do), you can licence it in any way. But if you distribute a py2exe generated windows application, then your code might be bound by the linked libraries. So if you are using PyGtk or wxpython, and creating windows executables using py2exe, you should look at the licences of these libraries too. AFAIK, these two widgets are quite liberal in linking and there is no restrictions in making commercial apps with them. - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip at puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From John.Gooch at echostar.com Tue Jul 12 18:44:15 2005 From: John.Gooch at echostar.com (Gooch, John) Date: Tue, 12 Jul 2005 10:44:15 -0600 Subject: [Tutor] Storing Data Records in XML File Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D541@riv-excha5.echostar.com> I have a Python script that stores the results of the processing that it does in a database, but it has to have an alternate way of storing its data in a database-friendly way (XML)in case the database is not available ( connected down, data store full, etc. ). Any recommendations on a way to do this? i.e. what modules what methods? Thanks in advance, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Don Parris Sent: Tuesday, July 12, 2005 9:58 AM To: Python tutor Subject: Re: [Tutor] OT python Licences On Tue, 12 Jul 2005 10:49:22 +0100 Dave S wrote: > This is a bit OT but here goes. > > My work wants me to write a fairly large python script to analyze some > technical ASCII data files. Python and its libraries are GPL. > > That being the case am I right in thinking that my script would also > have to be GPL and I would have to inform my employer as I hand it > over ? > > Secondly it would have to run in Windows, The results could pop up on > a DOS window. However I was looking at QT until I read the Windows > license. Are there any widget libraries that would allow me to program > for windows commercially without any license or fees ? > > Thanks in advance > Dave > > While Python is not GPL'ed, any work you do release under a GPL license can be used in-house without being redistributed. In a sense, that makes it proprietary, but it's still libre for the user - the main point of the GPL. As long as the program is not being redistributed, the GPL does not apply. IOW, your company is not forced to release the code. As soon as your employer distributes the code outside the company (public release), it falls under the terms of the GPL. The GPL FAQ is available at the FSF website, and offers some excellent answers to interesting questions. As stated in another e-mail the current Python license is compatible with the GPL. There were a couple of versions of Python (1.?.?) that the FSF considered incompatible. The GPL is copyleft, the Python License is a non-copyleft license, meaning that the code can be made proprietary. Don, who is preparing for his presentation on FOSS licenses at next month's CharLUG meeting. :-) -- evangelinux GNU Evangelist http://matheteuo.org/ http://www.lulu.com/dcparris "Free software is like God's love - you can share it with anyone anytime anywhere." _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From maxnoel_fr at yahoo.fr Tue Jul 12 18:56:55 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue, 12 Jul 2005 18:56:55 +0200 Subject: [Tutor] Storing Data Records in XML File In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D541@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D541@riv-excha5.echostar.com> Message-ID: On Jul 12, 2005, at 18:44, Gooch, John wrote: > I have a Python script that stores the results of the processing > that it > does in a > database, but it has to have an alternate way of storing its data in a > database-friendly way (XML)in case the database is not available > ( connected > down, data store full, etc. ). > > > Any recommendations on a way to do this? i.e. what modules what > methods? For all your XML processing needs, you need ElementTree (http:// effbot.org/). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___________________________________________________________________________ Appel audio GRATUIT partout dans le monde avec le nouveau Yahoo! Messenger Téléchargez cette version sur http://fr.messenger.yahoo.com From dyoo at hkn.eecs.berkeley.edu Tue Jul 12 19:01:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 12 Jul 2005 10:01:30 -0700 (PDT) Subject: [Tutor] Storing Data Records in XML File In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F0F60D541@riv-excha5.echostar.com> Message-ID: On Tue, 12 Jul 2005, Gooch, John wrote: > I have a Python script that stores the results of the processing that it > does in a database, but it has to have an alternate way of storing its > data in a database-friendly way (XML)in case the database is not > available ( connected down, data store full, etc. ). > > Any recommendations on a way to do this? i.e. what modules what methods? Hi John, Could you use the Sqlite library instead? It's also a database engine, but it's very embeddable: http://www.sqlite.org/ and if you have an application that's already talking through the db-api, it might be easiest to use sqlite as the alternative data store. Otherwise, I've heard very good things about the Amara library for doing XML data binding stuff: http://uche.ogbuji.net/tech/4Suite/amara/ Best of wishes! From python at venix.com Tue Jul 12 20:08:00 2005 From: python at venix.com (Python) Date: Tue, 12 Jul 2005 14:08:00 -0400 Subject: [Tutor] First Project - Ping Sweeper! Message-ID: <1121191680.13134.60.camel@www.venix.com> ping uses icmp. icmp does not have port numbers. icmp is a host-to- host protocol for managing the flow of packets and reporting errors. http://en.wikipedia.org/wiki/ICMP_Echo_Request describes the outgoing "ping packet", but is probably too low-level to be useful. Port numbers are used in UDP and TCP. The port scanning program will not help you with ping. UDP and TCP have port numbers because they are application-to-application protocols and use the port number to identify the target application. I checked the index of "Foundations of Python Network Programming" and did not see entries for icmp or ping. I have not noticed icmp support in the Python libraries. -- Lloyd Kvam Venix Corp From reed at intersiege.com Tue Jul 12 20:24:17 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Tue, 12 Jul 2005 14:24:17 -0400 Subject: [Tutor] First Project - Ping Sweeper! In-Reply-To: <1121191680.13134.60.camel@www.venix.com> References: <1121191680.13134.60.camel@www.venix.com> Message-ID: <42D40AD1.4030301@intersiege.com> Python wrote: > ping uses icmp. icmp does not have port numbers. icmp is a host-to- > host protocol for managing the flow of packets and reporting errors. > http://en.wikipedia.org/wiki/ICMP_Echo_Request > describes the outgoing "ping packet", but is probably too low-level to > be useful. > > Port numbers are used in UDP and TCP. The port scanning program will > not help you with ping. UDP and TCP have port numbers because they are > application-to-application protocols and use the port number to identify > the target application. > > I checked the index of "Foundations of Python Network Programming" and > did not see entries for icmp or ping. I have not noticed icmp support > in the Python libraries. > > http://www.monkey.org/~dugsong/dpkt/pydoc/icmp.html http://pynms.sourceforge.net/icmp.html And look around twistedmatrix ~r -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 keyID: 0x0FA09FCE From count0.djd at gmail.com Tue Jul 12 20:50:03 2005 From: count0.djd at gmail.com (David Driver) Date: Tue, 12 Jul 2005 13:50:03 -0500 Subject: [Tutor] domain logic and avoiding setters and setters. In-Reply-To: <001901c586b0$fca82050$22a78751@xp> References: <22803ae2050711140056e07a88@mail.gmail.com> <001901c586b0$fca82050$22a78751@xp> Message-ID: <22803ae205071211502f91699c@mail.gmail.com> I appreciate your input. You are correct. I read a bunch of LoD stuff Northeastern website. It codified a bunch of things that I had been working through. But what you are not seeing (I must be terrible at this, always hard to tell how much code to post) is this chunk of code represents an idea about ways to hang business rules in an inheritable way onto a persisted (sqlobject) object. It is really in the model. This is a sketch of what I am trying to accomplish. Application (Output) Presenter (renders HTML or other UI) Persisted object/default generator Editor (what we are looking at, is specific to the persisted object, holds the rules and updates/creates persisted object) Application (Input) Presenter and Editor will have some knowledge of the persisted object. They will directly access attributes in the persisted object. They will not directly unveil attributes to the application (or any layers that may be in between). So conceptually the domain object is just split into three classes and Demeter is observed everywhere else, at least as far as I understand it's principles. On 7/12/05, Alan G wrote: > I think you are missing the point a wee bit. > > The object should not allow you to access its internal data. > > You should not *need* to access its internal data. > > The object has responsibilities in the form of behaviours. > The internal data is only there to support those behaviours, > it should be of no interest to external objects, therefore > you do not need setters and getters. Its not the setXXX getXXX > thing thats wromg its the very idea that users of the object > would want to access the internal data that is wrong. > > In the words of Peter Coad, "Objects do it to themselves" > > Now in some applications you do need the internal values, > but usually its as a group. For example an Address class > might have a method to return the full address content, > but rather than provide individuual set/get methods per > field it would return the whole address as a string or > a tuple.(Note that both of these are immutable types!) > > In some cases you may actually choose to expose one > particular attribute, in which case a get/set pair for that > one attribute is OK - they represent a genuine responsibility > of the class. (Making it a property might be better still...) > Its providing get/set pairs for *every attribute* that breaks > good OOP practice. > > PS. For a more formal description of the above principle > look up "The Law of Demeter" on Google. > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Jul 12 22:01:52 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 12 Jul 2005 21:01:52 +0100 Subject: [Tutor] domain logic and avoiding setters and setters. References: <22803ae2050711140056e07a88@mail.gmail.com> <001901c586b0$fca82050$22a78751@xp> <22803ae205071211502f91699c@mail.gmail.com> Message-ID: <007701c5871c$8c523900$22a78751@xp> OK, I'll take a chance because as you say I don't know the details of what you are building. And if its a Framework for persistence, or an IDE for building persistence then get/set may be your best bet - after all that's why Java Beans have them so that Java IDEs can manipulate object properties at design time. But... > Application (Output) > Presenter (renders HTML or other UI) > Persisted object/default generator So the persisted object returns a string representation of its state (maybe as a csv?) which the Presenter parses and adds tags as needed? > Editor (what we are looking at, is specific to the persisted > object, holds the rules and updates/creates > persisted object) Not sure about this one? Why is 'editing' not a function of the persisted object? It might be valid if its not a relevant business function but if the object inherits a persistent mixin it should be an attribute of the mixin which object inherits. The rules should either be objects in their own right ot methods of the objects attributes or methods of the object - after all thats what objects are for: to hold their own business rules. If you really mean the storage rules (database constraints), then that might be a valid exception, but at that point the persistence mechanism is operating at the raw data level - ie the attributes of the object not the object itself. How do we get from the object to the data? By having a csv, or tlv or similar method on ll persistent objects. The tlv method of the object returns a tlv representation of the current object then the tlv of the superclass. This is standard object serialisation type upward delegation through an inheriance lattice. > Presenter and Editor will have some knowledge of the persisted > object. By doing so they cease to be either generic or reusable. They should communicate with the object via a standard protocol. They should not need to be aware of individual attributes they should only need the total state of the object. Editing implies changes of attribute value but those should only be made through the object's own protocol, even if that implies instantiating the object, calling the relevant operation and then persisting it again. Only where there are proven performamce issues should direct attribute access at the data level even be considered. > that may be in between). So conceptually the domain object is just > split into three classes and Demeter is > observed everywhere else, at least as far as I understand it's > principles. The question is why should it be broken here? The Framework/IDE scenario is the only one where it may be valid to beak demeter (and even then only rarely), but very few real world scenarios need to go down that route. But, it does rely totally on your domain and issues such as performance. Theoretical principles are fine until they hit the real world then they have to bend or be broken. But we should always try to follow them first, bend them next and break them as a ;ast resort - we will suffer later if we do otherwise. Good luck, Alan G. From pythontut at pusspaws.net Tue Jul 12 22:02:12 2005 From: pythontut at pusspaws.net (Dave S) Date: Tue, 12 Jul 2005 21:02:12 +0100 Subject: [Tutor] OT python Licences In-Reply-To: <42D39222.9040608@pusspaws.net> References: <42D39222.9040608@pusspaws.net> Message-ID: <42D421C4.7090201@pusspaws.net> Many thanks for all your input, you have been great. At the moment Tkinter is a favorite, I have started reading the documentation and it seems fairly straightforward + can do what I need. Many thanks once again :-) Dave From klappnase at freenet.de Tue Jul 12 22:51:09 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 12 Jul 2005 22:51:09 +0200 Subject: [Tutor] Tkinter Q's In-Reply-To: <42D2AAF1.9050400@gmail.com> References: <42D2AAF1.9050400@gmail.com> Message-ID: <20050712225109.5c962d54.klappnase@freenet.de> On Mon, 11 Jul 2005 17:22:57 +0000 Joseph Quigley wrote: Hi, Joseph, > Hi first off, here's my code: > > # -*- coding: utf-8 -*- > from Tkinter import * > import random > import time > import about > import quotes > > > def closeprog(): > raise SystemExit > > class main: > root = Tk() > frame = Frame() > root.title("Quoter %s" % (about.ver)) > root.minsize(300, 50) > > showquote = Label(root, text=random.choice(quotes.quote)) > showquote.pack() > > exit = Button(root, text="Exit", command=closeprog) > exit.pack(side=LEFT) > > aboutprg = Button(root, text="About", command=about.main) > aboutprg.pack(side=LEFT) > > > totalq = Label(root, text=quotes.qts) > totalq.pack(side=BOTTOM) > > root.mainloop() > > (I'd appreciate some suggestions, or notifications on how bad something is) > I think you should change the way you define the main class, so you keep references to the class attributes; it looks like your main class fires up a Tk() window, so it's probably best to subclass Tk() : class Main(Tk):# this doesn't really matter, but upper case letters are generally preferrred for class names def __init__(self, *args, **kw): Tk.__init__(self, *args, **kw) # at this point the Main() class practically is a Tk(), so it can be handled just like a regular # Tk() window from the outside; the "*args, **kw" construct allows to pass an arbitrary amount of # arguments and keyword arguments to the parent class. "self" is a placeholder for the class instance # that will be actually used in the code. # To get a benefit over a normal Tk() window you can now start adding attributes: self.showquote = Label(self, text=random.choice(quotes.quote)) self.showquote.pack() < etc. > # of course you can use the parent classes methods on "self", too: self.title("Quoter %s" % (about.ver)) self.minsize(300, 50) # now you can add a button which uses a "class-specific" command: self.switchbutton = Button, text="Switch quote", command=self.switch_quote) self.switchbutton.pack() # finally the class method has to be defined: def switch_quote(self): newquote = get_the_new_quote()# it's up to you how to do this of course self.showquote.configure(text=newquote) Now the Main() class can be used like a regular Tk() : root = Main() root.mainloop() And for something completely different: be careful mixing pack(side = LEFT / RIGHT) with pack(side = BOTTOM / TOP), you might not get the results you expected. For complex layouts you are probably better off using grid() ( or you will find that you have to use extra Frames to pack() your widgets in. I hope this helps Michael > I have a small problem: I don't know how to make a button that would > redisplay another quote in the same window, ie I need a button that > says: Show Another Quote. (Actually I don't know how to make it show > another quote even in a new window!!). I got the interface from Catfood > Fortune Cookie. > > Here's a tid-bit of the quotes module: > # Brian Kernighan > bk1 = """Controlling complexity is the essence of computer programming. > > -- Brian Kernighan""" > > yadayada = """Foo/bar""" > > quote = [bk1, yadayada] > > Thanks, > Joe > > -- > Unix Love, Linux Pride > > From bvande at po-box.mcgill.ca Tue Jul 12 23:08:09 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 12 Jul 2005 17:08:09 -0400 Subject: [Tutor] recursion odities accross diferent versions of the 2.4.1 interpreter Message-ID: <42D43139.2040407@po-box.mcgill.ca> Hi all, I'm playing about with some recursive functions where I am getting near the recursion limit. This caused me to do a test, and I am puzzled by the different results when run in the prompt, IDLE and PythonWin. My simple test code is: >>> c = 0 >>> def recursion_test(): global c c+=1 try: recursion_test() except: print c When this very same code is run in the different interpreters (or, different Python environments; I'm not sure of the correct terminology here) I get different results. I'll show those, skipping the identical code that created them: Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 >>> recursion_test() 999 >>> IDLE 1.1.1 >>> recursion_test() 996996 PythonWin 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32. >>> recursion_test() 993 993 993 >>> That the printed numbers differ doesn't worry me; I assume since IDLE and PythonWin are implemented in Python, the overhead of running them eats up a recursion level or 6, according to how exactly they are implemented. But the two puzzles are: 1) Why the difference in printing format (IDLE prints twice on one line, PythonWin thrice with different alignment)? and, 2) With (and only with) IDLE, I never regain control of the shell (note the lack of a terminal '>>>' and have to restart to do anything else. That feels bug-like. It seems a fair bet that the hypothesis for why the printed numbers are different is also at play in the last two puzzles. But, I was wondering if anyone could say something to shed a bit more light. In particular, is my sense of possible bug well grounded? Thanks and best, Brian vdB From jfouhy at paradise.net.nz Wed Jul 13 00:46:28 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 13 Jul 2005 10:46:28 +1200 (NZST) Subject: [Tutor] Tkinter Q's In-Reply-To: <42D2AAF1.9050400@gmail.com> References: <42D2AAF1.9050400@gmail.com> Message-ID: <1121208388.42d448446e348@www.paradise.net.nz> Quoting Joseph Quigley : > Hi first off, here's my code: > > # -*- coding: utf-8 -*- > from Tkinter import * > import random > import time > import about > import quotes > > > def closeprog(): > raise SystemExit > > class main: > root = Tk() > frame = Frame() > root.title("Quoter %s" % (about.ver)) > root.minsize(300, 50) > > showquote = Label(root, text=random.choice(quotes.quote)) > showquote.pack() > > exit = Button(root, text="Exit", command=closeprog) > exit.pack(side=LEFT) > > aboutprg = Button(root, text="About", command=about.main) > aboutprg.pack(side=LEFT) > > > totalq = Label(root, text=quotes.qts) > totalq.pack(side=BOTTOM) > > root.mainloop() > > (I'd appreciate some suggestions, or notifications on how bad something > is) Some comments --- You create a Frame, but you never use it. You've put a whole lot of code in a class, but it's not in a class method. This is kinda missing the point of using classes in the first place (and it just flat-out wouldn't work in the majority of OO languages). Here's what I would do: class Main(Frame): def __init__(self, master=None, **kw): Frame.__init__(self, master, **kw) showquote = Label(self, text=random.choice(quotes.quote)) showquote.pack() # etc if __name__ == '__main__': root = Tk() main = Main(root) main.pack(fill=BOTH, expand=True) root.mainloop() ### Do you see what I am doing there, and why it is different from your approach? > I have a small problem: I don't know how to make a button that would > redisplay another quote in the same window, ie I need a button that > says: Show Another Quote. (Actually I don't know how to make it show > another quote even in a new window!!). I got the interface from Catfood Once you've got a label, you can change its text attribute by using its .config() method. So, you could do something like this: # ... showquote = Label(self, text=random.choice(quotes.quote)) showquote.pack() def changeQuote(): currQuote = showquote.cget('config') # Get the current quote newQuote = random.choice(quotes.quote) while newQuote == currQuote: # Make sure the new quote differs newQuote = random.choice(quotes.quote) showquote.config(text=newQuote) Button(self, text='Show another quote', command=changeQuote).pack() -- John. From pindzola at charter.net Wed Jul 13 02:12:42 2005 From: pindzola at charter.net (Mike Pindzola) Date: Tue, 12 Jul 2005 19:12:42 -0500 Subject: [Tutor] python newbie..system call help Message-ID: <42D45C7A.3010901@charter.net> I am writing a small program to speed up the efficiency of me on my home linux machine. I need it to communicate serveral times to the bash shell to issue and retrieve info. I took a guess and tryed the system() function call, but python quickly rejected that. Should I be even trying to make a system call? Is there a better way to talk to the shell? Either way, please enlighten me. Thanks. Also, this is my first time using the python tutor and I am new to python itself also, although I have done small amounts of programming in other languages before...Please fill me in on any procedures in the mailing list. -Mike From jfouhy at paradise.net.nz Wed Jul 13 02:20:43 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 13 Jul 2005 12:20:43 +1200 (NZST) Subject: [Tutor] python newbie..system call help In-Reply-To: <42D45C7A.3010901@charter.net> References: <42D45C7A.3010901@charter.net> Message-ID: <1121214043.42d45e5b6c5a4@www.paradise.net.nz> Quoting Mike Pindzola : > Should I be even trying to make a system call? Is there a better way to > talk to the shell? Either way, please enlighten me. Thanks. There may be a better way to achieve what you want to do, without using the shell at all. For example, the os and os.path modules include a range of functions for manipulating files and directories (listing, walking, moving, renaming, et cetera). Perhaps, if you say what you are trying to achieve, we can give some pointers. -- John. From pindzola at charter.net Wed Jul 13 02:36:49 2005 From: pindzola at charter.net (Mike Pindzola) Date: Tue, 12 Jul 2005 19:36:49 -0500 Subject: [Tutor] python newbie..system call help In-Reply-To: <1121214043.42d45e5b6c5a4@www.paradise.net.nz> References: <42D45C7A.3010901@charter.net> <1121214043.42d45e5b6c5a4@www.paradise.net.nz> Message-ID: <42D46221.8010808@charter.net> Yes, I have did 'import os'. For starters I want to read the result of 'pwd' and print it out in the program for the user to see what path is being read. Also, I need to have a function to handle root access if the user does not have such privledges since I will be mounting and unmounting hardware. So a call to 'su' would be in order as well as sending the user provided password back to it. Aside from that, just so copying of files, making dirs, and changing file permissions. jfouhy at paradise.net.nz wrote: >Quoting Mike Pindzola : > > > >>Should I be even trying to make a system call? Is there a better way to >>talk to the shell? Either way, please enlighten me. Thanks. >> >> > >There may be a better way to achieve what you want to do, without using the >shell at all. For example, the os and os.path modules include a range of >functions for manipulating files and directories (listing, walking, moving, >renaming, et cetera). Perhaps, if you say what you are trying to achieve, we >can give some pointers. > > > From pindzola at charter.net Wed Jul 13 04:15:47 2005 From: pindzola at charter.net (Mike Pindzola) Date: Tue, 12 Jul 2005 21:15:47 -0500 Subject: [Tutor] python newbie..system call help In-Reply-To: <42D46221.8010808@charter.net> References: <42D45C7A.3010901@charter.net> <1121214043.42d45e5b6c5a4@www.paradise.net.nz> <42D46221.8010808@charter.net> Message-ID: <42D47953.4080308@charter.net> I have figured many things out. system works, i just forgot to type os.system(). I have been looking into the os module and am finding alot of useful stuff. I still need to workout the best way to ask a user for a root password, show **** when typed and then pass it to the system... thanks for any responses Mike Pindzola wrote: > Yes, I have did 'import os'. For starters I want to read the result of > 'pwd' and print it out in the program for the user to see what path is > being read. Also, I need to have a function to handle root access if > the user does not have such privledges since I will be mounting and > unmounting hardware. So a call to 'su' would be in order as well as > sending the user provided password back to it. > > Aside from that, just so copying of files, making dirs, and changing > file permissions. > > jfouhy at paradise.net.nz wrote: > >> Quoting Mike Pindzola : >> >> >> >>> Should I be even trying to make a system call? Is there a better way to >>> talk to the shell? Either way, please enlighten me. Thanks. >>> >> >> >> There may be a better way to achieve what you want to do, without >> using the >> shell at all. For example, the os and os.path modules include a >> range of >> functions for manipulating files and directories (listing, walking, >> moving, >> renaming, et cetera). Perhaps, if you say what you are trying to >> achieve, we >> can give some pointers. >> >> >> > From chuck at freshsources.com Wed Jul 13 05:57:47 2005 From: chuck at freshsources.com (Chuck Allison) Date: Tue, 12 Jul 2005 21:57:47 -0600 Subject: [Tutor] OT python Licences In-Reply-To: <42D3F1F1.8010704@lug-delhi.org> References: <42D39222.9040608@pusspaws.net> <42D3F1F1.8010704@lug-delhi.org> Message-ID: <343482475.20050712215747@freshsources.com> Hello Sandip, Tuesday, July 12, 2005, 10:38:09 AM, you wrote: SB> Dave S wrote: >> This is a bit OT but here goes. >> >> My work wants me to write a fairly large python script to analyze some >> technical ASCII data files. Python and its libraries are GPL. >> >> That being the case am I right in thinking that my script would also >> have to be GPL and I would have to inform my employer as I hand it over ? >> >> Secondly it would have to run in Windows, The results could pop up on a >> DOS window. However I was looking at QT until I read the Windows >> license. Are there any widget libraries that would allow me to program >> for windows commercially without any license or fees ? >> What about wxWindows, for which we have wxPython? -- Best regards, Chuck From dyoo at hkn.eecs.berkeley.edu Wed Jul 13 06:49:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 12 Jul 2005 21:49:41 -0700 (PDT) Subject: [Tutor] python newbie..system call help In-Reply-To: <42D47953.4080308@charter.net> Message-ID: On Tue, 12 Jul 2005, Mike Pindzola wrote: > I have figured many things out. system works, i just forgot to type > os.system(). I have been looking into the os module and am finding alot > of useful stuff. I still need to workout the best way to ask a user for > a root password, show **** when typed and then pass it to the system... Hi Mike, For the password thing, you may find the getpass module useful: http://www.python.org/doc/lib/module-getpass.html It'll do that password obscuring stuff for you. You mentioned earlier, though, that you might want to execute stuff using su --- have you considered using sudo? http://www.courtesan.com/sudo/sudo.html It might eliminate the need to type root passwords all the time, and if used properly, sudo's can be safer since it can be configured to provide access to a subset of commands. > > Aside from that, just so copying of files, making dirs, and changing > > file permissions. For the rest of these, it is possible to use utilities in Python's standard library instead of shelling out. Some of these functions live in the 'shutil' library: http://www.python.org/doc/lib/module-shutil.html and others in the 'os' module that you've been looking at earlier. For example, changing the current working directory can be a matter of calling the os.chdir() function. If you have more questions, please feel to bring them to the Tutor group. Good luck to you! From negroup at gmail.com Wed Jul 13 09:41:35 2005 From: negroup at gmail.com (Negroup -) Date: Wed, 13 Jul 2005 09:41:35 +0200 Subject: [Tutor] Query dictionaries with sql-like syntax Message-ID: <2fdabf19050713004175e3ed15@mail.gmail.com> Hi all, I hope my questions makes sense.. I'm trying to migrate a lot of data from an accounting system software to another using Python. Software A stores datas inside sql tables, software B too, with a different db structure. My idea has been to export sensible tables from db A, store them in python dictionaries, process/elaborate these dictionaries, and generate files containing data in a format that is importable from system B. Yes, it could seem a good idea.. however now I must handle a lot of dictionaries with a lot of related data. Since this is not just a simple exercise of mapping one field to another field 1-1, but elaborations/extrapolations on these datas are required, my question is: does a module/package/... exist to query a set of dictionaries using sql syntax (where I'm comfortable with)? It would be for me a great facility. Thanks you all. From sandip at lug-delhi.org Wed Jul 13 10:23:57 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Wed, 13 Jul 2005 13:53:57 +0530 Subject: [Tutor] Query dictionaries with sql-like syntax In-Reply-To: <2fdabf19050713004175e3ed15@mail.gmail.com> References: <2fdabf19050713004175e3ed15@mail.gmail.com> Message-ID: <42D4CF9D.8090604@lug-delhi.org> Negroup - wrote: > Hi all, I hope my questions makes sense.. > I'm trying to migrate a lot of data from an accounting system software > to another using Python. Software A stores datas inside sql tables, > software B too, with a different db structure. > > My idea has been to export sensible tables from db A, store them in > python dictionaries, process/elaborate these dictionaries, and > generate files containing data in a format that is importable from > system B. Yes, it could seem a good idea.. however now I must handle a > lot of dictionaries with a lot of related data. > Why dont you use python-sqlite to dump your data? You might need to modify your sql slightly(depending on your current db), but rest is all sql. - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip at puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From andreas at kostyrka.org Wed Jul 13 07:56:39 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 13 Jul 2005 07:56:39 +0200 Subject: [Tutor] Confused "from module import Name" better than "importmodule"? In-Reply-To: <017e01c58654$14566bb0$b1458651@xp> References: <42D29A83.3000509@cso.atmel.com> <017e01c58654$14566bb0$b1458651@xp> Message-ID: <1121234199.5240.19.camel@andi-lap> Personally the type of import statement depends upon the module imported, the use of the module and personal preferences. from Module import * produces certainly the danger of namespace pollution, and should be used if at all only with pervasive modules that are designed to be used this way. Typical examples where this is done this way include GUI modules like Tkinter. The module imported this way should provide a __all__ declaration. In many cases if the module imported is of huge importance to the importing module, one might use renaming as the solution: import module as m or import module ; m = module from Module import Name, Name2, ... Might be used if it's clear what Name, Name2 will do. import Module Minimizes the namespace pollution. Basically there are the following "objective" rules: a) "from module import *" is bad because of the uncontrolled (from the client side) name space pollution. Use only with caution with modules designed to be used this way. b) "from module import name" and "import module" are basically about as acceptable, but the "from" form does have technical problems with circular references, as it basically requires module to load completely. "import" on the other hand can bind an incomplete module, and in this way allows for circular references. c) import "module" provides a much stronger decoupling. It's easier to find all module objects in all modules and replace them than find all names that got imported from a different module. d) Python is basically a language that is dynamic and that provides quite a deal of introspection and manipulation at runtime. For example one can use imports in try/except blocks like this: try: import cPickle as Pickle except ImportError: import Pickle or even more dynamic funnier: dbmodule = __import__(db_name_to_use) e) import statements can happen at any level -> if an import is used only in rare cases it might make sense to include it inside a def. f) If "absolute" performance is wanted, the usual way is to include needed names into the local namespace of a function via default arguments. This way you get the name "for free" into the local namespace and local accesses are the fastest in Python: def some_func(param1, param2, some_really_important_external_func=module.func): Andreas Am Montag, den 11.07.2005, 21:06 +0100 schrieb Alan G: > > I'm confused. I was just reading the URL below.. > > > > http://jaynes.colorado.edu/PythonGuidelines.html > > Me too. :-) > > > and this statement confused me: "Always use from module import Name, > > Name2, Name3.. syntax instead of import module or from module import > > *. This is more efficient, reduces typing in the rest of the code, > > and it makes it much easier to see name collisions and to replace > > implementations." > > The efficiency gain is negligible. > The typing can be better reduced by using > > import modulename as m > > And it definitley doesn't make it easier to see name collisions, they > will > just silently collide and one or the other name will be hidden with > strange results! > > > To me, import module is more explicit. > > Undeniably so! > > > It seems to easier to read CoolModule.niceFunction() than just > > niceFunction(). > > Easier to read but slightly harder to type. Personally I can live with > it! > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20050713/c8107235/attachment-0001.pgp From pythontut at pusspaws.net Wed Jul 13 13:28:23 2005 From: pythontut at pusspaws.net (Dave S) Date: Wed, 13 Jul 2005 12:28:23 +0100 Subject: [Tutor] Tkinter query? Message-ID: <42D4FAD7.1010509@pusspaws.net> Hi all, Im on the Tkinter GUI learning curve :-) . Its going quite well - im reading O'reilly 'programming python' but I am unclear on the following I understand the standard form ie ... root = Tk() test = button(root, text = ..........).pack() etc I also understand .... independant_win = Toplevel(root) But I do not understand where Frame fits in to this ... ie from Tkinter import * class Hello(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) self.pack() Why not just use 'class Hello(root)' ? Or have I missed the point :-[ Dave From pythontut at pusspaws.net Wed Jul 13 14:03:13 2005 From: pythontut at pusspaws.net (Dave S) Date: Wed, 13 Jul 2005 13:03:13 +0100 Subject: [Tutor] Tkinter query? In-Reply-To: <42D4FAD7.1010509@pusspaws.net> References: <42D4FAD7.1010509@pusspaws.net> Message-ID: <42D50301.9020301@pusspaws.net> Dave S wrote: >Hi all, > >Im on the Tkinter GUI learning curve :-) . Its going quite well - im >reading O'reilly 'programming python' but I am unclear on the following > >I understand the standard form ie ... > >root = Tk() >test = button(root, text = ..........).pack() >etc > >I also understand .... > >independant_win = Toplevel(root) > >But I do not understand where Frame fits in to this ... ie > >from Tkinter import * >class Hello(Frame): > > def __init__(self, parent=None): > Frame.__init__(self, parent) > self.pack() > > >Why not just use 'class Hello(root)' ? Or have I missed the point :-[ > >Dave > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > OK am I right in thinging a 'Frame' always has a parent of a Tk() or possibly Toplevel() and its used to help in positioning a widget window with .pack() ? Dave From kent37 at tds.net Wed Jul 13 14:29:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Jul 2005 08:29:43 -0400 Subject: [Tutor] Tkinter query? In-Reply-To: <42D50301.9020301@pusspaws.net> References: <42D4FAD7.1010509@pusspaws.net> <42D50301.9020301@pusspaws.net> Message-ID: <42D50937.9090807@tds.net> Dave S wrote: >>But I do not understand where Frame fits in to this ... ie >> > >>from Tkinter import * > >>class Hello(Frame): >> >> def __init__(self, parent=None): >> Frame.__init__(self, parent) >> self.pack() >> >> >>Why not just use 'class Hello(root)' ? Or have I missed the point :-[ > > OK am I right in thinging a 'Frame' always has a parent of a Tk() or > possibly Toplevel() and its used to help in positioning a widget window > with .pack() ? Yes, that is one use of Frame - to help with positioning groups of widgets. A Frame subclass also can be used to package a group of widgets as a reusable whole and as a place to put controller code that makes a group of widgets work together. Kent From pythontut at pusspaws.net Wed Jul 13 15:25:46 2005 From: pythontut at pusspaws.net (Dave S) Date: Wed, 13 Jul 2005 14:25:46 +0100 Subject: [Tutor] Tkinter query? In-Reply-To: <42D50937.9090807@tds.net> References: <42D4FAD7.1010509@pusspaws.net> <42D50301.9020301@pusspaws.net> <42D50937.9090807@tds.net> Message-ID: <42D5165A.6000206@pusspaws.net> Kent Johnson wrote: >Dave S wrote: > > >>>But I do not understand where Frame fits in to this ... ie >>> >>> >>> >>>from Tkinter import * >> >> >> >>>class Hello(Frame): >>> >>> def __init__(self, parent=None): >>> Frame.__init__(self, parent) >>> self.pack() >>> >>> >>>Why not just use 'class Hello(root)' ? Or have I missed the point :-[ >>> >>> >>OK am I right in thinging a 'Frame' always has a parent of a Tk() or >>possibly Toplevel() and its used to help in positioning a widget window >>with .pack() ? >> >> > >Yes, that is one use of Frame - to help with positioning groups of widgets. > Ahh good > A Frame subclass also can be used to package a group of widgets as a reusable whole > So you can subclass it - that makes sense >and as a place to put controller code that makes a group of widgets work together. > > Haven't got to this bit yet, may bee in next chapter ... :-) >Kent > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From negroup at gmail.com Wed Jul 13 15:41:49 2005 From: negroup at gmail.com (Negroup -) Date: Wed, 13 Jul 2005 15:41:49 +0200 Subject: [Tutor] Query dictionaries with sql-like syntax In-Reply-To: <42D4CF9D.8090604@lug-delhi.org> References: <2fdabf19050713004175e3ed15@mail.gmail.com> <42D4CF9D.8090604@lug-delhi.org> Message-ID: <2fdabf19050713064179642221@mail.gmail.com> 2005/7/13, Sandip Bhattacharya : > Negroup - wrote: [cut] > > Why dont you use python-sqlite to dump your data? You might need to > modify your sql slightly(depending on your current db), but rest is all sql. Thanks for the suggestion, I didn't even know about python-sqlite existence... Probably, in another occasion I'll need to develop a such migra-tool I will at least consider to use python-sqlite. Now it would be quite hard (a lot of work has already been done). Anyway, I'm learning Python and just for exercise I'll try to implement a simple sql-like interface for querying dictionaries! Thank you. From kent37 at tds.net Wed Jul 13 16:01:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Jul 2005 10:01:28 -0400 Subject: [Tutor] Query dictionaries with sql-like syntax In-Reply-To: <2fdabf19050713064179642221@mail.gmail.com> References: <2fdabf19050713004175e3ed15@mail.gmail.com> <42D4CF9D.8090604@lug-delhi.org> <2fdabf19050713064179642221@mail.gmail.com> Message-ID: <42D51EB8.6090404@tds.net> Negroup - wrote: > Anyway, I'm learning Python and just for exercise I'll try to > implement a simple sql-like interface for querying dictionaries! It might be a better use of your time to learn about Python's built-in abilities to manipulate lists and dictionaries, which are powerful and simple. You don't say what kind of queries you need to do but they may be very simple to express directly in Python. My guess is that simple loops and list comprehensions would do a lot of the work for you. I'm going to guess that your data is expressed as lists of dictionaries. For example here is a list with two records: >>> r1 = { 'fname' : 'Kent', 'lname' : 'Johnson' } >>> r2 = { 'fname' : 'Negroup', 'lname' : None } >>> data = [ r1, r2 ] >>> data [{'lname': 'Johnson', 'fname': 'Kent'}, {'lname': None, 'fname': 'Negroup'}] Suppose I want to find everyone whose first name is 'Kent'. This is easy to do with a list comprehension: >>> [ r for r in data if r['fname'] == 'Kent' ] [{'lname': 'Johnson', 'fname': 'Kent'}] What if I want to compute a new field in the form lastname, firstname but handle the case of lastname == None? A helper function to compute the new field looks like this: >>> def makeLnameFname(fname, lname): ... if not lname: return fname ... return '%s, %s' % (lname, fname) ... Let's try it out to make sure it works: >>> makeLnameFname('Kent', 'Johnson') 'Johnson, Kent' >>> makeLnameFname('Negroup', None) 'Negroup' Now we go through the data adding a 'fullname' attribute to each record. A for loop makes short work of this: >>> for r in data: ... r['fullname'] = makeLnameFname(r['fname'], r['lname']) ... >>> data [{'lname': 'Johnson', 'fullname': 'Johnson, Kent', 'fname': 'Kent'}, {'lname': None, 'fullname': 'Negroup', 'fname': 'Negroup'}] I hope you can see that this is vastly easier than implementing an SQL engine. Python is very powerful for manipulating data structures and learning how to use that power is well worth the time. Kent From mhansen at cso.atmel.com Wed Jul 13 18:54:31 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed, 13 Jul 2005 10:54:31 -0600 Subject: [Tutor] deleting files that are older than x days old Message-ID: <42D54747.1000702@cso.atmel.com> From a python program, I want to delete certain files that are older than x days old. To get the time that the file was last modified, it looks like I need to use os.path.getmtime(path). This gives you the time represented in the number of seconds from the epoch. I'd like to convert this into a datetime object, but I can't seem to figure out how. Once it's a datetime object, I can do simple (datetime.datetime.today() - filedatetime).days to figure out the days old. How do you convert a time represented in seconds from the epoch into a datetime object? Mike From cpu.crazy at gmail.com Wed Jul 13 10:13:42 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Wed, 13 Jul 2005 08:13:42 +0000 Subject: [Tutor] Tkinter Q's In-Reply-To: References: Message-ID: <42D4CD36.3070705@gmail.com> Hi, what's the **kw stand for, used for? What does it mean? > Some comments --- > > You create a Frame, but you never use it. > > You've put a whole lot of code in a class, but it's not in a class method. This > is kinda missing the point of using classes in the first place (and it just > flat-out wouldn't work in the majority of OO languages). > > Here's what I would do: > > class Main(Frame): > def __init__(self, master=None, **kw): > Frame.__init__(self, master, **kw) > > showquote = Label(self, text=random.choice(quotes.quote)) > showquote.pack() > > # etc > > if __name__ == '__main__': > root = Tk() > main = Main(root) > main.pack(fill=BOTH, expand=True) > root.mainloop() > ### > > Do you see what I am doing there, and why it is different from your approach? Uh, not really, no. I'm very new to GUI. So you're saying that If I make the class actually do something (I edited and example in: An into to Tkinter, Fredrik Lundh). > > > Once you've got a label, you can change its text attribute by using its >.config() method. > > So, you could do something like this: > > # ... > showquote = Label(self, text=random.choice(quotes.quote)) > showquote.pack() > > def changeQuote(): > currQuote = showquote.cget('config') # Get the current quote > newQuote = random.choice(quotes.quote) > while newQuote == currQuote: # Make sure the new quote differs > newQuote = random.choice(quotes.quote) > showquote.config(text=newQuote) > Button(self, text='Show another quote', command=changeQuote).pack() Aaag. I'm confused... I just tried you changeQuote example with out the above stuff... didn't work. My error message: AttributeError: 'NoneType' object has no attribute 'config' so I edited it a little, still didn't work (same error). I tried the class Main(Frame) and didn't get it to work either. Do you think you could make it a little bit simpler? If you can't that's ok, I'll try to study it more. Thanks, Joe From kent37 at tds.net Wed Jul 13 19:50:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Jul 2005 13:50:47 -0400 Subject: [Tutor] deleting files that are older than x days old In-Reply-To: <42D54747.1000702@cso.atmel.com> References: <42D54747.1000702@cso.atmel.com> Message-ID: <42D55477.4080606@tds.net> Mike Hansen wrote: > How do you convert a time represented in seconds from the epoch into a datetime > object? Use datetime.datetime.fromtimestamp(): >>> import os, datetime >>> t=os.path.getmtime('build.xml') >>> t 1115045692 >>> d=datetime.datetime.fromtimestamp(t) >>> d datetime.datetime(2005, 5, 2, 10, 54, 52) Kent From bob at farms.coop Wed Jul 13 19:55:53 2005 From: bob at farms.coop (Bobby Castleberry) Date: Wed, 13 Jul 2005 12:55:53 -0500 Subject: [Tutor] deleting files that are older than x days old In-Reply-To: <42D54747.1000702@cso.atmel.com> References: <42D54747.1000702@cso.atmel.com> Message-ID: <42D555A9.4080809@farms.coop> Mike Hansen wrote: > From a python program, I want to delete certain files that are older than x >days old. > >How do you convert a time represented in seconds from the epoch into a datetime >object? > > using unix time (seconds from the epoch) is rather easy. what I would do in this case is something along these lines: import time import os.path import os path = ("/home/joe/test.sxc") ftime = os.path.getmtime(path) curtime = time.time() difftime = curtime - ftime if difftime > 604800: os.unlink(path) ------------------- coming from the linux world and most of my programming being in bash i'm very comfortable working in seconds (it's nice not to worry about all the conversion and just deal with actual math), 604800 is a week fyi, 3600 seconds in an hour, and 86400 seconds in a day. of course that doesn't answer your question, to answer your question look at ctime in the time module or I believe strftime would also work Bob new to python and still trying to grasp oo programming From alan.gauld at freenet.co.uk Wed Jul 13 20:00:20 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 13 Jul 2005 19:00:20 +0100 Subject: [Tutor] python newbie..system call help References: <42D45C7A.3010901@charter.net><1121214043.42d45e5b6c5a4@www.paradise.net.nz><42D46221.8010808@charter.net> <42D47953.4080308@charter.net> Message-ID: <00d101c587d4$bc0c5af0$22a78751@xp> > of useful stuff. I still need to workout the best way to ask a user > for a root password, show **** when typed and then pass it to the > system... There is a module for password handling - getpass I think it is called, but a browse of the library docs should find it. The other one you might need is popen() - there are several versions - which will allow you to read back the results of your system command - there is a new module 'command' in v2.4 too, butr I haven't upgraded yet... Alan G. From alan.gauld at freenet.co.uk Wed Jul 13 20:06:06 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Wed, 13 Jul 2005 19:06:06 +0100 Subject: [Tutor] Query dictionaries with sql-like syntax References: <2fdabf19050713004175e3ed15@mail.gmail.com> Message-ID: <00d701c587d5$8aaaa470$22a78751@xp> > I'm trying to migrate a lot of data from an accounting > system software to another using Python. he easiest way to do this is usually to create a set of views using SQL in one database that map to the schema in the other. You can then read the table data out of the views and export it into the other DB. This has the advantage of full SQL access to all tables in the source DB and use SQL to join and manipulate field data in populating the views. Default values can be added too. > required, my question is: does a module/package/... exist > to query a set of dictionaries using sql syntax I don't know of one, thats where the Python DBI comes in to access sql tables directly from Python, but perrsonally for migrations, whoich I sadly seem to spend a lot of time doing! - I prefer the view approach - provided you a) have access tothe underlying databases and b) they support views! HTH, Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Jul 13 20:13:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 13 Jul 2005 11:13:22 -0700 (PDT) Subject: [Tutor] Tkinter video lectures off the python-wiki Message-ID: Hi Dave, I saw that you're starting to learn Tkinter programming; as I was browsing through the Beginners Guide on the Python Wiki, I ran into this: http://wiki.python.org/moin/Intro_to_programming_with_Python_and_Tkinter Unfortunately, I can't watch it myself because my Linux box doesn't have the right divx plugin yet. But perhaps this will be interesting to Windows users. Best of wishes! From bvande at po-box.mcgill.ca Wed Jul 13 20:30:22 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 13 Jul 2005 14:30:22 -0400 Subject: [Tutor] deleting files that are older than x days old In-Reply-To: <42D54747.1000702@cso.atmel.com> References: <42D54747.1000702@cso.atmel.com> Message-ID: <42D55DBE.10500@po-box.mcgill.ca> Mike Hansen said unto the world upon 13/07/2005 12:54: > From a python program, I want to delete certain files that are older than x > days old. > > To get the time that the file was last modified, it looks like I need to use > os.path.getmtime(path). This gives you the time represented in the number of > seconds from the epoch. > > I'd like to convert this into a datetime object, but I can't seem to figure out > how. Once it's a datetime object, I can do simple (datetime.datetime.today() - > filedatetime).days to figure out the days old. > > How do you convert a time represented in seconds from the epoch into a datetime > object? > > Mike Hi Mike, Kent gave you the answer to the question you asked. But, for what you are doing, I'd think about something sort of along the lines of Bob's suggestion. The way below avoids going through datetime objects: >>> t = time.time() >>> t -= 5 * 24 * 60 * 60 >>> # t is now 5 days back from current seconds from epoch >>> def older_than_n_days(n, time_stamp): return time.time() - time_stamp < n * 24 * 60 * 60 >>> for i in range(3, 8): print older_than_n_days(i, t) False False False True True >>> Best, Brian vdB From mhansen at cso.atmel.com Wed Jul 13 21:22:11 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed, 13 Jul 2005 13:22:11 -0600 Subject: [Tutor] deleting files that are older than x days old In-Reply-To: References: Message-ID: <42D569E3.9000705@cso.atmel.com> > Subject: > Re: [Tutor] deleting files that are older than x days old > From: > Kent Johnson > Date: > Wed, 13 Jul 2005 13:50:47 -0400 > > CC: > tutor at python.org > > > Mike Hansen wrote: > >> How do you convert a time represented in seconds from the epoch into a >> datetime object? > > > Use datetime.datetime.fromtimestamp(): > > >>> import os, datetime > >>> t=os.path.getmtime('build.xml') > >>> t > 1115045692 > >>> d=datetime.datetime.fromtimestamp(t) > >>> d > datetime.datetime(2005, 5, 2, 10, 54, 52) > > Kent > The docs for fromtimestamp weren't clear to me. i.e. not spelling it out that it converts from seconds from the epoch(which must be the POSIX timestamp it's referring to). Thanks! And thanks to the others that replied on how to do this without using datetime. Mike From albertito_g at hotmail.com Wed Jul 13 23:36:44 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 13 Jul 2005 21:36:44 +0000 Subject: [Tutor] Minesweeper implementing 20%, weird problem with matrixes Message-ID: Hey tutors I think I got this a little, but I have a very weird problem This is the code I'm using: ###################### class buscaminas(object): def __init__(self): self.col=0 self.marcas=Tkinter.BooleanVar() self.color=Tkinter.BooleanVar() self.sonido=Tkinter.BooleanVar() self.fil=0 self.byob=0 menubar= Menu(root) archivo=Menu(menubar,tearoff=0) archivo.add_command(label="Nuevo",underline=0,command=self.initialize) archivo.add_radiobutton(label="F?cil",underline=0,command=lambda: self.nivel(9,9,10)) archivo.add_radiobutton(label="Medio",underline=0,command=lambda: self.nivel(16,16,40)) archivo.add_radiobutton(label="Dificil",underline=0,command=lambda: self.nivel(16,30,99)) archivo.add_radiobutton(label="Personalizado",underline=0,command=self.hello) archivo.add_separator() archivo.add_checkbutton(label="Marcas (?)",variable=self.marcas,underline=0,command=self.hello) archivo.add_checkbutton(label="Color",underline=0,command=self.hello) archivo.add_checkbutton(label="Sonido",underline=1,command=self.hello) archivo.add_separator() archivo.add_command(label="Mejores Tiempos",underline=8,command=self.hello) archivo.add_separator() archivo.add_command(label="Salir",underline=0,command=root.destroy) menubar.add_cascade(label="Juego",underline=0,menu=archivo) help = Menu(menubar, tearoff=0) help.add_command(label="Contenido", command=self.hello) help.add_command(label="Indice de ayuda", command=self.hello) help.add_command(label="Como usar la ayuda", command=self.hello) help.add_separator() help.add_command(label="Acerca de...", command=self.hello) menubar.add_cascade(label="Ayuda",underline=1, menu=help) root.config(menu=menubar) root.bind_all("",lambda d: self.hello()) root.bind_all("",lambda s: self.initialize()) root.bind_all("",lambda x: root.destroy()) def hello(self): print "funca" def initialize(self): self.buttonmatrix=[] self.statematrix=[] self.bombmatrix=[] for i in range(self.fil): aux=[] for j in range(self.col): aux.append(None) self.buttonmatrix.append(aux) self.bombmatrix.append(aux) self.statematrix.append(aux) self.bombs() def nivel(self,f,c,b): self.col=c self.fil=f self.byob=b self.initialize() def bombs(self): c=0 while not c==self.byob: fi=random.randrange(self.fil) co=random.randrange(self.col) if self.bombmatrix[fi][co]==None: self.bombmatrix[fi][co]=9 c+=1 self.numbers() def putnumber(self,row,column): c=0 fi=row-1 ci=column-1 ff=row+2 cf=column+2 for i in range(fi,ff): for j in range(ci,cf): if (i<0) or (i>=self.fil) or (j<0) or (j>=self.col): pass elif self.bombmatrix[i][j]==9: c+=1 else: pass return c def numbers(self): for i in range(self.fil): for j in range(self.col): if self.bombmatrix[i][j]==9: pass else: self.bombmatrix[i][j]=self.putnumber(i,j) self.nuevo() def nuevo(self): for el in self.buttonmatrix: print el for l in self.statematrix: print l for e in self.bombmatrix: print e def main(): global root root=Tk() root.title("Buscaminas") root.iconbitmap("images\mina.ico") a=buscaminas() root.mainloop() main() ############## The following variables are the one with the problem: self.bombmatrix, self.buttonmatrix, self.statematrix I initialize them by putting None along all the fields (this is to allow the user to have any size of matrix) then I charge with numbers the self.bombmatrix but weirdly the others variables are filled with the same values, which is very strange to me since I'm not assigning them each others Any hint? Thanks in advanced and sorry for the long piece of code Alberto From sandip at lug-delhi.org Wed Jul 13 23:54:12 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Thu, 14 Jul 2005 03:24:12 +0530 Subject: [Tutor] Tkinter Q's In-Reply-To: <42D4CD36.3070705@gmail.com> References: <42D4CD36.3070705@gmail.com> Message-ID: <42D58D84.2000307@lug-delhi.org> Joseph Quigley wrote: > Hi, > what's the **kw stand for, used for? What does it mean? > > [...] >> >>class Main(Frame): >> def __init__(self, master=None, **kw): >> Frame.__init__(self, master, **kw) >> It is the python way to pass along all keyword arguments (xxx=yyy). So in the above if Main was instantiated the following way: myframe = Main(name="some name", height="100") Then __init__ gets called with parameters: __init__(self,None, name="some name", height="100") The **kw here denotes the name and height keywords. Therefore Frame.__init__ is called with: __init__(self,None, name="some name", height="100") Without **kw, there is no other way to send an arbitary number of parameters to Frame.__init__. - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip at puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From klappnase at freenet.de Thu Jul 14 00:02:30 2005 From: klappnase at freenet.de (Michael Lange) Date: Thu, 14 Jul 2005 00:02:30 +0200 Subject: [Tutor] Tkinter Q's In-Reply-To: <42D4CD36.3070705@gmail.com> References: <42D4CD36.3070705@gmail.com> Message-ID: <20050714000230.148c472c.klappnase@freenet.de> On Wed, 13 Jul 2005 08:13:42 +0000 Joseph Quigley wrote: > Hi, > what's the **kw stand for, used for? What does it mean? > **kw means that there is an optional list of keyword arguments that you can pass to __init__ (for example: main = Main(background="black") ). Keyword, because there is defined set of keywords that may be used. > > Here's what I would do: > > > > class Main(Frame): > > def __init__(self, master=None, **kw): > > Frame.__init__(self, master, **kw) > > > > showquote = Label(self, text=random.choice(quotes.quote)) > > showquote.pack() > > > > # etc > > > > if __name__ == '__main__': > > root = Tk() > > main = Main(root) > > main.pack(fill=BOTH, expand=True) > > root.mainloop() > > ### > > > > Do you see what I am doing there, and why it is different from your approach? > Uh, not really, no. I'm very new to GUI. So you're saying that If I make the class actually do something (I edited and example in: > An into to Tkinter, Fredrik Lundh). O.k., let's try it in more detail class Main(Frame): def __init__(self, master=None, **kw): Frame.__init__(self, master, **kw) This defines a new class "Main"; the construct "Main(Frame)" means that "Main" is a subclass of Frame and so inherits all methods and other attributes of a Frame (like pack(), configure() and so on). The second line defines the classes __init__() method, which is called everytime you create a new instance of the Main class with e.g. " main = Main() ". There are three arguments passed to __init__() : "self" is the first, because everytime you call a class method, the first argument that is passed to the call is the class instance that does the call, e.g if you do " root.mainloop() ", the mainloop() method gets called with your root window as first argument. You actually don't need to call this variable "self", you could as well call it "joe", but everyone uses "self", and this makes sense, because it points to what is meant. The third line now is the first thing __init__() does: it calls the Frame's __init__() and passes "self" as first argument to it, so now actually when you do: main = Main() your variable "main" is set to what your __init__() method returns and this is at this point nothing else as that what Frame.__init__() returns - a newly created Frame instance. You see, all arguments that are passed to __init__() are passed to Frame.__init__(), so after these three lines The "Main" class is nothing more (or less) than a Frame. I hope this made sense so far. Now you are ready to add some useful features to your class, to make it "more" than a standard Frame; e.g. start with adding some widgets and one new class method: class Main(Frame): def __init__(self, master=None, **kw): Frame.__init__(self, master, **kw) self.label = Label(self, text="Hello") self.label.pack() self.button = Button(self, text="Change quote", command=self.change_quote) self.button.pack() def change_quote(self): if self.label['text'] == "Hello": self.label.configure(text="World") else: self.label.configure(text="Hello") You see, we added a Button and a Label to the Frame. As first argument we passed "self" to the widgets, which, you remember, is a Frame instance; by calling the variable "self.label" instead of just "label" however you did some more: you added a new attribute to the Frame instance. the advantage is that you now can access the label from the outside: root = Tk() main = Main(root) main.pack() main.label.configure(text="Foo") root.mainloop() changes the Label's text. The last thing is that you defined a new class method for the "Main" class: change_quote() You see, change_quote() is defined *outside* of __init__() (note the indentation level), so it becomes another class attribute, just as __init__() itself and all the methods inherited from Frame. You can try: root = Tk() main = Main(root) main.pack() root.after(3000, main.change_quote) root.mainloop() Here when you call "main.change_quote" the class instance is passed as first argument to the method, that's why you have to pass "self" as argument in the class method definition, basically the same as with __init__(), and that's why you have to use "self.change_quote" as command for the button. I hope this still made sense. > > def changeQuote(): > > currQuote = showquote.cget('config') # Get the current quote > > newQuote = random.choice(quotes.quote) > > while newQuote == currQuote: # Make sure the new quote differs > > newQuote = random.choice(quotes.quote) > > showquote.config(text=newQuote) > > Button(self, text='Show another quote', command=changeQuote).pack() > > Aaag. I'm confused... I just tried you changeQuote example with out the above stuff... didn't work. My error message: > AttributeError: 'NoneType' object has no attribute 'config' > Just a guess: a common mistake among Tkinter beginners is: mylabel = Label(parent, text="Hello").pack() The problem here is, because pack() returns None you don't have a reference to the Label, but set the "mylabel" variable to None. If this is what happened, you need to split the above into two lines: mylabel = Label(parent, text="hello") mylabel.pack() > so I edited it a little, still didn't work (same error). I tried the class Main(Frame) and didn't get it to work either. Do you think you could make it a little bit simpler? If you can't that's ok, I'll try to study it more. > The changeQuote() method in the example contains a typo: currQuote = showquote.cget('config') # Get the current quote ^^^^^^ this must be: currQuote = showquote.cget('text') I hope this helps Michael From kent37 at tds.net Thu Jul 14 00:10:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Jul 2005 18:10:28 -0400 Subject: [Tutor] deleting files that are older than x days old In-Reply-To: <42D569E3.9000705@cso.atmel.com> References: <42D569E3.9000705@cso.atmel.com> Message-ID: <42D59154.7020708@tds.net> Mike Hansen wrote: > The docs for fromtimestamp weren't clear to me. i.e. not spelling it out that it > converts from seconds from the epoch(which must be the POSIX timestamp it's > referring to). You just have to dig a little in the docs: datetime.datetime.fromtimestamp(timestamp[, tz]) Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). time.time() Return the time as a floating point number expressed in seconds since the epoch, in UTC. os.path.getmtime(path) Return the time of last modification of path. The return value is a number giving the number of seconds since the epoch (see the time module). Kent From dyoo at hkn.eecs.berkeley.edu Thu Jul 14 00:43:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 13 Jul 2005 15:43:42 -0700 (PDT) Subject: [Tutor] Minesweeper implementing 20%, weird problem with matrixes In-Reply-To: Message-ID: Hi Alberto, The issue you're seeing is in the intialize() code: ###### def initialize(self): self.buttonmatrix=[] self.statematrix=[] self.bombmatrix=[] for i in range(self.fil): aux=[] for j in range(self.col): aux.append(None) self.buttonmatrix.append(aux) self.bombmatrix.append(aux) self.statematrix.append(aux) self.bombs() ###### In particular, it's the reuse of the same list value who we will call 'aux'. Let's try something from the interpreter to show a simplified version of the problem: ###### >>> aux = [] >>> x = [aux, aux, aux] >>> aux.append(42) >>> aux [42] >>> x [[42], [42], [42]] ###### The last result might be surprising to you. Things might be clearer if we draw a diagram of what Python's universe looks like at this point: --------------------------- aux --------->[42] < ^^ \ | \ \ | | | x ---------> [ , , ] ---------------------------- My ascii art is terrible. *grin* But I hope it's a little clearer now that what's happening is that the list's values are all to the same thing. Does this make sense so far? Please feel free to ask more questions. From dyoo at hkn.eecs.berkeley.edu Thu Jul 14 00:45:20 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 13 Jul 2005 15:45:20 -0700 (PDT) Subject: [Tutor] Minesweeper implementing 20%, weird problem with matrixes In-Reply-To: Message-ID: > Does this make sense so far? Please feel free to ask more questions. I forgot to mention that you might want to look at: http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list since it's relevant to the code that you're writing. Best of wishes to you! From jfouhy at paradise.net.nz Thu Jul 14 00:54:16 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 14 Jul 2005 10:54:16 +1200 (NZST) Subject: [Tutor] Tkinter Q's In-Reply-To: <42D4CD36.3070705@gmail.com> References: <42D4CD36.3070705@gmail.com> Message-ID: <1121295256.42d59b983a001@www.paradise.net.nz> Quoting Joseph Quigley : > Hi, > what's the **kw stand for, used for? What does it mean? Sorry about that. A couple of people have already answered; I'll just give you a couple of examples which might help you understand: >>> def showArgs(**kw): ... print kw ... >>> showArgs(foo=1, bar=2, string='My string') {'foo': 1, 'bar': 2, 'string': 'My string'} Basically, **kw means "Take any keyword arguments that were unused, and put them in a dictionary called 'kw'". Here's another example: >>> def myFunction(x=1, y=2, **kw): ... print "x == %s, y == %s" % (x, y) ... print "Unused arguments:", kw ... >>> myFunction(a='foo', b='bar', y=8, c='baz', x=13) x == 13, y == 8 Unused arguments: {'a': 'foo', 'c': 'baz', 'b': 'bar'} Some of the keyword arguments are given explicit names, to make them easy to access. The remainder are available still in kw. You can also do the reverse: >>> def doSomeMaths(x=3, y=2, z=8): ... return (x+y)*z ... >>> kwargs = { 'x':4, 'y':3, 'z':2 } >>> doSomeMaths(**kwargs) 14 In this case, the dictionary 'args' is expanded into three keyword parameters: x=4, y=3, z=2 You can also do the same thing with positional parameters; in this case you just use one *. Does that help? > Uh, not really, no. I'm very new to GUI. So you're saying that If I make > the class actually do something (I edited and example in: > An into to Tkinter, Fredrik Lundh). Tkinter programming involves making Frames, Buttons, Labels, etc. and putting them all together. What I like to do is subclass Frame (or other things) to make new GUI components, which I can then pack() into Frames as normal. Here's a really basic example: from Tkinter import * class BlueLabel(Label): """ A Label with a blue background. """ def __init__(self, *args, **kw): kw['background'] = 'blue' Label.__init__(self, *args, **kw) if __name__ == '__main__': tk = Tk() l1 = Label(tk, text='This is a normal label.') l1.pack() l2 = BlueLabel(tk, text='This is a blue label.') l2.pack() tk.mainloop() (and, this time, I have tested this code :-) Although you may need to fix up the indentation a bit) > > currQuote = showquote.cget('config') # Get the current quote As Michael pointed out, this was a bug. Sorry. -- John. From denise.hartley at gmail.com Thu Jul 14 01:11:32 2005 From: denise.hartley at gmail.com (D. Hartley) Date: Wed, 13 Jul 2005 16:11:32 -0700 Subject: [Tutor] PIL's palette Message-ID: <8daabe560507131611c198134@mail.gmail.com> Hello, everyone! I am trying to figure out what a palette actually is, how it works, and what PIL's "putpalette()" does with a given data set (it has to be a string, I believe). PIL's documentation says very close to nothing at all, and googling it has given me several other examples of doing what I already know how to do, but without explaining why or what it's actually doing (i.e., making it transferrable to other, different situations). The example is this: lut = [] for i in range(256): lut.extend([255-i, i/2, i]) # lut.extend([i, i, i]) im.putpalette(lut) The first example I found had only the lut.extend([255-i, i/2, i]) command, the second had the one below it (which is now commented out). I've tried them both, on an image which is black and blue. The first one (lut.extend([255-i, i/2, i])) gives an image that is red and red (you can still see the shading between the two objects so you can kind of see they're both there, but everything's red). The second, they're both black. Does anyone know of a good tutorial or explanation (ideally with an example or two) of what this palette actually is doing? It seems to be a 768-long list of values (0-255), but when you take those 768 values and "associate" them with an image via putpalette... what are they doing? I need to understand what is happening to my pixels when the putpalette() is called, so I can understand how to do it differently and apply it to do what I want. Thanks for any suggestions/pointers! ~Denise From jfouhy at paradise.net.nz Thu Jul 14 01:19:12 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 14 Jul 2005 11:19:12 +1200 (NZST) Subject: [Tutor] Tkinter query? In-Reply-To: <42D50301.9020301@pusspaws.net> References: <42D4FAD7.1010509@pusspaws.net> <42D50301.9020301@pusspaws.net> Message-ID: <1121296752.42d5a170ebff0@www.paradise.net.nz> Quoting Dave S : > >But I do not understand where Frame fits in to this ... ie > > > >from Tkinter import * > >class Hello(Frame): > > > > def __init__(self, parent=None): > > Frame.__init__(self, parent) > > self.pack() > > > > > >Why not just use 'class Hello(root)' ? Or have I missed the point :-[ > > > OK am I right in thinging a 'Frame' always has a parent of a Tk() or > possibly Toplevel() and its used to help in positioning a widget window > with .pack() ? > > Dave There's two separate issues here ... class Hello(Frame): ... This means that Hello is a subclass of the Frame class. If you haven't already, you might want to read the Python tutorial; particularly the section on classes and inheritance: http://docs.python.org/tut/node11.html (this is an example of inheritance) Your second question: > OK am I right in thinging a 'Frame' always has a parent of a Tk() or > possibly Toplevel() and its used to help in positioning a widget window > with .pack() ? Frames are used to help with positioning other widgets, yes. They are also used to affect how the application looks: you can change the background colour of Frames, and also the border (to make them look like they are sticking out, for example). But you can (and frequently will) put Frames inside other Frames. Example: from Tkinter import * tk = Tk() tk.config(background='pink') tk.geometry('400x400') frame1 = Frame(tk, background='blue') frame1.pack(side=LEFT, padx=15, pady=15, expand=True, fill=BOTH) frame2 = Frame(tk, background='green', borderwidth=3, relief=RAISED) frame2.pack(side=LEFT, padx=15, pady=15, expand=True, fill=BOTH) frame3 = Frame(frame1, background='red', borderwidth=3, relief=SUNKEN) frame3.pack(side=TOP, padx=15, pady=15, expand=True, fill=BOTH) frame4 = Frame(frame1, background='white', borderwidth=3, relief=GROOVE) frame4.pack(side=TOP, padx=15, pady=15, expand=True, fill=BOTH) label1 = Label(frame4, text='Hello world!') label1.pack(expand=True) tk.mainloop() -- John. From alan.gauld at freenet.co.uk Thu Jul 14 02:12:18 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 14 Jul 2005 01:12:18 +0100 Subject: [Tutor] Minesweeper implementing 20%, weird problem with matrixes References: Message-ID: <010c01c58808$b30062b0$22a78751@xp> > I initialize them by putting None along all the fields Actually you don't. def initialize(self): self.buttonmatrix=[] self.statematrix=[] self.bombmatrix=[] 3 empty lists, so far so good. for i in range(self.fil): aux=[] for j in range(self.col): aux.append(None) a new list filled with None self.buttonmatrix.append(aux) self.bombmatrix.append(aux) self.statematrix.append(aux) THat same list inserted into all three lists, so they all point at the same internal list of Nones. So when you change one, you change all. Try using aux[:] instead to take a copy of aux... You could also use list comprehension instead of the loop/append: aux = [None for i in range(self.col)] HTH, Alan G. From zamb at saudi.net.sa Thu Jul 14 03:28:01 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Thu, 14 Jul 2005 04:28:01 +0300 Subject: [Tutor] OT python Licences In-Reply-To: <42D3F1F1.8010704@lug-delhi.org> References: <42D39222.9040608@pusspaws.net> <42D3F1F1.8010704@lug-delhi.org> Message-ID: <1121304481.21703.31.camel@localhost.localdomain> Hi everyone... On Tue, 2005-07-12 at 22:08 +0530, Sandip Bhattacharya wrote: > 2. Gtk. Simple API. A great RAD GUI builder (Glade). Cons are that you > have to have Pygtk installed on windows for your apps to run (I am not > sure if py2exe will package them for you as a standalone). Another con > is that it lacks a native windows look. On that other hand Gtk2 is quite > featureful. > One of the applications that uses GTK+ (version 2.X) and Python is BitTorrent? (starting with version 4.0). As far as I know, all GTK+ 2.x applications under Windows have a native look. I don't know my self as I don't have Windows. Here's some screen-shots for BitTorrent 4.x under Windows and judge for yourself: http://www.golem.de/0503/36804.html http://www.soft-ware.net/internet/news/fileshare/p04258.asp Click on "Screenshot vergr??ern" in the 2nd one for a bigger image. All links above are German as this is the only ones I could find fast. GTK+ is licensed under the GNU's LGPL (Lesser General Public License, found in the source code or from the web?) which pretty much allows you to link property code without any restrictions on that code *only*! (Any modifications to the GTK+ source must be re-released to the public of the whole package to be distributed or requested from a client who have received a copy of said package/application.) > > - Sandip > Sorry for being nit-picky (this is the 2nd time this day but on another list!). Ziyad. Footnotes: 1. http://www.bittorrent.com 2. http://www.gnu.org/copyleft/lesser.html From xecronix at yahoo.com Thu Jul 14 04:26:48 2005 From: xecronix at yahoo.com (Ron Weidner) Date: Wed, 13 Jul 2005 19:26:48 -0700 (PDT) Subject: [Tutor] tk entry focus Message-ID: <20050714022648.72727.qmail@web60622.mail.yahoo.com> I've struggled... Now I'm asking... What's wrong with this code? Or more to the point, how do you set the focus to an Entry widget? Traceback (most recent call last): File "./run_dialogue.py", line 33, in ? app = Run_dialogue( root ) File "./run_dialogue.py", line 23, in __init__ self.cmd.focus() AttributeError: 'NoneType' object has no attribute 'focus' class Run_dialogue: def __init__( self, master ): img_path = path.dirname(sys.argv[0]) img_path = path.abspath(img_path) #master.initial_focus.focus_set() master.geometry( "300x150+200+200") self.cmd_text = StringVar() self.frame = Frame( master ) self.icon = PhotoImage( file=img_path + "/target.gif" ) self.lbl_icon = Label( self.frame, image=self.icon ) self.lbl_icon.grid( row = 1, column = 0 ) self.label = Label( self.frame, text="Command: " ).grid( row = 1, column = 1 ) self.cmd = Entry( self.frame, textvariable=self.cmd_text ).grid( row = 1, column = 2 ) self.btn = Button( self.frame, text=" Run ", command=self.btn_run_click ) self.btn.grid( row = 2, column = 0, columnspan = 3, sticky = "e") self.btn.bind("", self.btn_run_click) self.frame.pack() self.cmd.focus() Ronald Weidner http://www.techport80.com PHP Software developer for hire. ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs From jfouhy at paradise.net.nz Thu Jul 14 04:46:57 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 14 Jul 2005 14:46:57 +1200 (NZST) Subject: [Tutor] tk entry focus In-Reply-To: <20050714022648.72727.qmail@web60622.mail.yahoo.com> References: <20050714022648.72727.qmail@web60622.mail.yahoo.com> Message-ID: <1121309217.42d5d221aed2e@www.paradise.net.nz> Quoting Ron Weidner : > What's wrong with this code? Or more to the point, > how do you set the focus to an Entry widget? Look at what the error message is saying: > self.cmd.focus() > AttributeError: 'NoneType' object has no attribute > 'focus' Translation: self.cmd is a 'NoneType' object. There is only one NoneType object: None. So, somehow, you have (effectively) done: self.cmd = None Let's see ... > self.cmd = Entry( self.frame, > textvariable=self.cmd_text ).grid( row = 1, column = 2 ) Aha. Here, you are creating an Entry widget, calling the grid() method on the entry widget, and then assigning to self.cmd the return value _of the grid() call_. This is extremely different from assigning to self.cmd the Entry widget just created. (can you guess what .grid() returns?) You need to break your code up into two lines: self.cmd = Entry(...) self.cmd.grid(...) Then give it a try :-) -- John. From sandip at lug-delhi.org Thu Jul 14 05:25:35 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Thu, 14 Jul 2005 08:55:35 +0530 Subject: [Tutor] OT python Licences In-Reply-To: <1121304481.21703.31.camel@localhost.localdomain> References: <42D39222.9040608@pusspaws.net> <42D3F1F1.8010704@lug-delhi.org> <1121304481.21703.31.camel@localhost.localdomain> Message-ID: <42D5DB2F.6060808@lug-delhi.org> ZIYAD A. M. AL-BATLY wrote: > > One of the applications that uses GTK+ (version 2.X) and Python is > BitTorrent? (starting with version 4.0). As far as I know, all GTK+ 2.x > applications under Windows have a native look. I don't know my self as > I don't have Windows. I use gimp on windows regularly. And the latest version of gimp for windows uses Gtk2.0. I wouldn't call this a native look, even if I dont see any aesthetic problem with Gtk2.0. Take a look at the following screenshot of Gimp for windows. http://gimp.org/screenshots/windowsxp_screenshot1.png I have a soft corner for Gtk myself, but I still can't say that it has a native windows look. BTW, thanks for the bittorrent link. Good to see Bram using Gtk now. Installing megs of wxwindows/python just to run bittorrent on various linux distros was quite a pain. > GTK+ is licensed under the GNU's LGPL (Lesser General Public License, > found in the source code or from the web?) which pretty much allows you > to link property code without any restrictions on that code *only*! > (Any modifications to the GTK+ source must be re-released to the public > of the whole package to be distributed or requested from a client who > have received a copy of said package/application.) You really should look at the wxwindows licence then. http://www.opensource.org/licenses/wxwindows.php It is LGPL + more freedom for commercial users. > > > Sorry for being nit-picky (this is the 2nd time this day but on another > list!). :) - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip at puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From webdev at matheteuo.org Thu Jul 14 06:17:56 2005 From: webdev at matheteuo.org (Don Parris) Date: Thu, 14 Jul 2005 00:17:56 -0400 Subject: [Tutor] OT python Licences In-Reply-To: <42D5DB2F.6060808@lug-delhi.org> References: <42D39222.9040608@pusspaws.net> <42D3F1F1.8010704@lug-delhi.org> <1121304481.21703.31.camel@localhost.localdomain> <42D5DB2F.6060808@lug-delhi.org> Message-ID: <20050714001756.0e4c49b6@luke.matheteuo.rel> On Thu, 14 Jul 2005 08:55:35 +0530 Sandip Bhattacharya wrote: > ZIYAD A. M. AL-BATLY wrote: > > > > You really should look at the wxwindows licence then. > http://www.opensource.org/licenses/wxwindows.php > > It is LGPL + more freedom for commercial users. > > > > > > > Commercial users, or non-free users? Remember that libre software *can* be distributed commercially as well. In fact, the FSF encourages people to do so - it's one of the freedoms afforded by the GPL. Don -- evangelinux GNU Evangelist http://matheteuo.org/ http://chaddb.sourceforge.net/ "Free software is like God's love - you can share it with anyone anytime anywhere." From sandip at lug-delhi.org Thu Jul 14 09:28:46 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Thu, 14 Jul 2005 12:58:46 +0530 Subject: [Tutor] OT python Licences In-Reply-To: <20050714001756.0e4c49b6@luke.matheteuo.rel> References: <42D39222.9040608@pusspaws.net> <42D3F1F1.8010704@lug-delhi.org> <1121304481.21703.31.camel@localhost.localdomain> <42D5DB2F.6060808@lug-delhi.org> <20050714001756.0e4c49b6@luke.matheteuo.rel> Message-ID: <42D6142E.2060003@lug-delhi.org> Don Parris wrote: > Commercial users, or non-free users? Remember that libre software *can* be > distributed commercially as well. In fact, the FSF encourages people to do > so - it's one of the freedoms afforded by the GPL. > I agree. Libre software can be distributed commercially, as long as the source is provided. However, here I am talking about the freedom of choice for commercial developers to *not* disclose the source of their programs. While it curtails the freedom of their users, the freedom to exercise this option is valuable to many developers. BSD, MIT, wxpython, (I am not sure but LGPL too?) licences provide this "freedom" (note the quote! Note the quote! :-P ) Before you snap my head off, let me clarify that by saying this I am NOT trying to promote closed source software. :) - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip at puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From mark.kels at gmail.com Thu Jul 14 10:16:57 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu, 14 Jul 2005 10:16:57 +0200 Subject: [Tutor] Virtual keyboard Message-ID: Hi list. I want to make a virtual keyboard with Tkinter. Can I have some pointers on how to do it? Will it be hard (it doesn't look so hard...)? Thanks. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From mark.kels at gmail.com Thu Jul 14 11:11:07 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu, 14 Jul 2005 11:11:07 +0200 Subject: [Tutor] Virtual keyboard In-Reply-To: <002201c58851$43bd5fe0$aa02a8c0@luke> References: <002201c58851$43bd5fe0$aa02a8c0@luke> Message-ID: On 7/14/05, luke wrote: > I don't think it will be hard, but it depends what you want to pass > keypresses to. > If you want your virtual keyboard to type in any program you will have to > deal with > focus issues and it seems to me that would be hard, if possible. > but if you just want it to type into its own (tkinter) text box, you're > right, that shouldn't be too hard. I do want it to type in any entry (websites, notepad and other programs), and thats what makes it harder. I dont think that shouldnt be too hard as well, but I have no idea how to do it. Anyway, thanks for the quick replay. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From jfouhy at paradise.net.nz Thu Jul 14 11:25:39 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 14 Jul 2005 21:25:39 +1200 (NZST) Subject: [Tutor] Virtual keyboard In-Reply-To: References: <002201c58851$43bd5fe0$aa02a8c0@luke> Message-ID: <1121333139.42d62f9388ae0@www.paradise.net.nz> Quoting Mark Kels : > I do want it to type in any entry (websites, notepad and other > programs), and thats what makes it harder. I dont think that shouldnt > be too hard as well, but I have no idea how to do it. You would need some way of getting a handle for the widget you want to type into.. I don't know how to do this (or even if you can), but I wonder if you might have more luck if you used PythonWin and the Microsoft factory classes to build your GUI? -- John. From mark.kels at gmail.com Thu Jul 14 11:36:32 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu, 14 Jul 2005 11:36:32 +0200 Subject: [Tutor] Virtual keyboard In-Reply-To: <1121333139.42d62f9388ae0@www.paradise.net.nz> References: <002201c58851$43bd5fe0$aa02a8c0@luke> <1121333139.42d62f9388ae0@www.paradise.net.nz> Message-ID: On 7/14/05, jfouhy at paradise.net.nz wrote: > You would need some way of getting a handle for the widget you want to type > into.. I don't know how to do this (or even if you can), but I wonder if you > might have more luck if you used PythonWin and the Microsoft factory classes to > build your GUI? That looks too hard... If there isnt an easyer solution I'll just find another project to work on :-) Thanks anyway, -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From peter at rt.sk Thu Jul 14 23:38:08 2005 From: peter at rt.sk (Peter Szinek) Date: Thu, 14 Jul 2005 23:38:08 +0200 Subject: [Tutor] PIL's palette In-Reply-To: <8daabe560507131611c198134@mail.gmail.com> References: <8daabe560507131611c198134@mail.gmail.com> Message-ID: <42D6DB40.2090409@rt.sk> Hey, DH>I am trying to figure out what a palette actually is, how it works, I did this VEEEERRRRYYYY long time ago (10+ years) in C-- (it was an embellished assembler) so don't kill me if this works other way in python/PIL, but as far as i remember, it worked like this: Your palette is a LookUp Table (LUT) - it is also named like this in your prog ('lut') - which is a 768-long list (or as in this case, a list of 256 lists, every inner list has 3 elements - so again you have 768 elements). So 3x256 or 1x768 is just an implementation detail. Let's see the 3x256 version: index | ---------------- 0 | [r,g,b] 1 | [r,g,b] 2 | [r,g,b] ... | ... | 255 | [r,g,b] an [r,g,b] list represents a color - i think you already know this - as red, green, blue, where 0 <= r,g,b <= 255. (e.g. (255,0,0) is the absolute red, (255,255,255) is the absolute white etc.) Now your picture looks like this: [8][10][3][55].... [25][100][210].... ... blah blah ... And when it is rendered, PIL looks up the color (hence lookup table) at the given index. So the first pixel of the image will be the color held at index 8 in the lookup table (or palette). So basically the palette is the comupter abstraction of a real painter's palette - the real painter has x colors on his palette, and says (by looking at the palette): ah, i need this intelligent shade of cobalt blue. You do the same here - you have a palette (the look up table) and say: ah, i need this color - so you put the INDEX of that color into the image, and when the computer is 'painting' he looks up the color at that index. DH>and what PIL's "putpalette()" does with a given data set It creates the palette, i.e. assigns a color to every index DH> lut = [] DH> for i in range(256): DH> lut.extend([255-i, i/2, i]) DH> # lut.extend([i, i, i]) DH> im.putpalette(lut) DH> DH> The first example I found had only the lut.extend([255-i, i/2, i]) DH> command, the second had the one below it (which is now commented out). DH> I've tried them both, on an image which is black and blue. DH> DH> The first one (lut.extend([255-i, i/2, i])) gives an image that is red DH> and red (you can still see the shading between the two objects so you DH> can kind of see they're both there, but everything's red). DH> DH> The second, they're both black. DH> Yep, because the first produces a palette like this: index | ---------------- 0 | [255,127,0] orange 1 | [254,127,1] 2 | [253,126,2] ... | (some kind of purple, magenta, red ...) ... | 255 | [0,0,0] black So i think the indices in your original blue image point to colors in the new palette which are 'red-like', hence the red-red combo. The second case, [i,i,i] will generate a perfect gryscale palette (255,255,255) is white, (0,0,0) is black, (i,i,i) is gray - (below (127,127,127) is light gray otherwise dark gray. Hence the black-black combo. HTH, Peter From negroup at gmail.com Thu Jul 14 12:26:35 2005 From: negroup at gmail.com (Negroup -) Date: Thu, 14 Jul 2005 12:26:35 +0200 Subject: [Tutor] Questions on file.read Message-ID: <2fdabf1905071403262edb0849@mail.gmail.com> >>> help(f.read) Help on built-in function read: read(...) read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. Hi tutors. What does "blocking-mode" mean, and how can I be sure that when reading a file I'm not in such modality (and eventually switch)? I need to read the whole content of a file, not just some pieces. Another question. Python tutorial states: "To read a file's contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it's your problem if the file is twice as large as your machine's memory." What does exactly mean that it's my problem (crash? an exception will be raised? fire and flames? xyz?). How can my recognize a "too big file" before read it? Thanks! From amonroe at columbus.rr.com Thu Jul 14 12:51:30 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu, 14 Jul 2005 06:51:30 -0400 Subject: [Tutor] OT python Licences In-Reply-To: <1121304481.21703.31.camel@localhost.localdomain> References: <42D39222.9040608@pusspaws.net> <42D3F1F1.8010704@lug-delhi.org> <1121304481.21703.31.camel@localhost.localdomain> Message-ID: <33520483235.20050714065130@columbus.rr.com> > As far as I know, all GTK+ 2.x > applications under Windows have a native look. I don't know my self as > I don't have Windows. My personal experience is that GTK apps (Ones I've used like GAIM, Inkscape, Ethereal) on Windows stick out like a sore thumb, GUI-wise. They tend not to use the same font, or font size as normal apps. They are typically slower at painting their menus to the screen. They also have other oddities such as tooltips that tend to "stick" on the screen, and they don't refresh their windows when viewed via VNC. Alan From johanmeskenscs3 at chromaticspaceandworld.com Thu Jul 14 12:52:57 2005 From: johanmeskenscs3 at chromaticspaceandworld.com (Johan Meskens CS3 jmcs3) Date: Thu, 14 Jul 2005 12:52:57 +0200 Subject: [Tutor] ot, " pythonmonks Message-ID: hello is there such a place as www.perlmonks.org for python ? kind regards jmcs3 From alan.gauld at freenet.co.uk Thu Jul 14 12:43:36 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 14 Jul 2005 11:43:36 +0100 Subject: [Tutor] Virtual keyboard References: <002201c58851$43bd5fe0$aa02a8c0@luke> Message-ID: <014001c58860$f7cad3f0$22a78751@xp> >> If you want your virtual keyboard to type in any program you will >> have to >> deal with focus issues and it seems to me that would be hard, if >> possible. > > I do want it to type in any entry (websites, notepad and other > programs), and thats what makes it harder. I dont think that > shouldnt > be too hard as well, but I have no idea how to do it. Assuming you are on Windows - and this is very platform specific - then you need to access the Windows API using either winall or ctypes. The API calls you should look at (on msdn.microsoft.com) are: HWND GetFocus(VOID) to get a handle to the window which currently has focus. and BOOL PostMessage( HWND hWnd, // handle of destination window UINT Msg, // message to post WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); Where Msg could be: WM_KEYDOWN Which has the following wParam and lParam values: nVirtKey = (int) wParam; // virtual-key code lKeyData = lParam; // key data So you are right its not too doifficult but does require fairly low level access to Windows. Sufficiently so that personally I'd build this using Delphi even though it is possible in Python! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Jul 14 15:17:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Jul 2005 09:17:36 -0400 Subject: [Tutor] Questions on file.read In-Reply-To: <2fdabf1905071403262edb0849@mail.gmail.com> References: <2fdabf1905071403262edb0849@mail.gmail.com> Message-ID: <42D665F0.5030506@tds.net> Negroup - wrote: > read(...) > read([size]) -> read at most size bytes, returned as a string. > > If the size argument is negative or omitted, read until EOF is reached. > Notice that when in non-blocking mode, less data than what was requested > may be returned, even if no size parameter was given. > > Hi tutors. > What does "blocking-mode" mean, and how can I be sure that when > reading a file I'm not in such modality (and eventually switch)? I > need to read the whole content of a file, not just some pieces. I don't know how to put a file in non-blocking mode but you don't have to worry about it for common usage. Use f.read() (with no arguments) to read the whole contents of a file. > > Another question. Python tutorial states: > > "To read a file's contents, call f.read(size), which reads some > quantity of data and returns it as a string. size is an optional > numeric argument. When size is omitted or negative, the entire > contents of the file will be read and returned; it's your problem if > the file is twice as large as your machine's memory." > > What does exactly mean that it's my problem (crash? an exception will > be raised? fire and flames? xyz?). How can my recognize a "too big > file" before read it? My guess is that it will raise MemoryError but I don't know for sure. Use os.path.getsize() to find out how big a file is. Kent From maxnoel_fr at yahoo.fr Thu Jul 14 15:17:47 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu, 14 Jul 2005 15:17:47 +0200 Subject: [Tutor] Questions on file.read In-Reply-To: <2fdabf1905071403262edb0849@mail.gmail.com> References: <2fdabf1905071403262edb0849@mail.gmail.com> Message-ID: On Jul 14, 2005, at 12:26, Negroup - wrote: > "To read a file's contents, call f.read(size), which reads some > quantity of data and returns it as a string. size is an optional > numeric argument. When size is omitted or negative, the entire > contents of the file will be read and returned; it's your problem if > the file is twice as large as your machine's memory." > > What does exactly mean that it's my problem (crash? an exception will > be raised? fire and flames? xyz?). How can my recognize a "too big > file" before read it? Python will try to read the entire file in memory. Now if the file is twice as large as your computer's memory, it will run out of it, and then switch to swap space (virtual memory) to fit the rest. You know how when you're running a resource-intensive game, sometimes the action freezes and you hear your hard drive thrashing like crazy? Same thing here. Things will slow down to a crawl. If the machine is a server, it's obviously a Bad Thing -- however, the box shouldn't crash. Things really get ugly when you run out of swap space. Most OS's set the swap file to somewhere between 1 and 2 times your actual RAM -- that is, if you have 256 megs of RAM, you can assume that anything that requires up to 640 megs will work (albeit slowly). Now if you manage to fill up both the physical RAM and the swap space, there won't be any more space to finish reading the file. If that happens, chances are your machine will crash. If it doesn't, Python will raise a MemoryError. In any case, this is something you *don't* want to happen. In the big hierarchy of Bad Things, there is only one thing worse than a MemoryError: >>> import sys >>> sys.is_computer_on_fire() True In any cas, you should try to avoid using file.read without a size parameter. If you're processing text files, reading them one line at a time would be a good start (for line in open ('filename.txt'): is an instance of Best Thing Ever). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___________________________________________________________________________ Appel audio GRATUIT partout dans le monde avec le nouveau Yahoo! Messenger Téléchargez cette version sur http://fr.messenger.yahoo.com From albertito_g at hotmail.com Thu Jul 14 15:36:49 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Thu, 14 Jul 2005 13:36:49 +0000 Subject: [Tutor] Minesweeper implementing 20%, weird problem with matrixes In-Reply-To: <010c01c58808$b30062b0$22a78751@xp> Message-ID: Hey I didn't notice that :P Thanks to Alan, I learn something new with the use of List Comprehension and thanks to Danny for the docs, they really helped a lot to understand the figure here I think I can say that Minesweeper implementing 23% with this problem solved Thanks a lot Alberto >From: "Alan G" >To: "Alberto Troiano" , >Subject: Re: [Tutor] Minesweeper implementing 20%,weird problem with >matrixes >Date: Thu, 14 Jul 2005 01:12:18 +0100 > > > I initialize them by putting None along all the fields > >Actually you don't. > > def initialize(self): > self.buttonmatrix=[] > self.statematrix=[] > self.bombmatrix=[] > >3 empty lists, so far so good. > > for i in range(self.fil): > aux=[] > for j in range(self.col): > aux.append(None) > >a new list filled with None > > self.buttonmatrix.append(aux) > self.bombmatrix.append(aux) > self.statematrix.append(aux) > >THat same list inserted into all three lists, so they all point >at the same internal list of Nones. So when you change one, >you change all. > >Try using aux[:] instead to take a copy of aux... >You could also use list comprehension instead of the loop/append: > >aux = [None for i in range(self.col)] > > >HTH, > >Alan G. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From 3dbernard at gmail.com Thu Jul 14 15:43:59 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 14 Jul 2005 09:43:59 -0400 Subject: [Tutor] Catching OLE error Message-ID: <61d0e2b405071406434b232dc6@mail.gmail.com> Hello, A simple question: what is the syntax in a try/except for the OLE error? Let say you want to catch OLE error: try: print stuff except OLEError: print 'ole' Now the problem is that I just can't seem to find anything how the exact grammar of this error! I have looked in the Python documentation, as well as the pywin32 documentation, I have tried many different ways of typing it, I googled around, but yet I just can't find it. Thanks Bernard From kent37 at tds.net Thu Jul 14 15:47:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 14 Jul 2005 09:47:44 -0400 Subject: [Tutor] Questions on file.read In-Reply-To: References: <2fdabf1905071403262edb0849@mail.gmail.com> Message-ID: <42D66D00.8010600@tds.net> Max Noel wrote: > In any cas, you should try to avoid using file.read without a size > parameter. If you're processing text files, reading them one line at a > time would be a good start (for line in open ('filename.txt'): is an > instance of Best Thing Ever). Yes, this is good advice, if you can process the file line-by-line that is the best way to do it. If you know you have to handle whole files that won't fit in memory you might want to use the mmap module. Kent From adam.jtm30 at gmail.com Thu Jul 14 16:02:44 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 14 Jul 2005 15:02:44 +0100 Subject: [Tutor] Catching OLE error In-Reply-To: References: <61d0e2b405071406434b232dc6@mail.gmail.com> Message-ID: Can you send me the output for an OLE error? The correct syntax should be included in the error message like this: Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' TypeError would be the exception so you would have: try: None + "foo" except: TypeError On 7/14/05, Bernard Lebel <3dbernard at gmail.com> wrote: > > Hello, > > A simple question: what is the syntax in a try/except for the OLE error? > > Let say you want to catch OLE error: > > try: print stuff > except OLEError: print 'ole' > > Now the problem is that I just can't seem to find anything how the > exact grammar of this error! I have looked in the Python > documentation, as well as the pywin32 documentation, I have tried many > different ways of typing it, I googled around, but yet I just can't > find it. > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050714/8da1dc46/attachment-0001.htm From 3dbernard at gmail.com Thu Jul 14 16:27:30 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 14 Jul 2005 10:27:30 -0400 Subject: [Tutor] Catching OLE error In-Reply-To: References: <61d0e2b405071406434b232dc6@mail.gmail.com> Message-ID: <61d0e2b405071407273bd4b060@mail.gmail.com> Very well. #INFO : < NewRenderShot > importAnimation> :: Import action for character ""... #ERROR : 2000 - Argument 0 (Source) is invalid #ERROR : 2001-ANIM-ApplyAction - Argument 0 is invalid - [line 3543 in D:\Software\Softimage\XSI_4.2\Application\DSScripts\action.vbs] #ERROR : 21000-ANIM-ImportAction - Traceback (most recent call last): # File " instead of the other languages. > some freinds advised me to create this isnce i am learning > programming python.. Writing web pages is only one kind of programming (And not really a very fun kind IMHO!). Python can do many other types of programs including GUI based applications too. But either CGI or Client Side Scripting (as the above technique is called) can be done in Python. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From cyresse at gmail.com Mon Jul 18 13:24:16 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 18 Jul 2005 23:24:16 +1200 Subject: [Tutor] Parsing problem Message-ID: Hi all, I am a Europa Universalis II freak, and in attempting to recreate a lost saved game, I had to delve into the mechanics of the save game file. Which, luckily, is plain text. It's formatted like this - country = { tag = ENG ai = { flags = { } combat = { DAU FRA ORL PRO } continent = { } area = { } region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" "TagoSea" "WCAtlanticSea" } war = 60 ferocity = no } } Now, it tends to conform to certain rules, which make it a bit easier, there's always a space either side of an equals sign and such forth, which should hopefully make parsing stuff like - date = { year = 1421 month = july day = 7 } a bit less complex, considering that it uses space to separate list items. What I need to do, is to turn this into a data structure, and I think this relates to XML in a way. Basically, I want to parse the above (I assume I'll be counting braces to find where I am) so that a country object called ENG has a dictionary called ai, which points to lists, integers, strings etc. and so forth. If anyone has any links to any (simple) examples of XML parsing or similar which could give me pointers as to how to go about this, it'd be much appreciated. Regards, Liam Clarke -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/72dc77bb/attachment.htm From alan.gauld at freenet.co.uk Mon Jul 18 13:20:14 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 18 Jul 2005 12:20:14 +0100 Subject: [Tutor] File transfer References: Message-ID: <00a001c58b8a$aba37090$77cc8651@xp> > I need to transfer a file from a "client" over a normal telephone > call (no You still need some kind of protocol between the two computers. Common protocol for file transfers include xmodem and zmodem and ISTR seeing modules for each of them on the vaults of parnassus. You could do it at the raw data level if you also have control of the remote computer, but thats hard, you effectively have to write your own protocol... If you are on unix you could use the 'fcntl' module. I think there is a non standard 'serial' module somewhere too. > ISP) or an internet connection (thro ISP) to a central "server". That's probably easiest using the standard ftplib module. > The "server" needs to open this file process it and then output a > file which > then needs to be sent back to the above client. Same principles apply provided you have access to the remote box. If you need to rely on it using existing tools it might get a tad more tricky! No idea about plone however... Alan G. From geon at post.cz Mon Jul 18 13:32:27 2005 From: geon at post.cz (geon) Date: Mon, 18 Jul 2005 13:32:27 +0200 Subject: [Tutor] ListBox in Tkinter Message-ID: <42DB934B.7090700@post.cz> Hi, I would like to ask if it is possible to create such a listbox (attached) in TKinter itself or must have pmw ot tix...or ... Thank you -- geon Vyj?mka je pravidlo. Rekurzivn?. -------------- next part -------------- A non-text attachment was scrubbed... Name: py.PNG Type: image/png Size: 1505 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050718/bd319d50/py.png From RPhillips at engineer.co.summit.oh.us Mon Jul 18 14:07:27 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Mon, 18 Jul 2005 08:07:27 -0400 Subject: [Tutor] how to add python code to a webpage Message-ID: Mustafa Abbasi asked: i want to create a simple page which has a form and takes in persons date of birth and give out exact age. how do i add python codeto an html page. i don't have any dreamweaver or frontpage. this is basically cuz some freinds advised me to create this isnce i am learning programming python.. so please help I find CherryPy is easy and lightweight to get started. http://www.cherrypy.org Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/da0de4e4/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Header Type: application/octet-stream Size: 561 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050718/da0de4e4/Header.obj From andreas at kostyrka.org Mon Jul 18 14:10:50 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 18 Jul 2005 14:10:50 +0200 Subject: [Tutor] File transfer In-Reply-To: References: Message-ID: <1121688650.4753.18.camel@andi-lap> Am Montag, den 18.07.2005, 11:39 +0200 schrieb Raj Moodley: > Hi All, am a newbie to python and need some help. > > > > I need to transfer a file from a ?client? over a normal telephone call > (no ISP) or an internet connection (thro ISP) to a central ?server?. Well, even without ISP you can have a TCP/IP connection. Or you can send the file directly over the modem connection. How this is accomplished is highly OS-dependant ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20050718/ed61c311/attachment.pgp From bellarchitects at gmail.com Mon Jul 18 15:17:11 2005 From: bellarchitects at gmail.com (Alex Nedelcu) Date: Mon, 18 Jul 2005 16:17:11 +0300 Subject: [Tutor] Hy, I'm a n00b to Python, have some questions Message-ID: Hy all, I am a Java/PHP programmer. I read the tutorial and I like the language. I am more interested in the web capabilities of the platform (CPython). I have some questions I'd like to ask you guys: 1. Is there any decent forum were people are talking in python ? 2. what about speed ? (any beginners question I suppose). Is it something to be concerned about ? Does anyone know how it compares to PHP ? (for Java I allready know) 3. I want any usefull resources you can provide me with 4. What's the hottest web framework right now that does not require an application server (meaning that it runs on fastcgi) Also, why is www.python.org so ugly :) ? If I'd like to point others to learn Python I would need a site that markets Python through eye-candy case studies, not some boring old site :). Just joking. I don't want to give examples of others. I am sure you guys know what I mean. Thank you, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/d1755bec/attachment-0001.htm From falcon3166 at hotmail.com Mon Jul 18 15:36:35 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 18 Jul 2005 07:36:35 -0600 Subject: [Tutor] Who uses input()? [was Re: question on "input"] References: Message-ID: Danny, It sure did, though I wish there was an easier way of coding it than int(raw_input())! Any ideas would gladly be appreciated. By the way, is there any code floating out there that can show how many possible mixtures there are, e.g. for x0, x1, x2, x3, and a0, a1, a2, and a3 for example. If there is, show me it, please. I'm getting confused writing my MasterMind and don't want to screw up bad, e.g. repeat the same answer in a different way. Thanks, Nathan Pinno. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Terry Reedy" ; Sent: Monday, July 18, 2005 2:14 AM Subject: Re: [Tutor] Who uses input()? [was Re: question on "input"] > > > On Mon, 18 Jul 2005, Nathan Pinno wrote: > >> I find it easier to remember and faster to code than int(raw_input()). >> The faster I can code a program, the better in my opinion. So what if it >> has a few bugs, I fix them gradually. > > Hi Nathan > > You're right, just as long as we're writing programs that are only meant > to be used by ourselves, and as long as we're sure that it's not talking > to the outside world. The driving issue behind getting paranoid is this: > it's getting much easier to write programs that we think might be just for > ourselves, but which become useful for others. > > And as soon as we write programs that other people are going to use, we > really do have to play by a different set of rules than just ease of > programming. Some folks were casual about eval(), and look what happened > to them: > > http://gulftech.org/?node=research&article_id=00088-07022005 > > They should have known better. > > This problem is not exclusive to programmers in PHP: programmers in > Python make the same kind of mistakes. As a concrete example, take a look > at the comments about the deprecated "SimpleCookie" and "SerialCookie" > functions: > > http://www.python.org/doc/lib/module-Cookie.html > > Again, they should have known better. And we should know better. > > So we do have a responsibility to state up front that using 'eval' (or > things that call 'eval' for us) is convenient, but it's not safe. That's > why we bug about it every so often. > > > Hope this helps! > > From falcon3166 at hotmail.com Mon Jul 18 15:40:49 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 18 Jul 2005 07:40:49 -0600 Subject: [Tutor] shape_calc.py References: Message-ID: Raj, Shape_calc is a calculator for finding information about shapes, e.g. perimeter, area, and so forth. HTH (Hope This Helps), Nathan Pinno ----- Original Message ----- From: Raj Moodley To: falcon3166 at hotmail.com Sent: Monday, July 18, 2005 2:54 AM Subject: shape_calc.py Hi Nathan, wanted to find out what is shape_calc.py about? Am a newbie. Kind regards Raj Moodley -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/7ff3f286/attachment.htm From albertito_g at hotmail.com Mon Jul 18 15:41:44 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 18 Jul 2005 13:41:44 +0000 Subject: [Tutor] Hy, I'm a n00b to Python, have some questions In-Reply-To: Message-ID: Hey Alex First of all welcome I've been programming in Python for almost 1 year now and I think I can answer two of your questions >1. Is there any decent forum were people are talking in python ? You found one of them, here you have people willing to help each others at no cost. Send an email with your problem and someone here will answer >2. what about speed ? (any beginners question I suppose). Is it something >to >be concerned about ? Does anyone know how it compares to PHP ? (for Java I >allready know) I have no experience in web Python but I do have experience with PHP, JavaScript and ASP.NET and I have to tell you: you can't compare PHP with JavaScript, PHP is server-side and JavaScript is Client-side so the speed is irrelevant because they are two different things. You can compare PHP with ASP. About Python I'm not sure if this is a server or client-side. This is the first thing I would ask. >3. I want any usefull resources you can provide me with You may want to invest in some books. Try searching in Amazon. I have one very practical called Python: Developing Applicattions In fact this is a database book, but the aim is Python on web pages with databases The autor is Sonu Mangla Best Regards Alberto >From: Alex Nedelcu >Reply-To: Alex Nedelcu >To: tutor at python.org >Subject: [Tutor] Hy, I'm a n00b to Python, have some questions >Date: Mon, 18 Jul 2005 16:17:11 +0300 > >Hy all, > >I am a Java/PHP programmer. >I read the tutorial and I like the language. I am more interested in the >web >capabilities of the platform (CPython). > >I have some questions I'd like to ask you guys: > >3. I want any usefull resources you can provide me with >4. What's the hottest web framework right now that does not require an >application server (meaning that it runs on fastcgi) > >Also, why is www.python.org so ugly :) ? If I'd >like >to point others to learn Python I would need a site that markets Python >through eye-candy case studies, not some boring old site :). Just joking. I >don't want to give examples of others. I am sure you guys know what I mean. > >Thank you, >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From albertito_g at hotmail.com Mon Jul 18 15:54:45 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 18 Jul 2005 13:54:45 +0000 Subject: [Tutor] Scrolling multilistbox help Message-ID: Hey tutors I'm using the Multilistbox class and I noticed that it only handles the mouse scroll and the scrollbar to go down or up.I succesfully implemented the sort function that came with the class I also added code to handle the up and down arrow keys and it goes down all right but only select the item and it doesn't scroll down or up How can make it go up or down? I'm sendind the class here: class MultiListbox(Frame): fila=0 sortedBy=-1 def __init__(self, master, lists): Frame.__init__(self, master) self.lists = [] for l,w,a in lists: frame = Frame(self,background="red"); frame.pack(side=LEFT, expand=YES, fill=BOTH) Button(frame,background="red",foreground="white",font="Verdana 8 bold",text=l, borderwidth=1, relief=RAISED,command=lambda a=a: self._sortBy(a)).pack(fill=X) lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0, relief=FLAT, exportselection=FALSE) lb.pack(expand=YES, fill=BOTH) self.lists.append(lb) lb.bind('', lambda e, s=self: s._select(e.y)) lb.bind('', lambda e, s=self: s._devolverfila(e.y)) lb.bind('', lambda e, s=self: s._devolverfila(e.y)) lb.bind('', lambda e, s=self: s._select(e.y)) lb.bind('', lambda s: _select1()) lb.bind('', lambda s: _select2()) lb.bind('', lambda e: 'break') lb.bind('', lambda e, s=self: s._b2motion(e.x, e.y)) lb.bind('', lambda e, s=self: s._button2(e.x, e.y)) frame = Frame(self,background="red"); frame.pack(side=LEFT, fill=Y) Label(frame,background="red",foreground="white",font="Verdana 8 bold", borderwidth=1, relief=RAISED).pack(fill=X) sb = Scrollbar(frame,background="red", orient=VERTICAL, command=self._scroll) sb.pack(expand=YES, fill=Y) self.lists[0]['yscrollcommand']=sb.set def _sortBy(self, column): """ Sort by a given column. """ if column == self.sortedBy: direction = -1 * self.direction else: direction = 1 elements = self.get(0, END) self.delete(0, END) elements.sort(lambda x, y: self._sortAssist(column, direction, x, y)) self.insert(END, *elements) self.sortedBy = column self.direction = direction def _sortAssist(self, column, direction, x, y): if column!=0: c = cmp(x[column], y[column]) if c: return direction * c else: return direction * cmp(x, y) else: c = cmp(int(x[column]), int(y[column])) if c: return direction * c else: return direction * cmp(x, y) def _select(self, y): row = self.lists[0].nearest(y) self.selection_clear(0, END) self.selection_set(row) self.fila=row return 'break' def _devolverfila(self, y): row = self.lists[0].nearest(y) self.selection_clear(0, END) self.selection_set(row) self.fila=row def _select1(self): if self.fila==self.size()-1: pass else: self.selection_clear(0, END) self.selection_set(self.fila+1) self.fila+=1 self._scroll() return 'break' def _select2(self): if self.fila==0: pass else: self.selection_clear(0, END) self.selection_set(self.fila-1) self.fila-=1 return 'break' def _button2(self, x, y): for l in self.lists: l.scan_mark(x, y) return 'break' def _b2motion(self, x, y): for l in self.lists: l.scan_dragto(x, y) return 'break' def _scroll(self, *args): for l in self.lists: apply(l.yview, args) def curselection(self): return self.lists[0].curselection() def delete(self, first, last=None): for l in self.lists: l.delete(first, last) def get(self, first, last=None): result = [] for l in self.lists: result.append(l.get(first,last)) if last: return apply(map, [None] + result) return result def index(self, index): self.lists[0].index(index) def insert(self, index, *elements): for e in elements: i = 0 for l in self.lists: l.insert(index, e[i]) i = i + 1 def size(self): return self.lists[0].size() def see(self, index): for l in self.lists: l.see(index) def selection_anchor(self, index): for l in self.lists: l.selection_anchor(index) def selection_clear(self, first, last=None): for l in self.lists: l.selection_clear(first, last) def selection_includes(self, index): return self.lists[0].selection_includes(index) def selection_set(self, first, last=None): for l in self.lists: l.selection_set(first, last) THanks in advanced Alberto From kent37 at tds.net Mon Jul 18 16:01:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Jul 2005 10:01:26 -0400 Subject: [Tutor] Parsing problem In-Reply-To: References: Message-ID: <42DBB636.5050906@tds.net> Liam Clarke wrote: > What I need to do, is to turn this into a data structure, and I think > this relates to XML in a way. Basically, I want to parse the above (I > assume I'll be counting braces to find where I am) so that a country > object called ENG has a dictionary called ai, which points to lists, > integers, strings etc. and so forth. > > If anyone has any links to any (simple) examples of XML parsing or > similar which could give me pointers as to how to go about this, it'd be > much appreciated. Take a look at pyparsing, I think it is the easiest Python parsing package. http://pyparsing.sourceforge.net/ Kent From alan.gauld at freenet.co.uk Mon Jul 18 16:05:30 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 18 Jul 2005 15:05:30 +0100 Subject: [Tutor] ListBox in Tkinter References: <42DB934B.7090700@post.cz> Message-ID: <00be01c58ba1$c3bc4be0$77cc8651@xp> > I would like to ask if it is possible to create such a listbox > (attached) in TKinter itself or must have pmw ot tix...or ... PMW is written in Tkinter so yes, you could do it yourself but it is not a native widget. Using PMW would be much easier! Alan G. From alan.gauld at freenet.co.uk Mon Jul 18 16:17:26 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 18 Jul 2005 15:17:26 +0100 Subject: [Tutor] Hy, I'm a n00b to Python, have some questions References: Message-ID: <00d401c58ba3$6f092e90$77cc8651@xp> > I am a Java/PHP programmer. Sorry to hear it ;-) > I read the tutorial and I like the language. I am more interested > in the web capabilities of the platform (CPython). For serious web work with python look at Zope. http://www.zope.org > 1. Is there any decent forum were people are talking in python ? Lots, look in the communities page for mailing lists etc. There is a wiki too. And of course comp.lang.python on newnet. > 2. what about speed ? > Is it something to be concerned about ? > Does anyone know how it compares to PHP ? > (for Java I allready know) The above set of questions are self contradictory. If you know about Java that means you know that Python is sometimes faster than Java and sometimes slower depending on what you are doing, how you build it etc. ( The same applies to almost any language including assembler - badly written assembler can be much worse than well written python utilising maoinly C libraries...) In practice almost any programming language will be "fast enough" for most purposes. IF OTOH you want to build a killer web site taking millions of hits per day you may want to look elsewhere (but it wouldn't be PHP or Java either!) or be prepared to spend a fortune on hardware... And probably both. > 3. I want any usefull resources you can provide me with Google... > 4. What's the hottest web framework right now that > does not require an application server (meaning that > it runs on fastcgi) Why constrain the solution? If an app server can run fast and small why not use one? Popular Python web platforms exist, they are nearly all freeware so try them and see what suits. Zope is the battleship, CherryPy(sp?) the lightweight with vanilla CGI etc around in various forms. > Also, why is www.python.org so ugly :) ? Dunno, its always been ugly since I started with Python in 1997 or so... HTH, Alan G. From andre.roberge at gmail.com Mon Jul 18 17:37:38 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Mon, 18 Jul 2005 12:37:38 -0300 Subject: [Tutor] Hy, I'm a n00b to Python, have some questions In-Reply-To: References: Message-ID: Alex Nedelcu wrote: [snip] > > Also, why is www.python.org so ugly :) ? If I'd > like to point others to learn Python I would need a site that markets > Python through eye-candy case studies, not some boring old site :). Just > joking. I don't want to give examples of others. I am sure you guys know > what I mean. > Well, joke or not, a new draft web site was shown at the recent Europython conference. I looked for it ... but my google skills didn't help me. (Tim Parkin at http://www.pollenation.net/ is the one that showed it.) Be prepared to see something nice :-) Andr? From geon at post.cz Mon Jul 18 17:54:34 2005 From: geon at post.cz (geon) Date: Mon, 18 Jul 2005 17:54:34 +0200 Subject: [Tutor] ListBox in Tkinter In-Reply-To: <00be01c58ba1$c3bc4be0$77cc8651@xp> References: <42DB934B.7090700@post.cz> <00be01c58ba1$c3bc4be0$77cc8651@xp> Message-ID: <42DBD0BA.8050103@post.cz> Alan G napsal(a): >> I would like to ask if it is possible to create such a listbox >> (attached) in TKinter itself or must have pmw ot tix...or ... > > > PMW is written in Tkinter so yes, you could do it yourself but it is > not a native widget. Using PMW would be much easier! > I have just found this: http://effbot.org/tkinterbook/optionmenu.htm - that is nearly what I needed , just another design. I think there are even other new widgets in new Tk/Tcl compared to the http://www.pythonware.com/library/tkinter/introduction/, but undocumented yet. Or poorly or only in original Tk documentation..... -- geon Vyj?mka je pravidlo. Rekurzivn?. From falcon3166 at hotmail.com Mon Jul 18 18:05:32 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 18 Jul 2005 10:05:32 -0600 Subject: [Tutor] shape_calc.py References: Message-ID: Raj, My original interest was for school, now I use it to develop games and apps. I work at McDonalds Restaurant as Crew. I have developed another app called mini_calc and a game called Guess the Number; and was working on Giant Calculator, but gave up on it. I am also working on a MasterMind-like game, but it giving me headaches :). Nathan Pinno. P.S. Enjoy the shape_calc. You can find Mini_calc and Guess the Number on my site at this address: http://www.npinnowebsite.ca/download.htm. ----- Original Message ----- From: Raj Moodley To: 'Nathan Pinno' Sent: Monday, July 18, 2005 9:56 AM Subject: RE: shape_calc.py Hi Nathan, thanks for the email, please send it to me, would like to improve my understanding. What do u do? What's your interest in Python? Have you developed any other apps using Python? Kind regards Raj Moodley ---------------------------------------------------------------------------- From: Nathan Pinno [mailto:falcon3166 at hotmail.com] Sent: 18 July 2005 03:41 PM To: Raj Moodley Cc: tutor at python.org Subject: Re: shape_calc.py Raj, Shape_calc is a calculator for finding information about shapes, e.g. perimeter, area, and so forth. HTH (Hope This Helps), Nathan Pinno ----- Original Message ----- From: Raj Moodley To: falcon3166 at hotmail.com Sent: Monday, July 18, 2005 2:54 AM Subject: shape_calc.py Hi Nathan, wanted to find out what is shape_calc.py about? Am a newbie. Kind regards Raj Moodley -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/388be1d5/attachment.htm From bill at celestial.net Mon Jul 18 18:55:26 2005 From: bill at celestial.net (Bill Campbell) Date: Mon, 18 Jul 2005 09:55:26 -0700 Subject: [Tutor] Performance difference, ``in'' vs ``has_key()'' In-Reply-To: References: <20050717181803.GB33691@alexis.mi.celestial.com> Message-ID: <20050718165526.GC32754@alexis.mi.celestial.com> On Sun, Jul 17, 2005, Danny Yoo wrote: >> A related question is where's the trade-off between using ``in'' with a >> list, and a dictionary? I presume that using it with small hashes will >> be faster than dictionries since it doesn't have to calculate the >> hashes. > >Hi Bill, > >Scanning for an elements in a list is a "linear" operation, in the sense >that the time it takes to search is proportional to the size of the list. >(Big list == big search time.) I just noticed that I said it backwards in my first post, ``using it with small hashes'' should have been ``using it with small lists'' (and my perl background leaks out referring to dictionaries as hashes :-). ... >This doesn't mean that dictionaries are always faster than lists: as you >know, calculating hash values can take time. But the cost of hashing is >usually negligible, since many of Python primitive data types (like >strings) automatically cache their hash values too! This would say that it's better to create the dictionary with string keys rather than tuples, but that seems pretty obvious in any case. The problem I'm working on involves going through a large list of invoices that are now zero balance, to purge those before a certain date that have no payment applications after that date. I have a dictionary of zero- balance invoices containing invoice objects, and each invoice object contains a list of invoice keys applied to it. This internal list may well contain keys that refer to invoices that are either non-zero or have a date after the cutoff date. # begin code snippet global invoices # dictionary of all zero balance invoices with date <= cutoff deleted = True while deleted: deleted = False keys = invoices.keys() for key in keys: # use try/except since the instance may be deleted try: invoice = invoices[keys] except KeyError: continue for appKey in invoice.appKeys: if not appKey in invoices: deleted = True del invoices[key] # this invoice can't be purged for appKey in invice.appKeys: try: del invoices[appKey] except KeyError: pass # finish processing invoices ... >A good book in algorithms will almost always cover the performance >characteristics of those two strategies; there are also a lot of good >resources on the web about them. NIST has two articles on those two: > > http://www.nist.gov/dads/HTML/linearSearch.html > http://www.nist.gov/dads/HTML/hashtab.html Thanks for the references (occassionaly there's something that government does that's actually useful :-). Bill -- INTERNET: bill at Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ When the customer has beaten upon you long enough, give him what he asks for, instead of what he needs. This is very strong medicine, and is normally only required once. -- The Consultant's Curse: From falcon3166 at hotmail.com Mon Jul 18 19:00:57 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 18 Jul 2005 11:00:57 -0600 Subject: [Tutor] Which is safer and easier to code, raw_input or int(raw_input))? Message-ID: Hi all, The subject line says it all. What's the answer? Let's let everyone talk about this. Nathan Pinno. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/d7625fb0/attachment-0001.htm From cpu.crazy at gmail.com Mon Jul 18 19:38:07 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Mon, 18 Jul 2005 11:38:07 -0600 Subject: [Tutor] How do I add an argument too... Message-ID: <42DBE8FF.7030600@gmail.com> How do I add an argument too my program (with sys.argv) so that at a console I can type: python foo.py -info or python foo.py open /home/joe/foo.txt Thanks, Joe From falcon3166 at hotmail.com Mon Jul 18 19:48:57 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Mon, 18 Jul 2005 11:48:57 -0600 Subject: [Tutor] Which is safer and easier to code, raw_input or int(raw_input))? References: <005301c58bc0$4cec1850$aa0ca8c0@luke> Message-ID: Luke and all, Anyone interested in helping me code that MasterMind-like game? I sure could use the help. Right now I'm taking time to write a program that will automatically show various combos (eg a0 and x3) so that I can figure out all the various combos, so that I don't miss any. Nathan Pinno ----- Original Message ----- From: luke To: Nathan Pinno Sent: Monday, July 18, 2005 11:44 AM Subject: Re: [Tutor] Which is safer and easier to code,raw_input or int(raw_input))? tmp = raw_input("hello, enter a number: ") try: tmp = int(tmp) except ValueError: print "sorry that wasn't a number" ----- Original Message ----- From: Nathan Pinno To: tutor at python.org Sent: Monday, July 18, 2005 12:00 PM Subject: [Tutor] Which is safer and easier to code,raw_input or int(raw_input))? Hi all, The subject line says it all. What's the answer? Let's let everyone talk about this. Nathan Pinno. -------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/1de00ff5/attachment.htm From bvande at po-box.mcgill.ca Mon Jul 18 19:54:22 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 18 Jul 2005 13:54:22 -0400 Subject: [Tutor] Who uses input()? [was Re: question on "input"] In-Reply-To: References: Message-ID: <42DBECCE.5060600@po-box.mcgill.ca> Nathan Pinno said unto the world upon 2005-07-18 09:36: > Danny, > > It sure did, though I wish there was an easier way of coding it than > int(raw_input())! Any ideas would gladly be appreciated. > Thanks, > Nathan Pinno. Hi Nathan, If you find it irritating to type int(raw_input()), just wrap it all into a function. The minimal thing would be: >>> def get_int(prompt): return int(raw_input(prompt)) But, if you are doing that, might as well make the function do a bit more: >>> def get_int(prompt): if not prompt.endswith('\n'): prompt += '\n' while True: try: temp = raw_input(prompt) return int(temp) except ValueError: print "'%s' is not an integer. Please try again.\n" %temp >>> a = get_int('I wanna number!') I wanna number! OK, one. 'OK, one.' is not an integer. Please try again. I wanna number! 5 >>> a 5 >>> If you make such a function, test it well, make it general, etc., then you can put it into your own user_input module and never have to write either int(raw_input) or input checking code again. (I've done something like this, with extra things like making sure prompt is an appropriate type of object, etc. Notice what happens as it is now if you do get_int(757575).) HTH, Brian vdB From jeff.maitland at gmail.com Mon Jul 18 20:02:35 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Mon, 18 Jul 2005 14:02:35 -0400 Subject: [Tutor] How do I add an argument too... In-Reply-To: <42DBE8FF.7030600@gmail.com> References: <42DBE8FF.7030600@gmail.com> Message-ID: <6829832e0507181102158731f5@mail.gmail.com> Well I use the getopt module. so in my foo.py it would be something like. import getopt try: opts, args = getopt.getopt(sys.argv[1:], "U:u:P:p:H:h:?", ["Username=", "username=", "Password=", "password=", "Help=","help="]) except getopt.GetoptError: print :nothing specila just an error" sys.exit(1) for o, a in opts: if o in ("-U", "-u", "--Username", "--username"): username = a if o in ("-P", "-p", "--Password", "--password"): password = a if o in ("-H", "-h","--Help", "--help","?"): print "foo help" Hope the example helps. Jeff From benvinger at yahoo.co.uk Mon Jul 18 20:06:11 2005 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Mon, 18 Jul 2005 19:06:11 +0100 (BST) Subject: [Tutor] Hy, I'm a n00b to Python, have some questions In-Reply-To: Message-ID: <20050718180611.47369.qmail@web25805.mail.ukl.yahoo.com> --- Alex Nedelcu wrote: > 4. What's the hottest web framework right now that > does not require an > application server (meaning that it runs on fastcgi) Take a look at Myghty - it seems pretty good - it is a Python rewrite of Perl::Mason (which Amazon.com is based on). You can run it through mod_python which I believe performs better than fastcgi. ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From rimbaudmiller at yahoo.com Mon Jul 18 20:26:19 2005 From: rimbaudmiller at yahoo.com (David Jimenez) Date: Mon, 18 Jul 2005 11:26:19 -0700 (PDT) Subject: [Tutor] cPickle.load() Message-ID: <20050718182619.45945.qmail@web53702.mail.yahoo.com> hello everybody, I am trying to learn to use Python. Currently, I am reading Michael Dawson's "Python Programming for the Absolute Beginner." Right now, I am having the following problem: I try to read all the pickles in a file, but keep on getting the same error: EOFError. This is what the code looks like: import cPickle, shelve print "Pickling lists." variety=["sweet","hot","dill"] shape=["whole","spear","chip"] brand=["Claussen","Heinz","Vlassic"] pickle_file=open("pickles1.dat","w") cPickle.dump(variety,pickle_file) cPickle.dump(shape,pickle_file) cPickle.dump(brand,pickle_file) pickle_file.close() print "\nUnpickling lists." pickle_file=open("pickles1.dat","rb") for i in pickle_file: i=cPickle.load(pickle_file) print i pickle_file.close() This is what I keep on getting: Pickling lists. Unpickling lists. Traceback (most recent call last): File "/Users/davidjimenez/Documents/trypickle", line 20, in -toplevel- i=cPickle.load(pickle_file) EOFError Thank you, David Jimenez __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon Jul 18 20:45:43 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 18 Jul 2005 11:45:43 -0700 (PDT) Subject: [Tutor] cPickle.load() In-Reply-To: <20050718182619.45945.qmail@web53702.mail.yahoo.com> Message-ID: On Mon, 18 Jul 2005, David Jimenez wrote: > I am trying to learn to use Python. Currently, I am > reading Michael Dawson's "Python Programming for the > Absolute Beginner." Right now, I am having the > following problem: I try to read all the pickles in a > file, but keep on getting the same error: EOFError. Hi David, A principle of symmetry is being violated here. *grin* That is, take a look at the way the pickle file is being opened in write mode: pickle_file=open("pickles1.dat","w") and then take a look at how it's being opened in read mode: pickle_file=open("pickles1.dat","rb") In the read case, I see that you're reading from the file in binary mode. This is fine. But you may need to do the same for write mode, because it's very possible for your platform to do some newline translation at write-time. Let's look at the code a little more. ##### for i in pickle_file: i=cPickle.load(pickle_file) print i ###### This shouldn't work, because using a loop across a file should only be done in text mode if we're interested in the lines of a file. But we definitely don't want to treat the pickle_file here as a list of lines. What you probably want to do instead is simply: ###### i = cPickle.load(pickle_file) print i i = cPickle.load(pickle_file) print i i = cPickle.load(pickle_file) print i ###### This looks slightly abominable, since it's not generalizing for an arbitrary number of objects. I've hardcoded this to assuming there are three pickles in the file, and that's silly. The issue is that we don't know offhand how many times we can unpickle before we hit the end of the file. One way to fix this is to pickle the number of elements up front, as the first pickled object. That way, when we're unpickling, we can do something like this: ###### number_of_pickles = cPickle.load(pickle_file) for n in range(number_of_pickles): p = cPickle.load(pickle_file) print p ###### An alternatively easier approach is to include all of the pickle sublists in a larger containing list, so that you can unpickle the whole jar at once. I hope this helps! From nephish at xit.net Mon Jul 18 21:13:41 2005 From: nephish at xit.net (nephish) Date: Mon, 18 Jul 2005 14:13:41 -0500 Subject: [Tutor] This should be easy Message-ID: <1121714021.6612.3.camel@localhost.localdomain> Hey there, i have a script that i am trying to use to add a record to a MySQL database. i keep getting a syntax error. this works cursor.execute("INSERT INTO Table ( numberone ) VALUES ( 'one');") but this does not cursor.execute("INSERT INTO Table ( numberone, numbertwo ) VALUES ( 'one','two');") what is getting scrambled here? the error i get is syntax error in MySQL query, check the documentation, blah blah blah thanks From albertito_g at hotmail.com Mon Jul 18 21:20:35 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 18 Jul 2005 19:20:35 +0000 Subject: [Tutor] Minesweeper the return Message-ID: Hi I now get stucked in the arguments of the buttons Here's what I've got: def crearbutton(self): for i in range(self.fil): for j in range(self.col): self.buttonmatrix[i][j]=Button(root,width=1,height=0,command=lambda: self.hello(i,j)) self.buttonmatrix[i][j].grid(row=i,column=j,sticky=N+S+W+E) def hello(self,f,c): self.buttonmatrix[f][c].configure(text="ddddd") I'm trying to create the buttons dinamically (that's not a problem) the problem is wherever I click the hello function returns the last button I created. I know that the problem is in the lambda part and that the variable i (the one I change the value within the for) but I don't how to fix it Any hints? Thanks in advanced Alberto From albertito_g at hotmail.com Mon Jul 18 21:36:54 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 18 Jul 2005 19:36:54 +0000 Subject: [Tutor] Scrolling multilistbox help Message-ID: Hey tutors I'm using the Multilistbox class and I noticed that it only handles the mouse scroll and the scrollbar to go down or up.I succesfully implemented the sort function that came with the class I also added code to handle the up and down arrow keys and it goes down all right but only select the item and it doesn't scroll down or up How can make it go up or down? I'm sendind the class here: class MultiListbox(Frame): fila=0 sortedBy=-1 def __init__(self, master, lists): Frame.__init__(self, master) self.lists = [] for l,w,a in lists: frame = Frame(self,background="red"); frame.pack(side=LEFT, expand=YES, fill=BOTH) Button(frame,background="red",foreground="white",font="Verdana 8 bold",text=l, borderwidth=1, relief=RAISED,command=lambda a=a: self._sortBy(a)).pack(fill=X) lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0, relief=FLAT, exportselection=FALSE) lb.pack(expand=YES, fill=BOTH) self.lists.append(lb) lb.bind('', lambda e, s=self: s._select(e.y)) lb.bind('', lambda e, s=self: s._devolverfila(e.y)) lb.bind('', lambda e, s=self: s._devolverfila(e.y)) lb.bind('', lambda e, s=self: s._select(e.y)) lb.bind('', lambda s: _select1()) lb.bind('', lambda s: _select2()) lb.bind('', lambda e: 'break') lb.bind('', lambda e, s=self: s._b2motion(e.x, e.y)) lb.bind('', lambda e, s=self: s._button2(e.x, e.y)) frame = Frame(self,background="red"); frame.pack(side=LEFT, fill=Y) Label(frame,background="red",foreground="white",font="Verdana 8 bold", borderwidth=1, relief=RAISED).pack(fill=X) sb = Scrollbar(frame,background="red", orient=VERTICAL, command=self._scroll) sb.pack(expand=YES, fill=Y) self.lists[0]['yscrollcommand']=sb.set def _sortBy(self, column): """ Sort by a given column. """ if column == self.sortedBy: direction = -1 * self.direction else: direction = 1 elements = self.get(0, END) self.delete(0, END) elements.sort(lambda x, y: self._sortAssist(column, direction, x, y)) self.insert(END, *elements) self.sortedBy = column self.direction = direction def _sortAssist(self, column, direction, x, y): if column!=0: c = cmp(x[column], y[column]) if c: return direction * c else: return direction * cmp(x, y) else: c = cmp(int(x[column]), int(y[column])) if c: return direction * c else: return direction * cmp(x, y) def _select(self, y): row = self.lists[0].nearest(y) self.selection_clear(0, END) self.selection_set(row) self.fila=row return 'break' def _devolverfila(self, y): row = self.lists[0].nearest(y) self.selection_clear(0, END) self.selection_set(row) self.fila=row def _select1(self): if self.fila==self.size()-1: pass else: self.selection_clear(0, END) self.selection_set(self.fila+1) self.fila+=1 self._scroll() return 'break' def _select2(self): if self.fila==0: pass else: self.selection_clear(0, END) self.selection_set(self.fila-1) self.fila-=1 return 'break' def _button2(self, x, y): for l in self.lists: l.scan_mark(x, y) return 'break' def _b2motion(self, x, y): for l in self.lists: l.scan_dragto(x, y) return 'break' def _scroll(self, *args): for l in self.lists: apply(l.yview, args) def curselection(self): return self.lists[0].curselection() def delete(self, first, last=None): for l in self.lists: l.delete(first, last) def get(self, first, last=None): result = [] for l in self.lists: result.append(l.get(first,last)) if last: return apply(map, [None] + result) return result def index(self, index): self.lists[0].index(index) def insert(self, index, *elements): for e in elements: i = 0 for l in self.lists: l.insert(index, e[i]) i = i + 1 def size(self): return self.lists[0].size() def see(self, index): for l in self.lists: l.see(index) def selection_anchor(self, index): for l in self.lists: l.selection_anchor(index) def selection_clear(self, first, last=None): for l in self.lists: l.selection_clear(first, last) def selection_includes(self, index): return self.lists[0].selection_includes(index) def selection_set(self, first, last=None): for l in self.lists: l.selection_set(first, last) THanks in advanced Alberto From ajikoe at gmail.com Mon Jul 18 21:50:35 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Mon, 18 Jul 2005 21:50:35 +0200 Subject: [Tutor] This should be easy In-Reply-To: <1121714021.6612.3.camel@localhost.localdomain> References: <1121714021.6612.3.camel@localhost.localdomain> Message-ID: the code looks ok for me, Can you post more specific, including the error ? pujo On 7/18/05, nephish wrote: > Hey there, > > i have a script that i am trying to use to add a record to a MySQL > database. > > i keep getting a syntax error. > > this works > cursor.execute("INSERT INTO Table ( numberone ) VALUES ( 'one');") > > but this does not > cursor.execute("INSERT INTO Table ( numberone, numbertwo ) VALUES > ( 'one','two');") > > what is getting scrambled here? > > the error i get is syntax error in MySQL query, check the documentation, > blah blah blah > > thanks > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cgw501 at york.ac.uk Mon Jul 18 22:00:25 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 18 Jul 2005 21:00:25 +0100 Subject: [Tutor] int uncallable Message-ID: Hi, This code: for line in satFile: lineListed = line.split() start = int(lineListed[5])-1 end = int(lineListed[6]) hitLength = end - start extra = len(lineListed[9]) total = hitLength + 2(extra) gives an error: Traceback (most recent call last): File "test2.py", line 29, in ? total = hitLength+ 2(extra) TypeError: 'int' object is not callable which confuses me. Why can't I call extra? Have I not called int objects when I define hitLength, and that works fine. Thanks, Chris From 3dbernard at gmail.com Mon Jul 18 22:00:38 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 18 Jul 2005 16:00:38 -0400 Subject: [Tutor] Creating MySQL table Message-ID: <61d0e2b405071813006d9606f@mail.gmail.com> Hello, How do I create a MySQL table in Python? Here is what I'm trying: import MySQLdb as sql def connect2db(): return sql.connect( blah blah blah ) oConnection = connect2db() oCursor = oConnection.cursor() sQuery = "CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\ 'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL AUTO_INCREMENT, 'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, PRIMARY KEY('ID') ) ENGINE = InnoDB" oCursor.execute( sQuery ) When I run that, I get this: Traceback (most recent call last): File "", line 1, in ? File "D:\Python24\Lib\site-packages\MySQLdb\cursors.py", line 137, in execute self.errorhandler(self, exc, value) File "D:\Python24\Lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''3DPipline'.'TB_MT_NAME' ( 'ID' INTERGER UNSIGNED CHARACTER SET latin1 COLLATE l' at line 1") Any pointer would be appreciated. Thanks Bernard From nephish at xit.net Mon Jul 18 22:02:38 2005 From: nephish at xit.net (nephish) Date: Mon, 18 Jul 2005 20:02:38 +0000 Subject: [Tutor] This should be easy Message-ID: <1121716958l.26274l.0l@texaspivot> ok here is the error i am getting. You have an error in your SQL syntax. Check the manual that corrosponds to your MySQL version for the right syntax near Name ) values ('one', 'two') thanks From albertito_g at hotmail.com Mon Jul 18 22:06:34 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 18 Jul 2005 20:06:34 +0000 Subject: [Tutor] This should be easy In-Reply-To: <1121716958l.26274l.0l@texaspivot> Message-ID: I think it would be better for us if you send us the entire line that's giving you problems along with the error its givin you so we can start somewhere Right now I don't know where to look at Best Regards Alberto >From: nephish >To: tutor at python.org >Subject: [Tutor] This should be easy >Date: Mon, 18 Jul 2005 20:02:38 +0000 > >ok here is the error i am getting. >You have an error in your SQL syntax. Check the manual that corrosponds >to your MySQL version for the right syntax near Name ) values ('one', >'two') > >thanks > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From kent37 at tds.net Mon Jul 18 22:10:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Jul 2005 16:10:59 -0400 Subject: [Tutor] int uncallable In-Reply-To: References: Message-ID: <42DC0CD3.5050600@tds.net> cgw501 at york.ac.uk wrote: > Hi, > > This code: > > for line in satFile: > lineListed = line.split() > start = int(lineListed[5])-1 > end = int(lineListed[6]) > hitLength = end - start > extra = len(lineListed[9]) > total = hitLength + 2(extra) You are trying to call 2 as a function - 2(extra). You can't do that. Maybe you mean 2*(extra) ?? Kent > > gives an error: > > Traceback (most recent call last): > File "test2.py", line 29, in ? > total = hitLength+ 2(extra) > TypeError: 'int' object is not callable > > which confuses me. Why can't I call extra? Have I not called int objects > when I define hitLength, and that works fine. > > Thanks, > > Chris > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From gordnjen at rogers.com Mon Jul 18 22:22:31 2005 From: gordnjen at rogers.com (gordnjen) Date: Mon, 18 Jul 2005 16:22:31 -0400 Subject: [Tutor] Forms Message-ID: <002001c58bd6$6d622d20$a471c545@JennineGord> HELP! This is my latest assignment: For this assignment, you will create a web script that lets the user explore RGB colours. On the first page the user sees, they should specify two RGB colours. When they submit this page, they should be presented with a range of colours in between the two. The intermediate colours will be calculated by your program. For example, if the user enters the colours red (100% red, 0% green, 0% blue) and white (100% red, 100% green, 100% blue), your program might output a page containing this: Your program must never output more than 150 total colours, no matter how many the user asks for. If the users asks for more, it should only output 150. You have to be careful about the spacing when outputting the RGB percentage values. You will have to convert the numbers to strings and concatenate them. For example, this statement will output part of the style attribute: print 'style="background-color: rgb(' + str(r) + '%' All of your XHTML (including generated XHTML) and CSS must be valid. 1. Create the query page that asks the user for the colours they want to view. 2. Create a web script that converts the values the user entered to integers, stores them in variables, and outputs them. 3. Modify the web script so it counts from 0 up to the number of steps they requested minus 1. So, if they ask for 5 steps, it outputs "0 1 2 3 4." 4. Modify the web script so it calculates and outputs the percentages of red for each step. Check these and make sure they're right: they start and end at the values specified by the user; there are the right number of steps; the steps are separated by the same amount. 5. Add in the calculation of the green and blue values and check those. 6. Use the calculated percentages to output the

s and make sure the colours look right. Make sure the generated XHTML is valid. 7. Add the checking for more than 150 steps. I have attached the two files I have so far for this. Please have a look and advise. Thanks! Jennine -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.9.0/50 - Release Date: 16/07/2005 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/1ca60b40/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 17147 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050718/1ca60b40/attachment-0001.jpeg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/1ca60b40/Secondone-0001.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/1ca60b40/Fifthone-0001.html From plc at med.unc.edu Mon Jul 18 22:25:53 2005 From: plc at med.unc.edu (Philip Carl) Date: Mon, 18 Jul 2005 16:25:53 -0400 Subject: [Tutor] Getting two files to print Message-ID: <42DC1051.6090303@med.unc.edu> I have no more hair to pull out, so I'm asking the group for help on a VERY simple question. I have two very similar text files to read-one with the final letters in the name 10%.txt and the other 20%.txt. I've written the following simple code to read these two files: # Program to read and print two text fiiles fileNameA = 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt' #text file one firstFile=open (fileNameA,'r') inFileLeftA = 1 #more file to read inLineA=[0] while inFileLeftA: inLineA = firstFile.readline() if (inLineA == ''): infileLeftA = 0 #if empty line end of first file else: print inLineA firstFile.close() fileNameB = 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt' #text file two secondFile=open (fileNameB,'r') inFileLeftB = 1 #more file to read inLineB=[0] while inFileLeftB: inLineB = secondFile.readline() if (inLineB == ''): infileLeftB = 0 #if empty line end of second file else: print inLineB secondFile.close() I realize that I probably ought to be able to code this more efficiently, but as a rank beginner I am less worried about efficiency than output. I can't seem to get BOTH files to print when run as presented, although when I split the program into two programs each file seems to print OK. As written here however, I can get the first but not the second textfile to print. What am I doing wrong?. Philip Carl Associate Professor of Pharmacology 1026A Mary Ellen Jones Bld. CB 7365 University of North Carolina Medical School Chapel Hill, NC 27599 Phone: 919-966-3544 FAX: 919-966-5640 From nephish at xit.net Mon Jul 18 22:32:55 2005 From: nephish at xit.net (nephish) Date: Mon, 18 Jul 2005 20:32:55 +0000 Subject: [Tutor] This should be easy In-Reply-To: (from albertito_g@hotmail.com on Mon Jul 18 15:06:34 2005) References: Message-ID: <1121718775l.26324l.0l@texaspivot> ok here is what i have, cursor.execute("INSERT INTO History (autoinc, Site Name) VALUES (888812, 'Test');") gives me this ''' _mysql_exceptions.ProgrammingError : (1064, "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name) VALUES (888812, 'Test')' at line 1") ''' the autoinc field isn't really an auto-increment field, its an int. That is left over from the migration from Access. there are other fields in the table but all can be null. this line works fine though cursor.execute("INSERT INTO History (autoinc) VALUES (888812);") this line does not cursor.execute("INSERT INTO History (Site Name) VALUES ('test');") can you not have spaces in a field name ? is the quotes gone awry? dont know what to do next. please help ! thanks On 07/18/2005 03:06:34 PM, Alberto Troiano wrote: > I think it would be better for us if you send us the entire line > that's giving you problems along with the error its givin you so we > can start somewhere > > Right now I don't know where to look at > > Best Regards > > Alberto > >> From: nephish >> To: tutor at python.org >> Subject: [Tutor] This should be easy >> Date: Mon, 18 Jul 2005 20:02:38 +0000 >> >> ok here is the error i am getting. >> You have an error in your SQL syntax. Check the manual that >> corrosponds >> to your MySQL version for the right syntax near Name ) values ('one', >> 'two') >> >> thanks >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > > Gaucho > > > From geon at post.cz Mon Jul 18 22:40:27 2005 From: geon at post.cz (geon) Date: Mon, 18 Jul 2005 22:40:27 +0200 Subject: [Tutor] replaying Message-ID: <42DC13BB.2000406@post.cz> Hi, Seems to me as very unuseful thing in this phorum, when I choose Replay to any message, the field "to whom or Receiver" is all the time not tutor at python.org but the original sender! Why? I can not understand that? It sould be prefferably posted back to mailing list IMHO. -- geon From albertito_g at hotmail.com Mon Jul 18 22:41:59 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Mon, 18 Jul 2005 20:41:59 +0000 Subject: [Tutor] This should be easy In-Reply-To: <1121718775l.26324l.0l@texaspivot> Message-ID: Hey Your problem is in the database I'm surprised how MySQL let you put a space in a field In MySQL you can't have spaces, as far as I know Try renaming the field by enteriig to the console and making the alter table sentence and put Site_Name instead of Site Name. Then make the query again and see what happens mysql> create table d(autoinc int(4) primary key,Site Name varchar(30)); ERROR 1064: You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name varchar(30))' This is the error I get from MySQL Server when I try to create a field with a space and check the solution: mysql> create table d(autoinc int(4) primary key,Site_Name varchar(30)); Query OK, 0 rows affected (0.14 sec) This should fix your problem. Best Regards to you Alberto >From: nephish >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] This should be easy >Date: Mon, 18 Jul 2005 20:32:55 +0000 > >ok here is what i have, >cursor.execute("INSERT INTO History (autoinc, Site Name) VALUES >(888812, 'Test');") > >gives me this >''' _mysql_exceptions.ProgrammingError : (1064, "You have an error in >your SQL syntax. Check the manual that corresponds to your MySQL >server version for the right syntax to use near 'Name) VALUES (888812, >'Test')' at line 1") ''' > >the autoinc field isn't really an auto-increment field, its an int. >That is left over from the migration from Access. > >there are other fields in the table but all can be null. > >this line works fine though >cursor.execute("INSERT INTO History (autoinc) VALUES (888812);") > >this line does not >cursor.execute("INSERT INTO History (Site Name) VALUES ('test');") > >can you not have spaces in a field name ? is the quotes gone awry? > >dont know what to do next. >please help ! > >thanks > > > > >On 07/18/2005 03:06:34 PM, Alberto Troiano wrote: > > I think it would be better for us if you send us the entire line > > that's giving you problems along with the error its givin you so we > > can start somewhere > > > > Right now I don't know where to look at > > > > Best Regards > > > > Alberto > > > >> From: nephish > >> To: tutor at python.org > >> Subject: [Tutor] This should be easy > >> Date: Mon, 18 Jul 2005 20:02:38 +0000 > >> > >> ok here is the error i am getting. > >> You have an error in your SQL syntax. Check the manual that > >> corrosponds > >> to your MySQL version for the right syntax near Name ) values ('one', > >> 'two') > >> > >> thanks > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > > > > > > Gaucho > > > > > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From gnumathetes at gmail.com Mon Jul 18 23:36:09 2005 From: gnumathetes at gmail.com (Don Parris) Date: Mon, 18 Jul 2005 17:36:09 -0400 Subject: [Tutor] Creating MySQL table In-Reply-To: <61d0e2b405071813006d9606f@mail.gmail.com> References: <61d0e2b405071813006d9606f@mail.gmail.com> Message-ID: <669261440507181436450c6f3a@mail.gmail.com> On 7/18/05, Bernard Lebel <3dbernard at gmail.com> wrote: > Hello, > > How do I create a MySQL table in Python? > > Here is what I'm trying: > > > import MySQLdb as sql > > def connect2db(): > return sql.connect( blah blah blah ) > > > oConnection = connect2db() > oCursor = oConnection.cursor() > > > sQuery = "CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\ > 'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci > NOT NULL AUTO_INCREMENT, > 'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, > PRIMARY KEY('ID') > ) > ENGINE = InnoDB" > > Looking above, I'm not sure why there's a "." after 3DPipeline. Also, the ";" should be placed after the last command before the closing parenthesis, not at the beginning. I have no idea about your use of the backslash. > When I run that, I get this: > > Traceback (most recent call last): > File "", line 1, in ? > File "D:\Python24\Lib\site-packages\MySQLdb\cursors.py", line 137, in execute > self.errorhandler(self, exc, value) > File "D:\Python24\Lib\site-packages\MySQLdb\connections.py", line > 33, in defaulterrorhandler > raise errorclass, errorvalue > _mysql_exceptions.ProgrammingError: (1064, "You have an error in your > SQL syntax; check the manual that corresponds to your MySQL server > version for the right syntax to use near ''3DPipline'.'TB_MT_NAME' ( > 'ID' INTERGER UNSIGNED CHARACTER SET latin1 COLLATE l' at line 1") > > This error message points to your SQL syntax. Notice that it wants you to check "your MySQL server version for the right syntax to use". That should alert you to the fact that your SQL syntax is incorrect. HTH, Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com Free software is like God's love - you can share it with anyone anywhere anytime! From benvinger at yahoo.co.uk Mon Jul 18 23:42:38 2005 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Mon, 18 Jul 2005 22:42:38 +0100 (BST) Subject: [Tutor] replaying In-Reply-To: <42DC13BB.2000406@post.cz> Message-ID: <20050718214238.3689.qmail@web25803.mail.ukl.yahoo.com> Mailman can be set up to reply to the forum, but people on this list prefer to live with pain! --- geon wrote: > Hi, > > Seems to me as very unuseful thing in this phorum, > when I choose Replay > to any message, the field "to whom or Receiver" is > all the time not > tutor at python.org but the original sender! Why? I can > not understand that? > > It sould be prefferably posted back to mailing list > IMHO. > > > -- > geon > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ___________________________________________________________ How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos http://uk.photos.yahoo.com From nephish at xit.net Mon Jul 18 23:59:45 2005 From: nephish at xit.net (nephish) Date: Mon, 18 Jul 2005 21:59:45 +0000 Subject: [Tutor] This should be easy In-Reply-To: (from albertito_g@hotmail.com on Mon Jul 18 15:41:59 2005) References: Message-ID: <1121723985l.27150l.0l@texaspivot> Hey! looks like that is what the problem was. i used the MySQL Migration toolkit to transfer all the records over from Access to MySQL. man, you really saved me a lot of time and frustration. should have written in about 6 hours ago thank you very much. On 07/18/2005 03:41:59 PM, Alberto Troiano wrote: > Hey > > Your problem is in the database > I'm surprised how MySQL let you put a space in a field > In MySQL you can't have spaces, as far as I know > Try renaming the field by enteriig to the console and making the > alter table sentence and put Site_Name instead of Site Name. Then > make the query again and see what happens > > mysql> create table d(autoinc int(4) primary key,Site Name > varchar(30)); > ERROR 1064: You have an error in your SQL syntax. Check the manual > that corresponds to your MySQL server version for the right syntax to > use near 'Name varchar(30))' > > This is the error I get from MySQL Server when I try to create a > field with a space and check the solution: > mysql> create table d(autoinc int(4) primary key,Site_Name > varchar(30)); > Query OK, 0 rows affected (0.14 sec) > > This should fix your problem. > > Best Regards to you > > Alberto > >> From: nephish >> To: Alberto Troiano >> CC: tutor at python.org >> Subject: Re: [Tutor] This should be easy >> Date: Mon, 18 Jul 2005 20:32:55 +0000 >> >> ok here is what i have, >> cursor.execute("INSERT INTO History (autoinc, Site Name) VALUES >> (888812, 'Test');") >> >> gives me this >> ''' _mysql_exceptions.ProgrammingError : (1064, "You have an error in >> your SQL syntax. Check the manual that corresponds to your MySQL >> server version for the right syntax to use near 'Name) VALUES >> (888812, >> 'Test')' at line 1") ''' >> >> the autoinc field isn't really an auto-increment field, its an int. >> That is left over from the migration from Access. >> >> there are other fields in the table but all can be null. >> >> this line works fine though >> cursor.execute("INSERT INTO History (autoinc) VALUES (888812);") >> >> this line does not >> cursor.execute("INSERT INTO History (Site Name) VALUES ('test');") >> >> can you not have spaces in a field name ? is the quotes gone awry? >> >> dont know what to do next. >> please help ! >> >> thanks >> >> >> >> >> On 07/18/2005 03:06:34 PM, Alberto Troiano wrote: >> > I think it would be better for us if you send us the entire line >> > that's giving you problems along with the error its givin you so we >> > can start somewhere >> > >> > Right now I don't know where to look at >> > >> > Best Regards >> > >> > Alberto >> > >> >> From: nephish >> >> To: tutor at python.org >> >> Subject: [Tutor] This should be easy >> >> Date: Mon, 18 Jul 2005 20:02:38 +0000 >> >> >> >> ok here is the error i am getting. >> >> You have an error in your SQL syntax. Check the manual that >> >> corrosponds >> >> to your MySQL version for the right syntax near Name ) values >> ('one', >> >> 'two') >> >> >> >> thanks >> >> >> >> _______________________________________________ >> >> Tutor maillist - Tutor at python.org >> >> http://mail.python.org/mailman/listinfo/tutor >> > >> > >> > Gaucho >> > >> > >> > >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > > Gaucho > > > From 3dbernard at gmail.com Tue Jul 19 00:15:42 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 18 Jul 2005 17:15:42 -0500 Subject: [Tutor] Creating MySQL table In-Reply-To: <669261440507181436450c6f3a@mail.gmail.com> References: <61d0e2b405071813006d9606f@mail.gmail.com> <669261440507181436450c6f3a@mail.gmail.com> Message-ID: <61d0e2b405071815156356777f@mail.gmail.com> See [Bernard] On 7/18/05, Don Parris wrote: > On 7/18/05, Bernard Lebel <3dbernard at gmail.com> wrote: > > Hello, > > > > How do I create a MySQL table in Python? > > > > Here is what I'm trying: > > > > > > import MySQLdb as sql > > > > def connect2db(): > > return sql.connect( blah blah blah ) > > > > > > oConnection = connect2db() > > oCursor = oConnection.cursor() > > > > > > sQuery = "CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\ > > 'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci > > NOT NULL AUTO_INCREMENT, > > 'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, > > PRIMARY KEY('ID') > > ) > > ENGINE = InnoDB" > > > > > Looking above, I'm not sure why there's a "." after 3DPipeline. Also, > the ";" should be placed after the last command before the closing > parenthesis, not at the beginning. I have no idea about your use of > the backslash. [Bernard] The backslash thing is a trick that you can use to lure Python, it acts like a line break in your code, and allows you to bypass the indentation. The dot is to separate the database from the table. Before the dot is the database. See later for the semi-colon. > > > > When I run that, I get this: > > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "D:\Python24\Lib\site-packages\MySQLdb\cursors.py", line 137, in execute > > self.errorhandler(self, exc, value) > > File "D:\Python24\Lib\site-packages\MySQLdb\connections.py", line > > 33, in defaulterrorhandler > > raise errorclass, errorvalue > > _mysql_exceptions.ProgrammingError: (1064, "You have an error in your > > SQL syntax; check the manual that corresponds to your MySQL server > > version for the right syntax to use near ''3DPipline'.'TB_MT_NAME' ( > > 'ID' INTERGER UNSIGNED CHARACTER SET latin1 COLLATE l' at line 1") > > > > > This error message points to your SQL syntax. Notice that it wants > you to check "your MySQL server version for the right syntax to use". > That should alert you to the fact that your SQL syntax is incorrect. > > HTH, > Don [Bernard] Well I kind of figured it was telling it's a syntax error. ;-) After trial and error for an hour or two, I managed to get it sorted. First, I noticed that in Python there is no need for a semi-colon terminator (even for SQL commands). Also, removing all quotes except the opening and closing one made the code work. The SQL book I am using uses DOS command line syntax, not Python, so I had to translate the examples into Python syntax. Cheers Bernard From gnumathetes at gmail.com Tue Jul 19 00:27:01 2005 From: gnumathetes at gmail.com (Don Parris) Date: Mon, 18 Jul 2005 18:27:01 -0400 Subject: [Tutor] Creating MySQL table In-Reply-To: <61d0e2b405071813006d9606f@mail.gmail.com> References: <61d0e2b405071813006d9606f@mail.gmail.com> Message-ID: <6692614405071815272fda29a9@mail.gmail.com> On 7/18/05, Bernard Lebel <3dbernard at gmail.com> wrote: > Hello, > > How do I create a MySQL table in Python? > > Here is what I'm trying: > > > import MySQLdb as sql > > def connect2db(): > return sql.connect( blah blah blah ) > > > oConnection = connect2db() > oCursor = oConnection.cursor() > > > sQuery = "CREATE TABLE '3DPipeline'.'TB_MT_NAME' (;\ > 'ID' INTEGER UNSIGNED CHARACTER SET latin1 COLLATE latin1_swedish_ci > NOT NULL AUTO_INCREMENT, > 'text' TINYTEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, > PRIMARY KEY('ID') > ) O.k., it looks like 3DPipeline is your database name, and TB_MT_NAME is your table name. Your single quotes, if needed at all, most likely need to look like: '3DPipeline.TB_MT_NAME'(\ fieldone key1 key2 key3\ fieldtwo key1 key2 key3\ fieldthree key1 key2 key3 ); If you're using the backslash for line continuation, you need to add the "\" at the end of each line in your SQL statement. Hope this is a bit more helpful. -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com Free software is like God's love - you can share it with anyone anywhere anytime! From bgailer at sbcglobal.net Mon Jul 18 21:30:53 2005 From: bgailer at sbcglobal.net (Bob Gailer) Date: Mon, 18 Jul 2005 12:30:53 -0700 Subject: [Tutor] ot, " pythonmonks In-Reply-To: References: Message-ID: <6.1.2.0.0.20050718122938.034645a8@pop.sbcglobal.yahoo.com> At 03:52 AM 7/14/2005, Johan Meskens CS3 jmcs3 wrote: >hello > >is there such a place as www.perlmonks.org for python ? My first and only visit to perlmonks leaves me puzzled. What is it for? All I see are posts and chats, nothing to help a newcomer grok the site. Bob Gailer phone 510 978 4454 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/35e59f47/attachment.htm From gnumathetes at gmail.com Tue Jul 19 00:33:43 2005 From: gnumathetes at gmail.com (Don Parris) Date: Mon, 18 Jul 2005 18:33:43 -0400 Subject: [Tutor] Creating MySQL table In-Reply-To: <61d0e2b405071815156356777f@mail.gmail.com> References: <61d0e2b405071813006d9606f@mail.gmail.com> <669261440507181436450c6f3a@mail.gmail.com> <61d0e2b405071815156356777f@mail.gmail.com> Message-ID: <66926144050718153310678aed@mail.gmail.com> On 7/18/05, Bernard Lebel <3dbernard at gmail.com> wrote: > See [Bernard] > > > [Bernard] Well I kind of figured it was telling it's a syntax error. ;-) > I didn't want to assume too much. ;) > After trial and error for an hour or two, I managed to get it sorted. > > First, I noticed that in Python there is no need for a semi-colon > terminator (even for SQL commands). > Also, removing all quotes except the opening and closing one made the code work. > That was where my last post was headed - and I left out the part about the semi-colons not being needed. I was looking at my own select queries. > The SQL book I am using uses DOS command line syntax, not Python, so I > had to translate the examples into Python syntax. > I got Python books. I can figure out the SQL stuff pretty easily - it's programming the front-end that twists my brain around. ;) Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com Free software is like God's love - you can share it with anyone anywhere anytime! From jfouhy at paradise.net.nz Tue Jul 19 00:30:31 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 19 Jul 2005 10:30:31 +1200 (NZST) Subject: [Tutor] Scrolling multilistbox help In-Reply-To: References: Message-ID: <1121725831.42dc2d87df253@www.paradise.net.nz> Quoting Alberto Troiano : > I'm using the Multilistbox class and I noticed that it only handles the > mouse scroll and the scrollbar to go down or up.I succesfully > implemented the sort function that came with the class > I also added code to handle the up and down arrow keys and it goes down > all right but only select the item and it doesn't scroll down or up > How can make it go up or down? I haven't actually tried your code, but this might be the problem here: > def _select1(self): > if self.fila==self.size()-1: > pass > else: > self.selection_clear(0, END) > self.selection_set(self.fila+1) > self.fila+=1 > self._scroll() > return 'break' > > def _scroll(self, *args): > for l in self.lists: > apply(l.yview, args) You call self._scroll with no arguments to make the selected index visible (I guess). But self._scroll just calls yview on each list..and yview with no arguments returns a tuple, but otherwise does nothing. Try replacing self._scroll with self.see --- possibly: self.see(self.fila). -- John. From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 00:51:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 18 Jul 2005 15:51:58 -0700 (PDT) Subject: [Tutor] replaying In-Reply-To: <42DC13BB.2000406@post.cz> Message-ID: On Mon, 18 Jul 2005, geon wrote: > Seems to me as very unuseful thing in this forum, when I choose Replay > to any message, the field "to whom or Receiver" is all the time not > tutor at python.org but the original sender! Why? I can not understand > that? [meta: mailing list admin stuff] Hi Geon, Yes, we've considered this before. It's actually not that difficult to enable this from the mailing list admin interface, so if we ever find the need to do this, I'll be happy to. However, there are significant downsides to enabling Reply-to munging: http://www.unicom.com/pw/reply-to-harmful.html I agree with most of those reasons, and so I won't enable Reply-to munging unless there's a real overriding reason that trumps the ones listed on that page. Hope that makes sense! From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 01:00:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 18 Jul 2005 16:00:02 -0700 (PDT) Subject: [Tutor] Forms In-Reply-To: <002001c58bd6$6d622d20$a471c545@JennineGord> Message-ID: Hello, > This is my latest assignment: [assignment cut] We should make this perfectly clear: we will not do your homework. > Please have a look and advise. If you're having a problem with Python programming, bring up the specific problem you're having, and we'll see what we can do to help clarify things for you. It is not that we don't want to help you: it's just that we will not do your work for you. What you've just done is write out the whole homework assignment, and asked the group: "What should I do?" Please understand that just dumping a homework assignment on the volunteers on this mailing list forum isn't nice --- it may not seem that way to you, but it's a bit demoralizing to us. See: http://www.catb.org/~esr/faqs/smart-questions.html as a rough guide to asking questions that people will be happy to answer. Good luck. From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 01:10:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 18 Jul 2005 16:10:51 -0700 (PDT) Subject: [Tutor] Minesweeper the return In-Reply-To: Message-ID: On Mon, 18 Jul 2005, Alberto Troiano wrote: > I'm trying to create the buttons dinamically (that's not a problem) the > problem is wherever I click the hello function returns the last button I > created. I know that the problem is in the lambda part and that the variable > i (the one I change the value within the for) but I don't how to fix it Hi Alberto, Ah, this one comes up a bit. *grin* Let's look at the code: ###### for i in range(self.fil): for j in range(self.col): self.buttonmatrix[i][j]=Button(root,width=1,height=0, command=lambda: self.hello(i,j)) ###### The issue is that all the dynamically generated functions are using the same 'i' and 'j' variables. The big issue is that, in Python, for-loops rebind the iterating variable name to different values, and that's what's causing the issue. Instead of using lambda directly, try something like this: ###### def make_hello(x, y): def new_hello_function(): self.hello(x, y) return new_hello_function for i in range(self.fil): for j in range(self.col): self.buttonmatrix[i][j]=Button(root,width=1,height=0, command=make_hello(i, j)) ###### There's some subtle lexical-binding stuff going on there, so if you'd like, we can talk about this more. If you're familiar with another programming language with lexical scope (like Scheme), we can talk about in terms of that language too. Hope this helps! From gordnjen at rogers.com Tue Jul 19 01:53:25 2005 From: gordnjen at rogers.com (gordnjen) Date: Mon, 18 Jul 2005 19:53:25 -0400 Subject: [Tutor] FW: Forms Message-ID: <008901c58bf3$e34aefa0$a471c545@JennineGord> Apparently, my last post was interpreted by some as "please do this assignment for me". By no means do I want this. What I would like, is for someone to look at my attached files and see if there is anything glaring they can see where I am going wrong. The error message that I get when I input values into the first page and click "Go" reads as follows: Script Error There was an error with your script and it didn't exit properly. This was its output: File "/home/jgates/public_html/Fifthone.py", line 12 print form int(["red1"].value),"%" ^ SyntaxError: invalid syntax The instructions I listed below were put there so that you could understand what exactly I was trying to do with these pages. Any help you could provide would be much appreciated. If you think I am out of line in asking the above, just ignore this post and I will get the drift. But any help would be a godsend!!! Thanks! Regards, Jennine -----Original Message----- From: gordnjen [mailto:gordnjen at rogers.com] Sent: July 18, 2005 4:23 PM To: 'tutor at python.org' Subject: Forms HELP! This is my latest assignment: For this assignment, you will create a web script that lets the user explore RGB colours. On the first page the user sees, they should specify two RGB colours. When they submit this page, they should be presented with a range of colours in between the two. The intermediate colours will be calculated by your program. For example, if the user enters the colours red (100% red, 0% green, 0% blue) and white (100% red, 100% green, 100% blue), your program might output a page containing this: Your program must never output more than 150 total colours, no matter how many the user asks for. If the users asks for more, it should only output 150. You have to be careful about the spacing when outputting the RGB percentage values. You will have to convert the numbers to strings and concatenate them. For example, this statement will output part of the style attribute: print 'style="background-color: rgb(' + str(r) + '%' All of your XHTML (including generated XHTML) and CSS must be valid. 1. Create the query page that asks the user for the colours they want to view. 2. Create a web script that converts the values the user entered to integers, stores them in variables, and outputs them. 3. Modify the web script so it counts from 0 up to the number of steps they requested minus 1. So, if they ask for 5 steps, it outputs "0 1 2 3 4." 4. Modify the web script so it calculates and outputs the percentages of red for each step. Check these and make sure they're right: they start and end at the values specified by the user; there are the right number of steps; the steps are separated by the same amount. 5. Add in the calculation of the green and blue values and check those. 6. Use the calculated percentages to output the
s and make sure the colours look right. Make sure the generated XHTML is valid. 7. Add the checking for more than 150 steps. I have attached the two files I have so far for this. Please have a look and advise. Thanks! Jennine -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.9.0/50 - Release Date: 16/07/2005 -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.9.0/50 - Release Date: 16/07/2005 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/366c9461/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 17147 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050718/366c9461/attachment-0001.jpeg -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/366c9461/Secondone-0001.html -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050718/366c9461/Fifthone-0001.html From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 03:03:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 18 Jul 2005 18:03:52 -0700 (PDT) Subject: [Tutor] FW: Forms In-Reply-To: <008901c58bf3$e34aefa0$a471c545@JennineGord> Message-ID: On Mon, 18 Jul 2005, gordnjen wrote: > There was an error with your script and it didn't exit properly. > > This was its output: > > File "/home/jgates/public_html/Fifthone.py", line 12 > > print form int(["red1"].value),"%" > > ^ > > SyntaxError: invalid syntax Hi Jennine, Ok, it looks like you're using the cgi.FieldStorage class and you're trying to look up the 'red1' value in the form. But it also looks like you have some int() stuff there that I'm not quite sure about yet. Is it ok if we strip that out for the moment, and simplify things to something smaller? (We can talk more about int() later.) ###### print form(["red1"].value),"%" ###### If you do this, you won't get a SyntaxError, although you'll probably get a different kind of error. *grin* So let's look at this a bit more. According to the documentation of the 'cgi' module, there's a : http://www.python.org/doc/lib/node467.html you can ask a form for its values by using getfirst(). So the code above would look like: ###### print form.getfirst('red1'), '%' ###### Try that and see if that works any better. From geon at post.cz Tue Jul 19 07:12:54 2005 From: geon at post.cz (geon) Date: Tue, 19 Jul 2005 07:12:54 +0200 Subject: [Tutor] replaying In-Reply-To: References: Message-ID: <42DC8BD6.4000304@post.cz> Danny Yoo napsal(a): >However, there are significant downsides to enabling Reply-to munging: > > http://www.unicom.com/pw/reply-to-harmful.html > >I agree with most of those reasons, and so I won't enable Reply-to munging >unless there's a real overriding reason that trumps the ones listed on >that page. > > Firtsly, sorry for my English. Then I must must admit I didnt understand all what is written in http://www.unicom.com/pw/reply-to-harmful.html and even I didnt read it attentively. Anyway the main reason IMHO why he decided to do so is having Elm (or even creating it?) which *easily* (I could say freedomly for "lector"=helper) supports both sending to mailing list and to original sender. I got tho some reason against: * I like to help. But I like to help all, All should have benefit from my replay. I know this from my own experience. Often, very often I browse the old messages and read what other wrote. Its also good when there are always the same questions.... My effort shouldnt die immendiately after sending my replay. The freedom of all is more that freedom of one. * My TB doesnt support it. And maybe even others mail clients.Its really wasting of time to change the adress all the time. I like to help, but if the was more of such a inconvieniencies I would give it up. My time is expensive :-) * There is no reason for questioner not to like to see my replay in mailing list, I think. Why would he do it? Why should he want me just for him? To be able to read your replay pls use easy english ;-) -- geon Vyj?mka je pravidlo. Rekurzivn?. From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 07:19:26 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 18 Jul 2005 22:19:26 -0700 (PDT) Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: On Mon, 18 Jul 2005, Liam Clarke wrote: > country = { > tag = ENG > ai = { > flags = { } > combat = { DAU FRA ORL PRO } > continent = { } > area = { } > region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" > "TagoSea" "WCAtlanticSea" } > war = 60 > ferocity = no > } > } [Long message ahead; skip if you're not interested.] Kent mentioned PyParsing, http://pyparsing.sourceforge.net/ which is a really excellent system. Here's a demo of what it can do, just so you have a better idea what pyparsing is capable of. (For the purposes of this demo, I'm doing 'import pyparsing', but in real usage, I'd probably use 'from pyparsing import ...' just to make things less verbose.) Let's say that we want to recognize a simpler subset of the data that you have there, something like: { fee fie foo fum } And let's imagine that we have a function parse() that can take a string like: ###### >>> testString = """ ... { fee fie foo fum } ... """ ###### This imaginary parse() function could turn that into something that looks like a Python value, like this: ###### >>> parse(testString) (["fee", "fie", "foo", "fum"]) ###### That's our goal; does this make sense so far? So how do we start? Instead of going at the big goal of doing: country = { fee fie foo fum } let's start small by teaching our system how to recognize the innermost parts, the small things like fee or foo. Let's start there: ###### >>> Symbol = pyparsing.Word(pyparsing.alphas) ###### We want a Symbol to be able to recognize a "Word" made up of alphabetic letters. Does this work? ###### >>> Symbol.parseString("fee") (['fee'], {}) ####### Symbol is now a thing that can parse a string, and return a list of results in a pyparsing.ParseResults object. Ok, if we can recognize Symbols, let's go for the jugular: { fee fie foo fum } Let's call this a Sequence. ###### >>> Sequence = "{" + pyparsing.ZeroOrMore(Symbol) + "}" ###### A Sequence is made up of zero or more Symbols. Wait, let's change that, for a moment, to "A Sequence is made up of zero or more Values." (You'll see why in a moment. *grin*) If we turn toward this strange way, then we need a definition for a Value: ###### >>> Value = Symbol ###### and now we can say that a Sequence is a bunch of Values: ###### >>> Sequence = "{" + pyparsing.ZeroOrMore(Value) + "}" ###### Let's try this out: ###### >>> Sequence.parseString('{ fee fie foo fum}') (['{', 'fee', 'fie', 'foo', 'fum', '}'], {}) ###### This is close, but it's not quite right: the problem is that we'd like to somehow group the results all together in a list, and without the braces. That is, we actually want to see: [['fee', 'fie', 'foo', 'fum']] in some form. (Remember, we want a list of a single result, and that result should be our Sequence.) How do we get this working? We have to tell pyparsing to "Group" the middle elements together in a collection, and to "suppress" the braces from the result. Here we go: ###### >>> Sequence = (pyparsing.Suppress("{") + ... pyparsing.Group(pyparsing.ZeroOrMore(Value)) + ... pyparsing.Suppress("}")) ###### Does this work? ###### >>> Sequence.parseString('{ fee fie foo fum}') ([(['fee', 'fie', 'foo', 'fum'], {})], {}) ###### That looks a little messy and more nested than expected. Actually, what's happening is that we're looking at that pyparsing.ParseResults object, so there's more nesting in the string representation than what's really there. We can use the ParseResults's asList() method to make it a little easier to see what the real result value looks like: ###### >>> Sequence.parseString('{ fee fie foo fum}').asList() [['fee', 'fie', 'foo', 'fum']] ###### That's better. Out of curiosity, wouldn't it be neat if we could parse out something like this? { fee fie {foo "fum"} } *cough* *cough* What we'd like to do is make Sequence itself a possible value. The problem is that then there's a little circularity involved: ### Illegal PyParsing pseudocode ### Value = Symbol | Sequence Sequence = (pyparsing.Suppress("{") + pyparsing.Group(pyparsing.ZeroOrMore(Value)) + pyparsing.Suppress("}")) ###### The problem is that Value can't be defined before Sequence is, and vice-versa. We break this problem by telling PyParsing "ok, the following rules will come up soon" and "forward" define them: ###### >>> Value = pyparsing.Forward() >>> Sequence = pyparsing.Forward() ###### and once we have these forward declarations, we can then reconnect them to their real definitions by using '<<'. (This looks bizarre, but it applies just to rules that are Forward()ed.) ###### Value << (Symbol | Sequence) Sequence << (pyparsing.Suppress("{") + pyparsing.Group(pyparsing.ZeroOrMore(Value)) + pyparsing.Suppress("}")) ###### Let's try it: ###### >>> Value.parseString(' { fee fie {foo fum} } ').asList() [['fee', 'fie', ['foo', 'fum']]] ###### Cool. Ok, that was a little artificial, but oh well. The idea is we now know how to say: A Value is either a Symbol or Sequence and A Sequence is a bunch of Values without getting into trouble with pyparsing, and that's important whenever we're dealing with things that have recursive structure... like: country = { tag = ENG ai = { flags = { } combat = { DAU FRA ORL PRO } continent = { } area = { } region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" "TagoSea" "WCAtlanticSea" } war = 60 ferocity = no } } Anyway, this is a really fast whirlwind tour of pyparsing, with some intentional glossing-over of hard stuff, just so you get a better idea of the core of parsing. Sorry if it went fast. *grin* If you have questions, please feel free to ask! From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 07:32:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 18 Jul 2005 22:32:35 -0700 (PDT) Subject: [Tutor] replaying In-Reply-To: <42DC8BD6.4000304@post.cz> Message-ID: > * There is no reason for questioner not to like to see my replay in > mailing list, I think. Why would he do it? Why should he want me just > for him? [meta: mailing list stuff. Not really Python-related[] Hi Geon, Yes, there is a good reason. Let us take a hypothetical situation. Let's say that there are two people, say person J and person D. And say that D wrote a slightly unfriendly reply on Tutor that didn't sit well, and person J rightfully responded back and wondered why D was so curt. It might be embarassing if the mailing list default was to have J's reply go directly to the Tutor list rather than to just D. Again, it might not, but who knows? If Reply-to munging was turned on by default, it would make such a mistake very likely. (And in the end, D might want to apologize to J; D was having a very busy day today. And it might be embarassing to have that automatically posted on Tutor too. Who knows?) We want to allow people to have the opportunity to easily respond in private, particularly for cases like this. All of this is purely hypothetical, of course. From cyresse at gmail.com Tue Jul 19 08:23:20 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 19 Jul 2005 18:23:20 +1200 Subject: [Tutor] Parsing problem In-Reply-To: References: Message-ID: Thanks guys, I daresay I will have a lot of questions regarding this, but at least I have a point to start digging and a better shovel! Cheers, Liam Clarke On 7/19/05, Danny Yoo wrote: > > > > On Mon, 18 Jul 2005, Liam Clarke wrote: > > > country = { > > tag = ENG > > ai = { > > flags = { } > > combat = { DAU FRA ORL PRO } > > continent = { } > > area = { } > > region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" > > "TagoSea" "WCAtlanticSea" } > > war = 60 > > ferocity = no > > } > > } > > [Long message ahead; skip if you're not interested.] > > > Kent mentioned PyParsing, > > http://pyparsing.sourceforge.net/ > > which is a really excellent system. Here's a demo of what it can do, just > so you have a better idea what pyparsing is capable of. > > (For the purposes of this demo, I'm doing 'import pyparsing', but in real > usage, I'd probably use 'from pyparsing import ...' just to make things > less verbose.) > > > Let's say that we want to recognize a simpler subset of the data that you > have there, something like: > > { fee fie foo fum } > > And let's imagine that we have a function parse() that can take a string > like: > > ###### > >>> testString = """ > ... { fee fie foo fum } > ... """ > ###### > > > This imaginary parse() function could turn that into something that looks > like a Python value, like this: > > ###### > >>> parse(testString) > (["fee", "fie", "foo", "fum"]) > ###### > > That's our goal; does this make sense so far? So how do we start? > > > > Instead of going at the big goal of doing: > > country = { fee fie foo fum } > > let's start small by teaching our system how to recognize the innermost > parts, the small things like fee or foo. Let's start there: > > ###### > >>> Symbol = pyparsing.Word(pyparsing.alphas) > ###### > > We want a Symbol to be able to recognize a "Word" made up of alphabetic > letters. Does this work? > > ###### > >>> Symbol.parseString("fee") > (['fee'], {}) > ####### > > Symbol is now a thing that can parse a string, and return a list of > results in a pyparsing.ParseResults object. > > > Ok, if we can recognize Symbols, let's go for the jugular: > > { fee fie foo fum } > > > Let's call this a Sequence. > > ###### > >>> Sequence = "{" + pyparsing.ZeroOrMore(Symbol) + "}" > ###### > > > A Sequence is made up of zero or more Symbols. > > > Wait, let's change that, for a moment, to "A Sequence is made up of zero > or more Values." (You'll see why in a moment. *grin*) > > > > If we turn toward this strange way, then we need a definition for a Value: > > ###### > >>> Value = Symbol > ###### > > and now we can say that a Sequence is a bunch of Values: > > ###### > >>> Sequence = "{" + pyparsing.ZeroOrMore(Value) + "}" > ###### > > > Let's try this out: > > ###### > >>> Sequence.parseString('{ fee fie foo fum}') > (['{', 'fee', 'fie', 'foo', 'fum', '}'], {}) > ###### > > > This is close, but it's not quite right: the problem is that we'd like to > somehow group the results all together in a list, and without the braces. > That is, we actually want to see: > > [['fee', 'fie', 'foo', 'fum']] > > in some form. (Remember, we want a list of a single result, and that > result should be our Sequence.) > > > How do we get this working? We have to tell pyparsing to "Group" the > middle elements together in a collection, and to "suppress" the braces > from the result. > > Here we go: > > ###### > >>> Sequence = (pyparsing.Suppress("{") + > ... pyparsing.Group(pyparsing.ZeroOrMore(Value)) + > ... pyparsing.Suppress("}")) > ###### > > Does this work? > > > ###### > >>> Sequence.parseString('{ fee fie foo fum}') > ([(['fee', 'fie', 'foo', 'fum'], {})], {}) > ###### > > > That looks a little messy and more nested than expected. > > > Actually, what's happening is that we're looking at that > pyparsing.ParseResults object, so there's more nesting in the string > representation than what's really there. We can use the ParseResults's > asList() method to make it a little easier to see what the real result > value looks like: > > ###### > >>> Sequence.parseString('{ fee fie foo fum}').asList() > [['fee', 'fie', 'foo', 'fum']] > ###### > > That's better. > > > > Out of curiosity, wouldn't it be neat if we could parse out something like > this? > > { fee fie {foo "fum"} } > > *cough* *cough* > > What we'd like to do is make Sequence itself a possible value. The > problem is that then there's a little circularity involved: > > > ### Illegal PyParsing pseudocode ### > Value = Symbol | Sequence > > Sequence = (pyparsing.Suppress("{") + > pyparsing.Group(pyparsing.ZeroOrMore(Value)) + > pyparsing.Suppress("}")) > ###### > > The problem is that Value can't be defined before Sequence is, and > vice-versa. We break this problem by telling PyParsing "ok, the following > rules will come up soon" and "forward" define them: > > ###### > >>> Value = pyparsing.Forward() > >>> Sequence = pyparsing.Forward() > ###### > > and once we have these forward declarations, we can then reconnect them to > their real definitions by using '<<'. (This looks bizarre, but it applies > just to rules that are Forward()ed.) > > ###### > Value << (Symbol | Sequence) > Sequence << (pyparsing.Suppress("{") + > pyparsing.Group(pyparsing.ZeroOrMore(Value)) + > pyparsing.Suppress("}")) > ###### > > > Let's try it: > > ###### > >>> Value.parseString(' { fee fie {foo fum} } ').asList() > [['fee', 'fie', ['foo', 'fum']]] > ###### > > > Cool. > > > Ok, that was a little artificial, but oh well. The idea is we now know > how to say: > > A Value is either a Symbol or Sequence > > and > > A Sequence is a bunch of Values > > without getting into trouble with pyparsing, and that's important whenever > we're dealing with things that have recursive structure... like: > > country = { > tag = ENG > ai = { > flags = { } > combat = { DAU FRA ORL PRO } > continent = { } > area = { } > region = { "British Isles" > "NorthSeaSea" > "ECAtlanticSea" > "NAtlanticSea" > "TagoSea" > "WCAtlanticSea" } > war = 60 > ferocity = no } > } > > Anyway, this is a really fast whirlwind tour of pyparsing, with some > intentional glossing-over of hard stuff, just so you get a better idea of > the core of parsing. Sorry if it went fast. *grin* > > > If you have questions, please feel free to ask! > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050719/0a4c6b6f/attachment-0001.htm From geon at post.cz Tue Jul 19 08:37:39 2005 From: geon at post.cz (geon) Date: Tue, 19 Jul 2005 08:37:39 +0200 Subject: [Tutor] OFFLIST Re: replaying In-Reply-To: <42DC9315.8000603@po-box.mcgill.ca> References: <42DC8BD6.4000304@post.cz> <42DC9315.8000603@po-box.mcgill.ca> Message-ID: <42DC9FB3.8060700@post.cz> Brian van den Broek napsal(a): >> * There is no reason for questioner not to like to see my replay in >> mailing list, I think. Why would he do it? Why should he want me just >> for him? > > > Sometimes I write privately. Sometimes people write me in private. > Most often in public, but sometimes people choose private. Like this > time. As Danny just wrote, this is not about Python, so I choose to > write a private email. > > I certainly have on other lists embarrassed :-[ myself by writing the > list when I meant to write a private email. That way, much > embarrassment and many people lose time. :-( > > The Tutor list way, if I get it wrong, little embarrassment and 2 > people loose time. :-| Sometimes , yes sometimes. The mailing list main mission should be to help all and not to support private messaging. In this case the statistics should come in. What is more often? To replay to the public or to the questioner? I would forgive some private messages in maling list if I could read well done answers to troubles I do need. In this system, that support private replays, most of quality answers fade away..... I might reapeted myself: the mailing should support collaboration in public, sharing the wisdom. Not just solving trouble of a single man, not substitue private chats. Of course, its all up to you, I open this thread only because it was so unusualy from all what I have seen up to now, that I just wanted to keep my habits..... Best wishes -- geon The Exlusion is Rule. P.S. Replay to All sends two emails, not just one to list, and that is also not what I would like to do. From tegmine at gmail.com Tue Jul 19 10:00:18 2005 From: tegmine at gmail.com (Luis N) Date: Tue, 19 Jul 2005 01:00:18 -0700 Subject: [Tutor] OT, Tcl & Python In-Reply-To: <001601c58a3d$5c67ecc0$2daa8851@xp> References: <77bfa81a05071601194319714@mail.gmail.com> <001601c58a3d$5c67ecc0$2daa8851@xp> Message-ID: <77bfa81a0507190100563caa84@mail.gmail.com> On 7/16/05, Alan G wrote: > > > I was wondering if someone knowledgeable of both Tcl and Python could > suggest whether it would > be a good or a bad idea to write a Python/Tk > application, with the motive to rewrite the application in > Tcl/Tk > > Oooh that's a tough one, it would depend on the program. > Python is a very different language to Tcl and you would need > to write the code in a Tcl style - don't use an OOP style for > the GUI for example. In fact I'd avoid OOP all together since > Tcl OOP is significantly different to Python OOP and not even > part of standard Tcl. ... You might like to take a quick run through the basics of my old > Python tutor which used Tcl as a comparison to Python. Its far > from comprehensive but would give a fairly good Python view > of Tcl. > > http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/index.htm > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld Thanks, this is a really good point. I've been examining incr Tcl with interest, but to learn Tcl/Tk by porting code from Python, its probably best to avoid incr Tcl/incr Widgets at first. Your tutor is really great, I've skimmed through it a bit, and will give it a more thorough read shortly. Thanks! Luis N -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050719/a5a854d8/attachment.htm From bvande at po-box.mcgill.ca Tue Jul 19 10:04:48 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 19 Jul 2005 04:04:48 -0400 Subject: [Tutor] [OT] Re: OFFLIST replaying In-Reply-To: <42DC9FB3.8060700@post.cz> References: <42DC8BD6.4000304@post.cz> <42DC9315.8000603@po-box.mcgill.ca> <42DC9FB3.8060700@post.cz> Message-ID: <42DCB420.6000300@po-box.mcgill.ca> Oh dear. You want all help to be in public so much that you will reply to a private email by taking it back to the list. Then you probably should have left in the part where I gave you step by step instructions on how to set Thunderbird up to Reply to All. I do think it is considered rude to publicly post something that was sent privately with an explicit [OFFLIST] tag in the subject line. Sorry for the way-off topic post, but the violation of the norms here bugs me. Best to all, Brian vdB From monashee88 at shaw.ca Tue Jul 19 10:15:02 2005 From: monashee88 at shaw.ca (John Montgomery) Date: Tue, 19 Jul 2005 01:15:02 -0700 Subject: [Tutor] replaying In-Reply-To: <42DC8BD6.4000304@post.cz> References: <42DC8BD6.4000304@post.cz> Message-ID: <20050719011502.32eb30c9.monashee88@shaw.ca> On Tue, 19 Jul 2005 07:12:54 +0200 geon wrote: > > * My TB doesnt support it. And maybe even others mail clients.Its really > wasting of time to change the adress all the time. I like to help, but > if the was more of such a inconvieniencies I would give it up. My time > is expensive :-) > Hi Geon & Danny, I am surprised that Thunderbird does not have a "Reply All" button. I use Sylpheed and if I hit Reply, the message goes to the list. If I hit Reply All, the messgae is sent to the original poster with a CC to the list. Either way it goes to the list which seems contrary to the way it is supposed to work. John Montgomery From tegmine at gmail.com Tue Jul 19 10:16:03 2005 From: tegmine at gmail.com (Luis N) Date: Tue, 19 Jul 2005 01:16:03 -0700 Subject: [Tutor] globals and map() Message-ID: <77bfa81a050719011673897ec@mail.gmail.com> I'd appreciate some comments on my use of globals and the map function. The idea here is that (simple) Metakit database definitions can be loaded dynamically from another Metakit database detifintion. (Yes this would likely be easier with a SQL database, don't ask!) Nasty code ahead: import metakit import marshal db = metakit.storage('addy.mk ',1) dbs = db.getas('dbs[db:S,marshal:B]') def li(i): i = i[:-2] return i def selectDB(f): if f.has_key('db'): d = [] d['db'] = f.get('db').value id = dbs.find(d) if id != -1: global desc, vw, primaryKey desc = marshal.loads(dbs[id].marshal) vw = db.getas('%s%s' % (dbs[id].db,desc)) desc = map(li,desc) primaryKey = desc[0] return desc, vw, primaryKey else: error(-1) else: error(select=None) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050719/d34825f0/attachment.htm From klappnase at freenet.de Tue Jul 19 10:46:44 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 19 Jul 2005 10:46:44 +0200 Subject: [Tutor] ListBox in Tkinter In-Reply-To: <42DBD0BA.8050103@post.cz> References: <42DB934B.7090700@post.cz> <00be01c58ba1$c3bc4be0$77cc8651@xp> <42DBD0BA.8050103@post.cz> Message-ID: <20050719104644.456fbfc0.klappnase@freenet.de> On Mon, 18 Jul 2005 17:54:34 +0200 geon wrote: > Alan G napsal(a): > > >> I would like to ask if it is possible to create such a listbox > >> (attached) in TKinter itself or must have pmw ot tix...or ... > > > > > > PMW is written in Tkinter so yes, you could do it yourself but it is > > not a native widget. Using PMW would be much easier! > > > I have just found this: http://effbot.org/tkinterbook/optionmenu.htm - > that is nearly what I needed , just another design. > I think there are even other new widgets in new Tk/Tcl compared to the > http://www.pythonware.com/library/tkinter/introduction/, but > undocumented yet. Or poorly or only in original Tk documentation..... > There are three new widgets in Tk 8.4: the Spinbox (an entry field with "up" and "down" arrow buttons), the PanedWindow , which lets you dynamically add resizable frames and the LabelFrame, a Frame with a decorative border and a Label in one of its corners. Regards Michael From misha.dunn at gmail.com Tue Jul 19 10:55:57 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Tue, 19 Jul 2005 10:55:57 +0200 Subject: [Tutor] This should be easy In-Reply-To: References: <1121714021.6612.3.camel@localhost.localdomain> Message-ID: I'm not sure why your first example worked: "Table" is a reserved word in SQL (i.e. it's used as a SQL command), so you shouldn't use it as a table name. Imagine a poor dumb computer trying to parse "create table table"... Cheers, Michael From klappnase at freenet.de Tue Jul 19 11:06:43 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue, 19 Jul 2005 11:06:43 +0200 Subject: [Tutor] Scrolling multilistbox help In-Reply-To: References: Message-ID: <20050719110643.26acfd69.klappnase@freenet.de> On Mon, 18 Jul 2005 13:54:45 +0000 "Alberto Troiano" wrote: > Hey tutors > > I'm using the Multilistbox class and I noticed that it only handles the > mouse scroll and the scrollbar to go down or up.I succesfully implemented > the sort function that came with the class > I also added code to handle the up and down arrow keys and it goes down all > right but only select the item and it doesn't scroll down or up > > How can make it go up or down? > I'm sendind the class here: > Hi Alberto, I haven't tested your code, but if I understand you correctly, the problem is that the list is not automatically scrolled when you select a new item with the Up and Down keys (right?). Maybe it's the easiest to add a line like this to your _select1() and _select2() methods: l.see(int(l.curselection()[0])) where l is the first of the listboxes; this should make sure the selected item is visible (at least if you use selectmode=SINGLE). If keeping all lists in sync works, this should be enough to scroll all other lists, too (like I said, untested though). I hope this helps Michael > class MultiListbox(Frame): > fila=0 > sortedBy=-1 > def __init__(self, master, lists): > Frame.__init__(self, master) > self.lists = [] > for l,w,a in lists: > frame = Frame(self,background="red"); frame.pack(side=LEFT, expand=YES, > fill=BOTH) > Button(frame,background="red",foreground="white",font="Verdana 8 > bold",text=l, borderwidth=1, relief=RAISED,command=lambda a=a: > self._sortBy(a)).pack(fill=X) > lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0, > relief=FLAT, exportselection=FALSE) > lb.pack(expand=YES, fill=BOTH) > self.lists.append(lb) > lb.bind('', lambda e, s=self: s._select(e.y)) > lb.bind('', lambda e, s=self: s._devolverfila(e.y)) > lb.bind('', lambda e, s=self: s._devolverfila(e.y)) > lb.bind('', lambda e, s=self: s._select(e.y)) > lb.bind('', lambda s: _select1()) > lb.bind('', lambda s: _select2()) > lb.bind('', lambda e: 'break') > lb.bind('', lambda e, s=self: s._b2motion(e.x, e.y)) > lb.bind('', lambda e, s=self: s._button2(e.x, e.y)) > frame = Frame(self,background="red"); frame.pack(side=LEFT, fill=Y) > Label(frame,background="red",foreground="white",font="Verdana 8 bold", > borderwidth=1, relief=RAISED).pack(fill=X) > sb = Scrollbar(frame,background="red", orient=VERTICAL, > command=self._scroll) > sb.pack(expand=YES, fill=Y) > self.lists[0]['yscrollcommand']=sb.set > > def _sortBy(self, column): > """ Sort by a given column. """ > if column == self.sortedBy: > direction = -1 * self.direction > else: > direction = 1 > elements = self.get(0, END) > self.delete(0, END) > elements.sort(lambda x, y: self._sortAssist(column, direction, x, > y)) > self.insert(END, *elements) > self.sortedBy = column > self.direction = direction > > def _sortAssist(self, column, direction, x, y): > if column!=0: > c = cmp(x[column], y[column]) > if c: > return direction * c > else: > return direction * cmp(x, y) > else: > c = cmp(int(x[column]), int(y[column])) > if c: > return direction * c > else: > return direction * cmp(x, y) > > def _select(self, y): > row = self.lists[0].nearest(y) > self.selection_clear(0, END) > self.selection_set(row) > self.fila=row > return 'break' > > def _devolverfila(self, y): > row = self.lists[0].nearest(y) > self.selection_clear(0, END) > self.selection_set(row) > self.fila=row > > def _select1(self): > if self.fila==self.size()-1: > pass > else: > self.selection_clear(0, END) > self.selection_set(self.fila+1) > self.fila+=1 > self._scroll() > return 'break' > > def _select2(self): > if self.fila==0: > pass > else: > self.selection_clear(0, END) > self.selection_set(self.fila-1) > self.fila-=1 > return 'break' > > def _button2(self, x, y): > for l in self.lists: l.scan_mark(x, y) > return 'break' > > def _b2motion(self, x, y): > for l in self.lists: l.scan_dragto(x, y) > return 'break' > > def _scroll(self, *args): > for l in self.lists: > apply(l.yview, args) > > def curselection(self): > return self.lists[0].curselection() > > def delete(self, first, last=None): > for l in self.lists: > l.delete(first, last) > > def get(self, first, last=None): > result = [] > for l in self.lists: > result.append(l.get(first,last)) > if last: return apply(map, [None] + result) > return result > > def index(self, index): > self.lists[0].index(index) > > def insert(self, index, *elements): > for e in elements: > i = 0 > for l in self.lists: > l.insert(index, e[i]) > i = i + 1 > > def size(self): > return self.lists[0].size() > > def see(self, index): > for l in self.lists: > l.see(index) > > def selection_anchor(self, index): > for l in self.lists: > l.selection_anchor(index) > > def selection_clear(self, first, last=None): > for l in self.lists: > l.selection_clear(first, last) > > def selection_includes(self, index): > return self.lists[0].selection_includes(index) > > def selection_set(self, first, last=None): > for l in self.lists: > l.selection_set(first, last) > > > THanks in advanced > > Alberto > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From damien.gouteux at gmail.com Tue Jul 19 11:43:22 2005 From: damien.gouteux at gmail.com (Damien) Date: Tue, 19 Jul 2005 11:43:22 +0200 Subject: [Tutor] Class variable & object variable Message-ID: <42DCCB3A.3000908@gmail.com> Hi, I am a little bit confuse about class variable & object variable (Python 2.4). I have: class A(object): d = 50 def __init__(self): print "Hello" >>> z = A() Hello >>> A.d 50 (it's nice) >>> z.d 50 (?) 1) Why ?? d is not an object variable but a class variable !!! For the object z, d is not defined (in my mind, not for Python, as you can see)(it's the same in Java : all static variables can be accessed from an object of the class or the class itself). It's very dangerous because: >>> z.d += 1 >>> z.d 51 (now a object var is created called 'd') >>> z.__class__.d 50 (and if we want the 'old' class var, we need to put the '.__class__.d' to acces to the class) Now the object var hides the class var. But the statement z.d+=1 is very confusing (at least, for me): z.d(new object var) = z.d(old class var) + 1 Is it possible to have 'd' only for the class and not for instances of this class ? and to have at (?) (z.d) an exception raised ? (like "d is not defined for object z"). Thank you, Damien. From cyresse at gmail.com Tue Jul 19 12:05:01 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 19 Jul 2005 22:05:01 +1200 Subject: [Tutor] replaying In-Reply-To: <20050719011502.32eb30c9.monashee88@shaw.ca> References: <42DC8BD6.4000304@post.cz> <20050719011502.32eb30c9.monashee88@shaw.ca> Message-ID: OT, but wasn't Sylpheed some futuristic fighter/bomber they made a bad movie about in the eighties? On 7/19/05, John Montgomery wrote: > > On Tue, 19 Jul 2005 07:12:54 +0200 > geon wrote: > > > > > * My TB doesnt support it. And maybe even others mail clients.Its really > > wasting of time to change the adress all the time. I like to help, but > > if the was more of such a inconvieniencies I would give it up. My time > > is expensive :-) > > > Hi Geon & Danny, > > I am surprised that Thunderbird does not have a "Reply All" button. > > I use Sylpheed and if I hit Reply, the message goes to the list. If I hit > Reply All, the messgae is sent to the original poster with a CC to the list. > Either way it goes to the list which seems contrary to the way it is > supposed to work. > > John Montgomery > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050719/c6e625c6/attachment.htm From kent37 at tds.net Tue Jul 19 12:56:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Jul 2005 06:56:11 -0400 Subject: [Tutor] globals and map() In-Reply-To: <77bfa81a050719011673897ec@mail.gmail.com> References: <77bfa81a050719011673897ec@mail.gmail.com> Message-ID: <42DCDC4B.4060800@tds.net> Luis N wrote: > I'd appreciate some comments on my use of globals and the map function. > > import metakit > import marshal > > db = metakit.storage('addy.mk ',1) > dbs = db.getas('dbs[db:S,marshal:B]') > > def li(i): > i = i[:-2] > return i > > def selectDB(f): > if f.has_key('db'): > d = [] > d['db'] = f.get('db').value The above line is not valid Python; list indices must be integers > id = dbs.find(d) > if id != -1: > global desc, vw, primaryKey > desc = marshal.loads(dbs[id].marshal) > vw = db.getas('%s%s' % (dbs[id].db,desc)) > desc = map(li,desc) This use of map seems fine to me. You could also write it as a list comprehension which is more mainstream Python idiom and maybe more readable in this case as it is self-contained: desc = [ i[:-2] for i in desc ] > primaryKey = desc[0] > return desc, vw, primaryKey I don't see the need for the global declaration; desc, vw, primaryKey are all assigned within this function and returned to the caller. Kent > else: > error(-1) > else: > error(select=None) > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From tegmine at gmail.com Tue Jul 19 13:59:36 2005 From: tegmine at gmail.com (Luis N) Date: Tue, 19 Jul 2005 04:59:36 -0700 Subject: [Tutor] globals and map() In-Reply-To: <42DCDC4B.4060800@tds.net> References: <77bfa81a050719011673897ec@mail.gmail.com> <42DCDC4B.4060800@tds.net> Message-ID: <77bfa81a050719045921304ba5@mail.gmail.com> On 7/19/05, Kent Johnson wrote: > > Luis N wrote: > > I'd appreciate some comments on my use of globals and the map function. > > > > import metakit > > import marshal > > > > db = metakit.storage('addy.mk ',1) > > dbs = db.getas('dbs[db:S,marshal:B]') > > > > def li(i): > > i = i[:-2] > > return i > > > > def selectDB(f): > > if f.has_key('db'): > > d = [] > > d['db'] = f.get('db').value > > The above line is not valid Python; list indices must be integers > id = dbs.find(d) > > if id != -1: > > global desc, vw, primaryKey > > desc = marshal.loads(dbs[id].marshal) > > vw = db.getas('%s%s' % (dbs[id].db,desc)) > > desc = map(li,desc) > > This use of map seems fine to me. You could also write it as a list > comprehension which is more mainstream Python idiom and maybe more readable > in this case as it is self-contained: > desc = [ i[:-2] for i in desc ] > > > primaryKey = desc[0] > > return desc, vw, primaryKey > > I don't see the need for the global declaration; desc, vw, primaryKey are > all assigned within this function and returned to the caller. Kent My blooper, should be d={} In this case consider desc, vw, and primaryKey to be of the same importance as dbs, other functions must access them in a way that renders their being local impossible, unless the logic where to be encapsulated in a class, which didn't seem necessary. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050719/12e22e5b/attachment.htm From alan.gauld at freenet.co.uk Tue Jul 19 14:08:31 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 19 Jul 2005 13:08:31 +0100 Subject: [Tutor] Which is safer and easier to code, raw_input or int(raw_input))? References: Message-ID: <004201c58c5a$94af0310$39968651@xp> > Subject: [Tutor] Which is safer and easier to code,raw_input or > int(raw_input))? val = int(raw_input()) is the same as val = raw_input() val = int(val) in terms of safety because it is the same I/O mechanism. Arguably wrapping the int() call around it makes it marginally safer since it throws an exception that bit sooner. Both are much safer than using input(), which may be what you had in mind? The int() wrapper may look like extra typing but if you include the extra quote signs you need at every comparison without the int conversion it rapidly evens out. if val == '5':... elif val == '7':... as opposed to if val == 5:... elif val == 7:... etc Also if you just capture the string its much harder to write control logic to correct an invalid number entry (eg the user types 'four' instead of '4', or even 'l'(ell) instead of '1') later than at the time you prompt for it, again a lot of extra coding. input() by comparison has so many opportunities to go wrong that, except for small personal use programs, its a non starter. Its not only malicious badness but using the example above, an ell instead of a one would result in the program variable 'l' being evaluated. 'l' could be a list, a function object, a string, anything! int(raw_input()) would detect the problem. My 2 cents, Alan G. From rob.andrews at gmail.com Tue Jul 19 14:15:33 2005 From: rob.andrews at gmail.com (Rob Andrews) Date: Tue, 19 Jul 2005 07:15:33 -0500 Subject: [Tutor] replaying In-Reply-To: References: <42DC13BB.2000406@post.cz> Message-ID: <8d757d2e05071905157843407e@mail.gmail.com> > However, there are significant downsides to enabling Reply-to munging: > > http://www.unicom.com/pw/reply-to-harmful.html > > I agree with most of those reasons, and so I won't enable Reply-to munging > unless there's a real overriding reason that trumps the ones listed on > that page. I found the arguments on the link you shared adequately persuasive. -Rob -- Golf with an attitude: http://www.ragingolf.com/ From alan.gauld at freenet.co.uk Tue Jul 19 14:29:03 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Tue, 19 Jul 2005 13:29:03 +0100 Subject: [Tutor] Class variable & object variable References: <42DCCB3A.3000908@gmail.com> Message-ID: <00b901c58c5d$72defa30$39968651@xp> > class A(object): > d = 50 > def __init__(self): > print "Hello" > > >>> z = A() > >>> A.d > 50 > >>> z.d > 50 > 1) Why ?? d is not an object variable but a class variable !!! Yes which means (definition of a class variable) that it's part of every class and instance of the class. > object z, d is not defined (in my mind, not for Python, as you can > see)(it's the same in Java : all static variables can be accessed > from an object of the class or the class itself). Thats what class attributes do, they are part of the class and thus of instances of the class. After all, methods are defined at the class level too and if they were not available to the instance except by calling like: A.f(z) it would get very tiresome. > It's very dangerous because: > >>> z.d += 1 > >>> z.d > 51 > (now a object var is created called 'd') And that I agree is confusing! THat is not standard class variable behaviour and I personally don't like it. But there isn't any single language I know where I like everything about it, so I live with it! It's Guido's language, so he gets to choose how features work! :-) > Is it possible to have 'd' only for the class and not for instances > of this class ? I donl;t think so but it is possible that some of the new metaclass stuff might allow that. Also you could probabnly use getattr()/settatr() to do something similar. HTH, Alan G. From kent37 at tds.net Tue Jul 19 14:43:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Jul 2005 08:43:54 -0400 Subject: [Tutor] globals and map() In-Reply-To: <77bfa81a050719045921304ba5@mail.gmail.com> References: <77bfa81a050719011673897ec@mail.gmail.com> <42DCDC4B.4060800@tds.net> <77bfa81a050719045921304ba5@mail.gmail.com> Message-ID: <42DCF58A.7040103@tds.net> Luis N wrote: > On 7/19/05, *Kent Johnson* > wrote: > > Luis N wrote: > > I'd appreciate some comments on my use of globals and the map > function. > > I don't see the need for the global declaration; desc, vw, > primaryKey are all assigned within this function and returned to the > caller. > > In this case consider desc, vw, and primaryKey to be of the same > importance as dbs, other functions must access them in a way that > renders their being local impossible, unless the logic where to be > encapsulated in a class, which didn't seem necessary. If you have several functions in one module that need access to the same variables, that is a good indication that using a class might be a better design. OTOH using a module to encapsulate the state (as globals) is OK if you only need one set of globals. Is there something that bothers you about using globals? I'm not sure why you asked for comments. Kent From damien.gouteux at gmail.com Tue Jul 19 14:56:17 2005 From: damien.gouteux at gmail.com (Damien) Date: Tue, 19 Jul 2005 14:56:17 +0200 Subject: [Tutor] Class variable & object variable In-Reply-To: <00b901c58c5d$72defa30$39968651@xp> References: <42DCCB3A.3000908@gmail.com> <00b901c58c5d$72defa30$39968651@xp> Message-ID: <42DCF871.9030308@gmail.com> thx for your quick (and complete) answers. to Alan G : I will try to see what setattr() and getattr() can do for me. I'm not used to this stuff. to Alex Nedelcu : If I understand correctly : There are two different references (A.d in the dict of the class A and z.d in the dict of the object z) but on the same object, am I right ? (with z = A()) Alan G a ?crit : >> class A(object): >> d = 50 >> def __init__(self): >> print "Hello" >> >> >>> z = A() >> >>> A.d >> 50 >> >>> z.d >> 50 >> 1) Why ?? d is not an object variable but a class variable !!! > > > Yes which means (definition of a class variable) that it's part of > every class and instance of the class. > >> object z, d is not defined (in my mind, not for Python, as you can >> see)(it's the same in Java : all static variables can be accessed >> from an object of the class or the class itself). > > > Thats what class attributes do, they are part of the class and > thus of instances of the class. After all, methods are defined at the > class level too and if they were not available to the instance > except by calling like: > > A.f(z) > > it would get very tiresome. > >> It's very dangerous because: >> >>> z.d += 1 >> >>> z.d >> 51 >> (now a object var is created called 'd') > > > And that I agree is confusing! THat is not standard class variable > behaviour and I personally don't like it. But there isn't any single > language I know where I like everything about it, so I live with it! > It's Guido's language, so he gets to choose how features work! :-) > >> Is it possible to have 'd' only for the class and not for instances >> of this class ? > > > I donl;t think so but it is possible that some of the new metaclass > stuff might allow that. Also you could probabnly use getattr()/settatr() > to do something similar. > > HTH, > > Alan G. > > From albertito_g at hotmail.com Tue Jul 19 15:00:38 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 19 Jul 2005 13:00:38 +0000 Subject: [Tutor] Scrolling multilistbox help In-Reply-To: <20050719110643.26acfd69.klappnase@freenet.de> Message-ID: Hey Michael It worked like a charm Thank GOD you understood what I wanted, you see speaking Spanish made me so hard to explain what the problem were but...I guess you just figured out To my code was this: self.see(int(self.curselection()[0])) Thank you very much Best Regards Alberto >From: Michael Lange >To: tutor at python.org >Subject: Re: [Tutor] Scrolling multilistbox help >Date: Tue, 19 Jul 2005 11:06:43 +0200 > >On Mon, 18 Jul 2005 13:54:45 +0000 >"Alberto Troiano" wrote: > > > Hey tutors > > > > I'm using the Multilistbox class and I noticed that it only handles the > > mouse scroll and the scrollbar to go down or up.I succesfully >implemented > > the sort function that came with the class > > I also added code to handle the up and down arrow keys and it goes down >all > > right but only select the item and it doesn't scroll down or up > > > > How can make it go up or down? > > I'm sendind the class here: > > > >Hi Alberto, > >I haven't tested your code, but if I understand you correctly, the problem >is that the list is not automatically scrolled when you select a new item >with >the Up and Down keys (right?). >Maybe it's the easiest to add a line like this to your _select1() and >_select2() methods: > > l.see(int(l.curselection()[0])) > >where l is the first of the listboxes; this should make sure the selected >item is visible >(at least if you use selectmode=SINGLE). If keeping all lists in sync >works, this >should be enough to scroll all other lists, too (like I said, untested >though). > >I hope this helps > >Michael > > > > > class MultiListbox(Frame): > > fila=0 > > sortedBy=-1 > > def __init__(self, master, lists): > > Frame.__init__(self, master) > > self.lists = [] > > for l,w,a in lists: > > frame = Frame(self,background="red"); frame.pack(side=LEFT, >expand=YES, > > fill=BOTH) > > Button(frame,background="red",foreground="white",font="Verdana 8 > > bold",text=l, borderwidth=1, relief=RAISED,command=lambda a=a: > > self._sortBy(a)).pack(fill=X) > > lb = Listbox(frame, width=w, borderwidth=0, selectborderwidth=0, > > relief=FLAT, exportselection=FALSE) > > lb.pack(expand=YES, fill=BOTH) > > self.lists.append(lb) > > lb.bind('', lambda e, s=self: s._select(e.y)) > > lb.bind('', lambda e, s=self: >s._devolverfila(e.y)) > > lb.bind('', lambda e, s=self: s._devolverfila(e.y)) > > lb.bind('', lambda e, s=self: s._select(e.y)) > > lb.bind('', lambda s: _select1()) > > lb.bind('', lambda s: _select2()) > > lb.bind('', lambda e: 'break') > > lb.bind('', lambda e, s=self: s._b2motion(e.x, e.y)) > > lb.bind('', lambda e, s=self: s._button2(e.x, e.y)) > > frame = Frame(self,background="red"); frame.pack(side=LEFT, fill=Y) > > Label(frame,background="red",foreground="white",font="Verdana 8 bold", > > borderwidth=1, relief=RAISED).pack(fill=X) > > sb = Scrollbar(frame,background="red", orient=VERTICAL, > > command=self._scroll) > > sb.pack(expand=YES, fill=Y) > > self.lists[0]['yscrollcommand']=sb.set > > > > def _sortBy(self, column): > > """ Sort by a given column. """ > > if column == self.sortedBy: > > direction = -1 * self.direction > > else: > > direction = 1 > > elements = self.get(0, END) > > self.delete(0, END) > > elements.sort(lambda x, y: self._sortAssist(column, direction, >x, > > y)) > > self.insert(END, *elements) > > self.sortedBy = column > > self.direction = direction > > > > def _sortAssist(self, column, direction, x, y): > > if column!=0: > > c = cmp(x[column], y[column]) > > if c: > > return direction * c > > else: > > return direction * cmp(x, y) > > else: > > c = cmp(int(x[column]), int(y[column])) > > if c: > > return direction * c > > else: > > return direction * cmp(x, y) > > > > def _select(self, y): > > row = self.lists[0].nearest(y) > > self.selection_clear(0, END) > > self.selection_set(row) > > self.fila=row > > return 'break' > > > > def _devolverfila(self, y): > > row = self.lists[0].nearest(y) > > self.selection_clear(0, END) > > self.selection_set(row) > > self.fila=row > > > > def _select1(self): > > if self.fila==self.size()-1: > > pass > > else: > > self.selection_clear(0, END) > > self.selection_set(self.fila+1) > > self.fila+=1 > > self._scroll() > > return 'break' > > > > def _select2(self): > > if self.fila==0: > > pass > > else: > > self.selection_clear(0, END) > > self.selection_set(self.fila-1) > > self.fila-=1 > > return 'break' > > > > def _button2(self, x, y): > > for l in self.lists: l.scan_mark(x, y) > > return 'break' > > > > def _b2motion(self, x, y): > > for l in self.lists: l.scan_dragto(x, y) > > return 'break' > > > > def _scroll(self, *args): > > for l in self.lists: > > apply(l.yview, args) > > > > def curselection(self): > > return self.lists[0].curselection() > > > > def delete(self, first, last=None): > > for l in self.lists: > > l.delete(first, last) > > > > def get(self, first, last=None): > > result = [] > > for l in self.lists: > > result.append(l.get(first,last)) > > if last: return apply(map, [None] + result) > > return result > > > > def index(self, index): > > self.lists[0].index(index) > > > > def insert(self, index, *elements): > > for e in elements: > > i = 0 > > for l in self.lists: > > l.insert(index, e[i]) > > i = i + 1 > > > > def size(self): > > return self.lists[0].size() > > > > def see(self, index): > > for l in self.lists: > > l.see(index) > > > > def selection_anchor(self, index): > > for l in self.lists: > > l.selection_anchor(index) > > > > def selection_clear(self, first, last=None): > > for l in self.lists: > > l.selection_clear(first, last) > > > > def selection_includes(self, index): > > return self.lists[0].selection_includes(index) > > > > def selection_set(self, first, last=None): > > for l in self.lists: > > l.selection_set(first, last) > > > > > > THanks in advanced > > > > Alberto > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From jsmith at medplus.com Tue Jul 19 14:34:25 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue, 19 Jul 2005 08:34:25 -0400 Subject: [Tutor] Buffering problem using subprocess module Message-ID: I am using the subprocess module in 2.4. Here's the fragment: bufcaller.py: import sys, subprocess proc = subprocess.Popen('python bufcallee.py', bufsize=0, shell=True, stdout=subprocess.PIPE) for line in proc.stdout: sys.stdout.write(line) bufcallee.py: import time print 'START' time.sleep(10) print 'STOP' Although the documentation says that the output should be unbuffered (bufsize=0) the program (bufcaller) pauses for 10 seconds and then prints START immediately followed by 'STOP' rather than pausing 10 seconds in between them. Note that I made bufcallee a Python script for ease of the example but in the real-world problem I am trying to solve it is simply an executable. Any ideas? Jeff From albertito_g at hotmail.com Tue Jul 19 15:13:26 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Tue, 19 Jul 2005 13:13:26 +0000 Subject: [Tutor] Minesweeper the return In-Reply-To: Message-ID: Hey Danny Thanks for the reply Please let's talk about this more! *grin* I'm not sure if I'm following you, what I see here is a function inside other function and the first function returns its inside function, but how does it work? I don't know Scheme, but I know a little of C#, VB.NET, Pascal, QBasic and C++ 6.0 But I would prefer to talk in theory or in general. Thanks in advanced Alberto >From: Danny Yoo >To: Alberto Troiano >CC: tutor at python.org >Subject: Re: [Tutor] Minesweeper the return >Date: Mon, 18 Jul 2005 16:10:51 -0700 (PDT) > > > >On Mon, 18 Jul 2005, Alberto Troiano wrote: > > > > I'm trying to create the buttons dinamically (that's not a problem) the > > problem is wherever I click the hello function returns the last button I > > created. I know that the problem is in the lambda part and that the >variable > > i (the one I change the value within the for) but I don't how to fix it > > >Hi Alberto, > >Ah, this one comes up a bit. *grin* Let's look at the code: > >###### >for i in range(self.fil): > for j in range(self.col): > self.buttonmatrix[i][j]=Button(root,width=1,height=0, > command=lambda: self.hello(i,j)) >###### > >The issue is that all the dynamically generated functions are using the >same 'i' and 'j' variables. The big issue is that, in Python, for-loops >rebind the iterating variable name to different values, and that's what's >causing the issue. > > >Instead of using lambda directly, try something like this: > >###### >def make_hello(x, y): > def new_hello_function(): > self.hello(x, y) > return new_hello_function > >for i in range(self.fil): > for j in range(self.col): > self.buttonmatrix[i][j]=Button(root,width=1,height=0, > command=make_hello(i, j)) >###### > > >There's some subtle lexical-binding stuff going on there, so if you'd >like, we can talk about this more. If you're familiar with another >programming language with lexical scope (like Scheme), we can talk about >in terms of that language too. > > >Hope this helps! > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From darryl at snakegully.nu Tue Jul 19 15:33:54 2005 From: darryl at snakegully.nu (Darryl Luff) Date: Tue, 19 Jul 2005 23:33:54 +1000 Subject: [Tutor] Saving class data to a text file In-Reply-To: <003b01c58a3f$1646d240$2daa8851@xp> References: <42D92231.4000306@snakegully.nu> <003b01c58a3f$1646d240$2daa8851@xp> Message-ID: <42DD0142.3060503@snakegully.nu> Alan G wrote: > ... > Take a look at the OOP topic in my tutor. It includes an examnple > of how to save/load objects to text files. Thanks Alan, Javier and Jonathon. The answers I got all showed me bits of Python I haven't seen before! I'll have to take a while to digest the others. I left another requirement out - the fields have to include their field names. I've been caught with perl scripts when using CSV files, and different scripts used different field orders... So the format str(dictionary) gives is really just what I want. It's line-oriented, and includes the field names. So for now I've stuck to using that. > ... > The native python solution would be to use pickle or shelve modules. > If it must be human friendly too then the approach in my tutor > supplemented by overloading the __repr__() method would work. I've overloaded __repr__ of the object to just return a str() of the internal dictionary. Is this OK? Or is __repr__ used for something else that I've now broken? So to save the object to a file I just write repr(object) + "\n". > ... > You might try eval() but it is full of security implications, rogue > code in your data could be evaluated and do who knows what kind of > mischief... I wasn't comfortable using eval() to retrieve the value, so I used a regex to unpack it. I think I do like the perl builtin $variable =~ /regex/ syntax better than the re.compile()/match() stuff. I'll include a stripped-down version of the object below. If anyone's looking for something to do I'd appreciate any comments on more 'python'y ways to do it! At a first look python looks OK. The indentation takes a bit of getting used to, especially when copying scripts out of emails! It's easy to space something wrong and have the script doing strange things! Thanks. ========= import re class Test: def __init__(self): self.dat = {} def __repr__(self): return str(self.dat) def GetName(self): if self.dat.has_key('name'): return self.dat['name'] else: return "" def SetName(self, n): self.dat['name'] = n def LoadFrom(self, line): self.dat = {} p = re.compile("'(.*?)'\s*:\s*('.*?'|\S+)\s*(.*)") print "Checking " + line m = p.search(line) while m: print "Matched " + m.group(1) + " = " + m.group(2) val = m.group(2) val.strip("'") self.dat[m.group(1)] = val m = p.search(m.group(3)) def ToString(self): return str(self.dat) filename = "/tmp/dat.txt" test = Test() test.SetName("Fred") f = open(filename, "w") f.write(repr(test) + "\n") f.close() test = Test() print "Retrieved: " + test.GetName() f = open(filename, "r") test.LoadFrom(f.readline()) f.close() print "Retrieved: " + test.GetName() From frank.hoffsummer at gmail.com Tue Jul 19 16:15:46 2005 From: frank.hoffsummer at gmail.com (frank h.) Date: Tue, 19 Jul 2005 16:15:46 +0200 Subject: [Tutor] use gzip with large files Message-ID: <60fae7c30507190715f42da0e@mail.gmail.com> hello all I am trying to write a script in python that parses a gzipped logfile the unzipped logfiles can be very large (>2GB) basically the statements file = gzip.GzipFile(logfile) data = file.read() for line in data.striplines(): .... would do what I want, but this is not feasible becasue the gzip files are so huge. So I do file.readline() in a for loop, but have no idea how long to continue, because I dont know how many lines the files contain. How do I check for end of file when using readline() ? simply put it in a while loop and enclose it with try: except: ? what would be the best (fastest) approach to deal with such large gzip files in python? thanks From phil at xfr.co.uk Tue Jul 19 17:05:48 2005 From: phil at xfr.co.uk (Philip Kilner) Date: Tue, 19 Jul 2005 16:05:48 +0100 Subject: [Tutor] replaying In-Reply-To: <20050719011502.32eb30c9.monashee88@shaw.ca> References: <42DC8BD6.4000304@post.cz> <20050719011502.32eb30c9.monashee88@shaw.ca> Message-ID: <42DD16CC.1030208@xfr.co.uk> Hi John, John Montgomery wrote: > I am surprised that Thunderbird does not have a "Reply All" button. > It does - and I just hit it! ;-) -- Regards, PhilK Email: phil at xfr.co.uk PGP Public key: http://www.xfr.co.uk Voicemail & Facsimile: 07092 070518 "You'll find that one part's sweet and one part's tart: say where the sweetness and the sourness start." - Tony Harrison From adam.jtm30 at gmail.com Tue Jul 19 17:34:25 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 19 Jul 2005 16:34:25 +0100 Subject: [Tutor] use gzip with large files In-Reply-To: <60fae7c30507190715f42da0e@mail.gmail.com> References: <60fae7c30507190715f42da0e@mail.gmail.com> Message-ID: If you use something like this: for line in file.readlines(): then line is a string to the next newline and it automatically detects the EOF and the same with file.readline() but that will give you one character at a time. On 7/19/05, frank h. wrote: > > hello all > I am trying to write a script in python that parses a gzipped logfile > > the unzipped logfiles can be very large (>2GB) > > basically the statements > > file = gzip.GzipFile(logfile) > data = file.read() > > for line in data.striplines(): > .... > > > would do what I want, but this is not feasible becasue the gzip files > are so huge. > > So I do file.readline() in a for loop, but have no idea how long to > continue, because I dont know how many lines the files contain. How do > I check for end of file when using readline() ? > simply put it in a while loop and enclose it with try: except: ? > > what would be the best (fastest) approach to deal with such large gzip > files in python? > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050719/ad12f5c2/attachment-0001.htm From kent37 at tds.net Tue Jul 19 18:51:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Jul 2005 12:51:36 -0400 Subject: [Tutor] use gzip with large files In-Reply-To: References: <60fae7c30507190715f42da0e@mail.gmail.com> Message-ID: <42DD2F98.3000101@tds.net> Adam Bark wrote: > If you use something like this: > > for line in file.readlines(): This will read the whole file into a list of lines; the OP doesn't want to read the whole file at once. > then line is a string to the next newline and it automatically detects > the EOF and the same with file.readline() but that will give you one > character at a time. ?? file.readline() reads by lines, not by characters. A file is also an iterator (by lines) so the simplest way to iterate over lines in a file is just for line in f: # process line Specifically frank should be able to use file = gzip.GzipFile(logfile) for line in file(): though 'file' is a bad choice of names as it is also a built-in. To check for EOF when using readline() just look for an empty string: while True: line = f.readline() if not line: break but 'for line in f' is preferable. Kent > > On 7/19/05, *frank h.* > wrote: > > hello all > I am trying to write a script in python that parses a gzipped logfile > > the unzipped logfiles can be very large (>2GB) > > basically the statements > > file = gzip.GzipFile(logfile) > data = file.read () > > for line in data.striplines(): > .... > > > would do what I want, but this is not feasible becasue the gzip files > are so huge. > > So I do file.readline() in a for loop, but have no idea how long to > continue, because I dont know how many lines the files contain. How do > I check for end of file when using readline() ? > simply put it in a while loop and enclose it with try: except: ? > > what would be the best (fastest) approach to deal with such large gzip > files in python? > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From sunny.tired at gmail.com Tue Jul 19 19:17:58 2005 From: sunny.tired at gmail.com (sunny sunny) Date: Tue, 19 Jul 2005 13:17:58 -0400 Subject: [Tutor] Getting singal strength of the received packet Message-ID: <8171b61605071910175ad0cf98@mail.gmail.com> Hi, I am sending and receiving for a simple server application over wirless link. Can I get the signal strength of the received packet in Python? One way would be to get the value of the RSSI from /proc/net/wireless. However I would like to get the signal strength (in terms of RSSI or dBm) of the specific packet. Is it possible to do this in Python. I am using hostAP driver, and know that using C, I can get the packet RSSI. Thanks Santosh. From 3dbernard at gmail.com Tue Jul 19 20:35:40 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 19 Jul 2005 14:35:40 -0400 Subject: [Tutor] Tkinter: justify label Message-ID: <61d0e2b405071911352d87bd6d@mail.gmail.com> Hello, Can you specify a justification for a label widget? I'm reading there is a justify option available on this page: http://www.pythonware.com/library/tkinter/introduction/x611-text-formatting.htm Although I don't know if this option works for label. If I try for sField in tFields: row = Frame( oRoot ) label = Label( row, width = 25, justify = LEFT, text = sField ) entry = Entry( row, width = 50, relief = RIDGE ) row.pack( side = TOP, fill = X ) label.pack( side = LEFT ) entry.pack( side = RIGHT, expand = YES, fill = X ) Nothing happens. However, if I put the justify option in the label.pack() call, then I get an error that I'm using an invalid option. Thanks Bernard From 3dbernard at gmail.com Tue Jul 19 22:13:53 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 19 Jul 2005 16:13:53 -0400 Subject: [Tutor] SQL headache with column Message-ID: <61d0e2b4050719131324e513fe@mail.gmail.com> Hello, Not sure if it's a Python thing, but... When sending command to the MySQL server by command line, I can use SHOW COLUMNS FROM , the list of all columns with a bunch of properties is printed. However, when I run the same command from Python and I store the result, the result is an integer that only tell the number of columns. I would like to get the column names! def getTableColumns( sTableName ): """ Lists and returns the list of columns from a given table. """ oConnection = connect2db() oCursor = oConnection.cursor() oResult = oCursor.execute( "SHOW COLUMNS FROM " + sTableName + "" ) print str( oResult ) oCursor.close() oConnection.close() Prints "33" (I have 33 columns) Thanks Bernard From hugonz-lists at h-lab.net Tue Jul 19 19:04:44 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 19 Jul 2005 12:04:44 -0500 Subject: [Tutor] use gzip with large files In-Reply-To: <60fae7c30507190715f42da0e@mail.gmail.com> References: <60fae7c30507190715f42da0e@mail.gmail.com> Message-ID: <42DD32AC.5040305@h-lab.net> for a file-like object with a read method: for line in file: if not line: break line will be "" for EOF, "\n" for an empty line. This will not read the whole file to RAM at once. I'm not familiar with the gzip module, but if the read() solution works for small files, the one I present will work for larger files. Hugo frank h. wrote: > hello all > I am trying to write a script in python that parses a gzipped logfile > > the unzipped logfiles can be very large (>2GB) > > basically the statements > > file = gzip.GzipFile(logfile) > data = file.read() > > for line in data.striplines(): > .... > > > would do what I want, but this is not feasible becasue the gzip files > are so huge. > > So I do file.readline() in a for loop, but have no idea how long to > continue, because I dont know how many lines the files contain. How do > I check for end of file when using readline() ? > simply put it in a while loop and enclose it with try: except: ? > > what would be the best (fastest) approach to deal with such large gzip > files in python? > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 22:31:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 19 Jul 2005 13:31:44 -0700 (PDT) Subject: [Tutor] SQL headache with column In-Reply-To: <61d0e2b4050719131324e513fe@mail.gmail.com> Message-ID: > oResult = oCursor.execute( "SHOW COLUMNS FROM " + sTableName + "" ) Hi Bernard, Try using oCursor.fetchall() after the execution. The return value of execute() are the number of rows affected, and you can then pull each fetched value by using either oCursor.fetchone() or oCursor.fetchall(). See: http://python.org/peps/pep-0249.html for more details about this. Hope this helps! From hugonz-lists at h-lab.net Tue Jul 19 22:31:48 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 19 Jul 2005 15:31:48 -0500 Subject: [Tutor] Getting singal strength of the received packet In-Reply-To: <8171b61605071910175ad0cf98@mail.gmail.com> References: <8171b61605071910175ad0cf98@mail.gmail.com> Message-ID: <42DD6334.6030602@h-lab.net> How would you get it with C? Based on this, we can know if it is possible with plain Python (and not writing a python module written in C) Do you do this with a library call? or maybe using FCTL or IOCTL? I have done IOCTL in python and it is quite easy, but some provisions have to be taken respecting the C types the interface expects... Hugo sunny sunny wrote: > Hi, > > I am sending and receiving for a simple server application over wirless link. > Can I get the signal strength of the received packet in Python? > > One way would be to get the value of the RSSI from /proc/net/wireless. > However I would like to get the signal strength (in terms of RSSI or > dBm) of the specific packet. Is it possible to do this in Python. > > I am using hostAP driver, and know that using C, I can get the packet RSSI. > > Thanks > Santosh. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From 3dbernard at gmail.com Tue Jul 19 22:43:09 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 19 Jul 2005 16:43:09 -0400 Subject: [Tutor] SQL headache with column In-Reply-To: References: <61d0e2b4050719131324e513fe@mail.gmail.com> Message-ID: <61d0e2b4050719134376306f37@mail.gmail.com> Ah yeah I to mention that I indeed tried fetchall(), but Python would raise an attribute error: def getTableColumns( sTableName ): """ Lists and returns the list of columns from a given table. """ oConnection = connect2db() oCursor = oConnection.cursor() oResult = oCursor.execute( "SHOW COLUMNS FROM " + sTableName + "" ) aRow = oResult.fetchall() print str( aRow ) oCursor.close() oConnection.close() Traceback (most recent call last): File "", line 1, in ? File "\\Linuxserver\prod\XSI\WORKGROUP_4.0\Data\Scripts\pipeline\sql.py", line 153, in getTableColumns aRow = oResult.fetchall() AttributeError: 'long' object has no attribute 'fetchall' Thanks Bernard On 7/19/05, Danny Yoo wrote: > > oResult = oCursor.execute( "SHOW COLUMNS FROM " + sTableName + "" ) > > Hi Bernard, > > Try using oCursor.fetchall() after the execution. The return value of > execute() are the number of rows affected, and you can then pull each > fetched value by using either oCursor.fetchone() or oCursor.fetchall(). > > See: > > http://python.org/peps/pep-0249.html > > for more details about this. Hope this helps! > > From fire.fox005 at gmail.com Tue Jul 19 22:46:21 2005 From: fire.fox005 at gmail.com (Sam Klinger) Date: Tue, 19 Jul 2005 15:46:21 -0500 Subject: [Tutor] Help with ebay profit/loss program error Message-ID: <14ee462f05071913466990b504@mail.gmail.com> Hi my name is Sam Klinger and I made a smal program to help find out the cost of listing and selling an item on ebay. However I see nothing wrong with the code but I get these error messages: 1. Insertion fee. 2. Selling Fees. 7. Quit. type in a number (1-7): 1 What is the starting price?9 Traceback (most recent call last): File "C:/Documents and Settings/Sam/My Documents/Hacks/Python Scripts/ebay_money.py", line 46, in ? compute_insertion_fee() File "C:/Documents and Settings/Sam/My Documents/Hacks/Python Scripts/ebay_money.py", line 8, in compute_insertion_fee if price <= .99: UnboundLocalError: local variable 'price' referenced before assignment Here is the code to my program: #gets the price of the item def listing_price(): price=input('What is the starting price?') #Gets the seling price def selling_price(): selling=input('What was the selling price?') #Computes the price of insertion def compute_insertion_fee(): if price <= .99: price= price+.25 elif price <= 9.99: price= price=.35 elif price <= 24.99: price= price=.60 elif price <= 49.99: price= price=1.20 elif price <= 199.99: price= price=2.40 elif price <= 499.99: price= price=3.60 elif price >= 500.00: price= price=4.80 print price #Computes the selling value def compute_final_value(): if selling == 0.00: print 'No fees' elif selling <= 25.00: selling= selling * .025 elif selling <= 1000.00: selling= ((selling - 25.00) * .0275)+ 1.31 elif selling >= 1000.00: selling= ((((selling - 25.00) - 1000.00) * .0150)+ 1.31+ 26.81) print selling # Prints the menu def print_menu(): print '1. Insertion fee.' print '2. Selling Fees.' print '7. Quit.' #Gets a menu choice from user menu_choice=0 print_menu() while menu_choice !=7: menu_choice= input("type in a number (1-7): ") if menu_choice == 1: listing_price() compute_insertion_fee() elif menu_choice == 2: selling_price() compute_final_value() elif menu_choice==7: pass I could really use so help thanks! From kent37 at tds.net Tue Jul 19 22:52:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Jul 2005 16:52:52 -0400 Subject: [Tutor] use gzip with large files In-Reply-To: <42DD32AC.5040305@h-lab.net> References: <60fae7c30507190715f42da0e@mail.gmail.com> <42DD32AC.5040305@h-lab.net> Message-ID: <42DD6824.7070200@tds.net> Hugo Gonz?lez Monteverde wrote: > for a file-like object with a read method: > > for line in file: > if not line: > break The test if not line: break is not needed with this form of looping; the loop will end automatically when it gets to the end of the file. > > line will be "" for EOF, "\n" for an empty line. No, you will not see the EOF in the loop, the loop will just terminate. Kent From hugonz at h-lab.net Tue Jul 19 19:19:14 2005 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 19 Jul 2005 12:19:14 -0500 Subject: [Tutor] How do I add an argument too... In-Reply-To: <42DBE8FF.7030600@gmail.com> References: <42DBE8FF.7030600@gmail.com> Message-ID: <42DD3612.6060907@h-lab.net> I use optparse wich can take some getting used to in the beginnning, but it help you easily create very powerful command line options. I is shipped with th epython distro. As soon as I get an example I wrote, I will post it to the list... Hugo Joseph Quigley wrote: > How do I add an argument too my program (with sys.argv) so that at a > console I can type: > > python foo.py -info > > or > python foo.py open /home/joe/foo.txt > > Thanks, > Joe > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Tue Jul 19 22:57:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 19 Jul 2005 13:57:29 -0700 (PDT) Subject: [Tutor] SQL headache with column In-Reply-To: <61d0e2b4050719134376306f37@mail.gmail.com> Message-ID: On Tue, 19 Jul 2005, Bernard Lebel wrote: > Ah yeah I to mention that I indeed tried fetchall(), but Python would > raise an attribute error: Hi Bernard, The cursor itself holds some internal state that mutates when we call cursor.execute(). So we use cursor.execute() often for it's side-effects. Use fetchall on the cursor, not the resulting return value of the execute()ion, and you should be ok. Hope this helps! From hugonz-lists at h-lab.net Tue Jul 19 23:02:02 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Tue, 19 Jul 2005 16:02:02 -0500 Subject: [Tutor] use gzip with large files In-Reply-To: <42DD6824.7070200@tds.net> References: <60fae7c30507190715f42da0e@mail.gmail.com> <42DD32AC.5040305@h-lab.net> <42DD6824.7070200@tds.net> Message-ID: <42DD6A4A.10208@h-lab.net> You're soooo right. missed that one, sorry... Kent Johnson wrote: > Hugo Gonz?lez Monteverde wrote: > >>for a file-like object with a read method: >> >>for line in file: >> if not line: >> break > > > The test > if not line: > break > is not needed with this form of looping; the loop will end automatically when it gets to the end of the file. > > >>line will be "" for EOF, "\n" for an empty line. > > > No, you will not see the EOF in the loop, the loop will just terminate. > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From 3dbernard at gmail.com Tue Jul 19 23:03:23 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Tue, 19 Jul 2005 17:03:23 -0400 Subject: [Tutor] SQL headache with column In-Reply-To: References: <61d0e2b4050719134376306f37@mail.gmail.com> Message-ID: <61d0e2b405071914034585783a@mail.gmail.com> Stupid me, you're right. Thanks Danny Bernard On 7/19/05, Danny Yoo wrote: > > > On Tue, 19 Jul 2005, Bernard Lebel wrote: > > > Ah yeah I to mention that I indeed tried fetchall(), but Python would > > raise an attribute error: > > Hi Bernard, > > The cursor itself holds some internal state that mutates when we call > cursor.execute(). So we use cursor.execute() often for it's side-effects. > > Use fetchall on the cursor, not the resulting return value of the > execute()ion, and you should be ok. > > > Hope this helps! > > From Xaviea.Bell at echostar.com Tue Jul 19 23:10:04 2005 From: Xaviea.Bell at echostar.com (Bell, Xaviea) Date: Tue, 19 Jul 2005 15:10:04 -0600 Subject: [Tutor] Help with ebay profit/loss program error Message-ID: <356F393A15F3A64F8F28F51D390D5B410EE06545@riv-excha4.echostar.com> It looks like theres a typo you have: price= price=.35. This would cause an error. -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Sam Klinger Sent: Tuesday, July 19, 2005 2:46 PM To: tutor at python.org Subject: [Tutor] Help with ebay profit/loss program error Hi my name is Sam Klinger and I made a smal program to help find out the cost of listing and selling an item on ebay. However I see nothing wrong with the code but I get these error messages: 1. Insertion fee. 2. Selling Fees. 7. Quit. type in a number (1-7): 1 What is the starting price?9 Traceback (most recent call last): File "C:/Documents and Settings/Sam/My Documents/Hacks/Python Scripts/ebay_money.py", line 46, in ? compute_insertion_fee() File "C:/Documents and Settings/Sam/My Documents/Hacks/Python Scripts/ebay_money.py", line 8, in compute_insertion_fee if price <= .99: UnboundLocalError: local variable 'price' referenced before assignment Here is the code to my program: #gets the price of the item def listing_price(): price=input('What is the starting price?') #Gets the seling price def selling_price(): selling=input('What was the selling price?') #Computes the price of insertion def compute_insertion_fee(): if price <= .99: price= price+.25 elif price <= 9.99: price= price=.35 elif price <= 24.99: price= price=.60 elif price <= 49.99: price= price=1.20 elif price <= 199.99: price= price=2.40 elif price <= 499.99: price= price=3.60 elif price >= 500.00: price= price=4.80 print price #Computes the selling value def compute_final_value(): if selling == 0.00: print 'No fees' elif selling <= 25.00: selling= selling * .025 elif selling <= 1000.00: selling= ((selling - 25.00) * .0275)+ 1.31 elif selling >= 1000.00: selling= ((((selling - 25.00) - 1000.00) * .0150)+ 1.31+ 26.81) print selling # Prints the menu def print_menu(): print '1. Insertion fee.' print '2. Selling Fees.' print '7. Quit.' #Gets a menu choice from user menu_choice=0 print_menu() while menu_choice !=7: menu_choice= input("type in a number (1-7): ") if menu_choice == 1: listing_price() compute_insertion_fee() elif menu_choice == 2: selling_price() compute_final_value() elif menu_choice==7: pass I could really use so help thanks! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From Christian.Wyglendowski at greenville.edu Tue Jul 19 23:23:38 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue, 19 Jul 2005 16:23:38 -0500 Subject: [Tutor] Getting singal strength of the received packet Message-ID: Signal strength is not stored in an IP packet. It is more of a radio-level statistic that would need to be gathered from the wireless device somehow. Christian > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of sunny sunny > Sent: Tuesday, July 19, 2005 12:18 PM > To: tutor at python.org > Subject: [Tutor] Getting singal strength of the received packet > > Hi, > > I am sending and receiving for a simple server application > over wirless link. > Can I get the signal strength of the received packet in Python? > > One way would be to get the value of the RSSI from /proc/net/wireless. > However I would like to get the signal strength (in terms of RSSI or > dBm) of the specific packet. Is it possible to do this in Python. > > I am using hostAP driver, and know that using C, I can get > the packet RSSI. > > Thanks > Santosh. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From missive at hotmail.com Tue Jul 19 23:59:22 2005 From: missive at hotmail.com (Lee Harr) Date: Wed, 20 Jul 2005 02:29:22 +0430 Subject: [Tutor] newbie help> audio IO + python Message-ID: >I've been looking at lots of sites and checked out the docs, but can't >find the info I am looking for to be able to detect audio input from >my sound card. You do not say if you need to do this in a cross-platform way. I thought maybe SDL (which is wrapped by pygame) might help, but this is closest I came : http://heavyspace.dyndns.org/corona/sdlscope/ _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From missive at hotmail.com Wed Jul 20 00:09:36 2005 From: missive at hotmail.com (Lee Harr) Date: Wed, 20 Jul 2005 02:39:36 +0430 Subject: [Tutor] Pager in Python? Message-ID: >Is there a command like more(1) or less(1) in python to display >the output of a command (e.g. dir()) one page at a time? How are you using dir() ? Is it in the "DOS Window" ? One option would be to just get a better console. You also might want to look at something like ipython. Using that, dir(foo) does not run through the pager, but foo? does (and provides a lot of nice extras also). _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.com/ From byron at christianfreebies.com Wed Jul 20 00:34:35 2005 From: byron at christianfreebies.com (Byron) Date: Tue, 19 Jul 2005 15:34:35 -0700 Subject: [Tutor] Getting singal strength of the received packet In-Reply-To: <8171b61605071910175ad0cf98@mail.gmail.com> References: <8171b61605071910175ad0cf98@mail.gmail.com> Message-ID: <42DD7FFB.6090806@christianfreebies.com> sunny sunny wrote: >Hi, > >I am sending and receiving for a simple server application over wirless link. >Can I get the signal strength of the received packet in Python? > Isn't this done strictly at the hardware level of the NIC? I don't believe that one can get this information from Python. Byron From jfouhy at paradise.net.nz Wed Jul 20 00:43:34 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 20 Jul 2005 10:43:34 +1200 (NZST) Subject: [Tutor] Help with ebay profit/loss program error In-Reply-To: <14ee462f05071913466990b504@mail.gmail.com> References: <14ee462f05071913466990b504@mail.gmail.com> Message-ID: <1121813014.42dd821609f61@www.paradise.net.nz> Quoting Sam Klinger : > Hi my name is Sam Klinger and I made a smal program to help find out > the cost of listing and selling an item on ebay. However I see nothing > wrong with the code but I get these error messages: Hi Sam, The problem is here: > def listing_price(): > price=input('What is the starting price?') This gets input from the user and stores it in a _local_ variable 'price'. When the function terminates, the variable goes out of existence. This means that, later on: > #Computes the price of insertion > def compute_insertion_fee(): > if price <= .99: > price= price+.25 'price' does not exist, so you get the error you are seeing. I recommend making use of the fact that functions can take parameters and can return values. For example: def listing_price(): price = float(raw_input('What is the starting price?')) return price def compute_insertion_fee(price): if price <= 0.99: # etc #Gets a menu choice from user menu_choice = 0 print_menu() while menu_choice !=7: menu_choice = int(raw_input("type in a number (1-7): ")) if menu_choice == 1: price = listing_price() compute_insertion_fee(price) # etc Incidentally: It is better to use raw_input, rather than input, for reasons that have been discussed several times on this list recently :-) -- John. From jfouhy at paradise.net.nz Wed Jul 20 01:00:23 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 20 Jul 2005 11:00:23 +1200 (NZST) Subject: [Tutor] Tkinter: justify label In-Reply-To: <61d0e2b405071911352d87bd6d@mail.gmail.com> References: <61d0e2b405071911352d87bd6d@mail.gmail.com> Message-ID: <1121814023.42dd860719eab@www.paradise.net.nz> Quoting Bernard Lebel <3dbernard at gmail.com>: > Can you specify a justification for a label widget? I'm reading there > is a justify option available on this page: > http://www.pythonware.com/library/tkinter/introduction/x611-text-formatting.htm > Although I don't know if this option works for label. It does; it just doesn't do what you think it does :-) justify is for multi-line labels. If you are looking to position the text within the label, you need to use anchor. eg: >>> from Tkinter import * >>> tk = Tk() >>> l1 = Label(tk, text='this is left\njustified', justify=LEFT) >>> l1.pack() >>> l2 = Label(tk, text='this, otoh, is right\njustified', justify=RIGHT) >>> l2.pack() >>> l3 = Label(tk, text='left aligned', anchor=W) >>> l3.pack(fill=X) >>> l4 = Label(tk, text='right aligned', anchor=E) >>> l4.pack(fill=X) -- John. From jfouhy at paradise.net.nz Wed Jul 20 01:18:09 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed, 20 Jul 2005 11:18:09 +1200 (NZST) Subject: [Tutor] Minesweeper the return In-Reply-To: References: Message-ID: <1121815089.42dd8a3106e59@www.paradise.net.nz> Quoting Alberto Troiano : > Please let's talk about this more! *grin* > I'm not sure if I'm following you, what I see here is a function inside > other function and the first function returns its inside function, but > how does it work? In Python, as in other modern languages, functions are "first-class" objects. In particular, you can pass functions as arguments to other functions, or return functions from other functions. I like examples: >>> def add(x, y): ... return x + y ... >>> f = add # Notice the lack of brackets after 'add' >>> f(3, 5) 8 >>> f(9, 12) 21 In this case, all I've done is assigned to f the function 'add'. This means that f is now a function, and I can call it, even though I never did 'def f(x, y)' anywhere. >>> def square(x): ... return x*x ... >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> map(square, range(10)) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] The 'map' builtin function takes two arguments: a function and a list. It makes a new list by applying the function to each element of the old list. ie: This is an example of passing a functino as an argument. Finally: >>> def makeAdder(x): ... def add(y): ... return x + y ... return add ... >>> f = makeAdder(5) >>> f(3) 8 >>> f(8) 13 'def add(y)' defines a function of one argument, which adds that argument to x, and returns the result. What is x? Well, x is a variable in the scope of makeAdder(); it gets bound to the argument you pass. In my example, x was bound to 5. So, effectively, we have created a new function by: 'def add(y): return 5 + y', and then returned that function to f. We can now call f and see the result. HTH! -- John. [ps: sorry for the troll.. I couldn't resist :-) ] From sunny.tired at gmail.com Wed Jul 20 04:49:58 2005 From: sunny.tired at gmail.com (sunny sunny) Date: Tue, 19 Jul 2005 22:49:58 -0400 Subject: [Tutor] Getting singal strength of the received packet In-Reply-To: <42DD7FFB.6090806@christianfreebies.com> References: <8171b61605071910175ad0cf98@mail.gmail.com> <42DD7FFB.6090806@christianfreebies.com> Message-ID: <8171b616050719194919cea5a3@mail.gmail.com> Hi, In C I have seen some programs such as kismet etc where c programs could be written to get the SS from the card. The idea probably is to read the prism 2 header from the driver. This I guess is a bit more lower than the "raw socket" where we can get the MAC layer frame. The prism 2 header gives you parameters such as the signal strength etc which depend on the physical channel. My knowledge in this area is limited. Santosh. On 7/19/05, Byron wrote: > sunny sunny wrote: > > >Hi, > > > >I am sending and receiving for a simple server application over wirless link. > >Can I get the signal strength of the received packet in Python? > > > > Isn't this done strictly at the hardware level of the NIC? I don't > believe that one can get this information from Python. > > Byron > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mdcooper at uvic.ca Wed Jul 20 08:18:09 2005 From: mdcooper at uvic.ca (mdcooper) Date: Tue, 19 Jul 2005 23:18:09 -0700 Subject: [Tutor] 3d manipulation Message-ID: <42E104FF@wm2.uvic.ca> Hello all, I need to make a program that will allow a user to rotate and translate a molecule (using the mouse) so as to bring any given atom of that molecule (or plane encompassing a number of atoms) to the X-Y plane (i.e. the Z component would be 0). I cannot find appropriate modules to allow this. If someone can point out a 3d manipulation module, I would be extremely appreciative. Thanks, Matthew mdcooper at uvic.ca From dyoo at hkn.eecs.berkeley.edu Wed Jul 20 08:30:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 19 Jul 2005 23:30:30 -0700 (PDT) Subject: [Tutor] Getting singal strength of the received packet In-Reply-To: <8171b616050719194919cea5a3@mail.gmail.com> Message-ID: On Tue, 19 Jul 2005, sunny sunny wrote: > In C I have seen some programs such as kismet etc where c programs could > be written to get the SS from the card. The idea probably is to read the > prism 2 header from the driver. This I guess is a bit more lower than > the "raw socket" where we can get the MAC layer frame. Hello, John Leach did mention starting to write a GNOME client for Kismet in Python: http://johnleach.co.uk/words/archives/date/2004/08/ I don't know how far his work as gone into making Kismet's data available from Python, but at least it looks like it's possible in theory. It looks like Kismet provides a server architecture that we might be able to take advantage of. In fact, there's already a project in Perl for this called 'gkismet': http://gkismet.sourceforge.net/ and there's nothing really tricky in there (most of the stuff in Connection.pm and PacketWindow.pm look pretty straightforward). gkismet reads very well --- they've abstracted things cleanly --- and their source code makes it pretty clear how things work. Once Kismet's up and running, they open a regular socket to Kismet (looks like Kismet's server runs on port 2501, perhaps?), and then start doing regular socket communication. There's a good Python socket HOWTO here: http://www.amk.ca/python/howto/sockets/ There's probably not much (except for human motivation) that stops one from using Kismet from Python. It would make an interesting project for someone with time. *grin* Hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Jul 20 08:38:11 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue, 19 Jul 2005 23:38:11 -0700 (PDT) Subject: [Tutor] 3d manipulation [VPython, or pyopengl, or pymol?] In-Reply-To: <42E104FF@wm2.uvic.ca> Message-ID: On Tue, 19 Jul 2005, mdcooper wrote: > I need to make a program that will allow a user to rotate and translate > a molecule (using the mouse) so as to bring any given atom of that > molecule (or plane encompassing a number of atoms) to the X-Y plane > (i.e. the Z component would be 0). I cannot find appropriate modules to > allow this. Hello, You might find the VPython project relevant to this: http://www.vpython.org/ Alternatively, something like the pyopengl library might work out: http://pyopengl.sourceforge.net/ OpenGL is a well-established standard in 3d animated graphics. However, this might be a bit too low-level. If it's possible for you to reuse exising work, take a look at PyMol: http://pymol.sourceforge.net/ PyMol uses OpenGL underneath the surface, and more than that, they provide the primitives for playing with molecules. They've already done most of the heavy lifting there, so you might be able to take advantage of this. I hope this helps! From work at infomaniak.ch Wed Jul 20 09:04:20 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Wed, 20 Jul 2005 09:04:20 +0200 Subject: [Tutor] SQL headache with column In-Reply-To: <61d0e2b405071914034585783a@mail.gmail.com> References: <61d0e2b4050719134376306f37@mail.gmail.com> <61d0e2b405071914034585783a@mail.gmail.com> Message-ID: <20050720070420.GC8689@obs.unige.ch> did you heard about sqlobject ? give a try...http://www.sqlobject.org/ Ced. -- Cedric BRINER From cyresse at gmail.com Wed Jul 20 14:05:20 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 21 Jul 2005 00:05:20 +1200 Subject: [Tutor] Parsing problem In-Reply-To: References: Message-ID: Well, I've been poking around and... well.. this is way better than writing complex regexes. To suit my needs, I need something that can handle - foo = bar foo = 20 foo = { bar 20 } foo = { bar = 20 baz} foo = {bar = 20 baz { dave henry}} OK, so the last one's extreme. So far, I can handle down to foo = { bar 20 }, but it looks ugly, so some feedback on my very rough usage of pyparsing would be great. >>> from pyparsing import Word, Suppress, alphas, nums >>> q = (Word(alphas) + Suppress("=") + ( ( Word(nums) | Word(alphas) ) | ( Suppress("{") + pyparsing.ZeroOrMore( Word (alphas) | Word(nums) ) + Suppress("}" ) ) ) ) >>> q.parseString("foo = bar").asList() ['foo', 'bar'] >>> q.parseString("a = 23").asList() ['a', '23'] >>> q.parseString(" foo = { bar baz 23 }").asList() ['foo', 'bar', 'baz', '23'] Yeech. I'm sure I can shorten that a whole lot ( I just found alphanums in the manual, d'oh. ), but it works pretty good out of the box. Thanks for the heads up. Couple of queries - I think I understand Danny's example of circular references. ------ Value << (Symbol | Sequence) Sequence << (pyparsing.Suppress("{") + pyparsing.Group(pyparsing.ZeroOrMore(Value)) + pyparsing.Suppress("}")) ------ Sequence depends on Value for it's *ahem* value, but Value depends on Sequence for it's value, so I'll play with that. Is anyone able to post an example of returning dictionaries from ParsingResults? If so, it would be brilliant. The documentation states - "the Dict class generates dictionary entries using the data of the input text - in addition to ParseResults listed as [ [ a1, b1, c1, ...], [ a2, b2, c2, ...] ] it also acts as a dictionary with entries defined as { a1 : [ b1, c1, ... ] }, { a2 : [ b2, c2, ... ] };" Problem is, I haven't figured out how to use it yet, I know I could use pyparsing.Group(stuff) to ensure proper key:value pairings. Thanks for the pointers so far, feeling very chuffed with myself for managing to get this far, I had strayed into VBA territory, it's nice to work with real objects again. And of course, always open to being shown the simple, elegant way. ;) Many thanks, Liam Clarke On 7/19/05, Liam Clarke wrote: > > Thanks guys, I daresay I will have a lot of questions regarding this, but > at least I have a point to start digging and a better shovel! > > Cheers, > > Liam Clarke > > On 7/19/05, Danny Yoo wrote: > > > > > > > > On Mon, 18 Jul 2005, Liam Clarke wrote: > > > > > country = { > > > tag = ENG > > > ai = { > > > flags = { } > > > combat = { DAU FRA ORL PRO } > > > continent = { } > > > area = { } > > > region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" > > "NAtlanticSea" > > > "TagoSea" "WCAtlanticSea" } > > > war = 60 > > > ferocity = no > > > } > > > } > > > > [Long message ahead; skip if you're not interested.] > > > > > > Kent mentioned PyParsing, > > > > http://pyparsing.sourceforge.net/ > > > > which is a really excellent system. Here's a demo of what it can do, > > just > > so you have a better idea what pyparsing is capable of. > > > > (For the purposes of this demo, I'm doing 'import pyparsing', but in > > real > > usage, I'd probably use 'from pyparsing import ...' just to make things > > less verbose.) > > > > > > Let's say that we want to recognize a simpler subset of the data that > > you > > have there, something like: > > > > { fee fie foo fum } > > > > And let's imagine that we have a function parse() that can take a string > > like: > > > > ###### > > >>> testString = """ > > ... { fee fie foo fum } > > ... """ > > ###### > > > > > > This imaginary parse() function could turn that into something that > > looks > > like a Python value, like this: > > > > ###### > > >>> parse(testString) > > (["fee", "fie", "foo", "fum"]) > > ###### > > > > That's our goal; does this make sense so far? So how do we start? > > > > > > > > Instead of going at the big goal of doing: > > > > country = { fee fie foo fum } > > > > let's start small by teaching our system how to recognize the innermost > > parts, the small things like fee or foo. Let's start there: > > > > ###### > > >>> Symbol = pyparsing.Word(pyparsing.alphas) > > ###### > > > > We want a Symbol to be able to recognize a "Word" made up of alphabetic > > letters. Does this work? > > > > ###### > > >>> Symbol.parseString("fee") > > (['fee'], {}) > > ####### > > > > Symbol is now a thing that can parse a string, and return a list of > > results in a pyparsing.ParseResults object. > > > > > > Ok, if we can recognize Symbols, let's go for the jugular: > > > > { fee fie foo fum } > > > > > > Let's call this a Sequence. > > > > ###### > > >>> Sequence = "{" + pyparsing.ZeroOrMore (Symbol) + "}" > > ###### > > > > > > A Sequence is made up of zero or more Symbols. > > > > > > Wait, let's change that, for a moment, to "A Sequence is made up of zero > > or more Values." (You'll see why in a moment. *grin*) > > > > > > > > If we turn toward this strange way, then we need a definition for a > > Value: > > > > ###### > > >>> Value = Symbol > > ###### > > > > and now we can say that a Sequence is a bunch of Values: > > > > ###### > > >>> Sequence = "{" + pyparsing.ZeroOrMore(Value) + "}" > > ###### > > > > > > Let's try this out: > > > > ###### > > >>> Sequence.parseString('{ fee fie foo fum}') > > (['{', 'fee', 'fie', 'foo', 'fum', '}'], {}) > > ###### > > > > > > This is close, but it's not quite right: the problem is that we'd like > > to > > somehow group the results all together in a list, and without the > > braces. > > That is, we actually want to see: > > > > [['fee', 'fie', 'foo', 'fum']] > > > > in some form. (Remember, we want a list of a single result, and that > > result should be our Sequence.) > > > > > > How do we get this working? We have to tell pyparsing to "Group" the > > middle elements together in a collection, and to "suppress" the braces > > from the result. > > > > Here we go: > > > > ###### > > >>> Sequence = (pyparsing.Suppress("{") + > > ... pyparsing.Group(pyparsing.ZeroOrMore(Value)) + > > ... pyparsing.Suppress ("}")) > > ###### > > > > Does this work? > > > > > > ###### > > >>> Sequence.parseString('{ fee fie foo fum}') > > ([(['fee', 'fie', 'foo', 'fum'], {})], {}) > > ###### > > > > > > That looks a little messy and more nested than expected. > > > > > > Actually, what's happening is that we're looking at that > > pyparsing.ParseResults object, so there's more nesting in the string > > representation than what's really there. We can use the ParseResults's > > asList() method to make it a little easier to see what the real result > > value looks like: > > > > ###### > > >>> Sequence.parseString('{ fee fie foo fum}').asList() > > [['fee', 'fie', 'foo', 'fum']] > > ###### > > > > That's better. > > > > > > > > Out of curiosity, wouldn't it be neat if we could parse out something > > like > > this? > > > > { fee fie {foo "fum"} } > > > > *cough* *cough* > > > > What we'd like to do is make Sequence itself a possible value. The > > problem is that then there's a little circularity involved: > > > > > > ### Illegal PyParsing pseudocode ### > > Value = Symbol | Sequence > > > > Sequence = (pyparsing.Suppress("{") + > > pyparsing.Group(pyparsing.ZeroOrMore(Value)) + > > pyparsing.Suppress ("}")) > > ###### > > > > The problem is that Value can't be defined before Sequence is, and > > vice-versa. We break this problem by telling PyParsing "ok, the > > following > > rules will come up soon" and "forward" define them: > > > > ###### > > >>> Value = pyparsing.Forward() > > >>> Sequence = pyparsing.Forward() > > ###### > > > > and once we have these forward declarations, we can then reconnect them > > to > > their real definitions by using '<<'. (This looks bizarre, but it > > applies > > just to rules that are Forward()ed.) > > > > ###### > > Value << (Symbol | Sequence) > > Sequence << (pyparsing.Suppress("{") + > > pyparsing.Group(pyparsing.ZeroOrMore(Value)) + > > pyparsing.Suppress("}")) > > ###### > > > > > > Let's try it: > > > > ###### > > >>> Value.parseString(' { fee fie {foo fum} } ').asList() > > [['fee', 'fie', ['foo', 'fum']]] > > ###### > > > > > > Cool. > > > > > > Ok, that was a little artificial, but oh well. The idea is we now know > > how to say: > > > > A Value is either a Symbol or Sequence > > > > and > > > > A Sequence is a bunch of Values > > > > without getting into trouble with pyparsing, and that's important > > whenever > > we're dealing with things that have recursive structure... like: > > > > country = { > > tag = ENG > > ai = { > > flags = { } > > combat = { DAU FRA ORL PRO } > > continent = { } > > area = { } > > region = { "British Isles" > > "NorthSeaSea" > > "ECAtlanticSea" > > "NAtlanticSea" > > "TagoSea" > > "WCAtlanticSea" } > > war = 60 > > ferocity = no } > > } > > > > Anyway, this is a really fast whirlwind tour of pyparsing, with some > > intentional glossing-over of hard stuff, just so you get a better idea > > of > > the core of parsing. Sorry if it went fast. *grin* > > > > > > If you have questions, please feel free to ask! > > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/91cd582c/attachment.htm From 3dbernard at gmail.com Wed Jul 20 14:28:41 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 20 Jul 2005 08:28:41 -0400 Subject: [Tutor] Tkinter: justify label In-Reply-To: <1121814023.42dd860719eab@www.paradise.net.nz> References: <61d0e2b405071911352d87bd6d@mail.gmail.com> <1121814023.42dd860719eab@www.paradise.net.nz> Message-ID: <61d0e2b405072005283b5b318b@mail.gmail.com> Awesome, thanks a bunch! Bernard On 7/19/05, jfouhy at paradise.net.nz wrote: > Quoting Bernard Lebel <3dbernard at gmail.com>: > > > Can you specify a justification for a label widget? I'm reading there > > is a justify option available on this page: > > http://www.pythonware.com/library/tkinter/introduction/x611-text-formatting.htm > > Although I don't know if this option works for label. > > It does; it just doesn't do what you think it does :-) > > justify is for multi-line labels. If you are looking to position the text > within the label, you need to use anchor. > > eg: > > >>> from Tkinter import * > >>> tk = Tk() > >>> l1 = Label(tk, text='this is left\njustified', justify=LEFT) > >>> l1.pack() > >>> l2 = Label(tk, text='this, otoh, is right\njustified', justify=RIGHT) > >>> l2.pack() > >>> l3 = Label(tk, text='left aligned', anchor=W) > >>> l3.pack(fill=X) > >>> l4 = Label(tk, text='right aligned', anchor=E) > >>> l4.pack(fill=X) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From albertito_g at hotmail.com Wed Jul 20 14:58:34 2005 From: albertito_g at hotmail.com (Alberto Troiano) Date: Wed, 20 Jul 2005 12:58:34 +0000 Subject: [Tutor] Minesweeper the return In-Reply-To: <1121815089.42dd8a3106e59@www.paradise.net.nz> Message-ID: I think I got it......finally.......*grin* I will try to put this in practice right away and let you know if I have so more problems or if I didn't understand what I think I did. jeje Thank you Jhon and Danny Best Regards, Alberto >From: jfouhy at paradise.net.nz >To: "tutor at python.org" >Subject: Re: [Tutor] Minesweeper the return >Date: Wed, 20 Jul 2005 11:18:09 +1200 (NZST) > >Quoting Alberto Troiano : > > > Please let's talk about this more! *grin* > > I'm not sure if I'm following you, what I see here is a function inside > > other function and the first function returns its inside function, but > > how does it work? > >In Python, as in other modern languages, functions are "first-class" >objects. >In particular, you can pass functions as arguments to other functions, or >return >functions from other functions. > >I like examples: > > >>> def add(x, y): >... return x + y >... > >>> f = add # Notice the lack of brackets after 'add' > >>> f(3, 5) >8 > >>> f(9, 12) >21 > >In this case, all I've done is assigned to f the function 'add'. This >means >that f is now a function, and I can call it, even though I never did 'def >f(x, >y)' anywhere. > > >>> def square(x): >... return x*x >... > >>> range(10) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> map(square, range(10)) >[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] > >The 'map' builtin function takes two arguments: a function and a list. It >makes >a new list by applying the function to each element of the old list. >ie: This is an example of passing a functino as an argument. > >Finally: > > >>> def makeAdder(x): >... def add(y): >... return x + y >... return add >... > >>> f = makeAdder(5) > >>> f(3) >8 > >>> f(8) >13 > >'def add(y)' defines a function of one argument, which adds that argument >to x, >and returns the result. What is x? Well, x is a variable in the scope of >makeAdder(); it gets bound to the argument you pass. In my example, x was >bound >to 5. So, effectively, we have created a new function by: 'def add(y): >return 5 >+ y', and then returned that function to f. We can now call f and see the >result. > >HTH! > >-- >John. > >[ps: sorry for the troll.. I couldn't resist :-) ] >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor Gaucho From 3dbernard at gmail.com Wed Jul 20 15:35:17 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Wed, 20 Jul 2005 09:35:17 -0400 Subject: [Tutor] Dynamically populate Tkinter OptionMenu with list Message-ID: <61d0e2b40507200635417d2cff@mail.gmail.com> Hello, I have this problem. I build a list of elements, and I never know in advance how many or what will be the elements. I then wish to populate an OptionMenu with this list of elements. How can I do that? The reason I'm asking is I'm building a little GUI to enter records in a SQL table. I want to give the user the choice of tables (with the OptionMenu), however we never know in advance the menus there will be in a given database. My current code below. It all starts with the last function, enterAsset(). # ----------------------------------------------------- # Table filling # ----------------------------------------------------- def getTables(): """ Get the list of tables from the database. """ oConnection = connect2db() oCursor = oConnection.cursor() oResult = oCursor.execute( "SHOW TABLES" ) aRows = oCursor.fetchall() aTables = [ tRow[0] for tRow in aRows ] oCursor.close() oConnection.close() return aTables def getTableColumns( sTableName ): """ Lists and returns the list of columns from a given table. """ oConnection = connect2db() oCursor = oConnection.cursor() oResult = oCursor.execute( "SHOW COLUMNS FROM " + sTableName ) aRows = oCursor.fetchall() aColumns = [ aRow[0] for aRow in aRows if aRow[0] != 'ID' ] oCursor.close() oConnection.close() return aColumns # ------------------------ # Tkinter functions def fetchAndDestroy(): """ Retrieves the values entered in the input fields. Maps them in-place to the label keys dictionary. Terminates the input field gui. """ for oEntry in aEntries: sEntry = oEntry.get() if sEntry == '': sEntry = 'null' dEntryValues.setdefault( str(oEntry), [] ).append( sEntry ) oRoot.destroy() def makeformAsset( oRoot, aColumns ): """ Generates the input form, based on the provided list of table columns. """ for sColumn in aColumns: oRow = Frame( oRoot ) oLabel = Label( oRow, width = 25, text = sColumn, anchor = E ) oEntry = Entry( oRow, width = 50, relief = RIDGE ) dEntryValues.setdefault( str(oEntry), [] ).append( sColumn ) oRow.pack( side = TOP, fill = X ) oLabel.pack( side = LEFT ) oEntry.pack( side = RIGHT, expand = YES, fill = X ) aEntries.append( oEntry ) def enterAsset(): """ Creates a form to fill in the info to create a new asset. """ global dEntryValues global oRoot global aEntries dEntryValues = {} oRoot = Tk() aEntries = [] # Get available tables aTables = getTables() var1 = StringVar() for sTable in aTables: oOption = OptionMenu( oRoot, var1, sTable ) oOption.pack( fill = X ) var1.set( aTables[0] ) sTableName = var1.get() # Get columns for this table aColumns = getTableColumns( sTableName ) makeformAsset( oRoot, aColumns ) Button( oRoot, text = 'OK', command = ( fetchAndDestroy ) ).pack( side = LEFT, expand = YES, fill = X ) oRoot.mainloop() Thanks Bernard From falcon3166 at hotmail.com Wed Jul 20 18:41:07 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 20 Jul 2005 10:41:07 -0600 Subject: [Tutor] shape_calc.py References: Message-ID: Alberto, Sounds great. Go right ahead, and if you have any ideas for any programs or modifications from the apps at my Download page at http://www.npinnowebsite.ca/download.htm, feel free to send them also. Nathan ----- Original Message ----- From: "Alberto Troiano" To: Sent: Monday, July 18, 2005 12:40 PM Subject: Re: [Tutor] shape_calc.py > Hey Nathan. I was watching your app and it seems like it's not finished yet. > Do you take constructive critics? > > First of all, the app only run once, so if I want to calc another area, I'll > have to run the prog again and that's not pretty nice > > Second, have you considered using GUI to make this app? Maybe show the > figure with its sizes or something like that > > I can send you the modifications I have made to your code if you're > interested. Don't mean to correct you or to stole your app, only suggestions > and ideas > > Best Regards to you > > Alberto > >>From: "Nathan Pinno" >>To: "Raj Moodley" >>CC: tutor at python.org >>Subject: Re: [Tutor] shape_calc.py >>Date: Mon, 18 Jul 2005 10:05:32 -0600 >> >> Raj, >> >> My original interest was for school, now I use it to develop games and >>apps. I work at McDonalds Restaurant as Crew. I have developed another app >>called mini_calc and a game called Guess the Number; and was working on >>Giant Calculator, but gave up on it. I am also working on a MasterMind-like >>game, but it giving me headaches :). >> >> Nathan Pinno. >> P.S. Enjoy the shape_calc. You can find Mini_calc and Guess the Number >>on my site at this address: http://www.npinnowebsite.ca/download.htm. >> ----- Original Message ----- >> From: Raj Moodley >> To: 'Nathan Pinno' >> Sent: Monday, July 18, 2005 9:56 AM >> Subject: RE: shape_calc.py >> >> >> Hi Nathan, thanks for the email, please send it to me, would like to >>improve my understanding. >> >> >> >> What do u do? What's your interest in Python? Have you developed any >>other apps using Python? >> >> >> >> Kind regards >> >> >> >> Raj Moodley >> >> >> >> >>---------------------------------------------------------------------------- >> >> From: Nathan Pinno [mailto:falcon3166 at hotmail.com] >> Sent: 18 July 2005 03:41 PM >> To: Raj Moodley >> Cc: tutor at python.org >> Subject: Re: shape_calc.py >> >> >> >> Raj, >> >> >> >> Shape_calc is a calculator for finding information about shapes, >>e.g. perimeter, area, and so forth. >> >> >> >> HTH (Hope This Helps), >> >> Nathan Pinno >> >> ----- Original Message ----- >> >> From: Raj Moodley >> >> To: falcon3166 at hotmail.com >> >> Sent: Monday, July 18, 2005 2:54 AM >> >> Subject: shape_calc.py >> >> >> >> Hi Nathan, wanted to find out what is shape_calc.py about? Am a >>newbie. >> >> >> >> Kind regards >> >> >> >> Raj Moodley >> >> >> >>_______________________________________________ >>Tutor maillist - Tutor at python.org >>http://mail.python.org/mailman/listinfo/tutor > > > Gaucho > > > From nephish at xit.net Wed Jul 20 18:55:35 2005 From: nephish at xit.net (nephish) Date: Wed, 20 Jul 2005 16:55:35 +0000 Subject: [Tutor] confusing smtp problem Message-ID: <1121878535l.32243l.0l@texaspivot> Hey there, i am trying to get an email through an SMTP server on a windows computer from a linux machine on the same network. >>> import smtplib >>> import MySQLdb >>> Server = smtplib.SMTP('10.10.10.32') >>> ToAddress = 'nephish at xit.net' >>> FromAddress = 'nephish at xit.net.com' >>> Message = 'Some text message' >>> Server.sendmail(FromAddress, ToAddress, Message) {} but nothing goes through, now if i do this... >>> Server.connect() i get this Traceback (innermost last): File "", line 1, in ? File "/usr/lib/python2.3/smtplib.py", line 303, in connect (code, msg) = self.getreply() File "/usr/lib/python2.3/smtplib.py", line 347, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed now if i use the server on this computer ('localhost') everything works ok. any ideas? thanks, <>< From cowen296piper at msn.com Wed Jul 20 20:17:21 2005 From: cowen296piper at msn.com (Brett C.) Date: Wed, 20 Jul 2005 14:17:21 -0400 Subject: [Tutor] Getting started Message-ID: Which Python version should I download, I have Windows XP and am just getting started in the programming area so alot of the descriptions are to confusing for me to understand, anyhelp would be appreciated From ajikoe at gmail.com Wed Jul 20 20:25:37 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 20 Jul 2005 20:25:37 +0200 Subject: [Tutor] Getting started In-Reply-To: References: Message-ID: try python 2.4.1 from this web site: http://www.python.org/download/ cheers, pujo On 7/20/05, Brett C. wrote: > Which Python version should I download, I have Windows XP and am just > getting started in the programming area so alot of the descriptions are to > confusing for me to understand, anyhelp would be appreciated > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sixbix at localnet.com Wed Jul 20 20:36:49 2005 From: sixbix at localnet.com (Kevin Bixler) Date: Wed, 20 Jul 2005 13:36:49 -0500 Subject: [Tutor] Reversing Message-ID: <001b01c58d59$fe4ef3c0$dd72b340@shmily> I was asked to make a program that reverses the text that a user would input. I have tried what I thought would work which is phrase.reverse(). phrase = the raw_input. Help! Thank you, Kevin Bixler -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050720/8fa11991/attachment.htm From tutor.python.org at pooryorick.com Wed Jul 20 21:00:48 2005 From: tutor.python.org at pooryorick.com (Poor Yorick) Date: Wed, 20 Jul 2005 15:00:48 -0400 Subject: [Tutor] Reversing In-Reply-To: <001b01c58d59$fe4ef3c0$dd72b340@shmily> References: <001b01c58d59$fe4ef3c0$dd72b340@shmily> Message-ID: <42DE9F60.3020100@pooryorick.com> Kevin Bixler wrote: > I was asked to make a program that reverses the text that a user would > input. I have tried what I thought would work which is > phrase.reverse(). phrase = the raw_input. Help! > Thank you, > Kevin Bixler Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = 'hello there' >>> a[::-1] 'ereht olleh' From andreengels at gmail.com Wed Jul 20 22:51:44 2005 From: andreengels at gmail.com (Andre Engels) Date: Wed, 20 Jul 2005 22:51:44 +0200 Subject: [Tutor] Getting two files to print In-Reply-To: <42DC1051.6090303@med.unc.edu> References: <42DC1051.6090303@med.unc.edu> Message-ID: <6faf39c905072013511a428c5d@mail.gmail.com> (answer at the bottom) On 7/18/05, Philip Carl wrote: > I have no more hair to pull out, so I'm asking the group for help on a > VERY simple question. I have two very similar text files to read-one > with the final letters in the name 10%.txt and the other 20%.txt. I've > written the following simple code to read these two files: > > # Program to read and print two text fiiles > fileNameA = > 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt' > #text file one > firstFile=open (fileNameA,'r') > inFileLeftA = 1 #more file to read > inLineA=[0] > while inFileLeftA: > inLineA = firstFile.readline() > if (inLineA == ''): > infileLeftA = 0 #if empty line end of first file > > else: > print inLineA > firstFile.close() > > fileNameB = > 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt' > #text file two > secondFile=open (fileNameB,'r') > inFileLeftB = 1 #more file to read > inLineB=[0] > while inFileLeftB: > inLineB = secondFile.readline() > if (inLineB == ''): > infileLeftB = 0 #if empty line end of second file > > else: > print inLineB > secondFile.close() > > I realize that I probably ought to be able to code this more > efficiently, but as a rank beginner I am less worried about efficiency > than output. I can't seem to get BOTH files to print when run as > presented, although when I split the program into two programs each file > seems to print OK. As written here however, I can get the first but > not the second textfile to print. What am I doing wrong?. You call the variable inFileLeftA, but when you try to set it to 0, you use the name infileLeftA instead. That's another variable, so inFileLeftA always remains 1. Regarding the "ought to be able to code this more efficiently": The obvious thing to do seems to be to use a function, so you have to type in everything once instead of twice, like this: # start of code def printTextFile(fn): # Print the contents of textfile fn file = open(fn,'r') inFileLeft = 1 inLine=[0] while inFileLeft: inLine = file.readline() if inLine == '': inFileLeft = 0 else: print inLine file.close() printTextFile('c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt') printTextFile('c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt') # end of code There are other things that could be improved, but this is the main one by far. Andre Engels From ghost04 at mwr.is Wed Jul 20 21:53:59 2005 From: ghost04 at mwr.is (Jimmy) Date: Wed, 20 Jul 2005 19:53:59 -0000 Subject: [Tutor] {Possible Spam?} How to use the import math function Message-ID: <200507201948.j6KJmcAo012790@mwr.mwr.is> My assignment is this: 4. Read chapter 3 from "How to Think Like a Computer Scientist" (see the background materials.) Implement all the examples and exercises in Python-Eclipse and after you have successfully run them, export them to be combined in a zip with with the other assignments above. The course material I have read is this: 3.4 Math functions In mathematics, you have probably seen functions like sin and log, and you have learned to evaluate expressions like sin(pi/2) and log(1/x). First, you evaluate the expression in parentheses (the argument). For example, pi/2 is approximately 1.571, and 1/x is 0.1 (if x happens to be 10.0). Then, you evaluate the function itself, either by looking it up in a table or by performing various computations. The sin of 1.571 is 1, and the log of 0.1 is -1 (assuming that logindicates the logarithm base 10). This process can be applied repeatedly to evaluate more complicated expressions like log(1/sin(pi/2)). First, you evaluate the argument of the innermost function, then evaluate the function, and so on. Python has a math module that provides most of the familiar mathematical functions. A module is a file that contains a collection of related functions grouped together. Before we can use the functions from a module, we have to import them: >>> import math To call one of the functions, we have to specify the name of the module and the name of the function, separated by a dot, also known as a period. This format is called dot notation. >>> decibel = math.log10 (17.0) >>> angle = 1.5 >>> height = math.sin(angle) The first statement sets decibel to the logarithm of 17, base 10. There is also a function called log that takes logarithm base e. The third statement finds the sine of the value of the variable angle. sin and the other trigonometric functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide by 360 and multiply by 2*pi. For example, to find the sine of 45 degrees, first calculate the angle in radians and then take the sine: >>> degrees = 45 >>> angle = degrees * 2 * math.pi / 360.0 >>> math.sin(angle) The constant pi is also part of the math module. If you know your geometry, you can verify the result by comparing it to the square root of two divided by two: >>> math.sqrt(2) / 2.0 0.707106781187 But I have no clue on how to make it work. I tried many different variations to get it to work but in the end nothing happened. Any help you guys can provide would be awesome, I am such a noob to programming it ain't even funny. Thanks.... Jimmy -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050720/2650f9aa/attachment.htm From andreengels at gmail.com Wed Jul 20 23:03:47 2005 From: andreengels at gmail.com (Andre Engels) Date: Wed, 20 Jul 2005 23:03:47 +0200 Subject: [Tutor] {Possible Spam?} How to use the import math function In-Reply-To: <6faf39c905072014033dcd41f9@mail.gmail.com> References: <200507201948.j6KJmcAo012790@mwr.mwr.is> <6faf39c905072014033dcd41f9@mail.gmail.com> Message-ID: <6faf39c90507201403422d50d5@mail.gmail.com> Please, be more precise. When you say "I tried many different variations", variations of what? And what kind of variations? When you say "to get it to work", what is "it"? When you say, "nothing happened", what do you mean exactly - did your program end with no output? Did it NOT end with no output? Did you get an error message? Andre Engels On 7/20/05, Jimmy wrote: > > > > My assignment is this: > > 4. Read chapter 3 from "How to Think Like a Computer Scientist" (see the > background materials.) Implement all the examples and exercises in > Python-Eclipse and after you have successfully run them, export them to be > combined in a zip with with the other assignments above. > > > > The course material I have read is this: > 3.4 Math functions > > In mathematics, you have probably seen functions like sin and log, and you > have learned to evaluate expressions like sin(pi/2) and log(1/x). First, you > evaluate the expression in parentheses (the argument). For example, pi/2 is > approximately 1.571, and 1/x is 0.1 (if x happens to be 10.0). > > Then, you evaluate the function itself, either by looking it up in a table > or by performing various computations. The sin of 1.571 is 1, and the log of > 0.1 is -1 (assuming that logindicates the logarithm base 10). > > This process can be applied repeatedly to evaluate more complicated > expressions like log(1/sin(pi/2)). First, you evaluate the argument of the > innermost function, then evaluate the function, and so on. > > Python has a math module that provides most of the familiar mathematical > functions. A module is a file that contains a collection of related > functions grouped together. > > Before we can use the functions from a module, we have to import them: > > >>> import math > > To call one of the functions, we have to specify the name of the module and > the name of the function, separated by a dot, also known as a period. This > format is called dot notation. > > >>> decibel = math.log10 (17.0) > >>> angle = 1.5 > >>> height = math.sin(angle) > > The first statement sets decibel to the logarithm of 17, base 10. There is > also a function called log that takes logarithm base e. > > The third statement finds the sine of the value of the variable angle. sin > and the other trigonometric functions (cos, tan, etc.) take arguments in > radians. To convert from degrees to radians, divide by 360 and multiply by > 2*pi. For example, to find the sine of 45 degrees, first calculate the angle > in radians and then take the sine: > > >>> degrees = 45 > >>> angle = degrees * 2 * math.pi / 360.0 > >>> math.sin(angle) > > The constant pi is also part of the math module. If you know your geometry, > you can verify the result by comparing it to the square root of two divided > by two: > > >>> math.sqrt(2) / 2.0 > 0.707106781187 > > But I have no clue on how to make it work. I tried many different > variations to get it to work but in the end nothing happened. Any help you > guys can provide would be awesome, I am such a noob to programming it ain't > even funny. Thanks???. > > > > > > Jimmy > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From dyoo at hkn.eecs.berkeley.edu Wed Jul 20 23:23:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 20 Jul 2005 14:23:35 -0700 (PDT) Subject: [Tutor] {Possible Spam?} How to use the import math function In-Reply-To: <200507201948.j6KJmcAo012790@mwr.mwr.is> Message-ID: On Wed, 20 Jul 2005, Jimmy wrote: > My assignment is this: [assignment cut] > But I have no clue on how to make it work. I tried many different > variations to get it to work but in the end nothing happened. Hi Jimmy, First, please note that we will not do homework assignments, so we will probably not be able to give direct help on this. I strongly recommend you look at: http://www.catb.org/~esr/faqs/smart-questions.html because it may help you learn how to ask questions that people are happy to help with. That being said, since something like this happened last week, I'll try to write with a cooler head this time. What you say "I have no clue how to make it work", even if you're confused, you should also try to say what "it" is. As it stands, we can't tell at all what you're getting stuck on: you can't be stuck on the whole of Chapter Three, so try to narrow things down. Are you getting stuck on what modules are, or how to use them, or ...? You might be shy about showing what you've done, because to you, they might look like beginner mistakes. And some of the variations you've tried might be correct, but perhaps you're not interpreting the results as being correct. Or you could be doing things completely wrong. *grin* That's probably not the case. But because we can't read minds well, we need to see the work you've done. We're not clarovoyant: we must see what you've tried so far, because we use what you show us to better understand what you're having trouble with. Also, you may want to look at some additional material just to get a different perspective on what you're learning. Here's one tutorial from Alan Gauld called "Learning to Program": http://www.freenetpages.co.uk/hp/alan.gauld/ I've found it personally easier to read than Allen Downey's "How to Think Like a Computer Scientist", but I know that's personal preference. You may also want to look at: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Good luck. From jfouhy at paradise.net.nz Thu Jul 21 00:19:09 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 21 Jul 2005 10:19:09 +1200 (NZST) Subject: [Tutor] Dynamically populate Tkinter OptionMenu with list In-Reply-To: <61d0e2b40507200635417d2cff@mail.gmail.com> References: <61d0e2b40507200635417d2cff@mail.gmail.com> Message-ID: <1121897949.42decddd129f5@www.paradise.net.nz> Quoting Bernard Lebel <3dbernard at gmail.com>: > I have this problem. I build a list of elements, and I never know in > advance how many or what will be the elements. > > I then wish to populate an OptionMenu with this list of elements. Do you know the list of elements before you create the option menu? If so, you can do something like this: # suppose aElements is the list of elements, and var1 is a StringVar. oOption = OptionMenu(oRoot, var1, aElements[0], *aElements[1:]) If you want to create the OptionMenu first, and then later set the list of elements ... then it is a bit more difficult. -- John. From jorge at bcs.org.uk Thu Jul 21 00:20:31 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Wed, 20 Jul 2005 23:20:31 +0100 Subject: [Tutor] single file .exe Message-ID: Hello, Is there a way of creating a Windows .exe from a .py file that does not involve unzipping several files onto a folder? Does someone know of a program that wraps all the files needed into one single (non-installable) executable? Cheers jorge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050720/121db530/attachment.htm From dlenning at shaw.ca Thu Jul 21 00:48:23 2005 From: dlenning at shaw.ca (dina lenning) Date: Wed, 20 Jul 2005 15:48:23 -0700 Subject: [Tutor] hello Message-ID: <24d1ebd433bdc6d43b7c5a43f26d1f02@shaw.ca> is this where i send my questions?? From cyresse at gmail.com Thu Jul 21 01:04:16 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 21 Jul 2005 11:04:16 +1200 Subject: [Tutor] hello In-Reply-To: <24d1ebd433bdc6d43b7c5a43f26d1f02@shaw.ca> References: <24d1ebd433bdc6d43b7c5a43f26d1f02@shaw.ca> Message-ID: Most likely. Are they questions regarding Python? On 7/21/05, dina lenning wrote: > > is this where i send my questions?? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/10531fc9/attachment.htm From cyresse at gmail.com Thu Jul 21 01:14:17 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 21 Jul 2005 11:14:17 +1200 Subject: [Tutor] Getting two files to print In-Reply-To: <6faf39c905072013511a428c5d@mail.gmail.com> References: <42DC1051.6090303@med.unc.edu> <6faf39c905072013511a428c5d@mail.gmail.com> Message-ID: Hi Philip, Ignore this if you want, but here's a simpler way to do it. fileNames = ['c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt' , 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt' ] for f in fileNames: openFile = file(f, 'r') for line in openFile: print line openFile.close() Instead of using openFile.readline() just use for line in openFile, it's much simpler and handles end of file for you. Regards, Liam Clarke On 7/21/05, Andre Engels wrote: > > (answer at the bottom) > > On 7/18/05, Philip Carl wrote: > > I have no more hair to pull out, so I'm asking the group for help on a > > VERY simple question. I have two very similar text files to read-one > > with the final letters in the name 10%.txt and the other 20%.txt. I've > > written the following simple code to read these two files: > > > > # Program to read and print two text fiiles > > fileNameA = > > 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt' > > #text file one > > firstFile=open (fileNameA,'r') > > inFileLeftA = 1 #more file to read > > inLineA=[0] > > while inFileLeftA: > > inLineA = firstFile.readline() > > if (inLineA == ''): > > infileLeftA = 0 #if empty line end of first file > > > > else: > > print inLineA > > firstFile.close() > > > > fileNameB = > > 'c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt' > > #text file two > > secondFile=open (fileNameB,'r') > > inFileLeftB = 1 #more file to read > > inLineB=[0] > > while inFileLeftB: > > inLineB = secondFile.readline() > > if (inLineB == ''): > > infileLeftB = 0 #if empty line end of second file > > > > else: > > print inLineB > > secondFile.close() > > > > I realize that I probably ought to be able to code this more > > efficiently, but as a rank beginner I am less worried about efficiency > > than output. I can't seem to get BOTH files to print when run as > > presented, although when I split the program into two programs each file > > seems to print OK. As written here however, I can get the first but > > not the second textfile to print. What am I doing wrong?. > > You call the variable inFileLeftA, but when you try to set it to 0, > you use the name infileLeftA instead. That's another variable, so > inFileLeftA always remains 1. > > > Regarding the "ought to be able to code this more efficiently": The > obvious thing to do seems to be to use a function, so you have to type > in everything once instead of twice, like this: > > # start of code > > def printTextFile(fn): > # Print the contents of textfile fn > file = open(fn,'r') > inFileLeft = 1 > inLine=[0] > while inFileLeft: > inLine = file.readline() > if inLine == '': > inFileLeft = 0 > else: > print inLine > file.close() > > > printTextFile('c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_10%.txt') > > printTextFile('c:/Python24/outputs_1ubq_alignments/output_1ubq_alignments_20%.txt') > > # end of code > > There are other things that could be improved, but this is the main one by > far. > > Andre Engels > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/6020128d/attachment.htm From reed at intersiege.com Thu Jul 21 01:38:57 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Wed, 20 Jul 2005 19:38:57 -0400 Subject: [Tutor] confusing smtp problem In-Reply-To: <1121899414l.1441l.0l@texaspivot.texaspivot.com> References: <1121878535l.32243l.0l@texaspivot> <42DE88B4.4060701@intersiege.com> <1121880849l.32243l.1l@texaspivot> <42DEB4CA.5060702@intersiege.com> <1121899414l.1441l.0l@texaspivot.texaspivot.com> Message-ID: <42DEE091.5070401@intersiege.com> nephish wrote: > ok, my fault. the router assigned the smtp server a different address > no longer 10.10.10.32, now 10.10.10.04 > tried the telnet thing and it worked, so i still dont know > why the script isnt working > > thanks Does it still give the same error???? ib.py", line 347, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed or is it different?? ~reed > > > On 07/20/2005 03:32:10 PM, Reed L. O'Brien wrote: >> nephish wrote: >> > On 07/20/2005 12:24:04 PM, Reed L. O'Brien wrote: >> >> nephish wrote: >> >> > Hey there, i am trying to get an email through an SMTP server on >> a >> >> > windows computer from a linux machine on the same network. >> >> > >> >> > >> >> >>>> import smtplib >> >> >>>> import MySQLdb >> >> >>>> Server = smtplib.SMTP('10.10.10.32') >> >> >>>> ToAddress = 'nephish at xit.net' >> >> >>>> FromAddress = 'nephish at xit.net.com' >> >> >>>> Message = 'Some text message' >> >> >>>> Server.sendmail(FromAddress, ToAddress, Message) >> >> >>>> >> >> > {} >> >> > >> >> > but nothing goes through, >> >> > now if i do this... >> >> > >> >> >>>> Server.connect() >> >> >>>> >> >> > >> >> > i get this >> >> > >> >> > Traceback (innermost last): >> >> > File "", line 1, in ? >> >> > File "/usr/lib/python2.3/smtplib.py", line 303, in connect >> >> > (code, msg) = self.getreply() >> >> > File "/usr/lib/python2.3/smtplib.py", line 347, in getreply >> >> > raise SMTPServerDisconnected("Connection unexpectedly >> closed") >> >> > SMTPServerDisconnected: Connection unexpectedly closed >> >> > >> >> > now if i use the server on this computer ('localhost') >> >> > everything works ok. >> >> > >> >> > any ideas? >> >> > thanks, >> >> > <>< >> >> > >> >> > _______________________________________________ >> >> > Tutor maillist - Tutor at python.org >> >> > http://mail.python.org/mailman/listinfo/tutor >> >> > >> >> Can you telnet to port 25 on the other server? >> >> What does it respond to an EHLO command? >> >> HELO? >> >> can you get it to deliver there? >> >> >> >> ~r >> >> >> >> -- >> >> 4.6692916090 >> >> 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') >> >> http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 >> >> keyID: 0x0FA09FCE >> >> >> >> >> >> >> >> >> > i did this >> > telnet 10.10.10.32 >> > it responded with "unable to connect to remote host, connection >> refused" >> > >> > hmmm, perhaps there is something i am missing here. >> > this computer sits at 10.10.10.24 >> > the mail server is at 10.10.10.32 >> > and the other computer on the lan that can use it effectivly is at >> > 10.10.10.5 maybe the program it is using is passing some sort of >> > parameter that i am missing here. >> > >> > will check it all out again. >> > >> > thanks >> > >> That would be >> """use the IP you choose in lieu of localhost >> The 25 tels it to connect to the smtp port""" >> telnet localhost 25 >> Trying 127.0.0.1... >> Connected to localhost.localdomain (127.0.0.1). >> Escape character is '^]'. >> 220 my.dom.com ESMTP >> EHLO any.com >> 250-my.dom.com >> 250-AUTH LOGIN CRAM-MD5 PLAIN >> 250-AUTH=LOGIN CRAM-MD5 PLAIN >> 250-STARTTLS >> 250-PIPELINING >> 250 8BITMIME >> >> Try HELO if EHLO doesn't work. If you can't connect at all, no smtp >> server is running; or it is running on a non-standard port. >> >> best, >> ~r >> >> >> -- >> 4.6692916090 >> 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') >> http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 >> keyID: 0x0FA09FCE >> >> >> >> >> > -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 keyID: 0x0FA09FCE From cyresse at gmail.com Thu Jul 21 01:58:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 21 Jul 2005 11:58:31 +1200 Subject: [Tutor] hello In-Reply-To: References: <24d1ebd433bdc6d43b7c5a43f26d1f02@shaw.ca> Message-ID: On this tutor list, we're not able to provide solutions to assignments or homework, but I'll help as I can. I'm also forwarding this to the list, as other people can probably help better than I. The problem you've been given is simple, (well, the Python bit is), but they haven't explained it very well. Check out this - http://www.freenetpages.co.uk/hp/alan.gauld/ It's a tutorial written by Alan Gauld, who answers emails on this list, look under - "The Raw Materials" and read about collections, as this is what your problem involves ( I assume you are ok with HTML.... :/) So, in your assignment, each cheque's details will look like this - >>> cheque = [ 1, 12.00, "foo" ] The [ ] bits mean that cheque is a list containing 1, 12.00 and "foo" as values. (You might want to play around with the Python interpreter.) Ok... that part is reasonably straight forward. Now, you can access each item in a list by using it's index. Remember that computers start counting at 0... ask a computer to count to ten and it will count 0,1,2,3,4,5,6,7,8,9 ....so, the 1st item of a list is actually item zero. Ok. So, to access the first item of cheque, you would do something like this at the Python prompt - >>> print cheque[0] 1 >>>print cheque[1] 12.00 >>>print cheque[2] foo Does that make sense? You can also have a list of lists. >>> manyCheques = [ [ 1, 12.00, "foo"], [2, 13.88, "bar"] ] Now, if you print the first item of manyCheques like so >>>print manyCheques[0] [1, 12.00, "foo"] So, the first item of manyCheques is a list too, (the square brackets.) So how to access the third item of the second list? >>> print manyCheques[1][2] (remember, computers start at 0) bar It's just a shorthand way of saying "print the 3rd item of the 2nd item of manyCheques". Um... You'll also need to learn a wee bit about looping, so I really do suggest starting with Alan's tutorial. Good luck, On 7/21/05, dina lenning wrote: > > YES...heres my problem > > I am a university student..will be a teacher in 2 years hopefully..and > have taken a first year computing course that said it required NO PRIOR > knowledge, but i am having great difficulty. The students (71 of them) > are all complaining, including myself , as we all find it too hard. > Anyway..i am having a heck of a time, but can not fail becasue i am on > student loans. I am looking for help for this assignment: > http://www.cs.sfu.ca/CC/165/popowich/assign-1/assign4 > also, do you think this is easy and should it be in a first year, no > prior knowledge course?? > Even if you can guide me to some resources that may help me work this > out that would be great. Thank you. > You could even just send the assignment code if you want :) > thanks dina > On 20-Jul-05, at 4:04 PM, Liam Clarke wrote: > > > Most likely. Are they questions regarding Python? > > > > On 7/21/05, dina lenning wrote: > >> > >> _______________________________________________ > >> Tutor maillist-Tutor at python.org > >> http://mail.python.org/mailman/listinfo/tutor > > > > > > > > -- > > 'There is only one basic human right, and that is to do as you damn > > well please. > > And with it comes the only basic human duty, to take the consequences.' > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/020282b3/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Thu Jul 21 02:11:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 20 Jul 2005 17:11:23 -0700 (PDT) Subject: [Tutor] single file .exe In-Reply-To: Message-ID: On Wed, 20 Jul 2005, Jorge Louis De Castro wrote: > Is there a way of creating a Windows .exe from a .py file that does not > involve unzipping several files onto a folder? Does someone know of a > program that wraps all the files needed into one single > (non-installable) executable? Hi Jorge, Would something like py2exe help? I believe it does do the kind of bundling that you're asking: http://starship.python.net/crew/theller/py2exe/ From bowman at mazirian.com Thu Jul 21 02:22:09 2005 From: bowman at mazirian.com (Bradford R. Bowman) Date: Wed, 20 Jul 2005 20:22:09 -0400 Subject: [Tutor] Moving all files in a directory Message-ID: <1121905329.12981.4.camel@phandaal> I know this should be easy, but how would I go about moving all files contained in one directory into another directory (as in the shell command "mv /path/to/dir1/* /path/to/dir2")? Is the os module's rename function used for this? -- Bradford R. Bowman GnuPG Public Key available at: http://mazirian.com/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20050720/13e50012/attachment.pgp From nephish at xit.net Thu Jul 21 03:02:03 2005 From: nephish at xit.net (nephish) Date: Wed, 20 Jul 2005 20:02:03 -0500 Subject: [Tutor] confusing smtp problem In-Reply-To: <42DEE091.5070401@intersiege.com> References: <1121878535l.32243l.0l@texaspivot> <42DE88B4.4060701@intersiege.com> <1121880849l.32243l.1l@texaspivot> <42DEB4CA.5060702@intersiege.com> <1121899414l.1441l.0l@texaspivot.texaspivot.com> <42DEE091.5070401@intersiege.com> Message-ID: <1121907723.10885.4.camel@localhost.localdomain> Sorry about the delay getting back on this one guys, yeah, i am running a linux machine. no firewall between here and there (both behind a firewall router) yeah, sylpheed does send on port 25 the windows machine has the Merek email server on board. i would like my scripts to be able to send to it, as a backup, but the debian linux MTA (Exim i think) is working. So it isn't too big a deal if it does not. telnet and helo does work, it lets me in from the command line from the linux machine (where my python scripts are) to the win machine (where the other mail server is) we dont need POP for this at all, we are sending only. incidentally, i appreciate you guys time and attention to this. all the best, shawn On Wed, 2005-07-20 at 19:38 -0400, Reed L. O'Brien wrote: > nephish wrote: > > ok, my fault. the router assigned the smtp server a different address > > no longer 10.10.10.32, now 10.10.10.04 > > tried the telnet thing and it worked, so i still dont know > > why the script isnt working > > > > thanks > Does it still give the same error???? > > ib.py", line 347, in getreply > raise SMTPServerDisconnected("Connection unexpectedly closed") > SMTPServerDisconnected: Connection unexpectedly closed > > or is it different?? > > ~reed > > > > > > > > On 07/20/2005 03:32:10 PM, Reed L. O'Brien wrote: > >> nephish wrote: > >> > On 07/20/2005 12:24:04 PM, Reed L. O'Brien wrote: > >> >> nephish wrote: > >> >> > Hey there, i am trying to get an email through an SMTP server on > >> a > >> >> > windows computer from a linux machine on the same network. > >> >> > > >> >> > > >> >> >>>> import smtplib > >> >> >>>> import MySQLdb > >> >> >>>> Server = smtplib.SMTP('10.10.10.32') > >> >> >>>> ToAddress = 'nephish at xit.net' > >> >> >>>> FromAddress = 'nephish at xit.net.com' > >> >> >>>> Message = 'Some text message' > >> >> >>>> Server.sendmail(FromAddress, ToAddress, Message) > >> >> >>>> > >> >> > {} > >> >> > > >> >> > but nothing goes through, > >> >> > now if i do this... > >> >> > > >> >> >>>> Server.connect() > >> >> >>>> > >> >> > > >> >> > i get this > >> >> > > >> >> > Traceback (innermost last): > >> >> > File "", line 1, in ? > >> >> > File "/usr/lib/python2.3/smtplib.py", line 303, in connect > >> >> > (code, msg) = self.getreply() > >> >> > File "/usr/lib/python2.3/smtplib.py", line 347, in getreply > >> >> > raise SMTPServerDisconnected("Connection unexpectedly > >> closed") > >> >> > SMTPServerDisconnected: Connection unexpectedly closed > >> >> > > >> >> > now if i use the server on this computer ('localhost') > >> >> > everything works ok. > >> >> > > >> >> > any ideas? > >> >> > thanks, > >> >> > <>< > >> >> > > >> >> > _______________________________________________ > >> >> > Tutor maillist - Tutor at python.org > >> >> > http://mail.python.org/mailman/listinfo/tutor > >> >> > > >> >> Can you telnet to port 25 on the other server? > >> >> What does it respond to an EHLO command? > >> >> HELO? > >> >> can you get it to deliver there? > >> >> > >> >> ~r > >> >> > >> >> -- > >> >> 4.6692916090 > >> >> 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') > >> >> http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 > >> >> keyID: 0x0FA09FCE > >> >> > >> >> > >> >> > >> >> > >> > i did this > >> > telnet 10.10.10.32 > >> > it responded with "unable to connect to remote host, connection > >> refused" > >> > > >> > hmmm, perhaps there is something i am missing here. > >> > this computer sits at 10.10.10.24 > >> > the mail server is at 10.10.10.32 > >> > and the other computer on the lan that can use it effectivly is at > >> > 10.10.10.5 maybe the program it is using is passing some sort of > >> > parameter that i am missing here. > >> > > >> > will check it all out again. > >> > > >> > thanks > >> > > >> That would be > >> """use the IP you choose in lieu of localhost > >> The 25 tels it to connect to the smtp port""" > >> telnet localhost 25 > >> Trying 127.0.0.1... > >> Connected to localhost.localdomain (127.0.0.1). > >> Escape character is '^]'. > >> 220 my.dom.com ESMTP > >> EHLO any.com > >> 250-my.dom.com > >> 250-AUTH LOGIN CRAM-MD5 PLAIN > >> 250-AUTH=LOGIN CRAM-MD5 PLAIN > >> 250-STARTTLS > >> 250-PIPELINING > >> 250 8BITMIME > >> > >> Try HELO if EHLO doesn't work. If you can't connect at all, no smtp > >> server is running; or it is running on a non-standard port. > >> > >> best, > >> ~r > >> > >> > >> -- > >> 4.6692916090 > >> 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') > >> http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 > >> keyID: 0x0FA09FCE > >> > >> > >> > >> > >> > > > > From bowman at mazirian.com Thu Jul 21 05:56:14 2005 From: bowman at mazirian.com (Bradford R. Bowman) Date: Wed, 20 Jul 2005 23:56:14 -0400 Subject: [Tutor] Moving all files in a directory In-Reply-To: <1121905329.12981.4.camel@phandaal> References: <1121905329.12981.4.camel@phandaal> Message-ID: <1121918174.12981.16.camel@phandaal> On Wed, 2005-07-20 at 20:22 -0400, Bradford R. Bowman wrote: > I know this should be easy, but how would I go about moving all files > contained in one directory into another directory (as in the shell > command "mv /path/to/dir1/* /path/to/dir2")? Is the os module's rename > function used for this? I ended up with this function: def movefiles(dir1, dir2): """Moves all files in dir1 to dir2""" contents = os.listdir(dir1) for file in contents: old = os.path.join(dir1, file) new = os.path.join(dir2, file) os.rename(old, new) It seems to work, but this looks inelegant. Does anyone have any better suggestions? -- Bradford R. Bowman GnuPG Public Key available at: http://mazirian.com/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20050720/410df76c/attachment.pgp From paul at alanweberassociates.com Thu Jul 21 09:52:48 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Thu, 21 Jul 2005 02:52:48 -0500 Subject: [Tutor] Parsing problem Message-ID: <20050721075251.DFB8C1E4007@bag.python.org> Liam, Kent, and Danny - It sure looks like pyparsing is taking on a life of its own! I can see I no longer am the only one pitching pyparsing at some of these applications! Yes, Liam, it is possible to create dictionary-like objects, that is, ParseResults objects that have named values in them. I looked into your application, and the nested assignments seem very similar to a ConfigParse type of structure. Here is a pyparsing version that handles the test data in your original post (I kept Danny Yoo's recursive list values, and added recursive dictionary entries): -------------------------- import pyparsing as pp listValue = pp.Forward() listSeq = pp.Suppress('{') + pp.Group(pp.ZeroOrMore(listValue)) + pp.Suppress('}') listValue << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | pp.Word(pp.alphanums) | listSeq ) keyName = pp.Word( pp.alphas ) entries = pp.Forward() entrySeq = pp.Suppress('{') + pp.Group(pp.OneOrMore(entries)) + pp.Suppress('}') entries << pp.Dict( pp.OneOrMore( pp.Group( keyName + pp.Suppress('=') + (entrySeq | listValue) ) ) ) -------------------------- Dict is one of the most confusing classes to use, and there are some examples in the examples directory that comes with pyparsing (see dictExample2.py), but it is still tricky. Here is some code to access your input test data, repeated here for easy reference: -------------------------- testdata = """\ country = { tag = ENG ai = { flags = { } combat = { DAU FRA ORL PRO } continent = { } area = { } region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" "TagoSea" "WCAtlanticSea" } war = 60 ferocity = no } } """ parsedEntries = entries.parseString(testdata) def dumpEntries(dct,depth=0): keys = dct.keys() keys.sort() for k in keys: print (' '*depth) + '- ' + k + ':', if isinstance(dct[k],pp.ParseResults): if dct[k][0].keys(): print dumpEntries(dct[k][0],depth+1) else: print dct[k][0] else: print dct[k] dumpEntries( parsedEntries ) print print parsedEntries.country[0].tag print parsedEntries.country[0].ai[0].war print parsedEntries.country[0].ai[0].ferocity -------------------------- This will print out: -------------------------- - country: - ai: - area: [] - combat: ['DAU', 'FRA', 'ORL', 'PRO'] - continent: [] - ferocity: no - flags: [] - region: ['British Isles', 'NorthSeaSea', 'ECAtlanticSea', 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] - war: 60 - tag: ENG ENG 60 No -------------------------- But I really dislike having to dereference those nested values using the 0'th element. So I'm going to fix pyparsing so that in the next release, you'll be able to reference the sub-elements as: print parsedEntries.country.tag print parsedEntries.country.ai.war print parsedEntries.country.ai.ferocity This *may* break some existing code, but Dict is not heavily used, based on feedback from users, and this may make it more useful in general, especially when data parses into nested Dict's. Hope this sheds more light than confusion! -- Paul McGuire From shantanoo at gmail.com Thu Jul 21 05:46:24 2005 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Thu, 21 Jul 2005 09:16:24 +0530 Subject: [Tutor] single file .exe In-Reply-To: References: Message-ID: <20050721034624.GA28607@dhoomketu.homeunix.net> +++ Jorge Louis De Castro [20-07-05 23:20 +0100]: | Hello, | | Is there a way of creating a Windows .exe from a .py file that does not involve unzipping several files onto a folder? | Does someone know of a program that wraps all the files needed into one single (non-installable) executable? | | Cheers | jorge py2exe? Shantanoo From tegmine at gmail.com Thu Jul 21 10:36:34 2005 From: tegmine at gmail.com (Luis N) Date: Thu, 21 Jul 2005 01:36:34 -0700 Subject: [Tutor] hello In-Reply-To: References: <24d1ebd433bdc6d43b7c5a43f26d1f02@shaw.ca> Message-ID: <77bfa81a05072101363d73759c@mail.gmail.com> On 7/21/05, dina lenning wrote: > > YES...heres my problem > > > > I am a university student..will be a teacher in 2 years hopefully..and > > have taken a first year computing course that said it required NO PRIOR > > knowledge, but i am having great difficulty. The students (71 of them) > > are all complaining, including myself , as we all find it too hard. > > Anyway..i am having a heck of a time, but can not fail becasue i am on > > student loans. I am looking for help for this assignment: > > http://www.cs.sfu.ca/CC/165/popowich/assign-1/assign4 > > Damn school, making things to hard for students! As a fellow SFU student, I can sympathize. But geez, I wish I'd known this course existed, it would have been an easy A. Graduating this fall though, and what does a business major really need to use a computer for anyway ;-) Luis. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/855acc6e/attachment.htm From kent37 at tds.net Thu Jul 21 12:26:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Jul 2005 06:26:42 -0400 Subject: [Tutor] single file .exe In-Reply-To: <20050721034624.GA28607@dhoomketu.homeunix.net> References: <20050721034624.GA28607@dhoomketu.homeunix.net> Message-ID: <42DF7862.9000200@tds.net> Shantanoo Mahajan wrote: > +++ Jorge Louis De Castro [20-07-05 23:20 +0100]: > | Hello, > | > | Is there a way of creating a Windows .exe from a .py file that does not involve unzipping several files onto a folder? > | Does someone know of a program that wraps all the files needed into one single (non-installable) executable? > | > | Cheers > | jorge > > py2exe? py2exe does not create a single file executable. Many people bundle the output of py2exe with an installer, but the OP prefers not to do this. Kent From jorge at bcs.org.uk Thu Jul 21 14:43:11 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Thu, 21 Jul 2005 13:43:11 +0100 Subject: [Tutor] Send attachment Message-ID: Hello, Any ideas how I can use Python and the Windows API to open a PC's mail client and send an attachment? The idea is saving some data onto a file and then invoke the email client (OE or Outlook or whatever is the default on the machine) with the recipient's address filled in and the file ready to be sent as an attachment. Kinda like when we right-click on a file and select the "send to mail recipient" behavior. Been reading docs, trying out samples, and googling this for a few days to no avail. Cheers jorge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/c7bc2763/attachment.htm From xecronix at yahoo.com Thu Jul 21 15:38:21 2005 From: xecronix at yahoo.com (Ron Weidner) Date: Thu, 21 Jul 2005 06:38:21 -0700 (PDT) Subject: [Tutor] Send attachment In-Reply-To: Message-ID: <20050721133821.14721.qmail@web60618.mail.yahoo.com> --- Jorge Louis De Castro wrote: > Hello, > > Any ideas how I can use Python and the Windows API > to open a PC's mail client and send an attachment? > The idea is saving some data onto a file and then > invoke the email client (OE or Outlook or whatever > is the default on the machine) with the recipient's > address filled in and the file ready to be sent as > an attachment. > Kinda like when we right-click on a file and select > the "send to mail recipient" behavior. > Been reading docs, trying out samples, and googling > this for a few days to no avail. > > Cheers I'm not sure how to do that but, if you learn how to use the smtp protocol, you won't need to use someones mail client. It's actually simple to use. Try looking at the problem from that angle and see if it gets you anywhere. Good luck -- Ronald Weidner http://www.techport80.com PHP Software developer for hire. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From reed at intersiege.com Thu Jul 21 16:21:14 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Thu, 21 Jul 2005 10:21:14 -0400 Subject: [Tutor] confusing smtp problem In-Reply-To: <1121907723.10885.4.camel@localhost.localdomain> References: <1121878535l.32243l.0l@texaspivot> <42DE88B4.4060701@intersiege.com> <1121880849l.32243l.1l@texaspivot> <42DEB4CA.5060702@intersiege.com> <1121899414l.1441l.0l@texaspivot.texaspivot.com> <42DEE091.5070401@intersiege.com> <1121907723.10885.4.camel@localhost.localdomain> Message-ID: <42DFAF5A.9040709@intersiege.com> nephish wrote: > Sorry about the delay getting back on this one guys, > yeah, i am running a linux machine. > no firewall between here and there (both behind a firewall router) > yeah, sylpheed does send on port 25 > the windows machine has the Merek email server on board. > i would like my scripts to be able to send to it, > as a backup, but the debian linux MTA (Exim i think) is working. > So it isn't too big a deal if it does not. > telnet and helo does work, it lets me in from the command line > from the linux machine (where my python scripts are) to the win > machine (where the other mail server is) > > we dont need POP for this at all, we are sending only. > > incidentally, i appreciate you guys time and attention to this. > > all the best, > shawn > > Does it still give the same error???? ib.py", line 347, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed or is it different?? ~reed -- 4.6692916090 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 keyID: 0x0FA09FCE From nephish at xit.net Thu Jul 21 17:17:11 2005 From: nephish at xit.net (nephish) Date: Thu, 21 Jul 2005 15:17:11 +0000 Subject: [Tutor] confusing smtp problem In-Reply-To: <42DFAF5A.9040709@intersiege.com> (from reed@intersiege.com on Thu Jul 21 09:21:14 2005) References: <1121878535l.32243l.0l@texaspivot> <42DE88B4.4060701@intersiege.com> <1121880849l.32243l.1l@texaspivot> <42DEB4CA.5060702@intersiege.com> <1121899414l.1441l.0l@texaspivot.texaspivot.com> <42DEE091.5070401@intersiege.com> <1121907723.10885.4.camel@localhost.localdomain> <42DFAF5A.9040709@intersiege.com> Message-ID: <1121959031l.3289l.0l@texaspivot.texaspivot.com> ok this is what i get when i use host = '10.10.10.04 25' resourse unavailable line = self.sock.recv(size,socket.MSG_PEEK) now if i use host = '10.10.10.04:25' it has all the appearences of having worked, but the email never gets to its destination. hmmmmmmmm. i tried it the first way because that is what let me connect and do the helo thing via telnet. On 07/21/2005 09:21:14 AM, Reed L. O'Brien wrote: > nephish wrote: > > Sorry about the delay getting back on this one guys, > > yeah, i am running a linux machine. > > no firewall between here and there (both behind a firewall router) > > yeah, sylpheed does send on port 25 > > the windows machine has the Merek email server on board. > > i would like my scripts to be able to send to it, > > as a backup, but the debian linux MTA (Exim i think) is working. > > So it isn't too big a deal if it does not. > > telnet and helo does work, it lets me in from the command line > > from the linux machine (where my python scripts are) to the win > > machine (where the other mail server is) > > > > we dont need POP for this at all, we are sending only. > > > > incidentally, i appreciate you guys time and attention to this. > > > > all the best, > > shawn > > > > > > Does it still give the same error???? > > ib.py", line 347, in getreply > raise SMTPServerDisconnected("Connection unexpectedly closed") > SMTPServerDisconnected: Connection unexpectedly closed > > or is it different?? > > ~reed > > -- > 4.6692916090 > 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') > http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 > keyID: 0x0FA09FCE > > > > From 3dbernard at gmail.com Thu Jul 21 18:14:42 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 21 Jul 2005 12:14:42 -0400 Subject: [Tutor] Dynamically populate Tkinter OptionMenu with list In-Reply-To: <1121897949.42decddd129f5@www.paradise.net.nz> References: <61d0e2b40507200635417d2cff@mail.gmail.com> <1121897949.42decddd129f5@www.paradise.net.nz> Message-ID: <61d0e2b40507210914609ac55@mail.gmail.com> Thanks John. Bernard On 7/20/05, jfouhy at paradise.net.nz wrote: > Quoting Bernard Lebel <3dbernard at gmail.com>: > > > I have this problem. I build a list of elements, and I never know in > > advance how many or what will be the elements. > > > > I then wish to populate an OptionMenu with this list of elements. > > Do you know the list of elements before you create the option menu? > > If so, you can do something like this: > > # suppose aElements is the list of elements, and var1 is a StringVar. > oOption = OptionMenu(oRoot, var1, aElements[0], *aElements[1:]) > > If you want to create the OptionMenu first, and then later set the list of > elements ... then it is a bit more difficult. > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From 3dbernard at gmail.com Thu Jul 21 18:19:00 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 21 Jul 2005 12:19:00 -0400 Subject: [Tutor] Tkinter event for changing OptionMenu items Message-ID: <61d0e2b405072109196ee6c95b@mail.gmail.com> Hello, I'm trying to bind an event to the changes made to an OptionMenu. Ie the user chooses a different item, the rest of the Tk window gets updated. To repopulate the window, a function would be called by the binding. Any suggestion? var1 = StringVar() var1.set( aTables[0] ) oOptionMenu = OptionMenu( oRoot, var1, aTables[0], *aTables[1:] ) sTableName = var1.get() oOptionMenu.bind( '', getTableColumns ) oOptionMenu.pack( fill = X ) Here the '' event is obviously not the one I'm looking for, but is there to illustrate what code I have so far. Thanks Bernard From klappnase at freenet.de Thu Jul 21 20:07:28 2005 From: klappnase at freenet.de (Michael Lange) Date: Thu, 21 Jul 2005 20:07:28 +0200 Subject: [Tutor] Tkinter event for changing OptionMenu items In-Reply-To: <61d0e2b405072109196ee6c95b@mail.gmail.com> References: <61d0e2b405072109196ee6c95b@mail.gmail.com> Message-ID: <20050721200728.5629d00f.klappnase@freenet.de> On Thu, 21 Jul 2005 12:19:00 -0400 Bernard Lebel <3dbernard at gmail.com> wrote: > Hello, > > I'm trying to bind an event to the changes made to an OptionMenu. Ie > the user chooses a different item, the rest of the Tk window gets > updated. To repopulate the window, a function would be called by the > binding. > > Any suggestion? > > > var1 = StringVar() > var1.set( aTables[0] ) > oOptionMenu = OptionMenu( oRoot, var1, aTables[0], *aTables[1:] ) > sTableName = var1.get() > oOptionMenu.bind( '', getTableColumns ) > oOptionMenu.pack( fill = X ) > > Here the '' event is obviously not the one I'm looking for, > but is there to illustrate what code I have so far. > > Hi Bernard, if I understand you correctly, the "" event of the OptionMenu's Menu may be the best bet for you (not very much tested though): oOptionMenu['menu'].bind('', getTableColumns) Otherwise you would probably have to call oOptionMenu['menu'].entryconfigure(command=...) on all menu entries. I hope this helps Michael From 3dbernard at gmail.com Thu Jul 21 20:16:05 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 21 Jul 2005 14:16:05 -0400 Subject: [Tutor] Tkinter event for changing OptionMenu items In-Reply-To: <20050721200728.5629d00f.klappnase@freenet.de> References: <61d0e2b405072109196ee6c95b@mail.gmail.com> <20050721200728.5629d00f.klappnase@freenet.de> Message-ID: <61d0e2b4050721111613d526b8@mail.gmail.com> Hi Michael, Let say I have a MenuOption, that consists of 3 items. This MenuOption sits on top of the Tkinter window. In the lower part, I have a bunch of widgets (text fields). When the choose a different item from the MenuOption, it would call a function that clears the lower part and repopulates it with new fields. My problem is binding this callback to the event of choosing an item. Bernard On 7/21/05, Michael Lange wrote: > On Thu, 21 Jul 2005 12:19:00 -0400 > Bernard Lebel <3dbernard at gmail.com> wrote: > > > Hello, > > > > I'm trying to bind an event to the changes made to an OptionMenu. Ie > > the user chooses a different item, the rest of the Tk window gets > > updated. To repopulate the window, a function would be called by the > > binding. > > > > Any suggestion? > > > > > > var1 = StringVar() > > var1.set( aTables[0] ) > > oOptionMenu = OptionMenu( oRoot, var1, aTables[0], *aTables[1:] ) > > sTableName = var1.get() > > oOptionMenu.bind( '', getTableColumns ) > > oOptionMenu.pack( fill = X ) > > > > Here the '' event is obviously not the one I'm looking for, > > but is there to illustrate what code I have so far. > > > > > > Hi Bernard, > > if I understand you correctly, the "" event of the OptionMenu's Menu may be the best > bet for you (not very much tested though): > > oOptionMenu['menu'].bind('', getTableColumns) > > Otherwise you would probably have to call oOptionMenu['menu'].entryconfigure(command=...) on all menu entries. > > I hope this helps > > Michael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cgw501 at york.ac.uk Thu Jul 21 21:39:36 2005 From: cgw501 at york.ac.uk (cgw501@york.ac.uk) Date: 21 Jul 2005 20:39:36 +0100 Subject: [Tutor] String slicing from tuple list Message-ID: Hi, I have a list of tuples like this: [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] Each tuple references coordinates of a big long string and they are in the 'right' order, i.e. earliest coordinate first within each tuple, and eearliest tuple first in the list. What I want to do is use this list of coordinates to retrieve the parts of the string *between* each tuple. So in my example I would want the slices [2367:6457], [8345:9086] and [10100:12304]. Hope this is clear. I'm coming up short of ideas of how to achieve this. I guess a for loop, but I'm not sure how I can index *the next item* in the list, if that makes sense, or perhaps there is another way. Any help, as ever, appreciated. Chris From dyoo at hkn.eecs.berkeley.edu Thu Jul 21 21:58:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 21 Jul 2005 12:58:22 -0700 (PDT) Subject: [Tutor] String slicing from tuple list In-Reply-To: Message-ID: On 21 Jul 2005 cgw501 at york.ac.uk wrote: > [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] > > What I want to do is use this list of coordinates to retrieve the parts > of the string *between* each tuple. So in my example I would want the > slices [2367:6457], [8345:9086] and [10100:12304]. Hope this is clear. Hi Chris, You can simplify the problem a bit by breaking it into smaller pieces. Given a list, such as: [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] can you write a function that takes that, and produces a new list of the in-betweens? [(2637, 6457), (8345, 9086), (10100, 12304)] Good luck! From geon at post.cz Thu Jul 21 21:59:46 2005 From: geon at post.cz (geon) Date: Thu, 21 Jul 2005 21:59:46 +0200 Subject: [Tutor] Tkinter event for changing OptionMenu items In-Reply-To: <61d0e2b405072109196ee6c95b@mail.gmail.com> References: <61d0e2b405072109196ee6c95b@mail.gmail.com> Message-ID: <42DFFEB2.1000505@post.cz> Bernard Lebel wrote: >Hello, > >I'm trying to bind an event to the changes made to an OptionMenu. Ie >the user chooses a different item, the rest of the Tk window gets >updated. To repopulate the window, a function would be called by the >binding. > >Any suggestion? > > >var1 = StringVar() >var1.set( aTables[0] ) >oOptionMenu = OptionMenu( oRoot, var1, aTables[0], *aTables[1:] ) >sTableName = var1.get() >oOptionMenu.bind( '', getTableColumns ) >oOptionMenu.pack( fill = X ) > > I might know what you mean - binding optionMenu with say w.bind('', tisk) is "too early", it is called not after the choice, but at the beginning, at clicking on the button. I found "curious" solution, here it is: (maybe it could be done otherwise, I would like to know, too..): from Tkinter import * OPTIONS = [ "egg", "bunny", "chicken" ] def callmeagain(): global state if state!=var.get(): print var.get() state=var.get() root.after(1000, callmeagain) root = Tk() var = StringVar() var.set(OPTIONS[2]) # default value state=var.get() w = OptionMenu (root, var, *OPTIONS) w.pack() callmeagain() root.mainloop() Maybe this could help, too. -- geon Vyj?mka je pravidlo. Rekurzivn?. From kent37 at tds.net Thu Jul 21 22:05:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Jul 2005 16:05:08 -0400 Subject: [Tutor] String slicing from tuple list In-Reply-To: References: Message-ID: <42DFFFF4.60209@tds.net> cgw501 at york.ac.uk wrote: > Hi, > > I have a list of tuples like this: > > [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] > > Each tuple references coordinates of a big long string and they are in the > 'right' order, i.e. earliest coordinate first within each tuple, and > eearliest tuple first in the list. What I want to do is use this list of > coordinates to retrieve the parts of the string *between* each tuple. So in > my example I would want the slices [2367:6457], [8345:9086] and > [10100:12304]. Hope this is clear. You could write a for loop that keeps some state. Another way is to preprocess the lists into what you want. zip() makes this easy: >>> data = [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] >>> >>> first, second = zip(*data) >>> first (1423, 6457, 9086, 12304) >>> second (2637, 8345, 10100, 15666) >>> starts = second[:-1] >>> starts (2637, 8345, 10100) >>> ends = first[1:] >>> ends (6457, 9086, 12304) >>> ranges = zip(starts, ends) >>> ranges [(2637, 6457), (8345, 9086), (10100, 12304)] Now you can get a list of slices of a string s with a simple list comp: slices = [ s[begin:end] for begin, end in ranges ] and of course the creation of ranges can be abbreviated: >>> first, second = zip(*data) >>> ranges = zip(second[:-1], first[1:]) Kent From tegmine at gmail.com Thu Jul 21 22:05:10 2005 From: tegmine at gmail.com (Luis N) Date: Thu, 21 Jul 2005 13:05:10 -0700 Subject: [Tutor] String slicing from tuple list In-Reply-To: References: Message-ID: <77bfa81a05072113056aac17eb@mail.gmail.com> On 21 Jul 2005 20:39:36 +0100, cgw501 at york.ac.uk wrote: > > Hi, > > I have a list of tuples like this: > > [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] > > Each tuple references coordinates of a big long string and they are in the > 'right' order, i.e. earliest coordinate first within each tuple, and > eearliest tuple first in the list. What I want to do is use this list of > coordinates to retrieve the parts of the string *between* each tuple. So > in > my example I would want the slices [2367:6457], [8345:9086] and > [10100:12304]. Hope this is clear. > > I'm coming up short of ideas of how to achieve this. I guess a for loop, > but I'm not sure how I can index *the next item* in the list, if that > makes > sense, or perhaps there is another way. > > Any help, as ever, appreciated. > > Chris > > Not sure if I follow you, seems like computational biology or something to > me, but my quick (and dirty) solution: > l = [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] for x in range(len(l)-1): > l[x][1], l[x+1][0] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/cce1bb4a/attachment.htm From cpu.crazy at gmail.com Thu Jul 21 22:44:27 2005 From: cpu.crazy at gmail.com (Joseph Quigley) Date: Thu, 21 Jul 2005 14:44:27 -0600 Subject: [Tutor] How do I add an argument too... In-Reply-To: <42DD3612.6060907@h-lab.net> References: <42DBE8FF.7030600@gmail.com> <42DD3612.6060907@h-lab.net> Message-ID: <42E0092B.6080909@gmail.com> optparse.. Can I download that as a module or do I have to download epython? Thanks, JQ Hugo Gonz?lez Monteverde wrote: > I use optparse wich can take some getting used to in the beginnning, > but it help you easily create very powerful command line options. I is > shipped with th epython distro. As soon as I get an example I wrote, I > will post it to the list... > > > Hugo From srini_iyyer_bio at yahoo.com Thu Jul 21 22:51:38 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 21 Jul 2005 13:51:38 -0700 (PDT) Subject: [Tutor] Will a dictionary based method work for this problem Message-ID: <20050721205138.20443.qmail@web53509.mail.yahoo.com> Hello group, I have a problem of classification of data. My data has two columns: Col. A refers section of a office and column B refers to name of the person: Col A Col B Accounts(A/c) Steve A/c Bill A/c Rafael Billing Mike Billing joshua Billing Steve Production Tom Production Mike Production Rafael Now my problem is: 1. Who are the people unique to Accounts? 2. Who are the people working for two sections of the office: ( Steve: A/c and Billing; Rafael : A/c and Production Mike: Billing and Production). This is just a simple example, in my list I have ~40 sections and ~10K people (this is repeated number and I do not know how many unique persons are there). Question to tutor: Could any one help me proceed further. Will a dictionary (key and values ) based method work for this kind of problem. Thank you in advance and looking forward to hear from you Thanks again Srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Thu Jul 21 23:13:40 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 21 Jul 2005 14:13:40 -0700 (PDT) Subject: [Tutor] Will a dictionary based method work for this problem In-Reply-To: <20050721205138.20443.qmail@web53509.mail.yahoo.com> Message-ID: > This is just a simple example, in my list I have ~40 > sections and ~10K people (this is repeated number and > I do not know how many unique persons are there). > > Question to tutor: > > Could any one help me proceed further. > Will a dictionary (key and values ) based method work > for this kind of problem. Hi Srivivas, You may want to consider a relational database approach. It is possible to do something like this in straight Python, but you'll be basically implementing the basic behavior provided by any good relational database. The kind of queries that you're asking: 1. Who are the people unique to Accounts? 2. Who are the people working for two sections of the office? are the ad-hoc queries that make relational databases a really big win --- it should be relatively straightforward to express those questions in SQL. There are a few free database system you can experiment with, like SQLite, PostGreSQL, or MySQL: http://www.sqlite.org/ http://www.postgresql.org/ http://www.mysql.com/ These systems interact well with Python through Python's DB-API. http://www.python.org/peps/pep-0249.html Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Jul 21 23:15:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 21 Jul 2005 14:15:42 -0700 (PDT) Subject: [Tutor] How do I add an argument too... In-Reply-To: <42E0092B.6080909@gmail.com> Message-ID: On Thu, 21 Jul 2005, Joseph Quigley wrote: > optparse.. Can I download that as a module or do I have to download > epython? Hi Joseph, optparse derives from a hird-party library called Optik, so in a pinch, you can probably just use Optik: http://optik.sourceforge.net/ It's also possible to port optparse back to older versions of Python, although that may take more work. Good luck! From srini_iyyer_bio at yahoo.com Thu Jul 21 23:24:16 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Thu, 21 Jul 2005 14:24:16 -0700 (PDT) Subject: [Tutor] Will a dictionary based method work for this problem In-Reply-To: Message-ID: <20050721212416.27355.qmail@web53505.mail.yahoo.com> Thanks Danny, I did not think of that at all. I have some experience with postgres. i will do that. thanks --- Danny Yoo wrote: > > > > This is just a simple example, in my list I have > ~40 > > sections and ~10K people (this is repeated number > and > > I do not know how many unique persons are there). > > > > Question to tutor: > > > > Could any one help me proceed further. > > Will a dictionary (key and values ) based method > work > > for this kind of problem. > > Hi Srivivas, > > You may want to consider a relational database > approach. It is possible > to do something like this in straight Python, but > you'll be basically > implementing the basic behavior provided by any good > relational database. > > > The kind of queries that you're asking: > > 1. Who are the people unique to Accounts? > > 2. Who are the people working for two sections > of the > office? > > are the ad-hoc queries that make relational > databases a really big win --- > it should be relatively straightforward to express > those questions in SQL. > > > There are a few free database system you can > experiment with, like SQLite, > PostGreSQL, or MySQL: > > http://www.sqlite.org/ > http://www.postgresql.org/ > http://www.mysql.com/ > > These systems interact well with Python through > Python's DB-API. > > http://www.python.org/peps/pep-0249.html > > > Good luck! > > > ____________________________________________________ Start your day with Yahoo! - make it your home page http://www.yahoo.com/r/hs From jorge at bcs.org.uk Thu Jul 21 23:47:48 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Thu, 21 Jul 2005 22:47:48 +0100 Subject: [Tutor] Efficient word count Message-ID: Hi there, I was wondering, and maybe this is because I come from a different programming language background, but is a word count using len(list) after a string.split, efficient if there are many words? Or should I write my own word count for large(ish) blocks of text (500-1000)? Cheers jorge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/4e63618c/attachment.htm From jfouhy at paradise.net.nz Fri Jul 22 00:40:05 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 22 Jul 2005 10:40:05 +1200 (NZST) Subject: [Tutor] Efficient word count In-Reply-To: References: Message-ID: <1121985605.42e024457b32b@www.paradise.net.nz> Quoting Jorge Louis De Castro : > I was wondering, and maybe this is because I come from a different > programming language background, but is a word count using len(list) > after a string.split, efficient if there are many words? Or should I > write my own word count for large(ish) blocks of text (500-1000)? Well, here's a few attempts at finding other ways of doing that: E:\Python24\Lib>python timeit.py -s "foo = 'word wrd wordwordword '*1000" "len(foo.split())" 1000 loops, best of 3: 1.44 msec per loop E:\Python24\Lib>python timeit.py -s "foo = 'word wrd wordwordword '*1000" "len([c for c in foo if c.isspace()])" 100 loops, best of 3: 9.18 msec per loop E:\Python24\Lib>python timeit.py -s "foo = 'word wrd wordwordword '*1000" "len([c for c in foo if c == ' '])" 100 loops, best of 3: 4.33 msec per loop At a guess, you might be able to do it faster if you wrote a word counter in C, because you could avoid building the list. But len(s.split()) is probably the quickest otherwise. See also http://www.python.org/doc/essays/list2str.html :-) -- John. From jfouhy at paradise.net.nz Fri Jul 22 01:40:51 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 22 Jul 2005 11:40:51 +1200 (NZST) Subject: [Tutor] Tkinter event for changing OptionMenu items In-Reply-To: <61d0e2b405072109196ee6c95b@mail.gmail.com> References: <61d0e2b405072109196ee6c95b@mail.gmail.com> Message-ID: <1121989251.42e03283a022b@www.paradise.net.nz> Quoting Bernard Lebel <3dbernard at gmail.com>: > I'm trying to bind an event to the changes made to an OptionMenu. Ie > the user chooses a different item, the rest of the Tk window gets > updated. To repopulate the window, a function would be called by the > binding. > > Any suggestion? The easiest way is to use a Pmw.OptionMenu, which has this functionality built-in :-) Alternatively, you can trace the StringVar you connect to the OptionMenu. I have never done anything with traces, but there are some instructions here: http://www.astro.washington.edu/owen/ROTKFolklore.html -- John. From cyresse at gmail.com Fri Jul 22 01:45:04 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri, 22 Jul 2005 11:45:04 +1200 Subject: [Tutor] Send attachment In-Reply-To: References: Message-ID: If it's Outlook, you can use the win32python library to control it via ActiveX/COM+ http://starship.python.net/crew/mhammond/ Here's an example using VB to control Outlook - http://support.microsoft.com/?kbid=220595 The language differs, but the basic principle remains the same. Create an Application.Outlook object, and then use it's methods. I know there's a way to use the default mail client ( as in Excel VBA's - application.showdialog(xlDialogs.SendMail) ) but blowed if I can figure it out. The above VBA bit automatically attaches the open spreadsheet, so unsure if you can hijack it. Good luck, and if you google how to use the default email client, let me know! Liam Clarke On 7/22/05, Jorge Louis De Castro wrote: > > Hello, > Any ideas how I can use Python and the Windows API to open a PC's mail > client and send an attachment? > The idea is saving some data onto a file and then invoke the email client > (OE or Outlook or whatever is the default on the machine) with the > recipient's address filled in and the file ready to be sent as an > attachment. > Kinda like when we right-click on a file and select the "send to mail > recipient" behavior. > Been reading docs, trying out samples, and googling this for a few days to > no avail. > Cheers > jorge > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050722/ebfaf29f/attachment.htm From jfouhy at paradise.net.nz Fri Jul 22 02:40:31 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri, 22 Jul 2005 12:40:31 +1200 (NZST) Subject: [Tutor] Microsoft python scripts Message-ID: <1121992831.42e0407f4c9fa@www.paradise.net.nz> via Dr Dobbs, check out: http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx It's a bunch of short python scripts provided by Microsoft, showing how to use win32com to do all sorts of stuff. Could be a very useful source of examples if you do development on Windows! -- John. From kent37 at tds.net Fri Jul 22 02:55:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Jul 2005 20:55:03 -0400 Subject: [Tutor] String slicing from tuple list In-Reply-To: References: <42DFFFF4.60209@tds.net> Message-ID: <42E043E7.2080300@tds.net> cgw501 at york.ac.uk wrote: > Hi Kent, > > Thanks for you solution, unfortunately, as Luis correctly inferred, I'm > doing computational biology, so my real data is HUGE and I got this error: > > Traceback (most recent call last): > File "stolen.py", line 62, in ? > first, second = zip(nonGenic) > ValueError: too many values to unpack That is a coding error, it should be zip(*nonGenic) <- note the asterisk. >>> data = [(1423, 2637),(6457, 8345),(9086, 10100),(12304, 15666)] >>> first, second = zip(data) Traceback (most recent call last): File "", line 1, in ? ValueError: too many values to unpack >>> first, second = zip(*data) >>> Kent From gordnjen at rogers.com Fri Jul 22 03:09:33 2005 From: gordnjen at rogers.com (gordnjen) Date: Thu, 21 Jul 2005 21:09:33 -0400 Subject: [Tutor] New Problems with script Message-ID: <004101c58e5a$0596fff0$a471c545@JennineGord> Hello all: I am VERY new at any programming of any sort, so any help would be appreciated. This is the new and improved error message I get when I am trying to run the attached script: Script Error There was an error with your script and it didn't exit properly. This was its output: File "/home/jgates/public_html/Fifthone2.py", line 36 print "#blend { Any advice? Jennine -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.323 / Virus Database: 267.9.2/55 - Release Date: 21/07/2005 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050721/fce51a95/attachment-0001.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Fifthone2.py Url: http://mail.python.org/pipermail/tutor/attachments/20050721/fce51a95/Fifthone2-0001.diff From hugonz-lists at h-lab.net Fri Jul 22 03:24:28 2005 From: hugonz-lists at h-lab.net (=?windows-1250?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 21 Jul 2005 20:24:28 -0500 Subject: [Tutor] New Problems with script In-Reply-To: <004101c58e5a$0596fff0$a471c545@JennineGord> References: <004101c58e5a$0596fff0$a471c545@JennineGord> Message-ID: <42E04ACC.7000100@h-lab.net> Hi, First of all, try to include the relevan code *inline* instead of attaching. This creates all sort of problems, specially that it prevents the list archive from gracefully displaying your message. You have this: print "#blend { width: 10em; padding: 0; border: 1px solid black; margin-left: 3em } Double quoted strings cannot span more than one line, you should use triple-quotes instead. In any case, you should try to run it outside the CGI environment to see what's wrong. In this case, you should have got a simple syntax error if run from the command line... if run from a CGI, it is more difficult to debug. Hope it helps, Hugo gordnjen wrote: > Hello all: > > I am VERY new at any programming of any sort, so any help would be > appreciated. > > This is the new and improved error message I get when I am trying to run > the attached script: > > Script Error > > > > There was an error with your script and it didn't exit properly. > > > > This was its output: > > > > File "/home/jgates/public_html/Fifthone2.py", line 36 > > print "#blend { > > > > Any advice? > > > > Jennine > > > > > -- > No virus found in this outgoing message. > Checked by AVG Anti-Virus. > Version: 7.0.323 / Virus Database: 267.9.2/55 - Release Date: 21/07/2005 > > > ------------------------------------------------------------------------ > > import cgitb; > cgitb.enable() > import cgi > form = cgi.FieldStorage() > > print "Content-type: text/html" > print > print """ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > """ > > red1 = int (form["red1"].value) > green1 = int (form["green1"].value) > blue1 = int (form["blue1"].value) > red2 = int (form["red2"].value) > green2 = int (form["green2"].value) > blue2 = int (form["blue2"].value) > > nsteps = int (form["steps"].value) > for i in range(nsteps): > print i, > > fraction = (i+1.0)/nsteps > r = (1-fraction)*red1 + fraction*red2 > g = (1-fraction)*green1 + fraction*green2 > b = (1-fraction)*blue1 + fraction*green2 > > > print "" > print "" > print "Colour Blend" > print '
print 'style="background-color: rgb(' + str(r) + '%,' + str(g) + '%,' + str(b) + '%)">' > print '
' > print "" > print "" > print "" > print "

Colour Blend

" > print "

Here is a mix of the two colours you specified:

" print "
" > print "
" > print "Return to the index.

" > print "" > print "" > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Fri Jul 22 04:29:01 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri, 22 Jul 2005 14:29:01 +1200 Subject: [Tutor] Microsoft python scripts In-Reply-To: <1121992831.42e0407f4c9fa@www.paradise.net.nz> References: <1121992831.42e0407f4c9fa@www.paradise.net.nz> Message-ID: That is just awesome, awesome, awesome. Big ups. On 7/22/05, jfouhy at paradise.net.nz wrote: > > via Dr Dobbs, check out: > http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.mspx > > It's a bunch of short python scripts provided by Microsoft, showing how to > use > win32com to do all sorts of stuff. > > Could be a very useful source of examples if you do development on > Windows! > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050722/63c14801/attachment.htm From byron at christianfreebies.com Fri Jul 22 04:33:51 2005 From: byron at christianfreebies.com (byron@christianfreebies.com) Date: Thu, 21 Jul 2005 22:33:51 -0400 Subject: [Tutor] hello In-Reply-To: <24d1ebd433bdc6d43b7c5a43f26d1f02@shaw.ca> References: <24d1ebd433bdc6d43b7c5a43f26d1f02@shaw.ca> Message-ID: <1121999631.42e05b0fe9c79@webmail.christianfreebies.com> Yes, it is. :-) Byron --- Quoting dina lenning : > is this where i send my questions?? ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From xecronix at yahoo.com Fri Jul 22 04:53:46 2005 From: xecronix at yahoo.com (Ron Weidner) Date: Thu, 21 Jul 2005 19:53:46 -0700 (PDT) Subject: [Tutor] Linux sound control Message-ID: <20050722025346.53128.qmail@web60623.mail.yahoo.com> It's simple, without any bells and whistles. Move the slider up and down to change the volume on your Linux system. Written in Python and Tkinter, this little program should work with any window manager. http://www.techport80.com/soundctrl/sound_ctrl.tgz -- Ronald Weidner http://www.techport80.com PHP Software developer for hire. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From nephish at xit.net Fri Jul 22 07:32:50 2005 From: nephish at xit.net (nephish) Date: Fri, 22 Jul 2005 00:32:50 -0500 Subject: [Tutor] confusing smtp problem In-Reply-To: <1121959031l.3289l.0l@texaspivot.texaspivot.com> References: <1121878535l.32243l.0l@texaspivot> <42DE88B4.4060701@intersiege.com> <1121880849l.32243l.1l@texaspivot> <42DEB4CA.5060702@intersiege.com> <1121899414l.1441l.0l@texaspivot.texaspivot.com> <42DEE091.5070401@intersiege.com> <1121907723.10885.4.camel@localhost.localdomain> <42DFAF5A.9040709@intersiege.com> <1121959031l.3289l.0l@texaspivot.texaspivot.com> Message-ID: <1122010370.14265.0.camel@localhost.localdomain> sorry i am late on this one didnt get a chance to look at it today, perhaps in the morning i will crack this open thanks guys! On Thu, 2005-07-21 at 15:17 +0000, nephish wrote: > ok this is what i get when i use host = '10.10.10.04 25' > resourse unavailable > line = self.sock.recv(size,socket.MSG_PEEK) > > now if i use host = '10.10.10.04:25' it has all the appearences of > having worked, but the email never gets to its destination. > > hmmmmmmmm. > > i tried it the first way because that is what let me connect and > do the helo thing via telnet. > > > On 07/21/2005 09:21:14 AM, Reed L. O'Brien wrote: > > nephish wrote: > > > Sorry about the delay getting back on this one guys, > > > yeah, i am running a linux machine. > > > no firewall between here and there (both behind a firewall router) > > > yeah, sylpheed does send on port 25 > > > the windows machine has the Merek email server on board. > > > i would like my scripts to be able to send to it, > > > as a backup, but the debian linux MTA (Exim i think) is working. > > > So it isn't too big a deal if it does not. > > > telnet and helo does work, it lets me in from the command line > > > from the linux machine (where my python scripts are) to the win > > > machine (where the other mail server is) > > > > > > we dont need POP for this at all, we are sending only. > > > > > > incidentally, i appreciate you guys time and attention to this. > > > > > > all the best, > > > shawn > > > > > > > > > > Does it still give the same error???? > > > > ib.py", line 347, in getreply > > raise SMTPServerDisconnected("Connection unexpectedly closed") > > SMTPServerDisconnected: Connection unexpectedly closed > > > > or is it different?? > > > > ~reed > > > > -- > > 4.6692916090 > > 'cmVlZG9icmllbkBnbWFpbC5jb20=\n'.decode('base64') > > http://www.spreadfirefox.com/?q=affiliates&id=16474&t=1 > > keyID: 0x0FA09FCE > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From winfried at tilanus.com Fri Jul 22 10:14:02 2005 From: winfried at tilanus.com (Winfried Tilanus) Date: Fri, 22 Jul 2005 10:14:02 +0200 (CDT) Subject: [Tutor] redirecting output to logfile and logrotate Message-ID: <200507220814.j6M8E2Zh005762@debbie.tilanus.com> Hi, I am installing a server-like python program that opens a logfile in the following way: # redirect output for logging to file applog = open(config.log, 'a', 1) sys.stdout = applog sys.stderr = sys.stdout Througout the program are lines like: print '[', time.asctime(),']', message[:3] The logfiles of the program can grow quite a big, so I decided to include them in logrotate. That is where the problem started: everytime the logfile gets rotated python loses track of it and stops logging. The program is running on a linux server with python 2.2. How can I make the logging (including stderr) 'logrotate-proof'? thanks & Best wishes, Winfried -- http://www.xs4all.nl/~wtilanus/ From surangasa at gmail.com Sun Jul 17 08:31:04 2005 From: surangasa at gmail.com (Suranga Sarukkali) Date: Sun, 17 Jul 2005 12:31:04 +0600 Subject: [Tutor] Please Help: Hacking Message-ID: <000001c58ecf$4bd06450$65c045ca@computer01> Python's Great fro Hacking Right? Please tell me more like when you tell it to a College Student (That tell's What I'm) and since I Sort of new to Programming in Python it's going be easy if done so. Please reply to me at your earliest convenience and by the way General Hacking Education will be Cool since the only hacking I've done is on a Hacking Simulation Game I downloaded yeas ago from http://g1.acid-play.com/download/a599b964/Hackerv1.zip witch got all the tools like Password Crackers Inbuilt to Simulate Hacking Large Company's and making cash from it. You can privately email me on surangasa at gmail.com I've been on the Mailing List some time and It's Great! Thanks for the People Developed it. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050717/22043cd8/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Suranga Sarukkali.vcf Type: text/x-vcard Size: 405 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050717/22043cd8/SurangaSarukkali.vcf From surangasa at gmail.com Wed Jul 20 17:55:21 2005 From: surangasa at gmail.com (Suranga Sarukkali) Date: Wed, 20 Jul 2005 21:55:21 +0600 Subject: [Tutor] HELP ME DUDE Message-ID: <000301c58ecf$564cdee0$65c045ca@computer01> Hay, you know what? when I connect to the internet the modem software(Error Free Software for Sure) say's a around 50-53.3Kbps connected though when I download a file from a server not p2ps or any of the kind service the downloads are even when connection is idle without any other method of bandwidth usage the downloads are at 4 Kilobytes per second but that should be around 8 Kilobytes per second as a thumb rule, you know that right? so I wonder is it's the malware or any type or WHAT could be the reason or even not how to get the said 53.3k (8KBs per second) download rate to my pc? oh remember to reply to me as soon as possible. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050720/f4688ad8/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: Suranga Sarukkali.vcf Type: text/x-vcard Size: 405 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050720/f4688ad8/SurangaSarukkali.vcf From adam.jtm30 at gmail.com Fri Jul 22 17:17:07 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Fri, 22 Jul 2005 16:17:07 +0100 Subject: [Tutor] Please Help: Hacking In-Reply-To: <000001c58ecf$4bd06450$65c045ca@computer01> References: <000001c58ecf$4bd06450$65c045ca@computer01> Message-ID: How to become a hacker On 7/17/05, Suranga Sarukkali wrote: > > Python's Great fro Hacking Right? Please tell me more like when you tell > it to a College Student (That tell's What I'm) and since I Sort of new to > Programming in Python it's going be easy if done so. Please reply to me at > your earliest convenience and by the way General Hacking Education will be > Cool since the only hacking I've done is on a Hacking Simulation Game I > downloaded yeas ago from > http://g1.acid-play.com/download/a599b964/Hackerv1.zip witch got all the > tools like Password Crackers Inbuilt to Simulate Hacking Large Company's and > making cash from it. You can privately email me on surangasa at gmail.com > I've been on the Mailing List some time and It's Great! Thanks for the > People Developed it. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050722/d2732aad/attachment.htm From zanesdad at bellsouth.net Fri Jul 22 17:24:06 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 22 Jul 2005 11:24:06 -0400 Subject: [Tutor] Please Help: Hacking In-Reply-To: <000001c58ecf$4bd06450$65c045ca@computer01> References: <000001c58ecf$4bd06450$65c045ca@computer01> Message-ID: <42E10F96.5080005@bellsouth.net> Suranga Sarukkali wrote: > Python's Great fro Hacking Right? Please tell me more like when you > tell it to a College Student (That tell's What I'm) and since I > Sort of new to Programming in Python it's going be easy if done so. > Please reply to me at your earliest convenience and by the way General > Hacking Education will be Cool since the only hacking I've done is on > a Hacking Simulation Game I downloaded yeas ago from > http://g1.acid-play.com/download/a599b964/Hackerv1.zip witch got all > the tools like Password Crackers Inbuilt to Simulate Hacking Large > Company's and making cash from it. You can privately email me on > surangasa at gmail.com > > I've been on the Mailing List some time and It's Great! Thanks for the > People Developed it. > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor > > Here you go. This should be enlightening: http://www.catb.org/~esr/writings/unix-koans/script-kiddie.html Jeremy Jones From byron at christianfreebies.com Fri Jul 22 19:38:16 2005 From: byron at christianfreebies.com (byron@christianfreebies.com) Date: Fri, 22 Jul 2005 11:38:16 -0600 Subject: [Tutor] Please Help: Hacking In-Reply-To: <42E10F96.5080005@bellsouth.net> References: <000001c58ecf$4bd06450$65c045ca@computer01> <42E10F96.5080005@bellsouth.net> Message-ID: <1122053896.42e12f080feaf@webmail.christianfreebies.com> Quoting Jeremy Jones : > Here you go. This should be enlightening: > > http://www.catb.org/~esr/writings/unix-koans/script-kiddie.html Hi Jeremy, That's great... Thanks for sharing the link. Byron --- ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From byron at christianfreebies.com Fri Jul 22 19:41:42 2005 From: byron at christianfreebies.com (byron@christianfreebies.com) Date: Fri, 22 Jul 2005 11:41:42 -0600 Subject: [Tutor] HELP ME DUDE In-Reply-To: <000301c58ecf$564cdee0$65c045ca@computer01> References: <000301c58ecf$564cdee0$65c045ca@computer01> Message-ID: <1122054102.42e12fd69541c@webmail.christianfreebies.com> Quoting Suranga Sarukkali : > Hay, you know what? when I connect to the internet the modem software(Error > Free Software for Sure) say's a around 50-53.3Kbps connected though when I > download a file from a server not p2ps or any of the kind service the > downloads are even when connection is idle without any other method of > bandwidth usage the downloads are at 4 Kilobytes per second but that should > be around 8 Kilobytes per second as a thumb rule, you know that right? so I > wonder is it's the malware or any type or WHAT could be the reason or even > not how to get the said 53.3k (8KBs per second) download rate to my pc? oh > remember to reply to me as soon as possible. Hi Suranga, This is a Python programming group. If you have any Python questions, then this is the place to ask them. However, Anything outside of that scope will probably not get you too much help. ;-) Byron --- ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From dyoo at hkn.eecs.berkeley.edu Fri Jul 22 20:46:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 22 Jul 2005 11:46:09 -0700 (PDT) Subject: [Tutor] redirecting output to logfile and logrotate In-Reply-To: <200507220814.j6M8E2Zh005762@debbie.tilanus.com> Message-ID: On Fri, 22 Jul 2005, Winfried Tilanus wrote: > I am installing a server-like python program that opens a logfile in the > following way: > > # redirect output for logging to file > applog = open(config.log, 'a', 1) > sys.stdout = applog > sys.stderr = sys.stdout > > Througout the program are lines like: > > print '[', time.asctime(),']', message[:3] > > The logfiles of the program can grow quite a big, so I decided to > include them in logrotate. Hi Winfried, You may want to look at the 'logging' module: http://docs.python.org/lib/module-logging.html because it comes with a RotatingFileHandler that behaves like logrotate for Python programs. > How can I make the logging (including stderr) 'logrotate-proof'? The approach to keep the log file open throughout the lifetime of the program is what's causing issues with logrotate. logrotate doesn't work nicely with persistant server programs, because the server keeps the file object open during the rotation, and that's bad. (Just as an aside: the Mailman folks run into a similar issue: http://www.python.org/cgi-bin/faqw-mm.py?req=show&file=faq04.007.htp) So if it's possible, I'd recommend using the RotatingFileHandler logger from Python's 'logging' Standard Library module instead of 'logrotate'. Hope this helps! From magoldfish at gmail.com Fri Jul 22 21:41:36 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Fri, 22 Jul 2005 15:41:36 -0400 Subject: [Tutor] tricky eval() problem Message-ID: <5e183f3d05072212412a3e8c25@mail.gmail.com> Here's a noodler I could use some help on: I need a class that can call a user-specified function with arbitrary (unknown) parameter lists. The trick, here, is that the user will dynamically specify the funciton to invoke, and each function may differ in the number of parameters passed during the call. For instance, suppose I define two dummy functions with different calling signatures: def foo1(a1, a2, a3): ... def foo2(a1): ... Then I seek a class, Caller class Caller(object): def execute(self, method, *parms): # some way to execute method That can be used in the following manner: >> c = Caller(); >> c.execute("foo1", 8, 9, 10) >> c.execute("foo2", "me") Any tips on tackling this? Thanks! Marcus From kent37 at tds.net Fri Jul 22 21:56:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 22 Jul 2005 15:56:04 -0400 Subject: [Tutor] tricky eval() problem In-Reply-To: <5e183f3d05072212412a3e8c25@mail.gmail.com> References: <5e183f3d05072212412a3e8c25@mail.gmail.com> Message-ID: <42E14F54.1070808@tds.net> Marcus Goldfish wrote: > Here's a noodler I could use some help on: I need a class that can > call a user-specified function with arbitrary (unknown) parameter > lists. The trick, here, is that the user will dynamically specify the > funciton to invoke, and each function may differ in the number of > parameters passed during the call. For instance, suppose I define two > dummy functions with different calling signatures: > > def foo1(a1, a2, a3): > ... > > def foo2(a1): > ... > > Then I seek a class, Caller > > class Caller(object): > def execute(self, method, *parms): > # some way to execute method > > That can be used in the following manner: > > >>>c = Caller(); >>>c.execute("foo1", 8, 9, 10) >>>c.execute("foo2", "me") > > > Any tips on tackling this? Something like this: def execute(self, method, *parms): fn = locals().get(method) or globals.get(method) if fn: fn(*parms) Seems like there should be a better way of looking up method but I can't think of it right now...if method is an instance method of Caller then you could use fn = getattr(self, method) (which will raise AttributeError if there is no such method) Kent From jsmith at medplus.com Fri Jul 22 22:36:50 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 22 Jul 2005 16:36:50 -0400 Subject: [Tutor] Something that Perl can do that Python can't? Message-ID: So here it is: handle unbuffered output from a child process. Here is the child process script (bufcallee.py): import time print 'START' time.sleep(10) print 'STOP' In Perl, I do: open(FILE, "python bufcallee.py |"); while ($line = ) { print "LINE: $line"; } in which case I get LINE: START followed by a 10 second pause and then LINE: STOP The equivalent in Python: import sys, os FILE = os.popen('python bufcallee.py') for line in FILE: print 'LINE:', line yields a 10 second pause followed by LINE: START LINE: STOP I have tried the subprocess module, the -u on both the original and called script, setting bufsize=0 explicitly but to no avail. I also get the same behavior on Windows and Linux. If anyone can disprove me or show me what I'm doing wrong, it would be appreciated. Jeff From jsmith at medplus.com Fri Jul 22 23:06:15 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 22 Jul 2005 17:06:15 -0400 Subject: [Tutor] Something that Perl can do that Python can't? Message-ID: Well, I finally managed to solve it myself by looking at some code. The solution in Python is a little non-intuitive but this is how to get it: while 1: line = stdout.readline() if not line: break print 'LINE:', line, If anyone can do it the more Pythonic way with some sort of iteration over stdout, please let me know. Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Smith, Jeff Sent: Friday, July 22, 2005 4:37 PM To: Tutor Subject: [Tutor] Something that Perl can do that Python can't? So here it is: handle unbuffered output from a child process. Here is the child process script (bufcallee.py): import time print 'START' time.sleep(10) print 'STOP' In Perl, I do: open(FILE, "python bufcallee.py |"); while ($line = ) { print "LINE: $line"; } in which case I get LINE: START followed by a 10 second pause and then LINE: STOP The equivalent in Python: import sys, os FILE = os.popen('python bufcallee.py') for line in FILE: print 'LINE:', line yields a 10 second pause followed by LINE: START LINE: STOP I have tried the subprocess module, the -u on both the original and called script, setting bufsize=0 explicitly but to no avail. I also get the same behavior on Windows and Linux. If anyone can disprove me or show me what I'm doing wrong, it would be appreciated. Jeff _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Sat Jul 23 13:15:15 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat, 23 Jul 2005 23:15:15 +1200 Subject: [Tutor] HELP ME DUDE In-Reply-To: <1122054102.42e12fd69541c@webmail.christianfreebies.com> References: <000301c58ecf$564cdee0$65c045ca@computer01> <1122054102.42e12fd69541c@webmail.christianfreebies.com> Message-ID: Also, please use punctuation and paragraphs. I'm not a grammar Nazi per se, but sheesh, that stuff is unreadable. And, as a general rule, a 56 kilobits pers second will download at 5.6Kilobytes per second at the very best. You're lucky to get 4 Kilobytes per second. Hence, ADSL is good. On 7/23/05, byron at christianfreebies.com wrote: > > Quoting Suranga Sarukkali : > > > Hay, you know what? when I connect to the internet the modem > software(Error > > Free Software for Sure) say's a around 50-53.3Kbps connected though when > I > > download a file from a server not p2ps or any of the kind service the > > downloads are even when connection is idle without any other method of > > bandwidth usage the downloads are at 4 Kilobytes per second but that > should > > be around 8 Kilobytes per second as a thumb rule, you know that right? > so I > > wonder is it's the malware or any type or WHAT could be the reason or > even > > not how to get the said 53.3k (8KBs per second) download rate to my pc? > oh > > remember to reply to me as soon as possible. > > > Hi Suranga, > > This is a Python programming group. If you have any Python questions, then > this > is the place to ask them. However, Anything outside of that scope will > probably not get you too much help. ;-) > > Byron > --- > > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050723/be81fbd3/attachment.htm From cyresse at gmail.com Sat Jul 23 13:26:26 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat, 23 Jul 2005 23:26:26 +1200 Subject: [Tutor] Parsing problem In-Reply-To: <20050721075251.DFB8C1E4007@bag.python.org> References: <20050721075251.DFB8C1E4007@bag.python.org> Message-ID: Howdy, I've attempted to follow your lead and have started from scratch, I could just copy and paste your solution (which works pretty well), but I want to understand what I'm doing *grin* However, I've been hitting a couple of ruts in the path to enlightenment. Is there a way to tell pyparsing that to treat specific escaped characters as just a slash followed by a letter? For the time being I've converted all backslashes to forwardslashes, as it was choking on \a in a file path. But my latest hitch, takes this form (apologies for large traceback) Traceback (most recent call last): File "", line 1, in ? File "parse.py", line 336, in parse parsedEntries = dicts.parseString(test_data) File "c:\python24\Lib\site-packages\pyparsing.py", line 616, in parseString loc, tokens = self.parse( instring.expandtabs(), 0 ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1367, in parseImpl loc, exprtokens = e.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 560, in parse raise ParseException, ( instring, len(instring), self.errmsg, self ) ParseException: Expected "}" (at char 9909), (line:325, col:5) The offending code can be found here (includes the data) - http://www.rafb.net/paste/results/L560wx80.html It's like pyparsing isn't recognising a lot of my "}"'s, as if I add another one, it throws the same error, same for adding another two... No doubt I've done something silly, but any help in finding the tragic flaw would be much appreciated. I need to get a parsingResults object out so I can learn how to work with the basic structure! Much regards, Liam Clarke On 7/21/05, Paul McGuire wrote: > > Liam, Kent, and Danny - > > It sure looks like pyparsing is taking on a life of its own! I can see I > no > longer am the only one pitching pyparsing at some of these applications! > > Yes, Liam, it is possible to create dictionary-like objects, that is, > ParseResults objects that have named values in them. I looked into your > application, and the nested assignments seem very similar to a ConfigParse > type of structure. Here is a pyparsing version that handles the test data > in your original post (I kept Danny Yoo's recursive list values, and added > recursive dictionary entries): > > -------------------------- > import pyparsing as pp > > listValue = pp.Forward() > listSeq = pp.Suppress('{') + pp.Group(pp.ZeroOrMore(listValue)) + > pp.Suppress('}') > listValue << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | > pp.Word(pp.alphanums) | listSeq ) > > keyName = pp.Word( pp.alphas ) > > entries = pp.Forward() > entrySeq = pp.Suppress('{') + pp.Group(pp.OneOrMore(entries)) + > pp.Suppress('}') > entries << pp.Dict( > pp.OneOrMore( > pp.Group( keyName + pp.Suppress('=') + (entrySeq | > listValue) ) ) ) > -------------------------- > > > Dict is one of the most confusing classes to use, and there are some > examples in the examples directory that comes with pyparsing (see > dictExample2.py), but it is still tricky. Here is some code to access your > input test data, repeated here for easy reference: > > -------------------------- > testdata = """\ > country = { > tag = ENG > ai = { > flags = { } > combat = { DAU FRA ORL PRO } > continent = { } > area = { } > region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" > "TagoSea" "WCAtlanticSea" } > war = 60 > ferocity = no > } > } > """ > parsedEntries = entries.parseString(testdata) > > def dumpEntries(dct,depth=0): > keys = dct.keys() > keys.sort() > for k in keys: > print (' '*depth) + '- ' + k + ':', > if isinstance(dct[k],pp.ParseResults): > if dct[k][0].keys(): > print > dumpEntries(dct[k][0],depth+1) > else: > print dct[k][0] > else: > print dct[k] > > dumpEntries( parsedEntries ) > > print > print parsedEntries.country[0].tag > print parsedEntries.country[0].ai[0].war > print parsedEntries.country[0].ai[0].ferocity > -------------------------- > > This will print out: > > -------------------------- > - country: > - ai: > - area: [] > - combat: ['DAU', 'FRA', 'ORL', 'PRO'] > - continent: [] > - ferocity: no > - flags: [] > - region: ['British Isles', 'NorthSeaSea', 'ECAtlanticSea', > 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] > - war: 60 > - tag: ENG > > ENG > 60 > No > -------------------------- > > But I really dislike having to dereference those nested values using the > 0'th element. So I'm going to fix pyparsing so that in the next release, > you'll be able to reference the sub-elements as: > > print parsedEntries.country.tag > print parsedEntries.country.ai.war > print parsedEntries.country.ai.ferocity > > This *may* break some existing code, but Dict is not heavily used, based > on > feedback from users, and this may make it more useful in general, > especially > when data parses into nested Dict's. > > Hope this sheds more light than confusion! > -- Paul McGuire > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050723/5ed6bd01/attachment.htm From winfried at tilanus.com Sat Jul 23 15:25:07 2005 From: winfried at tilanus.com (Winfried Tilanus) Date: Sat, 23 Jul 2005 15:25:07 +0200 (CDT) Subject: [Tutor] redirecting output to logfile and logrotate In-Reply-To: Message-ID: <200507231325.j6NDP6qW009114@debbie.tilanus.com> On Fri, 22 Jul 2005 11:46:09 -0700 (PDT), Danny Yoo wrote: Thanks Danny, (snip) >So if it's possible, I'd recommend using the RotatingFileHandler logger >from Python's 'logging' Standard Library module instead of 'logrotate'. That is the way I will go, the library (although not standard in Python 2.2) offers great facillities and shouldn't be too difficult to incorporate in the program. Somebody else suggested (in private) to make logrotate send a -HUP to the server program. But the server doesn't respond to that signal at the moment en (propperly) incorporating that in the program seems to be lot more work than altering the logging. Thanks for the suggestions! Best wishes, Winfried -- http://www.xs4all.nl/~wtilanus/ From cyresse at gmail.com Sat Jul 23 15:33:10 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun, 24 Jul 2005 01:33:10 +1200 Subject: [Tutor] Parsing problem In-Reply-To: References: <20050721075251.DFB8C1E4007@bag.python.org> Message-ID: Hmmm... just a quick update, I've been poking around and I'm obviously making some error of logic. Given a line - f = "j = { line = { foo = 10 bar = 20 } }" And given the following code - select = pp.Forward() select << pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore( (pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables) ) | select ) + pp.Suppress("}") sel.parseString(f) gives - (['j', 'line', '{', 'foo', '10', 'bar', '20'], {}) So I've got a bracket sneaking through there. Argh. My brain hurts. Is the | operator an exclusive or? Befuddled, Liam Clarke On 7/23/05, Liam Clarke wrote: > > Howdy, > > I've attempted to follow your lead and have started from scratch, I could > just copy and paste your solution (which works pretty well), but I want to > understand what I'm doing *grin* > > However, I've been hitting a couple of ruts in the path to enlightenment. > Is there a way to tell pyparsing that to treat specific escaped characters > as just a slash followed by a letter? For the time being I've converted all > backslashes to forwardslashes, as it was choking on \a in a file path. > > But my latest hitch, takes this form (apologies for large traceback) > > Traceback (most recent call last): > File "", line 1, in ? > File "parse.py", line 336, in parse > parsedEntries = dicts.parseString(test_data) > File "c:\python24\Lib\site-packages\pyparsing.py", line 616, in > parseString > loc, tokens = self.parse( instring.expandtabs(), 0 ) > File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl > return self.expr.parse( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line 1367, in parseImpl > loc, exprtokens = e.parse( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl > return self.expr.parse( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line 560, in parse > raise ParseException, ( instring, len(instring), self.errmsg, self ) > > ParseException: Expected "}" (at char 9909), (line:325, col:5) > > The offending code can be found here (includes the data) - > http://www.rafb.net/paste/results/L560wx80.html > > It's like pyparsing isn't recognising a lot of my "}"'s, as if I add > another one, it throws the same error, same for adding another two... > > No doubt I've done something silly, but any help in finding the tragic > flaw would be much appreciated. I need to get a parsingResults object out so > I can learn how to work with the basic structure! > > Much regards, > > Liam Clarke > > On 7/21/05, Paul McGuire wrote: > > > > Liam, Kent, and Danny - > > > > It sure looks like pyparsing is taking on a life of its own! I can see I > > no > > longer am the only one pitching pyparsing at some of these applications! > > > > Yes, Liam, it is possible to create dictionary-like objects, that is, > > ParseResults objects that have named values in them. I looked into your > > application, and the nested assignments seem very similar to a > > ConfigParse > > type of structure. Here is a pyparsing version that handles the test > > data > > in your original post (I kept Danny Yoo's recursive list values, and > > added > > recursive dictionary entries): > > > > -------------------------- > > import pyparsing as pp > > > > listValue = pp.Forward() > > listSeq = pp.Suppress ('{') + pp.Group(pp.ZeroOrMore(listValue)) + > > pp.Suppress('}') > > listValue << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | > > pp.Word(pp.alphanums) | listSeq ) > > > > keyName = pp.Word( pp.alphas ) > > > > entries = pp.Forward() > > entrySeq = pp.Suppress('{') + pp.Group(pp.OneOrMore(entries)) + > > pp.Suppress('}') > > entries << pp.Dict( > > pp.OneOrMore ( > > pp.Group( keyName + pp.Suppress('=') + (entrySeq | > > listValue) ) ) ) > > -------------------------- > > > > > > Dict is one of the most confusing classes to use, and there are some > > examples in the examples directory that comes with pyparsing (see > > dictExample2.py), but it is still tricky. Here is some code to access > > your > > input test data, repeated here for easy reference: > > > > -------------------------- > > testdata = """\ > > country = { > > tag = ENG > > ai = { > > flags = { } > > combat = { DAU FRA ORL PRO } > > continent = { } > > area = { } > > region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" > > "TagoSea" "WCAtlanticSea" } > > war = 60 > > ferocity = no > > } > > } > > """ > > parsedEntries = entries.parseString(testdata) > > > > def dumpEntries(dct,depth=0): > > keys = dct.keys() > > keys.sort() > > for k in keys: > > print (' '*depth) + '- ' + k + ':', > > if isinstance(dct[k],pp.ParseResults): > > if dct[k][0].keys(): > > print > > dumpEntries(dct[k][0],depth+1) > > else: > > print dct[k][0] > > else: > > print dct[k] > > > > dumpEntries( parsedEntries ) > > > > print > > print parsedEntries.country[0].tag > > print parsedEntries.country[0].ai[0].war > > print parsedEntries.country[0].ai[0].ferocity > > -------------------------- > > > > This will print out: > > > > -------------------------- > > - country: > > - ai: > > - area: [] > > - combat: ['DAU', 'FRA', 'ORL', 'PRO'] > > - continent: [] > > - ferocity: no > > - flags: [] > > - region: ['British Isles', 'NorthSeaSea', 'ECAtlanticSea', > > 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] > > - war: 60 > > - tag: ENG > > > > ENG > > 60 > > No > > -------------------------- > > > > But I really dislike having to dereference those nested values using the > > 0'th element. So I'm going to fix pyparsing so that in the next release, > > you'll be able to reference the sub-elements as: > > > > print parsedEntries.country.tag > > print parsedEntries.country.ai.war > > print parsedEntries.country.ai.ferocity > > > > This *may* break some existing code, but Dict is not heavily used, based > > on > > feedback from users, and this may make it more useful in general, > > especially > > when data parses into nested Dict's. > > > > Hope this sheds more light than confusion! > > -- Paul McGuire > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050724/e0627cbd/attachment-0001.htm From cyresse at gmail.com Sat Jul 23 16:02:32 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun, 24 Jul 2005 02:02:32 +1200 Subject: [Tutor] Parsing problem In-Reply-To: References: <20050721075251.DFB8C1E4007@bag.python.org> Message-ID: *sigh* I just read the documentation more carefully and found the difference between the | operator and the ^ operator. Input - j = { line = { foo = 10 bar = 20 } } New code sel = pp.Forward() values = ((pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables)) ^ sel) sel << (pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore(values) + pp.Suppress("}")) Output - (['j', 'line', 'foo', '10', 'bar', '20'], {}) My apologies for the deluge. Regards, Liam Clarke On 7/24/05, Liam Clarke wrote: > > Hmmm... just a quick update, I've been poking around and I'm obviously > making some error of logic. > > Given a line - > > f = "j = { line = { foo = 10 bar = 20 } }" > > And given the following code - > > select = pp.Forward() > select << > pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + > pp.OneOrMore( (pp.Word(pp.printables) + pp.Suppress("=") + > pp.Word(pp.printables) ) | select ) + pp.Suppress("}") > > sel.parseString(f) gives - > > (['j', 'line', '{', 'foo', '10', 'bar', '20'], {}) > > So I've got a bracket sneaking through there. Argh. My brain hurts. > > Is the | operator an exclusive or? > > Befuddled, > > Liam Clarke > > On 7/23/05, Liam Clarke wrote: > > > > Howdy, > > > > I've attempted to follow your lead and have started from scratch, I > > could just copy and paste your solution (which works pretty well), but I > > want to understand what I'm doing *grin* > > > > However, I've been hitting a couple of ruts in the path to > > enlightenment. Is there a way to tell pyparsing that to treat specific > > escaped characters as just a slash followed by a letter? For the time being > > I've converted all backslashes to forwardslashes, as it was choking on \a in > > a file path. > > > > But my latest hitch, takes this form (apologies for large traceback) > > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "parse.py", line 336, in parse > > parsedEntries = dicts.parseString(test_data) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 616, in > > parseString > > loc, tokens = self.parse( instring.expandtabs(), 0 ) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse > > loc,tokens = self.parseImpl( instring, loc, doActions ) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in > > parseImpl > > return self.expr.parse( instring, loc, doActions ) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse > > loc,tokens = self.parseImpl( instring, loc, doActions ) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 1367, in > > parseImpl > > loc, exprtokens = e.parse( instring, loc, doActions ) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse > > loc,tokens = self.parseImpl( instring, loc, doActions ) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in > > parseImpl > > return self.expr.parse( instring, loc, doActions ) > > File "c:\python24\Lib\site-packages\pyparsing.py", line 560, in parse > > raise ParseException, ( instring, len(instring), self.errmsg, self ) > > > > ParseException: Expected "}" (at char 9909), (line:325, col:5) > > > > The offending code can be found here (includes the data) - http://www.rafb.net/paste/results/L560wx80.html > > > > > > It's like pyparsing isn't recognising a lot of my "}"'s, as if I add > > another one, it throws the same error, same for adding another two... > > > > No doubt I've done something silly, but any help in finding the tragic > > flaw would be much appreciated. I need to get a parsingResults object out so > > I can learn how to work with the basic structure! > > > > Much regards, > > > > Liam Clarke > > > > On 7/21/05, Paul McGuire < paul at alanweberassociates.com> wrote: > > > > > > Liam, Kent, and Danny - > > > > > > It sure looks like pyparsing is taking on a life of its own! I can see > > > I no > > > longer am the only one pitching pyparsing at some of these > > > applications! > > > > > > Yes, Liam, it is possible to create dictionary-like objects, that is, > > > ParseResults objects that have named values in them. I looked into > > > your > > > application, and the nested assignments seem very similar to a > > > ConfigParse > > > type of structure. Here is a pyparsing version that handles the test > > > data > > > in your original post (I kept Danny Yoo's recursive list values, and > > > added > > > recursive dictionary entries): > > > > > > -------------------------- > > > import pyparsing as pp > > > > > > listValue = pp.Forward() > > > listSeq = pp.Suppress ('{') + pp.Group(pp.ZeroOrMore(listValue)) + > > > pp.Suppress('}') > > > listValue << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | > > > pp.Word(pp.alphanums) | listSeq ) > > > > > > keyName = pp.Word( pp.alphas ) > > > > > > entries = pp.Forward() > > > entrySeq = pp.Suppress('{') + pp.Group(pp.OneOrMore(entries)) + > > > pp.Suppress('}') > > > entries << pp.Dict( > > > pp.OneOrMore ( > > > pp.Group( keyName + pp.Suppress('=') + (entrySeq | > > > listValue) ) ) ) > > > -------------------------- > > > > > > > > > Dict is one of the most confusing classes to use, and there are some > > > examples in the examples directory that comes with pyparsing (see > > > dictExample2.py), but it is still tricky. Here is some code to access > > > your > > > input test data, repeated here for easy reference: > > > > > > -------------------------- > > > testdata = """\ > > > country = { > > > tag = ENG > > > ai = { > > > flags = { } > > > combat = { DAU FRA ORL PRO } > > > continent = { } > > > area = { } > > > region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" > > > "NAtlanticSea" > > > "TagoSea" "WCAtlanticSea" } > > > war = 60 > > > ferocity = no > > > } > > > } > > > """ > > > parsedEntries = entries.parseString(testdata) > > > > > > def dumpEntries(dct,depth=0): > > > keys = dct.keys() > > > keys.sort() > > > for k in keys: > > > print (' '*depth) + '- ' + k + ':', > > > if isinstance(dct[k],pp.ParseResults): > > > if dct[k][0].keys(): > > > print > > > dumpEntries(dct[k][0],depth+1) > > > else: > > > print dct[k][0] > > > else: > > > print dct[k] > > > > > > dumpEntries( parsedEntries ) > > > > > > print > > > print parsedEntries.country[0].tag > > > print parsedEntries.country[0].ai[0].war > > > print parsedEntries.country[0].ai[0].ferocity > > > -------------------------- > > > > > > This will print out: > > > > > > -------------------------- > > > - country: > > > - ai: > > > - area: [] > > > - combat: ['DAU', 'FRA', 'ORL', 'PRO'] > > > - continent: [] > > > - ferocity: no > > > - flags: [] > > > - region: ['British Isles', 'NorthSeaSea', 'ECAtlanticSea', > > > 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] > > > - war: 60 > > > - tag: ENG > > > > > > ENG > > > 60 > > > No > > > -------------------------- > > > > > > But I really dislike having to dereference those nested values using > > > the > > > 0'th element. So I'm going to fix pyparsing so that in the next > > > release, > > > you'll be able to reference the sub-elements as: > > > > > > print parsedEntries.country.tag > > > print parsedEntries.country.ai.war > > > print parsedEntries.country.ai.ferocity > > > > > > This *may* break some existing code, but Dict is not heavily used, > > > based on > > > feedback from users, and this may make it more useful in general, > > > especially > > > when data parses into nested Dict's. > > > > > > Hope this sheds more light than confusion! > > > -- Paul McGuire > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > -- > > 'There is only one basic human right, and that is to do as you damn well > > please. > > And with it comes the only basic human duty, to take the consequences.' > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050724/4319fa1e/attachment.htm From klappnase at freenet.de Sat Jul 23 23:20:02 2005 From: klappnase at freenet.de (Michael Lange) Date: Sat, 23 Jul 2005 23:20:02 +0200 Subject: [Tutor] Tkinter event for changing OptionMenu items In-Reply-To: <61d0e2b4050721111613d526b8@mail.gmail.com> References: <61d0e2b405072109196ee6c95b@mail.gmail.com> <20050721200728.5629d00f.klappnase@freenet.de> <61d0e2b4050721111613d526b8@mail.gmail.com> Message-ID: <20050723232002.39d3d001.klappnase@freenet.de> On Thu, 21 Jul 2005 14:16:05 -0400 Bernard Lebel <3dbernard at gmail.com> wrote: > Hi Michael, > > Let say I have a MenuOption, that consists of 3 items. This MenuOption > sits on top of the Tkinter window. > > In the lower part, I have a bunch of widgets (text fields). When the > choose a different item from the MenuOption, it would call a function > that clears the lower part and repopulates it with new fields. My > problem is binding this callback to the event of choosing an item. > > In this case I would try the StringVar()'s trace method, which you can use to track changes of its value; a simple example: >>> from Tkinter import * >>> root = Tk() >>> s = StringVar() >>> s.set('a') >>> om = OptionMenu(root, s, 'a', 'b', 'c', 'd') >>> om.pack() >>> def changed(*args): ... print s.get() ... >>> s.trace('w', changed) In the example changed() is called each time you select an item in the menu and with s.get() you can query the current selection and update the window according to the current value. I hope this helps Michael From paul at alanweberassociates.com Sat Jul 23 22:50:02 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Sat, 23 Jul 2005 15:50:02 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050723205010.723031E4006@bag.python.org> Liam - Glad you are sticking with pyparsing through some of these idiosyncracies! One thing that might simplify your life is if you are a bit more strict on specifying your grammar, especially using pp.printables as the character set for your various words and values. Is this statement really valid? Lw)r*)*dsflkj = sldjouwe)r#jdd According to your grammar, it is. Also, by using printables, you force your user to insert whitespace between the assignment target and the equals sign. I'm sure your users would like to enter a quick "a=1" once in a while, but since there is no whitespace, it will all be slurped into the left-hand side identifier. Let's create two expressions, LHS and RHS, to dictate what is valid on the left and right-hand side of the equals sign. (Well, it turns out I create a bunch of expressions here, in the process of defining LHS and RHS, but hopefullly, this will make some sense): EQUALS = pp.Suppress("=") LBRACE = pp.Suppress("{") RBRACE = pp.Suppress("}") identifier = pp.Word(pp.alphas, pp.alphanums + "_") integer = pp.Word(pp.nums+"-+", pp.nums) assignment = pp.Forward() LHS = identifier RHS = pp.Forward().setName("RHS") RHS << ( pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + pp.OneOrMore(assignment) + RBRACE ) ) assignment << pp.Group( LHS + EQUALS + RHS ) I leave it to you to flesh out what other possible value types can be included in RHS. Note also the use of the Group. Try running this snippet with and without Group and see how the results change. I think using Group will help you to build up a good parse tree for the matched tokens. Lastly, please note in the '<<' assignment to RHS that the expression is enclosed in parens. I originally left this as RHS << pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + pp.OneOrMore(assignment) + RBRACE ) And it failed to match! A bug! In my own code! The shame... This fails because '<<' has a higher precedence then '^', so RHS only worked if it was handed a quoted string. Probably good practice to always enclose in quotes the expression being assigned to a Forward using '<<'. -- Paul -----Original Message----- From: Liam Clarke [mailto:cyresse at gmail.com] Sent: Saturday, July 23, 2005 9:03 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem *sigh* I just read the documentation more carefully and found the difference between the | operator and the ^ operator. Input - j = { line = { foo = 10 bar = 20 } } New code sel = pp.Forward() values = ((pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables)) ^ sel) sel << (pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore(values) + pp.Suppress("}")) Output - (['j', 'line', 'foo', '10', 'bar', '20'], {}) My apologies for the deluge. Regards, Liam Clarke On 7/24/05, Liam Clarke wrote: Hmmm... just a quick update, I've been poking around and I'm obviously making some error of logic. Given a line - f = "j = { line = { foo = 10 bar = 20 } }" And given the following code - select = pp.Forward() select << pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore( (pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables) ) | select ) + pp.Suppress("}") sel.parseString(f) gives - (['j', 'line', '{', 'foo', '10', 'bar', '20'], {}) So I've got a bracket sneaking through there. Argh. My brain hurts. Is the | operator an exclusive or? Befuddled, Liam Clarke On 7/23/05, Liam Clarke wrote: Howdy, I've attempted to follow your lead and have started from scratch, I could just copy and paste your solution (which works pretty well), but I want to understand what I'm doing *grin* However, I've been hitting a couple of ruts in the path to enlightenment. Is there a way to tell pyparsing that to treat specific escaped characters as just a slash followed by a letter? For the time being I've converted all backslashes to forwardslashes, as it was choking on \a in a file path. But my latest hitch, takes this form (apologies for large traceback) Traceback (most recent call last): File "", line 1, in ? File "parse.py", line 336, in parse parsedEntries = dicts.parseString(test_data) File "c:\python24\Lib\site-packages\pyparsing.py", line 616, in parseString loc, tokens = self.parse( instring.expandtabs(), 0 ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1367, in parseImpl loc, exprtokens = e.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 560, in parse raise ParseException, ( instring, len(instring), self.errmsg, self ) ParseException: Expected "}" (at char 9909), (line:325, col:5) The offending code can be found here (includes the data) - http://www.rafb.net/paste/results/L560wx80.html It's like pyparsing isn't recognising a lot of my "}"'s, as if I add another one, it throws the same error, same for adding another two... No doubt I've done something silly, but any help in finding the tragic flaw would be much appreciated. I need to get a parsingResults object out so I can learn how to work with the basic structure! Much regards, Liam Clarke On 7/21/05, Paul McGuire < paul at alanweberassociates.com > wrote: Liam, Kent, and Danny - It sure looks like pyparsing is taking on a life of its own! I can see I no longer am the only one pitching pyparsing at some of these applications! Yes, Liam, it is possible to create dictionary-like objects, that is, ParseResults objects that have named values in them. I looked into your application, and the nested assignments seem very similar to a ConfigParse type of structure. Here is a pyparsing version that handles the test data in your original post (I kept Danny Yoo's recursive list values, and added recursive dictionary entries): -------------------------- import pyparsing as pp listValue = pp.Forward() listSeq = pp.Suppress ('{') + pp.Group(pp.ZeroOrMore(listValue)) + pp.Suppress('}') listValue << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | pp.Word(pp.alphanums) | listSeq ) keyName = pp.Word( pp.alphas ) entries = pp.Forward() entrySeq = pp.Suppress('{') + pp.Group(pp.OneOrMore(entries)) + pp.Suppress('}') entries << pp.Dict( pp.OneOrMore ( pp.Group( keyName + pp.Suppress('=') + (entrySeq | listValue) ) ) ) -------------------------- Dict is one of the most confusing classes to use, and there are some examples in the examples directory that comes with pyparsing (see dictExample2.py), but it is still tricky. Here is some code to access your input test data, repeated here for easy reference: -------------------------- testdata = """\ country = { tag = ENG ai = { flags = { } combat = { DAU FRA ORL PRO } continent = { } area = { } region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" "TagoSea" "WCAtlanticSea" } war = 60 ferocity = no } } """ parsedEntries = entries.parseString(testdata) def dumpEntries(dct,depth=0): keys = dct.keys() keys.sort() for k in keys: print (' '*depth) + '- ' + k + ':', if isinstance(dct[k],pp.ParseResults): if dct[k][0].keys(): print dumpEntries(dct[k][0],depth+1) else: print dct[k][0] else: print dct[k] dumpEntries( parsedEntries ) print print parsedEntries.country[0].tag print parsedEntries.country[0].ai[0].war print parsedEntries.country[0].ai[0].ferocity -------------------------- This will print out: -------------------------- - country: - ai: - area: [] - combat: ['DAU', 'FRA', 'ORL', 'PRO'] - continent: [] - ferocity: no - flags: [] - region: ['British Isles', 'NorthSeaSea', 'ECAtlanticSea', 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] - war: 60 - tag: ENG ENG 60 No -------------------------- But I really dislike having to dereference those nested values using the 0'th element. So I'm going to fix pyparsing so that in the next release, you'll be able to reference the sub-elements as: print parsedEntries.country.tag print parsedEntries.country.ai.war print parsedEntries.country.ai.ferocity This *may* break some existing code, but Dict is not heavily used, based on feedback from users, and this may make it more useful in general, especially when data parses into nested Dict's. Hope this sheds more light than confusion! -- Paul McGuire _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' From mwalsh at groktech.org Sun Jul 24 06:28:21 2005 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 24 Jul 2005 00:28:21 -0400 Subject: [Tutor] Send attachment In-Reply-To: References: Message-ID: <42E318E5.30002@groktech.org> Jorge Louis De Castro wrote: > Hello, > > Any ideas how I can use Python and the Windows API to open a PC's mail > client and send an attachment? > The idea is saving some data onto a file and then invoke the email > client (OE or Outlook or whatever is the default on the machine) with > the recipient's address filled in and the file ready to be sent as an > attachment. Not sure if it would work for your particular situation/environment, but you might try to write out a mime encoded text file with an .eml extension, and then use... import os os.startfile('foo.eml') # I think os.startfile is windows only > Kinda like when we right-click on a file and select the "send to mail > recipient" behavior. > Been reading docs, trying out samples, and googling this for a few days > to no avail. > > Cheers > jorge From mi.janssen at gmail.com Sun Jul 24 14:34:54 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Sun, 24 Jul 2005 14:34:54 +0200 Subject: [Tutor] redirecting output to logfile and logrotate In-Reply-To: <200507231325.j6NDP6qW009114@debbie.tilanus.com> References: <200507231325.j6NDP6qW009114@debbie.tilanus.com> Message-ID: <1ff2dfbf0507240534d5a2194@mail.gmail.com> On 7/23/05, Winfried Tilanus wrote: > Somebody else suggested (in private) to make logrotate send a -HUP this was me. Sorry for that, I'm still unfamilar with gmail. Danny's suggestion using RotatingFileHandler is better than mine, cause it uses a standard module. I suggest to consider using SysLogHandler for fairly sized server apps which get distributed. This way the user has full control over the logfiles (where to store, when to rotate, how to compress and when to delete) by normal configuring via syslogd and logrotate (Well this means it's normal to configure syslogd and logrotate for a sysadmin user...). regards Michael From fred.dixon at gmail.com Sun Jul 24 17:30:16 2005 From: fred.dixon at gmail.com (Fred) Date: Sun, 24 Jul 2005 15:30:16 +0000 (UTC) Subject: [Tutor] single file .exe References: <20050721034624.GA28607@dhoomketu.homeunix.net> <42DF7862.9000200@tds.net> Message-ID: > py2exe does not create a single file executable. Many people bundle the output of py2exe with an installer, > but the OP prefers not to do this. cx_freeze http://starship.python.net/crew/atuining/cx_Freeze/ From bowman at mazirian.com Sun Jul 24 20:02:43 2005 From: bowman at mazirian.com (Bradford R. Bowman) Date: Sun, 24 Jul 2005 14:02:43 -0400 Subject: [Tutor] Checking for executables Message-ID: <1122228163.13071.9.camel@phandaal> I am writing a script that is a wrapper for a number of other utilities often found on *nix workstations, including the rar and par2 utilities. I want the script to check whether those utilities are installed at the outset (and not when they are needed later on in the script, which I suppose I could just use exception handling to do). Here's what I have now: import commands for cmd in ('rar', 'par2'): if commands.getstatusoutput('which ' + cmd)[0] != 0: print "Fatal error: cannot find the %s executable." % cmd sys.exit() This appears to work, but, as I'm just beginning with python/programming, I thought there might be something in the standard library that just does what I want. Am I recreating the wheel here? -- Bradford R. Bowman GnuPG Public Key available at: http://mazirian.com/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: This is a digitally signed message part Url : http://mail.python.org/pipermail/tutor/attachments/20050724/7cb148f0/attachment.pgp From cyresse at gmail.com Mon Jul 25 06:49:05 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 25 Jul 2005 16:49:05 +1200 Subject: [Tutor] Parsing problem In-Reply-To: <42e45874.6d292813.5e00.1a23SMTPIN_ADDED@mx.gmail.com> References: <42e45874.6d292813.5e00.1a23SMTPIN_ADDED@mx.gmail.com> Message-ID: Hi Paul, My apologies, as I was jumping into my car after sending that email, it clicked in my brain. "Oh yeah... initial & body..." But good to know about how to accept valid numbers. Sorry, getting a bit too quick to fire off emails here. Regards, Liam Clarke On 7/25/05, Paul McGuire wrote: > > Liam - > > The two arguments to Word work this way: > - the first argument lists valid *initial* characters > - the second argument lists valid *body* or subsequent characters > > For example, in the identifier definition, > > identifier = pp.Word(pp.alphas, pp.alphanums + "_/:.") > > identifiers *must* start with an alphabetic character, and then may be > followed by 0 or more alphanumeric or _/: or . characters. If only one > argument is supplied, then the same string of characters is used as both > initial and body. Identifiers are very typical for 2 argument Word's, as > they often start with alphas, but then accept digits and other > punctuation. > No whitespace is permitted within a Word. The Word matching will end when > a > non-body character is seen. > > Using this definition: > > integer = pp.Word(pp.nums+"-+.", pp.nums) > > It will accept "+123", "-345", "678", and ".901". But in a real number, a > period may occur anywhere in the number, not just as the initial > character, > as in "3.14159". So your bodyCharacters must also include a ".", as in: > > integer = pp.Word(pp.nums+"-+.", pp.nums+".") > > Let me say, though, that this is a very permissive definition of integer - > for one thing, we really should rename it something like "number", since > it > now accepts non-integers as well! But also, there is no restriction on the > frequency of body characters. This definition would accept a "number" that > looks like "3.4.3234.111.123.3234". If you are certain that you will only > receive valid inputs, then this simple definition will be fine. But if you > will have to handle and reject erroneous inputs, then you might do better > with a number definition like: > > number = Combine( Word( "+-"+nums, nums ) + > Optional( point + Optional( Word( nums ) ) ) ) > > This will handle "+123", "-345", "678", and "0.901", but not ".901". If > you > want to accept numbers that begin with "."s, then you'll need to tweak > this > a bit further. > > One last thing: you may want to start using setName() on some of your > expressions, as in: > > number = Combine( Word( "+-"+nums, nums ) + > Optional( point + Optional( Word( nums ) ) ) > ).setName("number") > > Note, this is *not* the same as setResultsName. Here setName is attaching > a > name to this pattern, so that when it appears in an exception, the name > will > be used instead of an encoded pattern string (such as W:012345...). No > need > to do this for Literals, the literal string is used when it appears in an > exception. > > -- Paul > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050725/4ea79eee/attachment.htm From cyresse at gmail.com Mon Jul 25 14:38:15 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 26 Jul 2005 00:38:15 +1200 Subject: [Tutor] Parsing problem In-Reply-To: References: <42e45874.6d292813.5e00.1a23SMTPIN_ADDED@mx.gmail.com> Message-ID: Hi Paul, Well various tweaks and such done, it parses perfectly, so much thanks, I think I now have a rough understanding of the basics of pyparsing. Now, onto the fun part of optimising it. At the moment, I'm looking at 2 - 5 minutes to parse a 2000 line country section, and that's with psyco. Only problem is, I have 157 country sections... I am running a 650 MHz processor, so that isn't helping either. I read this quote on http://pyparsing.sourceforge.net. *"Thanks again for your help and thanks for writing pyparser! It seems my code needed to be optimized and now I am able to parse a 200mb file in 3 seconds. Now I can stick my tongue out at the Perl guys ;)"* I'm jealous, 200mb in 3 seconds, my file's only 4mb. Are there any general approaches to optimisation that work well? My current thinking is to use string methods to split the string into each component section, and then parse each section to a bare minimum key, value. ie - instead of parsing x = { foo = { bar = 10 bob = 20 } type = { z = { } y = { } }} out fully, just parse to "x":"{ foo = { bar = 10 bob = 20 } type = { z = { } y = { } }}" I'm thinking that would avoid the complicated nested structure I have now, and I could parse data out of the string as needed, if needed at all. Erk, I don't know, I've never had to optimise anything. Much thanks for creating pyparsing, and doubly thank-you for your assistance in learning how to use it. Regards, Liam Clarke On 7/25/05, Liam Clarke wrote: > > Hi Paul, > > My apologies, as I was jumping into my car after sending that email, it > clicked in my brain. > "Oh yeah... initial & body..." > > But good to know about how to accept valid numbers. > > Sorry, getting a bit too quick to fire off emails here. > > Regards, > > Liam Clarke > > On 7/25/05, Paul McGuire wrote: > > > > Liam - > > > > The two arguments to Word work this way: > > - the first argument lists valid *initial* characters > > - the second argument lists valid *body* or subsequent characters > > > > For example, in the identifier definition, > > > > identifier = pp.Word(pp.alphas, pp.alphanums + "_/:.") > > > > identifiers *must* start with an alphabetic character, and then may be > > followed by 0 or more alphanumeric or _/: or . characters. If only one > > argument is supplied, then the same string of characters is used as both > > initial and body. Identifiers are very typical for 2 argument Word's, as > > they often start with alphas, but then accept digits and other > > punctuation. > > No whitespace is permitted within a Word. The Word matching will end > > when a > > non-body character is seen. > > > > Using this definition: > > > > integer = pp.Word(pp.nums+"-+.", pp.nums) > > > > It will accept "+123", "-345", "678", and ".901". But in a real number, > > a > > period may occur anywhere in the number, not just as the initial > > character, > > as in "3.14159". So your bodyCharacters must also include a ".", as in: > > > > integer = pp.Word(pp.nums+"-+.", pp.nums+".") > > > > Let me say, though, that this is a very permissive definition of integer > > - > > for one thing, we really should rename it something like "number", since > > it > > now accepts non-integers as well! But also, there is no restriction on > > the > > frequency of body characters. This definition would accept a "number" > > that > > looks like "3.4.3234.111.123.3234". If you are certain that you will > > only > > receive valid inputs, then this simple definition will be fine. But if > > you > > will have to handle and reject erroneous inputs, then you might do > > better > > with a number definition like: > > > > number = Combine( Word( "+-"+nums, nums ) + > > Optional( point + Optional( Word( nums ) ) ) ) > > > > This will handle "+123", "-345", "678", and "0.901", but not ".901". If > > you > > want to accept numbers that begin with "."s, then you'll need to tweak > > this > > a bit further. > > > > One last thing: you may want to start using setName() on some of your > > expressions, as in: > > > > number = Combine( Word( "+-"+nums, nums ) + > > Optional( point + Optional( Word( nums ) ) ) > > ).setName("number") > > > > Note, this is *not* the same as setResultsName. Here setName is > > attaching a > > name to this pattern, so that when it appears in an exception, the name > > will > > be used instead of an encoded pattern string (such as W:012345...). No > > need > > to do this for Literals, the literal string is used when it appears in > > an > > exception. > > > > -- Paul > > > > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050726/2253d486/attachment.htm From nephish at xit.net Mon Jul 25 19:26:11 2005 From: nephish at xit.net (nephish) Date: Mon, 25 Jul 2005 17:26:11 +0000 Subject: [Tutor] how to write a line Message-ID: <1122312371l.11263l.0l@texaspivot.texaspivot.com> Hey there, kinda newbie question here. i know how to read the lines of a txt file. i know how to write a txt file. but how do i overwrite a line value with another value ? i mean, how do go to, say, line 3 of a text file and replace what is written on line 3 with something else? thanks <>< From missive at hotmail.com Mon Jul 25 21:40:32 2005 From: missive at hotmail.com (Lee Harr) Date: Tue, 26 Jul 2005 00:10:32 +0430 Subject: [Tutor] Pager in Python? In-Reply-To: Message-ID: > > >Is there a command like more(1) or less(1) in python to display > > >the output of a command (e.g. dir()) one page at a time? > > > > > > How are you using dir() ? > > > > Is it in the "DOS Window" ? > > One option would be to just get a better console. > >I am using Python 2.4 on RedHat Linux 8.0. In xterm window:{{{ >python >import os >dir(os) >}}} >and the screen scrolls continuously. > Hi; Please stay on the list... xterm is a pretty old console. Even so, you do have access to a scroll buffer by pressing Shift-PageUp and Shift-PageDown. That may be enough to do what you need to do. There are also some command line switches for xterm to add scrollbars if you need. I am not a big fan of xterm, though. I use konsole. That said, I still think you may want to try ipython. You might also be happy just using help(os) instead of dir(os) The help screens feed through the pager, and you get more info about what each thing is along with the names. _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From cyresse at gmail.com Sun Jul 24 17:21:12 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 25 Jul 2005 03:21:12 +1200 Subject: [Tutor] Parsing problem In-Reply-To: <42e2ad7d.6d888c59.03ac.1e56SMTPIN_ADDED@mx.gmail.com> References: <42e2ad7d.6d888c59.03ac.1e56SMTPIN_ADDED@mx.gmail.com> Message-ID: Hi Paul, That is fantastic. It works, and using that pp.group is the key with the nested braces. I just ran this on the actual file after adding a few more possible values inside the group, and it parsed the entire header structure rather nicely. Now this will probably sound silly, but from the bit header = {... ... } it continues on with province = {... } and so forth. Now, once it reads up to the closing bracket of the header section, it returns that parsed nicely. Is there a way I can tell it to continue onwards? I can see that it's stopping at one group. Pyparsing is wonderful, but boy... as learning curves go, I'm somewhat over my head. I've tried this - Code http://www.rafb.net/paste/results/3Dm7FF35.html Current data http://www.rafb.net/paste/results/3cWyt169.html assignment << (pp.OneOrMore(pp.Group( LHS + EQUALS + RHS ))) to try and continue the parsing, but no luck. I've been running into the File "c:\python24\Lib\site-packages\pyparsing.py", line 1427, in parseImpl raise maxException pyparsing.ParseException: Expected "}" (at char 742), (line:35, col:5) hassle again. From the CPU loading, I'm worried I've got myself something very badly recursive going on, but I'm unsure of how to use validate() I've noticed that a few of the sections in between contain values like this - foo = { BAR = { HUN = 10 SOB = 6 } oof = { HUN = { } SOB = 4 } } and so I've stuck pp.empty into my RHS possible values. What unintended side effects may I get from using pp.empty? From the docs, it sounds like a wildcard token, rather than matching a null. Using pp.empty has resolved my apparent problem with empty {}'s causing my favourite exception, but I'm just worried that I'm casting my net too wide. Oh, and, if there's a way to get a 'last line parsed' value so as to start parsing onwards, it would ease my day, as the only way I've found to get the whole thing parsed is to use another x = { ... } around the whole of the data, and now, I'm only getting the 'x' returned, so if I could parse by section, it would help my understanding of what's happening. I'm still trial and error-ing a bit too much at the moment. Regards, Liam Clarke On 7/24/05, Paul McGuire wrote: > > Liam - > > Glad you are sticking with pyparsing through some of these idiosyncracies! > > One thing that might simplify your life is if you are a bit more strict on > specifying your grammar, especially using pp.printables as the character > set > for your various words and values. Is this statement really valid? > > Lw)r*)*dsflkj = sldjouwe)r#jdd > > According to your grammar, it is. Also, by using printables, you force > your > user to insert whitespace between the assignment target and the equals > sign. > I'm sure your users would like to enter a quick "a=1" once in a while, but > since there is no whitespace, it will all be slurped into the left-hand > side > identifier. > > Let's create two expressions, LHS and RHS, to dictate what is valid on the > left and right-hand side of the equals sign. (Well, it turns out I create > a > bunch of expressions here, in the process of defining LHS and RHS, but > hopefullly, this will make some sense): > > EQUALS = pp.Suppress("=") > LBRACE = pp.Suppress("{") > RBRACE = pp.Suppress("}") > identifier = pp.Word(pp.alphas, pp.alphanums + "_") > integer = pp.Word(pp.nums+"-+", pp.nums) > assignment = pp.Forward() > LHS = identifier > RHS = pp.Forward().setName("RHS") > RHS << ( pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + > pp.OneOrMore(assignment) + RBRACE ) ) > assignment << pp.Group( LHS + EQUALS + RHS ) > > I leave it to you to flesh out what other possible value types can be > included in RHS. > > Note also the use of the Group. Try running this snippet with and without > Group and see how the results change. I think using Group will help you to > build up a good parse tree for the matched tokens. > > Lastly, please note in the '<<' assignment to RHS that the expression is > enclosed in parens. I originally left this as > > RHS << pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + > pp.OneOrMore(assignment) + RBRACE ) > > And it failed to match! A bug! In my own code! The shame... > > This fails because '<<' has a higher precedence then '^', so RHS only > worked > if it was handed a quoted string. Probably good practice to always enclose > in quotes the expression being assigned to a Forward using '<<'. > > -- Paul > > > -----Original Message----- > From: Liam Clarke [mailto:cyresse at gmail.com] > Sent: Saturday, July 23, 2005 9:03 AM > To: Paul McGuire > Cc: tutor at python.org > Subject: Re: [Tutor] Parsing problem > > *sigh* I just read the documentation more carefully and found the > difference > between the > | operator and the ^ operator. > > Input - > > j = { line = { foo = 10 bar = 20 } } > > New code > > sel = pp.Forward() > values = ((pp.Word(pp.printables) + pp.Suppress("=") + > pp.Word(pp.printables)) ^ sel) > sel << (pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + > pp.OneOrMore(values) + pp.Suppress("}")) > > Output - > > (['j', 'line', 'foo', '10', 'bar', '20'], {}) > > My apologies for the deluge. > > Regards, > > Liam Clarke > > > On 7/24/05, Liam Clarke wrote: > > Hmmm... just a quick update, I've been poking around and I'm > obviously making some error of logic. > > Given a line - > > f = "j = { line = { foo = 10 bar = 20 } }" > > And given the following code - > > select = pp.Forward() > select << > pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + > pp.OneOrMore( (pp.Word(pp.printables) + pp.Suppress("=") + > pp.Word(pp.printables) ) | select ) + pp.Suppress("}") > > sel.parseString(f) gives - > > (['j', 'line', '{', 'foo', '10', 'bar', '20'], {}) > > So I've got a bracket sneaking through there. Argh. My brain hurts. > > Is the | operator an exclusive or? > > Befuddled, > > Liam Clarke > > > > On 7/23/05, Liam Clarke wrote: > > Howdy, > > I've attempted to follow your lead and have started from > scratch, I could just copy and paste your solution (which works pretty > well), but I want to understand what I'm doing *grin* > > However, I've been hitting a couple of ruts in the path to > enlightenment. Is there a way to tell pyparsing that to treat specific > escaped characters as just a slash followed by a letter? For the time > being > I've converted all backslashes to forwardslashes, as it was choking on \a > in > a file path. > > But my latest hitch, takes this form (apologies for large > traceback) > > Traceback (most recent call last): > File "", line 1, in ? > File "parse.py", line 336, in parse > parsedEntries = dicts.parseString(test_data) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 616, in parseString > loc, tokens = self.parse( instring.expandtabs(), 0 ) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 558, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 1518, in parseImpl > return self.expr.parse( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 558, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 1367, in parseImpl > loc, exprtokens = e.parse( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 558, in parse > loc,tokens = self.parseImpl( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 1518, in parseImpl > return self.expr.parse( instring, loc, doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", line > 560, in parse > raise ParseException, ( instring, len(instring), > self.errmsg, self ) > > ParseException: Expected "}" (at char 9909), (line:325, > col:5) > > The offending code can be found here (includes the data) - > http://www.rafb.net/paste/results/L560wx80.html > > It's like pyparsing isn't recognising a lot of my "}"'s, as > if I add another one, it throws the same error, same for adding another > two... > > No doubt I've done something silly, but any help in finding > the tragic flaw would be much appreciated. I need to get a parsingResults > object out so I can learn how to work with the basic structure! > > Much regards, > > Liam Clarke > > > > On 7/21/05, Paul McGuire < paul at alanweberassociates.com > > wrote: > > Liam, Kent, and Danny - > > It sure looks like pyparsing is taking on a life of > its own! I can see I no > longer am the only one pitching pyparsing at some of > these applications! > > Yes, Liam, it is possible to create dictionary-like > objects, that is, > ParseResults objects that have named values in them. > I looked into your > application, and the nested assignments seem very > similar to a ConfigParse > type of structure. Here is a pyparsing version that > handles the test data > in your original post (I kept Danny Yoo's recursive > list values, and added > recursive dictionary entries): > > -------------------------- > import pyparsing as pp > > listValue = pp.Forward() > listSeq = pp.Suppress ('{') + > pp.Group(pp.ZeroOrMore(listValue)) + > pp.Suppress('}') > listValue << ( > pp.dblQuotedString.setParseAction(pp.removeQuotes) | > pp.Word(pp.alphanums) | listSeq ) > > keyName = pp.Word( pp.alphas ) > > entries = pp.Forward() > entrySeq = pp.Suppress('{') + > pp.Group(pp.OneOrMore(entries)) + > pp.Suppress('}') > entries << pp.Dict( > pp.OneOrMore ( > pp.Group( keyName + pp.Suppress('=') > + (entrySeq | > listValue) ) ) ) > -------------------------- > > > Dict is one of the most confusing classes to use, > and there are some > examples in the examples directory that comes with > pyparsing (see > dictExample2.py), but it is still tricky. Here is > some code to access your > input test data, repeated here for easy reference: > > -------------------------- > testdata = """\ > country = { > tag = ENG > ai = { > flags = { } > combat = { DAU FRA ORL PRO } > continent = { } > area = { } > region = { "British Isles" "NorthSeaSea" > "ECAtlanticSea" "NAtlanticSea" > "TagoSea" "WCAtlanticSea" } > war = 60 > ferocity = no > } > } > """ > parsedEntries = entries.parseString(testdata) > > def dumpEntries(dct,depth=0): > keys = dct.keys() > keys.sort() > for k in keys: > print (' '*depth) + '- ' + k + ':', > if isinstance(dct[k],pp.ParseResults): > if dct[k][0].keys(): > print > dumpEntries(dct[k][0],depth+1) > else: > print dct[k][0] > else: > print dct[k] > > dumpEntries( parsedEntries ) > > print > print parsedEntries.country[0].tag > print parsedEntries.country[0].ai[0].war > print parsedEntries.country[0].ai[0].ferocity > -------------------------- > > This will print out: > > -------------------------- > - country: > - ai: > - area: [] > - combat: ['DAU', 'FRA', 'ORL', 'PRO'] > - continent: [] > - ferocity: no > - flags: [] > - region: ['British Isles', 'NorthSeaSea', > 'ECAtlanticSea', > 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] > - war: 60 > - tag: ENG > > ENG > 60 > No > -------------------------- > > But I really dislike having to dereference those > nested values using the > 0'th element. So I'm going to fix pyparsing so that > in the next release, > you'll be able to reference the sub-elements as: > > print parsedEntries.country.tag > print parsedEntries.country.ai.war > print parsedEntries.country.ai.ferocity > > This *may* break some existing code, but Dict is not > heavily used, based on > feedback from users, and this may make it more > useful in general, especially > when data parses into nested Dict's. > > Hope this sheds more light than confusion! > -- Paul McGuire > > _______________________________________________ > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > 'There is only one basic human right, and that is to do as > you damn well please. > And with it comes the only basic human duty, to take the > consequences.' > > > > > -- > 'There is only one basic human right, and that is to do as you damn > well please. > And with it comes the only basic human duty, to take the > consequences.' > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050725/1c094f01/attachment-0001.htm From paul at alanweberassociates.com Sun Jul 24 18:36:06 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Sun, 24 Jul 2005 11:36:06 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050724163614.C3DE21E4006@bag.python.org> Liam - Great, this sounds like it's coming together. Don't be discouraged, parsing text like this has many forward/backward steps. As far as stopping after one assignent, well, you might kick yourself over this, but the answer is that you are no longer parsing just a single assignment, but a list of them. You cannot parse more than one assignment with assignment as you have it, and you shouldn't. Instead, expand the scope of the parser to correspond to the expanded scope of input, as in: listOfAssignments = OneOrMore( assignment ) Now listOfAssignments is your root BNF, that you use to call parseString against the contents of the input file. Looking at your code, you might prefer to just enclose the contents inside the braces inside an Optional, or a ZeroOrMore. Seeing the other possible elements that might be in your braces, will this work? ZeroOrMore will take care of the empty option, and recursively nesting RHS will avoid having to repeat the other "scalar" entries. RHS << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) ^ identifier ^ integer ^ pp.Group( LBRACE + pp.ZeroOrMore( assignment ^ RHS ) + RBRACE ) ) -- Paul -----Original Message----- From: Liam Clarke [mailto:cyresse at gmail.com] Sent: Sunday, July 24, 2005 10:21 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem Hi Paul, That is fantastic. It works, and using that pp.group is the key with the nested braces. I just ran this on the actual file after adding a few more possible values inside the group, and it parsed the entire header structure rather nicely. Now this will probably sound silly, but from the bit header = {... ... } it continues on with province = {... } and so forth. Now, once it reads up to the closing bracket of the header section, it returns that parsed nicely. Is there a way I can tell it to continue onwards? I can see that it's stopping at one group. Pyparsing is wonderful, but boy... as learning curves go, I'm somewhat over my head. I've tried this - Code http://www.rafb.net/paste/results/3Dm7FF35.html Current data http://www.rafb.net/paste/results/3cWyt169.html assignment << (pp.OneOrMore(pp.Group( LHS + EQUALS + RHS ))) to try and continue the parsing, but no luck. I've been running into the File "c:\python24\Lib\site-packages\pyparsing.py", line 1427, in parseImpl raise maxException pyparsing.ParseException: Expected "}" (at char 742), (line:35, col:5) hassle again. From the CPU loading, I'm worried I've got myself something very badly recursive going on, but I'm unsure of how to use validate() I've noticed that a few of the sections in between contain values like this - foo = { BAR = { HUN = 10 SOB = 6 } oof = { HUN = { } SOB = 4 } } and so I've stuck pp.empty into my RHS possible values. What unintended side effects may I get from using pp.empty? From the docs, it sounds like a wildcard token, rather than matching a null. Using pp.empty has resolved my apparent problem with empty {}'s causing my favourite exception, but I'm just worried that I'm casting my net too wide. Oh, and, if there's a way to get a 'last line parsed' value so as to start parsing onwards, it would ease my day, as the only way I've found to get the whole thing parsed is to use another x = { ... } around the whole of the data, and now, I'm only getting the 'x' returned, so if I could parse by section, it would help my understanding of what's happening. I'm still trial and error-ing a bit too much at the moment. Regards, Liam Clarke On 7/24/05, Paul McGuire wrote: Liam - Glad you are sticking with pyparsing through some of these idiosyncracies! One thing that might simplify your life is if you are a bit more strict on specifying your grammar, especially using pp.printables as the character set for your various words and values. Is this statement really valid? Lw)r*)*dsflkj = sldjouwe)r#jdd According to your grammar, it is. Also, by using printables, you force your user to insert whitespace between the assignment target and the equals sign. I'm sure your users would like to enter a quick "a=1" once in a while, but since there is no whitespace, it will all be slurped into the left-hand side identifier. Let's create two expressions, LHS and RHS, to dictate what is valid on the left and right-hand side of the equals sign. (Well, it turns out I create a bunch of expressions here, in the process of defining LHS and RHS, but hopefullly, this will make some sense): EQUALS = pp.Suppress ("=") LBRACE = pp.Suppress("{") RBRACE = pp.Suppress("}") identifier = pp.Word(pp.alphas, pp.alphanums + "_") integer = pp.Word(pp.nums+"-+", pp.nums) assignment = pp.Forward() LHS = identifier RHS = pp.Forward().setName("RHS") RHS << ( pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + pp.OneOrMore(assignment) + RBRACE ) ) assignment << pp.Group( LHS + EQUALS + RHS ) I leave it to you to flesh out what other possible value types can be included in RHS. Note also the use of the Group. Try running this snippet with and without Group and see how the results change. I think using Group will help you to build up a good parse tree for the matched tokens. Lastly, please note in the '<<' assignment to RHS that the expression is enclosed in parens. I originally left this as RHS << pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + pp.OneOrMore(assignment) + RBRACE ) And it failed to match! A bug! In my own code! The shame... This fails because '<<' has a higher precedence then '^', so RHS only worked if it was handed a quoted string. Probably good practice to always enclose in quotes the expression being assigned to a Forward using '<<'. -- Paul -----Original Message----- From: Liam Clarke [mailto: cyresse at gmail.com] Sent: Saturday, July 23, 2005 9:03 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem *sigh* I just read the documentation more carefully and found the difference between the | operator and the ^ operator. Input - j = { line = { foo = 10 bar = 20 } } New code sel = pp.Forward () values = ((pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables)) ^ sel) sel << (pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore(values) + pp.Suppress("}")) Output - (['j', 'line', 'foo', '10', 'bar', '20'], {}) My apologies for the deluge. Regards, Liam Clarke On 7/24/05, Liam Clarke < cyresse at gmail.com > wrote: Hmmm... just a quick update, I've been poking around and I'm obviously making some error of logic. Given a line - f = "j = { line = { foo = 10 bar = 20 } }" And given the following code - select = pp.Forward() select << pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore ( (pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables) ) | select ) + pp.Suppress("}") sel.parseString(f) gives - (['j', 'line', '{', 'foo', '10', 'bar', '20'], {}) So I've got a bracket sneaking through there. Argh. My brain hurts. Is the | operator an exclusive or? Befuddled, Liam Clarke On 7/23/05, Liam Clarke < cyresse at gmail.com > wrote: Howdy, I've attempted to follow your lead and have started from scratch, I could just copy and paste your solution (which works pretty well), but I want to understand what I'm doing *grin* However, I've been hitting a couple of ruts in the path to enlightenment. Is there a way to tell pyparsing that to treat specific escaped characters as just a slash followed by a letter? For the time being I've converted all backslashes to forwardslashes, as it was choking on \a in a file path. But my latest hitch, takes this form (apologies for large traceback) Traceback (most recent call last): File "", line 1, in ? File "parse.py", line 336, in parse parsedEntries = dicts.parseString(test_data) File "c:\python24\Lib\site-packages\pyparsing.py", line 616, in parseString loc, tokens = self.parse( instring.expandtabs(), 0 ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1367, in parseImpl loc, exprtokens = e.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 560, in parse raise ParseException, ( instring, len(instring), self.errmsg, self ) ParseException: Expected "}" (at char 9909), (line:325, col:5) The offending code can be found here (includes the data) - http://www.rafb.net/paste/results/L560wx80.html It's like pyparsing isn't recognising a lot of my "}"'s, as if I add another one, it throws the same error, same for adding another two... No doubt I've done something silly, but any help in finding the tragic flaw would be much appreciated. I need to get a parsingResults object out so I can learn how to work with the basic structure! Much regards, Liam Clarke On 7/21/05, Paul McGuire < paul at alanweberassociates.com > wrote: Liam, Kent, and Danny - It sure looks like pyparsing is taking on a life of its own! I can see I no longer am the only one pitching pyparsing at some of these applications! Yes, Liam, it is possible to create dictionary-like objects, that is, ParseResults objects that have named values in them. I looked into your application, and the nested assignments seem very similar to a ConfigParse type of structure. Here is a pyparsing version that handles the test data in your original post (I kept Danny Yoo's recursive list values, and added recursive dictionary entries): -------------------------- import pyparsing as pp listValue = pp.Forward() listSeq = pp.Suppress ('{') + pp.Group(pp.ZeroOrMore(listValue)) + pp.Suppress('}') listValue << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | pp.Word(pp.alphanums) | listSeq ) keyName = pp.Word( pp.alphas ) entries = pp.Forward() entrySeq = pp.Suppress('{') + pp.Group(pp.OneOrMore(entries)) + pp.Suppress('}') entries << pp.Dict( pp.OneOrMore ( pp.Group( keyName + pp.Suppress('=') + (entrySeq | listValue) ) ) ) -------------------------- Dict is one of the most confusing classes to use, and there are some examples in the examples directory that comes with pyparsing (see dictExample2.py), but it is still tricky. Here is some code to access your input test data, repeated here for easy reference: -------------------------- testdata = """\ country = { tag = ENG ai = { flags = { } combat = { DAU FRA ORL PRO } continent = { } area = { } region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" "TagoSea" "WCAtlanticSea" } war = 60 ferocity = no } } """ parsedEntries = entries.parseString(testdata) def dumpEntries(dct,depth=0): keys = dct.keys() keys.sort() for k in keys: print (' '*depth) + '- ' + k + ':', if isinstance(dct[k],pp.ParseResults): if dct[k][0].keys(): print dumpEntries(dct[k][0],depth+1) else: print dct[k][0] else: print dct[k] dumpEntries( parsedEntries ) print print parsedEntries.country[0].tag print parsedEntries.country[0].ai[0].war print parsedEntries.country[0].ai[0].ferocity -------------------------- This will print out: -------------------------- - country: - ai: - area: [] - combat: ['DAU', 'FRA', 'ORL', 'PRO'] - continent: [] - ferocity: no - flags: [] - region: ['British Isles', 'NorthSeaSea', 'ECAtlanticSea', 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] - war: 60 - tag: ENG ENG 60 No -------------------------- But I really dislike having to dereference those nested values using the 0'th element. So I'm going to fix pyparsing so that in the next release, you'll be able to reference the sub-elements as: print parsedEntries.country.tag print parsedEntries.country.ai.war print parsedEntries.country.ai.ferocity This *may* break some existing code, but Dict is not heavily used, based on feedback from users, and this may make it more useful in general, especially when data parses into nested Dict's. Hope this sheds more light than confusion! -- Paul McGuire _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' From paul at alanweberassociates.com Mon Jul 25 03:00:59 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Sun, 24 Jul 2005 20:00:59 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050725010108.18E891E4007@bag.python.org> Liam - I just uploaded an update to pyparsing, version 1.3.2, that should fix the problem with using nested Dicts. Now you won't need to use [0] to dereference the "0'th" element, just reference the nested elements as a.b.c, or a["b"]["c"]. -- Paul -----Original Message----- From: Liam Clarke [mailto:cyresse at gmail.com] Sent: Sunday, July 24, 2005 10:21 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem Hi Paul, That is fantastic. It works, and using that pp.group is the key with the nested braces. I just ran this on the actual file after adding a few more possible values inside the group, and it parsed the entire header structure rather nicely. Now this will probably sound silly, but from the bit header = {... ... } it continues on with province = {... } and so forth. Now, once it reads up to the closing bracket of the header section, it returns that parsed nicely. Is there a way I can tell it to continue onwards? I can see that it's stopping at one group. Pyparsing is wonderful, but boy... as learning curves go, I'm somewhat over my head. I've tried this - Code http://www.rafb.net/paste/results/3Dm7FF35.html Current data http://www.rafb.net/paste/results/3cWyt169.html assignment << (pp.OneOrMore(pp.Group( LHS + EQUALS + RHS ))) to try and continue the parsing, but no luck. I've been running into the File "c:\python24\Lib\site-packages\pyparsing.py", line 1427, in parseImpl raise maxException pyparsing.ParseException: Expected "}" (at char 742), (line:35, col:5) hassle again. From the CPU loading, I'm worried I've got myself something very badly recursive going on, but I'm unsure of how to use validate() I've noticed that a few of the sections in between contain values like this - foo = { BAR = { HUN = 10 SOB = 6 } oof = { HUN = { } SOB = 4 } } and so I've stuck pp.empty into my RHS possible values. What unintended side effects may I get from using pp.empty? From the docs, it sounds like a wildcard token, rather than matching a null. Using pp.empty has resolved my apparent problem with empty {}'s causing my favourite exception, but I'm just worried that I'm casting my net too wide. Oh, and, if there's a way to get a 'last line parsed' value so as to start parsing onwards, it would ease my day, as the only way I've found to get the whole thing parsed is to use another x = { ... } around the whole of the data, and now, I'm only getting the 'x' returned, so if I could parse by section, it would help my understanding of what's happening. I'm still trial and error-ing a bit too much at the moment. Regards, Liam Clarke On 7/24/05, Paul McGuire wrote: Liam - Glad you are sticking with pyparsing through some of these idiosyncracies! One thing that might simplify your life is if you are a bit more strict on specifying your grammar, especially using pp.printables as the character set for your various words and values. Is this statement really valid? Lw)r*)*dsflkj = sldjouwe)r#jdd According to your grammar, it is. Also, by using printables, you force your user to insert whitespace between the assignment target and the equals sign. I'm sure your users would like to enter a quick "a=1" once in a while, but since there is no whitespace, it will all be slurped into the left-hand side identifier. Let's create two expressions, LHS and RHS, to dictate what is valid on the left and right-hand side of the equals sign. (Well, it turns out I create a bunch of expressions here, in the process of defining LHS and RHS, but hopefullly, this will make some sense): EQUALS = pp.Suppress ("=") LBRACE = pp.Suppress("{") RBRACE = pp.Suppress("}") identifier = pp.Word(pp.alphas, pp.alphanums + "_") integer = pp.Word(pp.nums+"-+", pp.nums) assignment = pp.Forward() LHS = identifier RHS = pp.Forward().setName("RHS") RHS << ( pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + pp.OneOrMore(assignment) + RBRACE ) ) assignment << pp.Group( LHS + EQUALS + RHS ) I leave it to you to flesh out what other possible value types can be included in RHS. Note also the use of the Group. Try running this snippet with and without Group and see how the results change. I think using Group will help you to build up a good parse tree for the matched tokens. Lastly, please note in the '<<' assignment to RHS that the expression is enclosed in parens. I originally left this as RHS << pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE + pp.OneOrMore(assignment) + RBRACE ) And it failed to match! A bug! In my own code! The shame... This fails because '<<' has a higher precedence then '^', so RHS only worked if it was handed a quoted string. Probably good practice to always enclose in quotes the expression being assigned to a Forward using '<<'. -- Paul -----Original Message----- From: Liam Clarke [mailto: cyresse at gmail.com] Sent: Saturday, July 23, 2005 9:03 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem *sigh* I just read the documentation more carefully and found the difference between the | operator and the ^ operator. Input - j = { line = { foo = 10 bar = 20 } } New code sel = pp.Forward () values = ((pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables)) ^ sel) sel << (pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore(values) + pp.Suppress("}")) Output - (['j', 'line', 'foo', '10', 'bar', '20'], {}) My apologies for the deluge. Regards, Liam Clarke On 7/24/05, Liam Clarke < cyresse at gmail.com > wrote: Hmmm... just a quick update, I've been poking around and I'm obviously making some error of logic. Given a line - f = "j = { line = { foo = 10 bar = 20 } }" And given the following code - select = pp.Forward() select << pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") + pp.OneOrMore ( (pp.Word(pp.printables) + pp.Suppress("=") + pp.Word(pp.printables) ) | select ) + pp.Suppress("}") sel.parseString(f) gives - (['j', 'line', '{', 'foo', '10', 'bar', '20'], {}) So I've got a bracket sneaking through there. Argh. My brain hurts. Is the | operator an exclusive or? Befuddled, Liam Clarke On 7/23/05, Liam Clarke < cyresse at gmail.com > wrote: Howdy, I've attempted to follow your lead and have started from scratch, I could just copy and paste your solution (which works pretty well), but I want to understand what I'm doing *grin* However, I've been hitting a couple of ruts in the path to enlightenment. Is there a way to tell pyparsing that to treat specific escaped characters as just a slash followed by a letter? For the time being I've converted all backslashes to forwardslashes, as it was choking on \a in a file path. But my latest hitch, takes this form (apologies for large traceback) Traceback (most recent call last): File "", line 1, in ? File "parse.py", line 336, in parse parsedEntries = dicts.parseString(test_data) File "c:\python24\Lib\site-packages\pyparsing.py", line 616, in parseString loc, tokens = self.parse( instring.expandtabs(), 0 ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1367, in parseImpl loc, exprtokens = e.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 558, in parse loc,tokens = self.parseImpl( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 1518, in parseImpl return self.expr.parse( instring, loc, doActions ) File "c:\python24\Lib\site-packages\pyparsing.py", line 560, in parse raise ParseException, ( instring, len(instring), self.errmsg, self ) ParseException: Expected "}" (at char 9909), (line:325, col:5) The offending code can be found here (includes the data) - http://www.rafb.net/paste/results/L560wx80.html It's like pyparsing isn't recognising a lot of my "}"'s, as if I add another one, it throws the same error, same for adding another two... No doubt I've done something silly, but any help in finding the tragic flaw would be much appreciated. I need to get a parsingResults object out so I can learn how to work with the basic structure! Much regards, Liam Clarke On 7/21/05, Paul McGuire < paul at alanweberassociates.com > wrote: Liam, Kent, and Danny - It sure looks like pyparsing is taking on a life of its own! I can see I no longer am the only one pitching pyparsing at some of these applications! Yes, Liam, it is possible to create dictionary-like objects, that is, ParseResults objects that have named values in them. I looked into your application, and the nested assignments seem very similar to a ConfigParse type of structure. Here is a pyparsing version that handles the test data in your original post (I kept Danny Yoo's recursive list values, and added recursive dictionary entries): -------------------------- import pyparsing as pp listValue = pp.Forward() listSeq = pp.Suppress ('{') + pp.Group(pp.ZeroOrMore(listValue)) + pp.Suppress('}') listValue << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | pp.Word(pp.alphanums) | listSeq ) keyName = pp.Word( pp.alphas ) entries = pp.Forward() entrySeq = pp.Suppress('{') + pp.Group(pp.OneOrMore(entries)) + pp.Suppress('}') entries << pp.Dict( pp.OneOrMore ( pp.Group( keyName + pp.Suppress('=') + (entrySeq | listValue) ) ) ) -------------------------- Dict is one of the most confusing classes to use, and there are some examples in the examples directory that comes with pyparsing (see dictExample2.py), but it is still tricky. Here is some code to access your input test data, repeated here for easy reference: -------------------------- testdata = """\ country = { tag = ENG ai = { flags = { } combat = { DAU FRA ORL PRO } continent = { } area = { } region = { "British Isles" "NorthSeaSea" "ECAtlanticSea" "NAtlanticSea" "TagoSea" "WCAtlanticSea" } war = 60 ferocity = no } } """ parsedEntries = entries.parseString(testdata) def dumpEntries(dct,depth=0): keys = dct.keys() keys.sort() for k in keys: print (' '*depth) + '- ' + k + ':', if isinstance(dct[k],pp.ParseResults): if dct[k][0].keys(): print dumpEntries(dct[k][0],depth+1) else: print dct[k][0] else: print dct[k] dumpEntries( parsedEntries ) print print parsedEntries.country[0].tag print parsedEntries.country[0].ai[0].war print parsedEntries.country[0].ai[0].ferocity -------------------------- This will print out: -------------------------- - country: - ai: - area: [] - combat: ['DAU', 'FRA', 'ORL', 'PRO'] - continent: [] - ferocity: no - flags: [] - region: ['British Isles', 'NorthSeaSea', 'ECAtlanticSea', 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] - war: 60 - tag: ENG ENG 60 No -------------------------- But I really dislike having to dereference those nested values using the 0'th element. So I'm going to fix pyparsing so that in the next release, you'll be able to reference the sub-elements as: print parsedEntries.country.tag print parsedEntries.country.ai.war print parsedEntries.country.ai.ferocity This *may* break some existing code, but Dict is not heavily used, based on feedback from users, and this may make it more useful in general, especially when data parses into nested Dict's. Hope this sheds more light than confusion! -- Paul McGuire _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' From cyresse at gmail.com Mon Jul 25 04:49:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon, 25 Jul 2005 14:49:31 +1200 Subject: [Tutor] Parsing problem In-Reply-To: <42e439ce.33447d80.5740.2c83SMTPIN_ADDED@mx.gmail.com> References: <42e439ce.33447d80.5740.2c83SMTPIN_ADDED@mx.gmail.com> Message-ID: Hi Paul, I am kicking myself for the pp.OneOrMore(assignments) bit. It's parsing well now, it stops whenever it hits a character it can't handle, ( a minus sign snuck in instead of a equals at one point, but I think I put it there) this makes tweaking quite easy. Just a quick query on how Word works. These two lines - identifier = pp.Word(pp.alphas, pp.alphanums + "_/:.") integer = pp.Word(pp.nums+"-+.", pp.nums) It's stopped at integer values which contain a decimal point, which I thought I'd taken care of with my additions to the above. How do the initChars and bodyChars affect a token? Regards, Liam Clarke On 7/25/05, Paul McGuire wrote: > > Liam - > > I just uploaded an update to pyparsing, version 1.3.2, that should fix the > problem with using nested Dicts. Now you won't need to use [0] to > dereference the "0'th" element, just reference the nested elements as > a.b.c, > or a["b"]["c"]. > > -- Paul > > > -----Original Message----- > From: Liam Clarke [mailto:cyresse at gmail.com] > Sent: Sunday, July 24, 2005 10:21 AM > To: Paul McGuire > Cc: tutor at python.org > Subject: Re: [Tutor] Parsing problem > > Hi Paul, > > That is fantastic. It works, and using that pp.group is the key with the > nested braces. > > I just ran this on the actual file after adding a few more possible values > inside the group, and it parsed the entire header structure rather nicely. > > Now this will probably sound silly, but from the bit > > header = {... > ... > } > > it continues on with > > province = {... > } > > and so forth. > > Now, once it reads up to the closing bracket of the header section, it > returns that parsed nicely. > Is there a way I can tell it to continue onwards? I can see that it's > stopping at one group. > > Pyparsing is wonderful, but boy... as learning curves go, I'm somewhat > over > my head. > > I've tried this - > > Code http://www.rafb.net/paste/results/3Dm7FF35.html > Current data http://www.rafb.net/paste/results/3cWyt169.html > > assignment << (pp.OneOrMore(pp.Group( LHS + EQUALS + RHS ))) > > to try and continue the parsing, but no luck. > > I've been running into the > > File "c:\python24\Lib\site-packages\pyparsing.py", line 1427, in parseImpl > raise maxException > pyparsing.ParseException: Expected "}" (at char 742), (line:35, col:5) > > hassle again. From the CPU loading, I'm worried I've got myself something > very badly recursive going on, but I'm unsure of how to use validate() > > I've noticed that a few of the sections in between contain values like > this > - > > foo = { BAR = { HUN = 10 SOB = 6 } oof = { HUN = { } SOB = 4 } } > > and so I've stuck pp.empty into my RHS possible values. What unintended > side > effects may I get from using pp.empty? From the docs, it sounds like a > wildcard token, rather than matching a null. > > Using pp.empty has resolved my apparent problem with empty {}'s causing my > favourite exception, but I'm just worried that I'm casting my net too > wide. > > Oh, and, if there's a way to get a 'last line parsed' value so as to start > parsing onwards, it would ease my day, as the only way I've found to get > the > whole thing parsed is to use another x = { ... } around the whole of the > data, and now, I'm only getting the 'x' returned, so if I could parse by > section, it would help my understanding of what's happening. > > I'm still trial and error-ing a bit too much at the moment. > > Regards, > > Liam Clarke > > > > > > On 7/24/05, Paul McGuire wrote: > > Liam - > > Glad you are sticking with pyparsing through some of these > idiosyncracies! > > One thing that might simplify your life is if you are a bit more > strict on > specifying your grammar, especially using pp.printables as the > character set > for your various words and values. Is this statement really valid? > > Lw)r*)*dsflkj = sldjouwe)r#jdd > > According to your grammar, it is. Also, by using printables, you > force your > user to insert whitespace between the assignment target and the > equals sign. > I'm sure your users would like to enter a quick "a=1" once in a > while, but > since there is no whitespace, it will all be slurped into the > left-hand side > identifier. > > Let's create two expressions, LHS and RHS, to dictate what is valid > on the > left and right-hand side of the equals sign. (Well, it turns out I > create a > bunch of expressions here, in the process of defining LHS and RHS, > but > hopefullly, this will make some sense): > > EQUALS = pp.Suppress ("=") > LBRACE = pp.Suppress("{") > RBRACE = pp.Suppress("}") > identifier = pp.Word(pp.alphas, pp.alphanums + "_") > integer = pp.Word(pp.nums+"-+", pp.nums) > assignment = pp.Forward() > LHS = identifier > RHS = pp.Forward().setName("RHS") > RHS << ( pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( > LBRACE + > pp.OneOrMore(assignment) + RBRACE ) ) > assignment << pp.Group( LHS + EQUALS + RHS ) > > I leave it to you to flesh out what other possible value types can > be > included in RHS. > > Note also the use of the Group. Try running this snippet with and > without > Group and see how the results change. I think using Group will help > you to > build up a good parse tree for the matched tokens. > > Lastly, please note in the '<<' assignment to RHS that the > expression is > enclosed in parens. I originally left this as > > RHS << pp.dblQuotedString ^ identifier ^ integer ^ pp.Group( LBRACE > + > pp.OneOrMore(assignment) + RBRACE ) > > And it failed to match! A bug! In my own code! The shame... > > This fails because '<<' has a higher precedence then '^', so RHS > only worked > if it was handed a quoted string. Probably good practice to always > enclose > in quotes the expression being assigned to a Forward using '<<'. > > -- Paul > > > -----Original Message----- > From: Liam Clarke [mailto: cyresse at gmail.com] > Sent: Saturday, July 23, 2005 9:03 AM > To: Paul McGuire > Cc: tutor at python.org > Subject: Re: [Tutor] Parsing problem > > *sigh* I just read the documentation more carefully and found the > difference > between the > | operator and the ^ operator. > > Input - > > j = { line = { foo = 10 bar = 20 } } > > New code > > sel = pp.Forward () > values = ((pp.Word(pp.printables) + pp.Suppress("=") + > pp.Word(pp.printables)) ^ sel) > sel << (pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") > + > pp.OneOrMore(values) + pp.Suppress("}")) > > Output - > > (['j', 'line', 'foo', '10', 'bar', '20'], {}) > > My apologies for the deluge. > > Regards, > > Liam Clarke > > > On 7/24/05, Liam Clarke < cyresse at gmail.com > > wrote: > > Hmmm... just a quick update, I've been poking around and I'm > obviously making some error of logic. > > Given a line - > > f = "j = { line = { foo = 10 bar = 20 } }" > > And given the following code - > > select = pp.Forward() > select << > pp.Word(pp.printables) + pp.Suppress("=") + pp.Suppress("{") > + > pp.OneOrMore ( (pp.Word(pp.printables) + pp.Suppress("=") + > pp.Word(pp.printables) ) | select ) + pp.Suppress("}") > > sel.parseString(f) gives - > > (['j', 'line', '{', 'foo', '10', 'bar', '20'], {}) > > So I've got a bracket sneaking through there. Argh. My brain > hurts. > > Is the | operator an exclusive or? > > Befuddled, > > Liam Clarke > > > > On 7/23/05, Liam Clarke < cyresse at gmail.com > wrote: > > Howdy, > > I've attempted to follow your lead and have started > from > scratch, I could just copy and paste your solution (which works > pretty > well), but I want to understand what I'm doing *grin* > > However, I've been hitting a couple of ruts in the > path to > enlightenment. Is there a way to tell pyparsing that to treat > specific > escaped characters as just a slash followed by a letter? For the > time being > I've converted all backslashes to forwardslashes, as it was choking > on \a in > a file path. > > But my latest hitch, takes this form (apologies for > large > traceback) > > Traceback (most recent call last): > File "", line 1, in ? > File "parse.py", line 336, in parse > parsedEntries = dicts.parseString(test_data) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 616, in parseString > loc, tokens = self.parse( instring.expandtabs(), > 0 ) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 558, in parse > loc,tokens = self.parseImpl( instring, loc, > doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 1518, in parseImpl > return self.expr.parse( instring, loc, doActions > ) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 558, in parse > loc,tokens = self.parseImpl( instring, loc, > doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 1367, in parseImpl > loc, exprtokens = e.parse( instring, loc, > doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 558, in parse > loc,tokens = self.parseImpl( instring, loc, > doActions ) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 1518, in parseImpl > return self.expr.parse( instring, loc, doActions > ) > File "c:\python24\Lib\site-packages\pyparsing.py", > line > 560, in parse > raise ParseException, ( instring, len(instring), > self.errmsg, self ) > > ParseException: Expected "}" (at char 9909), > (line:325, > col:5) > > The offending code can be found here (includes the > data) - > http://www.rafb.net/paste/results/L560wx80.html > > It's like pyparsing isn't recognising a lot of my > "}"'s, as > if I add another one, it throws the same error, same for adding > another > two... > > No doubt I've done something silly, but any help in > finding > the tragic flaw would be much appreciated. I need to get a > parsingResults > object out so I can learn how to work with the basic structure! > > Much regards, > > Liam Clarke > > > > On 7/21/05, Paul McGuire < > paul at alanweberassociates.com > > wrote: > > Liam, Kent, and Danny - > > It sure looks like pyparsing is taking on a > life of > its own! I can see I no > longer am the only one pitching pyparsing at > some of > these applications! > > Yes, Liam, it is possible to create > dictionary-like > objects, that is, > ParseResults objects that have named values > in them. > I looked into your > application, and the nested assignments seem > very > similar to a ConfigParse > type of structure. Here is a pyparsing > version that > handles the test data > in your original post (I kept Danny Yoo's > recursive > list values, and added > recursive dictionary entries): > > -------------------------- > import pyparsing as pp > > listValue = pp.Forward() > listSeq = pp.Suppress ('{') + > pp.Group(pp.ZeroOrMore(listValue)) + > pp.Suppress('}') > listValue << ( > pp.dblQuotedString.setParseAction(pp.removeQuotes) | > pp.Word(pp.alphanums) | > listSeq ) > > keyName = pp.Word( pp.alphas ) > > entries = pp.Forward() > entrySeq = pp.Suppress('{') + > pp.Group(pp.OneOrMore(entries)) + > pp.Suppress('}') > entries << pp.Dict( > pp.OneOrMore ( > pp.Group( keyName + > pp.Suppress('=') > + (entrySeq | > listValue) ) ) ) > -------------------------- > > > Dict is one of the most confusing classes to > use, > and there are some > examples in the examples directory that > comes with > pyparsing (see > dictExample2.py), but it is still tricky. > Here is > some code to access your > input test data, repeated here for easy > reference: > > -------------------------- > testdata = """\ > country = { > tag = ENG > ai = { > flags = { } > combat = { DAU FRA ORL PRO } > continent = { } > area = { } > region = { "British Isles" "NorthSeaSea" > "ECAtlanticSea" "NAtlanticSea" > "TagoSea" "WCAtlanticSea" } > war = 60 > ferocity = no > } > } > """ > parsedEntries = > entries.parseString(testdata) > > def dumpEntries(dct,depth=0): > keys = dct.keys() > keys.sort() > for k in keys: > print (' '*depth) + '- ' + k + ':', > if > isinstance(dct[k],pp.ParseResults): > if dct[k][0].keys(): > print > > dumpEntries(dct[k][0],depth+1) > else: > print dct[k][0] > else: > print dct[k] > > dumpEntries( parsedEntries ) > > print > print parsedEntries.country[0].tag > print parsedEntries.country[0].ai[0].war > print > parsedEntries.country[0].ai[0].ferocity > -------------------------- > > This will print out: > > -------------------------- > - country: > - ai: > - area: [] > - combat: ['DAU', 'FRA', 'ORL', 'PRO'] > - continent: [] > - ferocity: no > - flags: [] > - region: ['British Isles', > 'NorthSeaSea', > 'ECAtlanticSea', > 'NAtlanticSea', 'TagoSea', 'WCAtlanticSea'] > - war: 60 > - tag: ENG > > ENG > 60 > No > -------------------------- > > But I really dislike having to dereference > those > nested values using the > 0'th element. So I'm going to fix pyparsing > so that > in the next release, > you'll be able to reference the sub-elements > as: > > print parsedEntries.country.tag > print parsedEntries.country.ai.war > print parsedEntries.country.ai.ferocity > > This *may* break some existing code, but > Dict is not > heavily used, based on > feedback from users, and this may make it > more > useful in general, especially > when data parses into nested Dict's. > > Hope this sheds more light than confusion! > -- Paul McGuire > > > _______________________________________________ > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > 'There is only one basic human right, and that is to > do as > you damn well please. > And with it comes the only basic human duty, to take > the > consequences.' > > > > > -- > 'There is only one basic human right, and that is to do as > you damn > well please. > And with it comes the only basic human duty, to take the > consequences.' > > > > > -- > 'There is only one basic human right, and that is to do as you damn > well > please. > And with it comes the only basic human duty, to take the > consequences.' > > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050725/d8592823/attachment-0001.htm From paul at alanweberassociates.com Mon Jul 25 05:11:43 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Sun, 24 Jul 2005 22:11:43 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050725031154.36A5A1E400A@bag.python.org> Liam - The two arguments to Word work this way: - the first argument lists valid *initial* characters - the second argument lists valid *body* or subsequent characters For example, in the identifier definition, identifier = pp.Word(pp.alphas, pp.alphanums + "_/:.") identifiers *must* start with an alphabetic character, and then may be followed by 0 or more alphanumeric or _/: or . characters. If only one argument is supplied, then the same string of characters is used as both initial and body. Identifiers are very typical for 2 argument Word's, as they often start with alphas, but then accept digits and other punctuation. No whitespace is permitted within a Word. The Word matching will end when a non-body character is seen. Using this definition: integer = pp.Word(pp.nums+"-+.", pp.nums) It will accept "+123", "-345", "678", and ".901". But in a real number, a period may occur anywhere in the number, not just as the initial character, as in "3.14159". So your bodyCharacters must also include a ".", as in: integer = pp.Word(pp.nums+"-+.", pp.nums+".") Let me say, though, that this is a very permissive definition of integer - for one thing, we really should rename it something like "number", since it now accepts non-integers as well! But also, there is no restriction on the frequency of body characters. This definition would accept a "number" that looks like "3.4.3234.111.123.3234". If you are certain that you will only receive valid inputs, then this simple definition will be fine. But if you will have to handle and reject erroneous inputs, then you might do better with a number definition like: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ) This will handle "+123", "-345", "678", and "0.901", but not ".901". If you want to accept numbers that begin with "."s, then you'll need to tweak this a bit further. One last thing: you may want to start using setName() on some of your expressions, as in: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ).setName("number") Note, this is *not* the same as setResultsName. Here setName is attaching a name to this pattern, so that when it appears in an exception, the name will be used instead of an encoded pattern string (such as W:012345...). No need to do this for Literals, the literal string is used when it appears in an exception. -- Paul From paul at alanweberassociates.com Mon Jul 25 15:11:04 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Mon, 25 Jul 2005 08:11:04 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050725131116.F0C141E4007@bag.python.org> Liam - Could you e-mail me your latest grammar? The last version I had includes this definition for RHS: RHS << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) ^ identifier ^ integer ^ pp.Group( LBRACE + pp.ZeroOrMore( assignment ^ RHS ) + RBRACE ) ) What happens if you replace the '^' operators with '|', as in: RHS << ( pp.dblQuotedString.setParseAction(pp.removeQuotes) | identifier | integer | pp.Group( LBRACE + pp.ZeroOrMore( assignment | RHS ) + RBRACE ) ) I think earlier on, you needed to use '^' because your various terms were fairly vague (you were still using Word(pp.printables), which would accept just about anything). But now I think there is little ambiguity between a quoted string, identifier, etc., and simple '|' or MatchFirst's will do. This is about the only optimization I can think of. -- Paul -----Original Message----- From: Liam Clarke [mailto:cyresse at gmail.com] Sent: Monday, July 25, 2005 7:38 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem Hi Paul, Well various tweaks and such done, it parses perfectly, so much thanks, I think I now have a rough understanding of the basics of pyparsing. Now, onto the fun part of optimising it. At the moment, I'm looking at 2 - 5 minutes to parse a 2000 line country section, and that's with psyco. Only problem is, I have 157 country sections... I am running a 650 MHz processor, so that isn't helping either. I read this quote on http://pyparsing.sourceforge.net. "Thanks again for your help and thanks for writing pyparser! It seems my code needed to be optimized and now I am able to parse a 200mb file in 3 seconds. Now I can stick my tongue out at the Perl guys ;)" I'm jealous, 200mb in 3 seconds, my file's only 4mb. Are there any general approaches to optimisation that work well? My current thinking is to use string methods to split the string into each component section, and then parse each section to a bare minimum key, value. ie - instead of parsing x = { foo = { bar = 10 bob = 20 } type = { z = { } y = { } }} out fully, just parse to "x":"{ foo = { bar = 10 bob = 20 } type = { z = { } y = { } }}" I'm thinking that would avoid the complicated nested structure I have now, and I could parse data out of the string as needed, if needed at all. Erk, I don't know, I've never had to optimise anything. Much thanks for creating pyparsing, and doubly thank-you for your assistance in learning how to use it. Regards, Liam Clarke On 7/25/05, Liam Clarke wrote: Hi Paul, My apologies, as I was jumping into my car after sending that email, it clicked in my brain. "Oh yeah... initial & body..." But good to know about how to accept valid numbers. Sorry, getting a bit too quick to fire off emails here. Regards, Liam Clarke On 7/25/05, Paul McGuire < paul at alanweberassociates.com > wrote: Liam - The two arguments to Word work this way: - the first argument lists valid *initial* characters - the second argument lists valid *body* or subsequent characters For example, in the identifier definition, identifier = pp.Word(pp.alphas, pp.alphanums + "_/:.") identifiers *must* start with an alphabetic character, and then may be followed by 0 or more alphanumeric or _/: or . characters. If only one argument is supplied, then the same string of characters is used as both initial and body. Identifiers are very typical for 2 argument Word's, as they often start with alphas, but then accept digits and other punctuation. No whitespace is permitted within a Word. The Word matching will end when a non-body character is seen. Using this definition: integer = pp.Word(pp.nums+"-+.", pp.nums) It will accept "+123", "-345", "678", and ".901". But in a real number, a period may occur anywhere in the number, not just as the initial character, as in "3.14159". So your bodyCharacters must also include a ".", as in: integer = pp.Word(pp.nums+"-+.", pp.nums+".") Let me say, though, that this is a very permissive definition of integer - for one thing, we really should rename it something like "number", since it now accepts non-integers as well! But also, there is no restriction on the frequency of body characters. This definition would accept a "number" that looks like "3.4.3234.111.123.3234". If you are certain that you will only receive valid inputs, then this simple definition will be fine. But if you will have to handle and reject erroneous inputs, then you might do better with a number definition like: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ) This will handle "+123", "-345", "678", and "0.901", but not ".901". If you want to accept numbers that begin with "."s, then you'll need to tweak this a bit further. One last thing: you may want to start using setName() on some of your expressions, as in: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ).setName("number") Note, this is *not* the same as setResultsName. Here setName is attaching a name to this pattern, so that when it appears in an exception, the name will be used instead of an encoded pattern string (such as W:012345...). No need to do this for Literals, the literal string is used when it appears in an exception. -- Paul -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' From paul at alanweberassociates.com Mon Jul 25 15:21:50 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Mon, 25 Jul 2005 08:21:50 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050725132209.263201E4007@bag.python.org> One other thing, Liam. Download the latest version of pyparsing (1.3.2), and make this change to the assignment statement: assignment << pp.Dict( pp.Group( LHS + EQUALS + RHS ) ) Now you can write clean-looking code like: test = """j = { line = { foo = 10 bar = 20 } } }""" res = assignment.parseString(test) print res print res.j print res.j.line print res.j.line.foo print res.j.line.bar And get: [['j', [['line', [['foo', '10'], ['bar', '20']]]]]] [['line', [['foo', '10'], ['bar', '20']]]] [['foo', '10'], ['bar', '20']] 10 20 -- Paul -----Original Message----- From: Liam Clarke [mailto:cyresse at gmail.com] Sent: Monday, July 25, 2005 7:38 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem Hi Paul, Well various tweaks and such done, it parses perfectly, so much thanks, I think I now have a rough understanding of the basics of pyparsing. Now, onto the fun part of optimising it. At the moment, I'm looking at 2 - 5 minutes to parse a 2000 line country section, and that's with psyco. Only problem is, I have 157 country sections... I am running a 650 MHz processor, so that isn't helping either. I read this quote on http://pyparsing.sourceforge.net. "Thanks again for your help and thanks for writing pyparser! It seems my code needed to be optimized and now I am able to parse a 200mb file in 3 seconds. Now I can stick my tongue out at the Perl guys ;)" I'm jealous, 200mb in 3 seconds, my file's only 4mb. Are there any general approaches to optimisation that work well? My current thinking is to use string methods to split the string into each component section, and then parse each section to a bare minimum key, value. ie - instead of parsing x = { foo = { bar = 10 bob = 20 } type = { z = { } y = { } }} out fully, just parse to "x":"{ foo = { bar = 10 bob = 20 } type = { z = { } y = { } }}" I'm thinking that would avoid the complicated nested structure I have now, and I could parse data out of the string as needed, if needed at all. Erk, I don't know, I've never had to optimise anything. Much thanks for creating pyparsing, and doubly thank-you for your assistance in learning how to use it. Regards, Liam Clarke On 7/25/05, Liam Clarke wrote: Hi Paul, My apologies, as I was jumping into my car after sending that email, it clicked in my brain. "Oh yeah... initial & body..." But good to know about how to accept valid numbers. Sorry, getting a bit too quick to fire off emails here. Regards, Liam Clarke On 7/25/05, Paul McGuire < paul at alanweberassociates.com > wrote: Liam - The two arguments to Word work this way: - the first argument lists valid *initial* characters - the second argument lists valid *body* or subsequent characters For example, in the identifier definition, identifier = pp.Word(pp.alphas, pp.alphanums + "_/:.") identifiers *must* start with an alphabetic character, and then may be followed by 0 or more alphanumeric or _/: or . characters. If only one argument is supplied, then the same string of characters is used as both initial and body. Identifiers are very typical for 2 argument Word's, as they often start with alphas, but then accept digits and other punctuation. No whitespace is permitted within a Word. The Word matching will end when a non-body character is seen. Using this definition: integer = pp.Word(pp.nums+"-+.", pp.nums) It will accept "+123", "-345", "678", and ".901". But in a real number, a period may occur anywhere in the number, not just as the initial character, as in "3.14159". So your bodyCharacters must also include a ".", as in: integer = pp.Word(pp.nums+"-+.", pp.nums+".") Let me say, though, that this is a very permissive definition of integer - for one thing, we really should rename it something like "number", since it now accepts non-integers as well! But also, there is no restriction on the frequency of body characters. This definition would accept a "number" that looks like "3.4.3234.111.123.3234". If you are certain that you will only receive valid inputs, then this simple definition will be fine. But if you will have to handle and reject erroneous inputs, then you might do better with a number definition like: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ) This will handle "+123", "-345", "678", and "0.901", but not ".901". If you want to accept numbers that begin with "."s, then you'll need to tweak this a bit further. One last thing: you may want to start using setName() on some of your expressions, as in: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ).setName("number") Note, this is *not* the same as setResultsName. Here setName is attaching a name to this pattern, so that when it appears in an exception, the name will be used instead of an encoded pattern string (such as W:012345...). No need to do this for Literals, the literal string is used when it appears in an exception. -- Paul -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' From paul at alanweberassociates.com Mon Jul 25 17:16:09 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Mon, 25 Jul 2005 10:16:09 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050725151619.87A281E4007@bag.python.org> Liam - I made some changes and timed them, I think this problem is solvable. (All timings are done using your data, on a P4 800MHz laptop.) 1. Baseline, the current state, in the parser code you sent me: bracketGroup << ( pp.Group( LBRACE + ( pp.empty ^ pp.OneOrMore(assignment) ^ pp.OneOrMore(identifier) ^ pp.OneOrMore(pp.dblQuotedString) ^ pp.OneOrMore(number) ^ pp.OneOrMore(bracketGroup) ) + RBRACE ) ) Time: 02:20.71 (mm:ss.sss) Just for general edification, '^' means Or, and it will evaluate all the alternatives and choose the longest match (in regexp docs, this is sometimes referred to as "greedy" matching); '|' means MatchFirst, and it will only evaluate alternatives until it finds a match (which I refer to as "eager" matching). In the past, I've had only slight results converting '^' to '|', but since this is a recursive expression, evaluating all of the possible alternatives can involve quite a bit of processing before selecting the longest. 2. Convert to '|', replace empty with ZeroOrMore: bracketGroup << ( pp.Group( LBRACE + pp.ZeroOrMore( assignment | identifier | pp.dblQuotedString | number | bracketGroup ) + RBRACE ) ) Time: 00:14.57 This is getting us somewhere! Replaced empty and OneOrMore's with a single ZeroOrMore, and changed from '^' to '|'. Since there is no overlap of the various alternatives *in their current order*, it is safe to use '|'. (This would not be the case if assignment came after identifier - this should be a hint on how to resolve the 'empty' problem.) One problem with this expression is that it will permit mixed bracket groups, such as { "A" 10 b=1000 {} }. 3. Go back to baseline, change '^' to '|', *and put empty at the end* bracketGroup << ( pp.Group( LBRACE + ( pp.OneOrMore(assignment) | pp.OneOrMore(identifier) | pp.OneOrMore(pp.dblQuotedString) | pp.OneOrMore(number) | pp.OneOrMore(bracketGroup) | pp.empty ) + RBRACE ) ) Time: 00:12.04 Best solution yet! This is faster than #2, since, once a match is made on the first term within a bracketGroup, all others in the group are expected to be the same type. Since '|' means "take first match", we resolve empty's "accept anything" behavior simply by putting it at the end of the list. 4. Make change in #3, also convert '^' to '|' in RHS. RHS << ( pp.dblQuotedString | identifier | number | bracketGroup ) Time: 00:01.15 Voila! I'm happy to say, this is the first time I've seen a 100X improvement, mostly by replacing '^' by '|'. While this is not *always* possible (see the CORBA IDL parser in the examples directory), it is worth the effort, especially with a recursive expression. The one item to be wary of when using '|' is when expressions mask each other. The easiest example is when trying to parse numbers, which may be integers or reals. If I write the expression as (assuming that integers will match a sequence of digits, and reals will match digits with a decimal point and some more digits): number = (integer | real) I will never match a real number! The integer expression "masks" the real, and since it occurs first, it will match first. The two solutions are: number = (integer ^ real) Or number = (real | integer) That is, use an Or, which will match the longest, or reorder the MatchFirst to put the most restrictive expression first. Welcome to pyparsing, please let me know how your project goes! -- Paul -----Original Message----- From: Liam Clarke [mailto:cyresse at gmail.com] Sent: Monday, July 25, 2005 8:31 AM To: Paul McGuire Subject: Re: [Tutor] Parsing problem Hi Paul, I've attached the latest version. It includes my sample data within the file. The sample data came in at 8 minutes 32 seconds without Pysco, 5 minutes 25 with, on a 650MHz Athlon. I was pondering whether breaking the test data down into separate bits via some preprocessing and feeding the simpler data structures in would help at all. Unfortunately, as I'm using pp.empty to deal with empty bracket sets (which were causing my 'expected "}" ' exceptions), using | matches to pp.empty first. I'm not sure how to get around the empty brackets without using that. I also get the feeling that pyparsing was more designed for making parsing small complex expressions easy, as opposed to my data churning. That said, I can think of about ten different projects I'd played with before giving up because of a problem that pyparsing handles elegantly. Usually it was regexes that got me. So if I have to attack this another way, at least I know the basics of a good module now. :) Much thanks for your time and energy, having read your listing on the c2 wiki (I searched for pyparsing on the offchance) I can see you're a busy man, and I'm grateful for your efforts to help me. Regards, Liam Clarke On 7/26/05, Paul McGuire wrote: Liam- Please send me your latest version of the grammar, and I will post suggestions on the Tutor list. -- Paul -----Original Message----- From: Liam Clarke [mailto: cyresse at gmail.com ] Sent: Monday, July 25, 2005 7:38 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] Parsing problem Hi Paul, Well various tweaks and such done, it parses perfectly, so much thanks, I think I now have a rough understanding of the basics of pyparsing. Now, onto the fun part of optimising it. At the moment, I'm looking at 2 - 5 minutes to parse a 2000 line country section, and that's with psyco. Only problem is, I have 157 country sections... I am running a 650 MHz processor, so that isn't helping either. I read this quote on http://pyparsing.sourceforge.net . "Thanks again for your help and thanks for writing pyparser! It seems my code needed to be optimized and now I am able to parse a 200mb file in 3 seconds. Now I can stick my tongue out at the Perl guys ;)" I'm jealous, 200mb in 3 seconds, my file's only 4mb. Are there any general approaches to optimisation that work well? My current thinking is to use string methods to split the string into each component section, and then parse each section to a bare minimum key, value. ie - instead of parsing x = { foo = { bar = 10 bob = 20 } type = { z = { } y = { } }} out fully, just parse to "x":"{ foo = { bar = 10 bob = 20 } type = { z = { } y = { } }}" I'm thinking that would avoid the complicated nested structure I have now, and I could parse data out of the string as needed, if needed at all. Erk, I don't know, I've never had to optimise anything. Much thanks for creating pyparsing, and doubly thank-you for your assistance in learning how to use it. Regards, Liam Clarke On 7/25/05, Liam Clarke wrote: Hi Paul, My apologies, as I was jumping into my car after sending that email, it clicked in my brain. "Oh yeah... initial & body..." But good to know about how to accept valid numbers. Sorry, getting a bit too quick to fire off emails here. Regards, Liam Clarke On 7/25/05, Paul McGuire < paul at alanweberassociates.com > > wrote: Liam - The two arguments to Word work this way: - the first argument lists valid *initial* characters - the second argument lists valid *body* or subsequent characters For example, in the identifier definition, identifier = pp.Word(pp.alphas, pp.alphanums + "_/:.") identifiers *must* start with an alphabetic character, and then may be followed by 0 or more alphanumeric or _/: or . characters. If only one argument is supplied, then the same string of characters is used as both initial and body. Identifiers are very typical for 2 argument Word's, as they often start with alphas, but then accept digits and other punctuation. No whitespace is permitted within a Word. The Word matching will end when a non-body character is seen. Using this definition: integer = pp.Word(pp.nums+"-+.", pp.nums) It will accept "+123", "-345", "678", and ".901". But in a real number, a period may occur anywhere in the number, not just as the initial character, as in "3.14159". So your bodyCharacters must also include a ".", as in: integer = pp.Word(pp.nums+"-+.", pp.nums+".") Let me say, though, that this is a very permissive definition of integer - for one thing, we really should rename it something like "number", since it now accepts non-integers as well! But also, there is no restriction on the frequency of body characters. This definition would accept a "number" that looks like "3.4.3234.111.123.3234". If you are certain that you will only receive valid inputs, then this simple definition will be fine. But if you will have to handle and reject erroneous inputs, then you might do better with a number definition like: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ) This will handle "+123", "-345", "678", and "0.901", but not ".901". If you want to accept numbers that begin with "."s, then you'll need to tweak this a bit further. One last thing: you may want to start using setName() on some of your expressions, as in: number = Combine( Word( "+-"+nums, nums ) + Optional( point + Optional( Word( nums ) ) ) ).setName("number") Note, this is *not* the same as setResultsName. Here setName is attaching a name to this pattern, so that when it appears in an exception, the name will be used instead of an encoded pattern string (such as W:012345...). No need to do this for Literals, the literal string is used when it appears in an exception. -- Paul -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' From dyoo at hkn.eecs.berkeley.edu Mon Jul 25 23:18:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 25 Jul 2005 14:18:08 -0700 (PDT) Subject: [Tutor] how to write a line In-Reply-To: <1122312371l.11263l.0l@texaspivot.texaspivot.com> Message-ID: On Mon, 25 Jul 2005, nephish wrote: > i know how to read the lines of a txt file. > i know how to write a txt file. > > but how do i overwrite a line value with another value ? > > i mean, how do go to, say, line 3 of a text file and replace what is > written on line 3 with something else? Hi Nephish, It's slightly difficult to replace a single line of a file if all of the lines are different lengths. But if you can hold the whole file in memory at once, then the following should work: readlines() the file's contents into a list. Do changes on that list of lines. writelines() all the lines back out. So the idea is that we use an intermediate list and do all our work on that list first. We treat the files just as storage. Does this make sense? Please feel free to ask more questions about this. From nephish at xit.net Mon Jul 25 23:34:49 2005 From: nephish at xit.net (nephish) Date: Mon, 25 Jul 2005 21:34:49 +0000 Subject: [Tutor] how to write a line In-Reply-To: (from dyoo@hkn.eecs.berkeley.edu on Mon Jul 25 16:18:08 2005) References: Message-ID: <1122327289l.11974l.0l@texaspivot.texaspivot.com> i get it. manipulate everything while it is read. make my changes and use writelines(list from readlines earlier) so i kinda just hold everything in the list until i overwrite the original. thats great. my file is only 8 lines long. no problem thanks a lot ! Seems easy now. -shawn On 07/25/2005 04:18:08 PM, Danny Yoo wrote: > > > On Mon, 25 Jul 2005, nephish wrote: > > > i know how to read the lines of a txt file. > > i know how to write a txt file. > > > > but how do i overwrite a line value with another value ? > > > > i mean, how do go to, say, line 3 of a text file and replace what is > > written on line 3 with something else? > > Hi Nephish, > > It's slightly difficult to replace a single line of a file if all of > the > lines are different lengths. > > But if you can hold the whole file in memory at once, then the > following > should work: > > readlines() the file's contents into a list. > > Do changes on that list of lines. > > writelines() all the lines back out. > > So the idea is that we use an intermediate list and do all our work on > that list first. We treat the files just as storage. > > Does this make sense? Please feel free to ask more questions about > this. > > > > From alan.gauld at freenet.co.uk Tue Jul 26 00:41:45 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 25 Jul 2005 23:41:45 +0100 Subject: [Tutor] Pager in Python? References: Message-ID: <006501c5916a$09cfc760$18378651@xp> > xterm is a pretty old console. Even so, you do have access to a > ... > command line switches for xterm to add scrollbars if you need. The best scroll bars ever invented IMHO, much more powerful and controllable than those in OS X or Windoze, even better then the OpenLook scrollers of yesteryear! > I am not a big fan of xterm, though. I use konsole. xterm is bulky but other than that I like it a lot. > You might also be happy just using help(os) instead of dir(os) But help() is much better than dir for most interactive things. In a program dir is probably more useful though! Alan G. Back from vacation... From alan.gauld at freenet.co.uk Tue Jul 26 00:45:42 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Mon, 25 Jul 2005 23:45:42 +0100 Subject: [Tutor] how to write a line References: <1122312371l.11263l.0l@texaspivot.texaspivot.com> Message-ID: <006901c5916a$96e3ce80$18378651@xp> > but how do i overwrite a line value with another value ? > > i mean, how do go to, say, line 3 of a text file and replace > what is written on line 3 with something else? You can't do it directly easily unless the new version happens to be the exact same length as the original. In practice you have to adopt the same approach as your word processor does: read the file into memory, change the line in memory then write the whoile file back out overwriting the original file (you may want to save the original version as a backup while your at it!) If the change is the exact same number of bytes you can do it by messing around with the seek() and write() functions but its messy and easy to get wrong! There are some examples of the first approach in my tutorial in the file handling topic... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jfouhy at paradise.net.nz Tue Jul 26 00:56:06 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue, 26 Jul 2005 10:56:06 +1200 (NZST) Subject: [Tutor] Pager in Python? In-Reply-To: References: Message-ID: <1122332166.42e56e06eb750@www.paradise.net.nz> > > > >Is there a command like more(1) or less(1) in python to display > > > >the output of a command (e.g. dir()) one page at a time? You could always write your own ... eg: def page(it, numLines=20): if isinstance(it, dict): it = it.iteritems() for i, x in enumerate(it): print x if (i+1) % numLines == 0: raw_input('Press to continue...') -- John. From cyresse at gmail.com Tue Jul 26 10:22:15 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue, 26 Jul 2005 20:22:15 +1200 Subject: [Tutor] Parsing problem In-Reply-To: <42e5023e.50cee608.3608.ffff883dSMTPIN_ADDED@mx.gmail.com> References: <42e5023e.50cee608.3608.ffff883dSMTPIN_ADDED@mx.gmail.com> Message-ID: ...Oh my gosh, that is awesome. Thanks so much. I had started playing with the positioning of various patterns and using |, but it was getting into the early AM, so I stopped. Prematurely, it seems. I also got a point 0.1 second increase in speed by merging number and identifier, as the values will always be treated as strings, and are being written by a programme, so there's very little need to error check what's being parsed in. And it felt nice to improve it a wee bit myself. : ) Also interesting is that our processors, which aren't overly far apart in clock speed, vary so greatly in processing this problem. Maybe Intel is better.... *grin* Much thanks sir. Regards, Liam Clarke On 7/26/05, Paul McGuire wrote: > > Liam - > > I made some changes and timed them, I think this problem is solvable. (All > timings are done using your data, on a P4 800MHz laptop.) > > 1. Baseline, the current state, in the parser code you sent me: > > bracketGroup << ( pp.Group( LBRACE + ( pp.empty ^ pp.OneOrMore(assignment) > ^ > pp.OneOrMore(identifier) ^ pp.OneOrMore(pp.dblQuotedString) ^ > pp.OneOrMore(number) ^ pp.OneOrMore(bracketGroup) ) + RBRACE ) ) > > Time: 02:20.71 (mm:ss.sss) > > Just for general edification, '^' means Or, and it will evaluate all the > alternatives and choose the longest match (in regexp docs, this is > sometimes > referred to as "greedy" matching); '|' means MatchFirst, and it will only > evaluate alternatives until it finds a match (which I refer to as "eager" > matching). In the past, I've had only slight results converting '^' to > '|', > but since this is a recursive expression, evaluating all of the possible > alternatives can involve quite a bit of processing before selecting the > longest. > > 2. Convert to '|', replace empty with ZeroOrMore: > > bracketGroup << ( pp.Group( LBRACE + pp.ZeroOrMore( assignment | > identifier > | pp.dblQuotedString | number | bracketGroup ) + RBRACE ) ) > > Time: 00:14.57 > > This is getting us somewhere! Replaced empty and OneOrMore's with a single > ZeroOrMore, and changed from '^' to '|'. Since there is no overlap of the > various alternatives *in their current order*, it is safe to use '|'. > (This > would not be the case if assignment came after identifier - this should be > a > hint on how to resolve the 'empty' problem.) One problem with this > expression is that it will permit mixed bracket groups, such as { "A" 10 > b=1000 {} }. > > 3. Go back to baseline, change '^' to '|', *and put empty at the end* > > bracketGroup << ( pp.Group( LBRACE + ( pp.OneOrMore(assignment) | > pp.OneOrMore(identifier) | pp.OneOrMore(pp.dblQuotedString) | > pp.OneOrMore(number) | pp.OneOrMore(bracketGroup) | pp.empty ) + RBRACE ) > ) > > Time: 00:12.04 > > Best solution yet! This is faster than #2, since, once a match is made on > the first term within a bracketGroup, all others in the group are expected > to be the same type. Since '|' means "take first match", we resolve > empty's > "accept anything" behavior simply by putting it at the end of the list. > > 4. Make change in #3, also convert '^' to '|' in RHS. > > RHS << ( pp.dblQuotedString | identifier | number | bracketGroup ) > > Time: 00:01.15 > > Voila! I'm happy to say, this is the first time I've seen a 100X > improvement, mostly by replacing '^' by '|'. While this is not *always* > possible (see the CORBA IDL parser in the examples directory), it is worth > the effort, especially with a recursive expression. > > The one item to be wary of when using '|' is when expressions mask each > other. The easiest example is when trying to parse numbers, which may be > integers or reals. If I write the expression as (assuming that integers > will match a sequence of digits, and reals will match digits with a > decimal > point and some more digits): > > number = (integer | real) > > I will never match a real number! The integer expression "masks" the real, > and since it occurs first, it will match first. The two solutions are: > > number = (integer ^ real) > Or > number = (real | integer) > > That is, use an Or, which will match the longest, or reorder the > MatchFirst > to put the most restrictive expression first. > > Welcome to pyparsing, please let me know how your project goes! > > -- Paul > > > -----Original Message----- > From: Liam Clarke [mailto:cyresse at gmail.com] > Sent: Monday, July 25, 2005 8:31 AM > To: Paul McGuire > Subject: Re: [Tutor] Parsing problem > > Hi Paul, > > I've attached the latest version. It includes my sample data within the > file. The sample data came in at 8 minutes 32 seconds without Pysco, 5 > minutes 25 with, on a 650MHz Athlon. > > I was pondering whether breaking the test data down into separate bits via > some preprocessing and feeding the simpler data structures in would help > at > all. > > Unfortunately, as I'm using pp.empty to deal with empty bracket sets > (which > were causing my 'expected "}" ' exceptions), using | matches to pp.empty > first. > > I'm not sure how to get around the empty brackets without using that. > > I also get the feeling that pyparsing was more designed for making parsing > small complex expressions easy, as opposed to my data churning. That said, > I > can think of about ten different projects I'd played with before giving up > because of a problem that pyparsing handles elegantly. > Usually it was regexes that got me. So if I have to attack this another > way, > at least I know the basics of a good module now. :) > > Much thanks for your time and energy, having read your listing on the c2 > wiki (I searched for pyparsing on the offchance) I can see you're a busy > man, and I'm grateful for your efforts to help me. > > Regards, > > Liam Clarke > > > On 7/26/05, Paul McGuire wrote: > > Liam- > > Please send me your latest version of the grammar, and I will post > suggestions on the Tutor list. > > -- Paul > > -----Original Message----- > From: Liam Clarke [mailto: cyresse at gmail.com > ] > Sent: Monday, July 25, 2005 7:38 AM > To: Paul McGuire > Cc: tutor at python.org > Subject: Re: [Tutor] Parsing problem > > Hi Paul, > > Well various tweaks and such done, it parses perfectly, so much > thanks, I > think I now have a rough understanding of the basics of pyparsing. > > Now, onto the fun part of optimising it. At the moment, I'm looking > at 2 - 5 > minutes to parse a 2000 line country section, and that's with psyco. > Only > problem is, I have 157 country sections... > > I am running a 650 MHz processor, so that isn't helping either. I > read this > quote on http://pyparsing.sourceforge.net . > > "Thanks again for your help and thanks for writing pyparser! It > seems my > code needed to be optimized and now I am able to parse a 200mb file > in 3 > seconds. Now I can stick my tongue out at the Perl guys ;)" > > I'm jealous, 200mb in 3 seconds, my file's only 4mb. > > Are there any general approaches to optimisation that work well? > > My current thinking is to use string methods to split the string > into each > component section, and then parse each section to a bare minimum > key, value. > ie - instead of parsing > > x = { foo = { bar = 10 bob = 20 } type = { z = { } y = { } }} > > out fully, just parse to "x":"{ foo = { bar = 10 bob = 20 } type = { > z = { } > y = { } }}" > > I'm thinking that would avoid the complicated nested structure I > have now, > and I could parse data out of the string as needed, if needed at > all. > > Erk, I don't know, I've never had to optimise anything. > > Much thanks for creating pyparsing, and doubly thank-you for your > assistance > in learning how to use it. > > Regards, > > Liam Clarke > > On 7/25/05, Liam Clarke wrote: > > Hi Paul, > > My apologies, as I was jumping into my car after sending > that email, > it clicked in my brain. > "Oh yeah... initial & body..." > > But good to know about how to accept valid numbers. > > Sorry, getting a bit too quick to fire off emails here. > > Regards, > > Liam Clarke > > > On 7/25/05, Paul McGuire < paul at alanweberassociates.com > > > wrote: > > > Liam - > > The two arguments to Word work this way: > - the first argument lists valid *initial* > characters > - the second argument lists valid *body* or > subsequent > characters > > For example, in the identifier definition, > > identifier = pp.Word(pp.alphas, pp.alphanums + > "_/:.") > > identifiers *must* start with an alphabetic > character, and > then may be > followed by 0 or more alphanumeric or _/: or . > characters. > If only one > argument is supplied, then the same string of > characters is > used as both > initial and body. Identifiers are very typical for > 2 > argument Word's, as > they often start with alphas, but then accept digits > and > other punctuation. > No whitespace is permitted within a Word. The Word > matching > will end when a > non-body character is seen. > > Using this definition: > > integer = pp.Word(pp.nums+"-+.", pp.nums) > > It will accept "+123", "-345", "678", and ".901". > But in a > real number, a > period may occur anywhere in the number, not just as > the > initial character, > as in "3.14159". So your bodyCharacters must also > include a > ".", as in: > > integer = pp.Word(pp.nums+"-+.", pp.nums+".") > > Let me say, though, that this is a very permissive > definition of integer - > for one thing, we really should rename it something > like > "number", since it > now accepts non-integers as well! But also, there > is no > restriction on the > frequency of body characters. This definition would > accept > a "number" that > looks like "3.4.3234.111.123.3234". If you are > certain that > you will only > receive valid inputs, then this simple definition > will be > fine. But if you > will have to handle and reject erroneous inputs, > then you > might do better > with a number definition like: > > number = Combine( Word( "+-"+nums, nums ) + > Optional( point + Optional( Word( > nums ) ) > ) ) > > This will handle "+123", "-345", "678", and "0.901", > but not > ".901". If you > want to accept numbers that begin with "."s, then > you'll > need to tweak this > a bit further. > > One last thing: you may want to start using > setName() on > some of your > expressions, as in: > > number = Combine( Word( "+-"+nums, nums ) + > Optional( point + Optional( Word( > nums ) ) > ) > ).setName("number") > > Note, this is *not* the same as setResultsName. > Here > setName is attaching a > name to this pattern, so that when it appears in an > exception, the name will > be used instead of an encoded pattern string (such > as > W:012345...). No need > to do this for Literals, the literal string is used > when it > appears in an > exception. > > -- Paul > > > > > > > > -- > > 'There is only one basic human right, and that is to do as > you damn > well please. > And with it comes the only basic human duty, to take the > consequences.' > > > > > -- > 'There is only one basic human right, and that is to do as you damn > well > please. > And with it comes the only basic human duty, to take the > consequences.' > > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences.' > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050726/7f511586/attachment-0001.htm From jorge at bcs.org.uk Tue Jul 26 13:31:48 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Tue, 26 Jul 2005 12:31:48 +0100 Subject: [Tutor] Quickest way to find a folder on windows Message-ID: Hi all, What is the quickest way to find/search a folder on windows? Specifically, I want to find the 'My Documents' folder on different machines but since this one lies in different user-specific folders (the user account on XP) I'm being forced to traverse the whole drive looking for it (though I can start from 'Documents and Settings' to prune the search space) Is there a faster way? I know this is very reliant on the windows search API so maybe I'm stuck with my solution Any help is appreciated cheers j -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050726/289f96cd/attachment.htm From mwalsh at groktech.org Tue Jul 26 14:37:38 2005 From: mwalsh at groktech.org (Martin Walsh) Date: Tue, 26 Jul 2005 08:37:38 -0400 Subject: [Tutor] Quickest way to find a folder on windows In-Reply-To: References: Message-ID: <42E62E92.4000206@groktech.org> Jorge Louis De Castro wrote: > Hi all, > > What is the quickest way to find/search a folder on windows? > Specifically, I want to find the 'My Documents' folder on different > machines but since this one lies in different user-specific folders (the > user account on XP) I'm being forced to traverse the whole drive looking > for it (though I can start from 'Documents and Settings' to prune the > search space) While this doesn't go directly toward answering your fast search a folder question, it might get you closer for finding special folders -- and others on the list will certainly have a more concise solution take a look at os.path.expanduser() and os.environ, which are available cross-platform .>>> # on my setup (non-standard %HOME%), this works .>>> os.path.join(os.path.expanduser('~'), 'My Documents') 'H:\\My Documents' .>>> os.path.join(os.environ['USERPROFILE'], 'My Documents') 'C:\\Documents and Settings\\martin walsh\\My Documents' as you can see, because of my non-standard setup, I get 2 different results in this instance, Mark Hammond's win32 extensions can possibly help. Tim Golden has written the winshell module, uses win32 -- and includes a helper for "finding" the 'My Documents' folder -- it's available here: http://tgolden.sc.sabren.com/python/winshell.html >>> import winshell # must have pywin32 & winshell installed >>> winshell.my_documents() 'H:\\my documents' HTH, Marty > > Is there a faster way? I know this is very reliant on the windows search > API so maybe I'm stuck with my solution > Any help is appreciated > > cheers > j > From kent37 at tds.net Tue Jul 26 14:47:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 26 Jul 2005 08:47:08 -0400 Subject: [Tutor] Quickest way to find a folder on windows In-Reply-To: References: Message-ID: <42E630CC.8030600@tds.net> Jorge Louis De Castro wrote: > Hi all, > > What is the quickest way to find/search a folder on windows? > Specifically, I want to find the 'My Documents' folder on different > machines but since this one lies in different user-specific folders (the > user account on XP) I'm being forced to traverse the whole drive looking > for it (though I can start from 'Documents and Settings' to prune the > search space) See http://tgolden.sc.sabren.com/python/winshell.html http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/65f3787bb3a4d4df/29561089b44ef1bb?q=%22my+documents%22&rnum=3&hl=en#29561089b44ef1bb http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/c448fb4625f43b4d/15963628098c5130?q=%22my+documents%22&rnum=15&hl=en#15963628098c5130 Kent From johnp at milwaukielumber.com Tue Jul 26 17:18:35 2005 From: johnp at milwaukielumber.com (John Purser) Date: Tue, 26 Jul 2005 08:18:35 -0700 Subject: [Tutor] Quickest way to find a folder on windows In-Reply-To: Message-ID: <200507261518.j6QFIZ7V031112@email.morseintranet.com> Since the "My Documents" folder can be re-named you need to search the registry to see what the user's "my documents" folder is. I'm not sure what domain constraints might do to this setting. Perhaps the most efficient method if you were just interested in the current user's "My Documents" directory would be to determine the current value of the %HOME% variable. John Purser ________________________________ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Jorge Louis De Castro Sent: Tuesday, July 26, 2005 04:32 To: tutor at python.org Subject: [Tutor] Quickest way to find a folder on windows Hi all, What is the quickest way to find/search a folder on windows? Specifically, I want to find the 'My Documents' folder on different machines but since this one lies in different user-specific folders (the user account on XP) I'm being forced to traverse the whole drive looking for it (though I can start from 'Documents and Settings' to prune the search space) Is there a faster way? I know this is very reliant on the windows search API so maybe I'm stuck with my solution Any help is appreciated cheers j From paul at alanweberassociates.com Tue Jul 26 15:37:54 2005 From: paul at alanweberassociates.com (Paul McGuire) Date: Tue, 26 Jul 2005 08:37:54 -0500 Subject: [Tutor] Parsing problem In-Reply-To: Message-ID: <20050726133800.E0D711E4002@bag.python.org> > Also interesting is that our processors, which aren't overly > far apart in clock speed, vary so greatly in processing this > problem. Maybe Intel is better.... *grin* Urp, turns out I have an "Athlon Inside" label right here on the deck of my laptop! Maybe the difference is my 1.2Gb of RAM. It's an Athlon XP-M 3000+, which runs about 800MHz to save battery power, but can ratchet up to 1.6GHz when processing. Cheers! -- Paul From falcon3166 at hotmail.com Wed Jul 27 08:36:19 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 00:36:19 -0600 Subject: [Tutor] Thanks. Message-ID: Thanks all for helping me. Thanks to the group, I have figured out a way to make Giant Calculator and any program repeat until the user wants to exit. Thanks again, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/d8a7b83f/attachment.htm From gnumathetes at gmail.com Wed Jul 27 16:13:22 2005 From: gnumathetes at gmail.com (Don Parris) Date: Wed, 27 Jul 2005 10:13:22 -0400 Subject: [Tutor] Problem with pgbd & datetime Message-ID: <6692614405072707132ced3a48@mail.gmail.com> O.k., I'm running SUSE Linux 9.2, Python 2.3.4, I have changed my DB back-end from MySQL to Postgres for the larger feature set. However, in attempting to load the pgdb module for use in my script, I got this message (same when I try it at the command-line): >>> pgdb.connect('localhost:chaddb_a_test:donp:d1o1l2l4') Traceback (most recent call last): File "", line 1, in ? NameError: name 'pgdb' is not defined >>> import pgdb Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/site-packages/pgdb.py", line 65, in ? except ImportError: import DateTime ImportError: No module named DateTime In the pgdb module, I found this (which matches with the traceback): # Marc-Andre is changing where DateTime goes. This handles it either way. try: from mx import DateTime except ImportError: import DateTime Do I just need to modify pgdb.py to import datetime instead of DateTime? Or is there something more to this? I could spend a fair amount of time searching the archives. Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com "Hey man, whatever pickles your list!" From davholla2002 at yahoo.co.uk Wed Jul 27 17:42:02 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 27 Jul 2005 16:42:02 +0100 (BST) Subject: [Tutor] Select rows and columns in excel Message-ID: <20050727154202.75597.qmail@web25402.mail.ukl.yahoo.com> Dear Tutors, I know how to open files in python, however what I want to do is select some information from an excel spreadsheet and save it as a .dat file. The bit, I am stuck on is :- How can I select all rows with a row number greater than x for a certain column ? Thanks in advance David Holland --------------------------------- Yahoo! Messenger NEW - crystal clear PC to PCcalling worldwide with voicemail -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/31366a07/attachment.htm From golarru at hotmail.com Wed Jul 27 19:04:34 2005 From: golarru at hotmail.com (Xabier Gonzalez) Date: Wed, 27 Jul 2005 19:04:34 +0200 Subject: [Tutor] Python and Excel Message-ID: Hello! Honestly, I?m new in Python. I wanted to know about the possibility of importing .txt text files from Excel and manage the contents (creating graphics...) using Python. I?ve read about the win32com module and I would like to find a good example just to take the right way. Thank you! From golarru at hotmail.com Wed Jul 27 19:04:36 2005 From: golarru at hotmail.com (Xabier Gonzalez) Date: Wed, 27 Jul 2005 19:04:36 +0200 Subject: [Tutor] Python and Excel Message-ID: Hello! Honestly, I?m new in Python. I wanted to know about the possibility of importing .txt text files from Excel and manage the contents (creating graphics...) using Python. I?ve read about the win32com module and I would like to find a good example just to take the right way. Thank you! From lordverminard at gmail.com Wed Jul 27 19:20:43 2005 From: lordverminard at gmail.com (Mustafa) Date: Wed, 27 Jul 2005 22:20:43 +0500 Subject: [Tutor] anything to do??? Message-ID: <42E7C26B.8020605@gmail.com> i hav just finished learning pythob from "A byte of python"(an online book) so i wanted to apply my new skills. to learn and to have some fun. is there any place which lists jobs to be done...you know minor jobs and requests thats nobody has found time to do. i would point out that i am not looking for a JOB as job with payment. i am looking for a JOB that is to be done and nobody has done it yet. also aside from this is there any other way i could use python and improve. i figure this practice will make me a lot better. but if anybody else has any ideas than that would be good too . From gsf at panix.com Wed Jul 27 19:40:28 2005 From: gsf at panix.com (Gabriel Farrell) Date: Wed, 27 Jul 2005 13:40:28 -0400 Subject: [Tutor] Problem with pgbd & datetime In-Reply-To: <6692614405072707132ced3a48@mail.gmail.com> References: <6692614405072707132ced3a48@mail.gmail.com> Message-ID: <20050727174028.GB1890@panix.com> Are you using PyGreSQL? import pgdb works fine for me with PyGreSQL. I'm on Debian but I assume there's a package for it for SUSE. gsf On Wed, Jul 27, 2005 at 10:13:22AM -0400, Don Parris wrote: > O.k., I'm running SUSE Linux 9.2, Python 2.3.4, > > I have changed my DB back-end from MySQL to Postgres for the larger > feature set. However, in attempting to load the pgdb module for use > in my script, I got this message (same when I try it at the > command-line): > > >>> pgdb.connect('localhost:chaddb_a_test:donp:d1o1l2l4') > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'pgdb' is not defined > >>> import pgdb > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/site-packages/pgdb.py", line 65, in ? > except ImportError: import DateTime > ImportError: No module named DateTime > > > In the pgdb module, I found this (which matches with the traceback): > # Marc-Andre is changing where DateTime goes. This handles it either way. > try: from mx import DateTime > except ImportError: import DateTime > > Do I just need to modify pgdb.py to import datetime instead of > DateTime? Or is there something more to this? I could spend a fair > amount of time searching the archives. > > Don > -- > DC Parris GNU Evangelist > http://matheteuo.org/ > gnumathetes at gmail.com > "Hey man, whatever pickles your list!" > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From gsf at panix.com Wed Jul 27 19:45:26 2005 From: gsf at panix.com (Gabriel Farrell) Date: Wed, 27 Jul 2005 13:45:26 -0400 Subject: [Tutor] anything to do??? In-Reply-To: <42E7C26B.8020605@gmail.com> References: <42E7C26B.8020605@gmail.com> Message-ID: <20050727174526.GC1890@panix.com> I assume you have checked out http://wiki.python.org/moin/VolunteerOpportunities . I've improved a lot by just reading this list and following along with the successes and failures (always temporary, I hope) of others. gsf On Wed, Jul 27, 2005 at 10:20:43PM +0500, Mustafa wrote: > i hav just finished learning pythob from "A byte of python"(an online > book) so i wanted to apply my new skills. to learn and to have some fun. > is there any place which lists jobs to be done...you know minor jobs and > requests thats nobody has found time to do. > i would point out that i am not looking for a JOB as job with payment. > i am looking for a JOB that is to be done and nobody has done it yet. > > also aside from this is there any other way i could use python and > improve. i figure this practice will make me a lot better. but if anybody > else has any ideas than that would be good too . > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From falcon3166 at hotmail.com Wed Jul 27 21:03:22 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 13:03:22 -0600 Subject: [Tutor] How do I make Python draw? Message-ID: How do I make Python draw a shape? e.g. a triangle Is there a specific module that I have to call, or what is the command(s)? Thanks, Nathan Pinno P.S. Knowing this will help me make my shape_calc program better. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/5c0e5b27/attachment.htm From falcon3166 at hotmail.com Wed Jul 27 21:22:42 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 13:22:42 -0600 Subject: [Tutor] How do I go about this? Message-ID: Hi all, How do I go about the following: I want to write a program that will print two lists one after another, then show all the available possibilities for matches e.g a0 and x0. Here is what I have so far: lista = [x0, x1, x2, x3] listb = [a0, a1, a2, a3] print lista print listb Thanks for the help, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/2ac34351/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Jul 27 22:47:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 27 Jul 2005 13:47:52 -0700 (PDT) Subject: [Tutor] Select rows and columns in excel In-Reply-To: <20050727154202.75597.qmail@web25402.mail.ukl.yahoo.com> Message-ID: On Wed, 27 Jul 2005, David Holland wrote: > I know how to open files in python, however what I want to do is select > some information from an excel spreadsheet and save it as a .dat file. Hi David, Excel spreadsheets are a bit more difficult to work with. They're not plain text files, but have their own internal binary format, so you'll probably need a library to deal with them. Many people deal with Excel by either converting the files to something plain-textish, like the 'csv' format, or they get Python to talk to Excel directly. If you can output your excel spreadsheet in 'csv' format, then Python's 'csv' module should be useful: http://www.python.org/doc/lib/module-csv.html and doing the selection should just be a matter of skipping enough rows, in the file, and then paying attention to the particular column you want. But if you want to go another route --- to talk closely with Excel --- that might take some more involvement, since it's so tightly bound with Windows programming. The book "Python Programming on Win32" has a chapter on how to talk to Excel through Python: http://www.oreilly.com/catalog/pythonwin32/ and if you're interested in this approach, you may want to talk with the python-win32 folks: http://mail.python.org/mailman/listinfo/python-win32 Hope this helps! From dyoo at hkn.eecs.berkeley.edu Wed Jul 27 22:52:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 27 Jul 2005 13:52:36 -0700 (PDT) Subject: [Tutor] Python and Excel In-Reply-To: Message-ID: On Wed, 27 Jul 2005, Xabier Gonzalez wrote: > Honestly, I´m new in Python. I wanted to know about the possibility of > importing .txt text files from Excel and manage the contents (creating > graphics...) using Python. I´ve read about the win32com module and I > would like to find a good example just to take the right way. Hi Xabier, It's possible and very doable. The canonical reference to doing this stuff seems to be the book "Python Programming on Win32", which talks about the specific issues Python programmers have to know to work with Windows-specific stuff. http://www.oreilly.com/catalog/pythonwin32/ Unfortunately, many of us here don't have win32api expertise. If you're interested in doing win32api programming, your best bet is to talk with the python-win32 mailing list folks: they should be able to give you good references. But if you have general Python questions, please feel free to ask here; we'll be glad to help. Good luck! From tegmine at gmail.com Wed Jul 27 23:01:42 2005 From: tegmine at gmail.com (Luis N) Date: Wed, 27 Jul 2005 14:01:42 -0700 Subject: [Tutor] How do I go about this? In-Reply-To: References: Message-ID: <77bfa81a050727140141f33477@mail.gmail.com> On 7/27/05, Nathan Pinno wrote: > > Hi all, > How do I go about the following: I want to write a program that will > print two lists one after another, then show all the available possibilities > for matches e.g a0 and x0. > Here is what I have so far: > lista = [x0, x1, x2, x3] > listb = [a0, a1, a2, a3] > print lista > print listb > Thanks for the help, > Nathan Pinno > Hi, Could you give some additional information as to what you intend to do? If you are strictly matching, by position within the lists, such that you would print the list elements only if: for x in range(min(len(lista),len(listb))): a = lista[x] b = listb[x] if a == b: print a, b that is easy, however, if you want to match more complex patterns, or wish to match list elements not in the same position then the complexity of the task increases. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/d8f21a8d/attachment.htm From tegmine at gmail.com Wed Jul 27 23:03:36 2005 From: tegmine at gmail.com (Luis N) Date: Wed, 27 Jul 2005 14:03:36 -0700 Subject: [Tutor] How do I go about this? In-Reply-To: <77bfa81a050727140141f33477@mail.gmail.com> References: <77bfa81a050727140141f33477@mail.gmail.com> Message-ID: <77bfa81a05072714031fa12c29@mail.gmail.com> On 7/27/05, Luis N wrote: > > On 7/27/05, Nathan Pinno wrote: > > > Hi all, > > How do I go about the following: I want to write a program that will > > print two lists one after another, then show all the available possibilities > > for matches e.g a0 and x0. > > Here is what I have so far: > > lista = [x0, x1, x2, x3] > > listb = [a0, a1, a2, a3] > > print lista > > print listb > > Thanks for the help, > > Nathan Pinno > > > > > Hi, > > Could you give some additional information as to what you intend to do? If > you are strictly matching, by position within the lists, such that you would > print the list elements only if: > > for x in range(min(len(lista),len(listb))): > a = lista[x] > b = listb[x] > if a[1] == b[1]: > print a, b > > that is easy, however, if you want to match more complex patterns, or wish > to match list elements not in the same position then the complexity of the > task increases. > Woops, I forgot the a[1], b[1] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/a9984e69/attachment.htm From dyoo at hkn.eecs.berkeley.edu Wed Jul 27 23:04:30 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 27 Jul 2005 14:04:30 -0700 (PDT) Subject: [Tutor] How do I make Python draw? In-Reply-To: Message-ID: On Wed, 27 Jul 2005, Nathan Pinno wrote: > How do I make Python draw a shape? e.g. a triangle Is there a specific > module that I have to call, or what is the command(s)? Hi Nathan, If you'd like to start doing graphical stuff, you might want to look at the Tkinter module. http://www.python.org/doc/lib/module-Tkinter.html There's an introduction to it here: http://www.pythonware.com/library/tkinter/introduction/ Just to whet your appetite, here's a quick-and-dirty demo program that should draw a triangle for you: ###### """Draws a triangle on a Tkinter canvas.""" from Tkinter import * canvas = Canvas() canvas.create_polygon([(1, 1), (1, 200), (100, 100)]) canvas.pack() canvas.update_idletasks() ###### If you want to do more sophisticated graphics stuff, there are alternative packages, like pygame: http://www.pygame.org/news.html If you have more questions, please feel free to ask! From falcon3166 at hotmail.com Wed Jul 27 23:07:48 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 15:07:48 -0600 Subject: [Tutor] How do I go about this? References: <77bfa81a050727140141f33477@mail.gmail.com> Message-ID: Luis and all, I want to more than matching, I am trying to find all the available combos, e.g a1 == x1 or a1 == x2 or a1 != x1. HTH, Nathan Pinno I also noticed you forgot the a[1] == b[1]. (grin) :) ----- Original Message ----- From: Luis N To: tutor at python.org Sent: Wednesday, July 27, 2005 3:01 PM Subject: Re: [Tutor] How do I go about this? On 7/27/05, Nathan Pinno wrote: Hi all, How do I go about the following: I want to write a program that will print two lists one after another, then show all the available possibilities for matches e.g a0 and x0. Here is what I have so far: lista = [x0, x1, x2, x3] listb = [a0, a1, a2, a3] print lista print listb Thanks for the help, Nathan Pinno Hi, Could you give some additional information as to what you intend to do? If you are strictly matching, by position within the lists, such that you would print the list elements only if: for x in range(min(len(lista),len(listb))): a = lista[x] b = listb[x] if a == b: print a, b that is easy, however, if you want to match more complex patterns, or wish to match list elements not in the same position then the complexity of the task increases. ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/3af97a8f/attachment.htm From falcon3166 at hotmail.com Wed Jul 27 23:13:02 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 15:13:02 -0600 Subject: [Tutor] How do I make Python draw? References: Message-ID: Thanks. Will ask if I have any more questions. Maybe I won't have to go to Visual Basic to write my games. Maybe Python will do the trick. Thanks again. Nathan Pinno ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: Sent: Wednesday, July 27, 2005 3:04 PM Subject: Re: [Tutor] How do I make Python draw? > > > On Wed, 27 Jul 2005, Nathan Pinno wrote: > >> How do I make Python draw a shape? e.g. a triangle Is there a specific >> module that I have to call, or what is the command(s)? > > Hi Nathan, > > If you'd like to start doing graphical stuff, you might want to look at > the Tkinter module. > > http://www.python.org/doc/lib/module-Tkinter.html > > There's an introduction to it here: > > http://www.pythonware.com/library/tkinter/introduction/ > > > Just to whet your appetite, here's a quick-and-dirty demo program that > should draw a triangle for you: > > ###### > """Draws a triangle on a Tkinter canvas.""" > > from Tkinter import * > canvas = Canvas() > canvas.create_polygon([(1, 1), (1, 200), (100, 100)]) > canvas.pack() > canvas.update_idletasks() > ###### > > > If you want to do more sophisticated graphics stuff, there are alternative > packages, like pygame: > > http://www.pygame.org/news.html > > > If you have more questions, please feel free to ask! > > From dyoo at hkn.eecs.berkeley.edu Wed Jul 27 23:13:11 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 27 Jul 2005 14:13:11 -0700 (PDT) Subject: [Tutor] How do I go about this? In-Reply-To: Message-ID: On Wed, 27 Jul 2005, Nathan Pinno wrote: > How do I go about the following: I want to write a program that will > print two lists one after another, then show all the available > possibilities for matches e.g a0 and x0. > lista = [x0, x1, x2, x3] > listb = [a0, a1, a2, a3] Hi Nathan, It sounds like you're asking for the mathematical idea of "crossing" both lists together. Here's a slightly simpler problem that might be easier for you to solve: Let's say you have an element 'x0' in hand, as well as 'listb'. Can you produce all the matches between x0 and each element in listb? Let's call this function match(). (If you have a better name for this, use that name instead. *grin*). We'd expect match() to behave something like this: match('x0', ['a0', 'a1', 'a2', 'a3']) ==> [('x0', 'a0'), ('x0', 'a1'), ('x0', 'a2'), ('x0', 'a3')] Can you write 'match()'? If so, you should be very close in writing something that crosses both lists together. Good luck! From falcon3166 at hotmail.com Wed Jul 27 23:19:56 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 15:19:56 -0600 Subject: [Tutor] Why does this NameError appear? Message-ID: Here is the code: lista = [x0, x1, x2, x3] listb = [a0, a1, a2, a3] print lista print listb print match (lista, listb) And here is the error: Traceback (most recent call last): File "D:\Python22\matches.py", line 1, in ? lista = [x0, x1, x2, x3] NameError: name 'x0' is not defined Thanks in advance, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/f83b8bd3/attachment.htm From ajikoe at gmail.com Wed Jul 27 23:52:54 2005 From: ajikoe at gmail.com (Pujo Aji) Date: Wed, 27 Jul 2005 23:52:54 +0200 Subject: [Tutor] matplotlib (pylab) backends Message-ID: Hello I write a program which launch pylab from windows GUI (using wxpython). I found some problem here. If I use the default backends program in matplotlibrc which is TkAgg I have this result: 1. I click button the plot is showed 2. I close the plot 3. I click the button to show the plot the second time. it shows the plot but I can't closed it (it hangs. If I use the WX as my backends program ( i have to change manually in matplotlibrc) I have this result: 1. I click button the plot is showed 2. I close the plot 3. I click the button to show the plot the second time. it shows perfect. 4. I close my GUI this time the program doesn't totally close (I can check from windows manager process). What's the problem here. I use pylab.show() to show the program. Sincerely Yours, pujo From rabidpoobear at gmail.com Thu Jul 28 00:36:34 2005 From: rabidpoobear at gmail.com (luke) Date: Wed, 27 Jul 2005 17:36:34 -0500 Subject: [Tutor] How do I make Python draw? References: Message-ID: <006501c592fb$a5a29770$aa0ca8c0@luke> > Thanks. Will ask if I have any more questions. Maybe I won't have to go to > Visual Basic to write my games. Maybe Python will do the trick. Oh my god. Don't ever compare Python to Basic on a python mailing list. You'll get eaten alive ;-) Seriously though, If you take the time to learn PyGame, it's about the easiest and best way to write a game in any language (from scratch that is.) I highly recommend it. In fact I'm writing a PyGame game right now. If you're interested in seeing the source at some point, Just ask. Although I won't send it just yet because it has no drawing code ATM. Just game logic. Hope ThAt HeLPs. Don't ever resort to Visual Basic. If you think something would be easier in VB then ask us and we will tell you how to do it in Python. VB is not a good language to learn because it is the complete opposite of every other programming language. I really can't think of a reason to use VB over Python, C++ or Java. From adam.jtm30 at gmail.com Thu Jul 28 00:51:13 2005 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 27 Jul 2005 23:51:13 +0100 Subject: [Tutor] How do I make Python draw? In-Reply-To: <006501c592fb$a5a29770$aa0ca8c0@luke> References: <006501c592fb$a5a29770$aa0ca8c0@luke> Message-ID: Hey luke what kind of game is it? Can I have a look when at your source as well? Cheers. Adam On 7/27/05, luke wrote: > > > > Thanks. Will ask if I have any more questions. Maybe I won't have to go > to > > Visual Basic to write my games. Maybe Python will do the trick. > Oh my god. > Don't ever compare Python to Basic on a python mailing list. > You'll get eaten alive ;-) > > Seriously though, > If you take the time to learn PyGame, it's about the easiest and > best way to write a game in any language (from scratch that is.) > I highly recommend it. > In fact I'm writing a PyGame game right now. > If you're interested in seeing the source at some point, > Just ask. > Although I won't send it just yet because it has no drawing code ATM. > Just game logic. > > Hope ThAt HeLPs. > Don't ever resort to Visual Basic. > If you think something would be easier in VB then ask us > and we will tell you how to do it in Python. > VB is not a good language to learn because it > is the complete opposite of every other programming language. > > I really can't think of a reason to use VB over Python, C++ or Java. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/bde4666f/attachment.htm From falcon3166 at hotmail.com Thu Jul 28 00:52:59 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 16:52:59 -0600 Subject: [Tutor] How do I make Python draw? References: <006501c592fb$a5a29770$aa0ca8c0@luke> Message-ID: Luke, Thanks for the reminder. Though I might try Java, but having problems with errors left, right and center. G2G, Nathan ----- Original Message ----- From: "luke" To: "Nathan Pinno" ; "Danny Yoo" Cc: Sent: Wednesday, July 27, 2005 4:36 PM Subject: Re: [Tutor] How do I make Python draw? > >> Thanks. Will ask if I have any more questions. Maybe I won't have to go >> to >> Visual Basic to write my games. Maybe Python will do the trick. > Oh my god. > Don't ever compare Python to Basic on a python mailing list. > You'll get eaten alive ;-) > > Seriously though, > If you take the time to learn PyGame, it's about the easiest and > best way to write a game in any language (from scratch that is.) > I highly recommend it. > In fact I'm writing a PyGame game right now. > If you're interested in seeing the source at some point, > Just ask. > Although I won't send it just yet because it has no drawing code ATM. > Just game logic. > > Hope ThAt HeLPs. > Don't ever resort to Visual Basic. > If you think something would be easier in VB then ask us > and we will tell you how to do it in Python. > VB is not a good language to learn because it > is the complete opposite of every other programming language. > > I really can't think of a reason to use VB over Python, C++ or Java. > > From jfouhy at paradise.net.nz Thu Jul 28 00:55:10 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 28 Jul 2005 10:55:10 +1200 (NZST) Subject: [Tutor] Select rows and columns in excel In-Reply-To: <20050727154202.75597.qmail@web25402.mail.ukl.yahoo.com> References: <20050727154202.75597.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <1122504910.42e810cedbf48@www.paradise.net.nz> Quoting David Holland : > Dear Tutors, > > I know how to open files in python, however what I want to do is select > some information from an excel spreadsheet and save it as a .dat file. > The bit, I am stuck on is :- > How can I select all rows with a row number greater than x for a certain > column ? If you don't want to go with COM, there are a couple of packages that might be useful: xlrd and pyExcelerator. I've used pyExcelerator; it includes functions to parse a spreadsheet into a dictionary. You could do something like this (untested): import pyExcelerator workBook = pyExcelerator.parse_xls('myfile.xls') sheet = workBook['Sheet1'] # Or whatever the worksheet is called print sheet.items()[:5] # prints something like: ((3, 2), 'foo'), ((1, 0), 'bar'), etc rowsAbove3 = dict([(x, sheet[x]) for x in sheet if x[0] > 3]) # etc -- John. From falcon3166 at hotmail.com Thu Jul 28 01:05:10 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 17:05:10 -0600 Subject: [Tutor] How do I make Python draw? References: Message-ID: Pygame looks solid. I'm sold on it. Maybe I'll be able to code my Guess the Number Sequence Game with it using Python. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: Sent: Wednesday, July 27, 2005 3:04 PM Subject: Re: [Tutor] How do I make Python draw? > > > On Wed, 27 Jul 2005, Nathan Pinno wrote: > >> How do I make Python draw a shape? e.g. a triangle Is there a specific >> module that I have to call, or what is the command(s)? > > Hi Nathan, > > If you'd like to start doing graphical stuff, you might want to look at > the Tkinter module. > > http://www.python.org/doc/lib/module-Tkinter.html > > There's an introduction to it here: > > http://www.pythonware.com/library/tkinter/introduction/ > > > Just to whet your appetite, here's a quick-and-dirty demo program that > should draw a triangle for you: > > ###### > """Draws a triangle on a Tkinter canvas.""" > > from Tkinter import * > canvas = Canvas() > canvas.create_polygon([(1, 1), (1, 200), (100, 100)]) > canvas.pack() > canvas.update_idletasks() > ###### > > > If you want to do more sophisticated graphics stuff, there are alternative > packages, like pygame: > > http://www.pygame.org/news.html > > > If you have more questions, please feel free to ask! > > From falcon3166 at hotmail.com Thu Jul 28 01:11:23 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 17:11:23 -0600 Subject: [Tutor] How do I go about this? [was Re: Who uses input()? [was Re: question on "input"]] References: Message-ID: I first posted my question in this post, but no one seemed to answer me. ----- Original Message ----- From: "Nathan Pinno" To: "Danny Yoo" Cc: ; "Terry Reedy" Sent: Monday, July 18, 2005 7:36 AM Subject: Re: [Tutor] Who uses input()? [was Re: question on "input"] > Danny, > > It sure did, though I wish there was an easier way of coding it than > int(raw_input())! Any ideas would gladly be appreciated. > > By the way, is there any code floating out there that can show how many > possible mixtures there are, e.g. for x0, x1, x2, x3, and a0, a1, a2, and > a3 > for example. If there is, show me it, please. I'm getting confused writing > my MasterMind and don't want to screw up bad, e.g. repeat the same answer > in > a different way. > > Thanks, > Nathan Pinno. > ----- Original Message ----- > From: "Danny Yoo" > To: "Nathan Pinno" > Cc: "Terry Reedy" ; > Sent: Monday, July 18, 2005 2:14 AM > Subject: Re: [Tutor] Who uses input()? [was Re: question on "input"] > > > > > > > > On Mon, 18 Jul 2005, Nathan Pinno wrote: > > > >> I find it easier to remember and faster to code than int(raw_input()). > >> The faster I can code a program, the better in my opinion. So what if > it > >> has a few bugs, I fix them gradually. > > > > Hi Nathan > > > > You're right, just as long as we're writing programs that are only > meant > > to be used by ourselves, and as long as we're sure that it's not > talking > > to the outside world. The driving issue behind getting paranoid is > this: > > it's getting much easier to write programs that we think might be just > for > > ourselves, but which become useful for others. > > > > And as soon as we write programs that other people are going to use, we > > really do have to play by a different set of rules than just ease of > > programming. Some folks were casual about eval(), and look what > happened > > to them: > > > > http://gulftech.org/?node=research&article_id=00088-07022005 > > > > They should have known better. > > > > This problem is not exclusive to programmers in PHP: programmers in > > Python make the same kind of mistakes. As a concrete example, take a > look > > at the comments about the deprecated "SimpleCookie" and "SerialCookie" > > functions: > > > > http://www.python.org/doc/lib/module-Cookie.html > > > > Again, they should have known better. And we should know better. > > > > So we do have a responsibility to state up front that using 'eval' (or > > things that call 'eval' for us) is convenient, but it's not safe. > That's > > why we bug about it every so often. > > > > > > Hope this helps! > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Jul 28 01:11:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 27 Jul 2005 19:11:32 -0400 Subject: [Tutor] Python and Excel In-Reply-To: References: Message-ID: <42E814A4.40806@tds.net> Xabier Gonzalez wrote: > Hello! > > Honestly, I?m new in Python. I wanted to know about the possibility of > importing .txt text files from Excel and manage the contents (creating > graphics...) using Python. What kind of text files? If they are comma-separated-value files, you can read them easily using the csv module. Kent From gnumathetes at gmail.com Thu Jul 28 01:13:49 2005 From: gnumathetes at gmail.com (Don Parris) Date: Wed, 27 Jul 2005 19:13:49 -0400 Subject: [Tutor] Problem with pgbd & datetime In-Reply-To: <20050727174028.GB1890@panix.com> References: <6692614405072707132ced3a48@mail.gmail.com> <20050727174028.GB1890@panix.com> Message-ID: <66926144050727161317a827c8@mail.gmail.com> On 7/27/05, Gabriel Farrell wrote: > Are you using PyGreSQL? import pgdb works fine for me with PyGreSQL. > I'm on Debian but I assume there's a package for it for SUSE. > > gsf > > pg/pgdb are both part of the PyGreSQL distribution. You can choose whichever you want to use, but pgdb supports the 2.0 API, whereas (according to the readme) pg does not. I will try pg when I get back to my box tonight, but would prefer to use pgdb. All of this should have been configured properly when I installed SUSE Linux 9.2 last Fall. The MySQLdb module works fine - the pgdb should as well. Perhaps I should post this over on the DB Sig list. Regards, Don -- DC Parris GNU Evangelist http://matheteuo.org/ gnumathetes at gmail.com "Hey man, whatever pickles your list!" From falcon3166 at hotmail.com Thu Jul 28 01:17:06 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 17:17:06 -0600 Subject: [Tutor] I'm stumped. Message-ID: How do I split the list members up in the following code? What am I forgetting? lista = [] listb = [] lista = raw_input("Enter lista, separated by commas: ") listb = raw_input("Enter listb, separated by commas: ") print lista print listb for item in lista: for other in listb: print item,other Thanks in advance, Nathan Pinno -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050727/e286d51a/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Thu Jul 28 01:25:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 27 Jul 2005 16:25:24 -0700 (PDT) Subject: [Tutor] OT: we won't eat VB programmers for lunch [Was: How do I make Python draw?] In-Reply-To: <006501c592fb$a5a29770$aa0ca8c0@luke> Message-ID: On Wed, 27 Jul 2005, luke wrote: > > Thanks. Will ask if I have any more questions. Maybe I won't have to > > go to Visual Basic to write my games. Maybe Python will do the trick. > > Oh my god. > Don't ever compare Python to Basic on a python mailing list. > > You'll get eaten alive ;-) [text cut] > VB is not a good language to learn because it is the complete opposite > of every other programming language. Hi Luke, I think we should be a bit more sympathetic than that. I once had the very unpleasant experience of being at the receiving end of programming language elitism, and it did not feel nice at all. I guess I'm trying to say: it might not be the best thing to do to vehemently say: "Visual Basic is bad". The problem is that it has a strong tendency to be interpreted as the personal insult: "Visual Basic programmers are bad". And that's not likely to be taken well. *grin* From dyoo at hkn.eecs.berkeley.edu Thu Jul 28 01:28:26 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 27 Jul 2005 16:28:26 -0700 (PDT) Subject: [Tutor] I'm stumped. In-Reply-To: Message-ID: On Wed, 27 Jul 2005, Nathan Pinno wrote: > How do I split the list members up in the following code? Hi Nathan, Try using a string's split() method. For example: ###### >>> "hello world this is a test".split() ['hello', 'world', 'this', 'is', 'a', 'test'] >>> "hello world this is a test".split('i') ['hello world th', 's ', 's a test'] ###### By default, split() will break on whitespace, but we can give an optional parameter to split on a different delimiting string. For more details, see: http://www.python.org/doc/lib/string-methods.html From dyoo at hkn.eecs.berkeley.edu Thu Jul 28 01:39:59 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 27 Jul 2005 16:39:59 -0700 (PDT) Subject: [Tutor] How do I go about this? [was Re: Who uses input()? [was Re: question on "input"]] In-Reply-To: Message-ID: > I first posted my question in this post, but no one seemed to answer me. > > > > It sure did, though I wish there was an easier way of coding it than > > int(raw_input())! Any ideas would gladly be appreciated. Hi Nathan, About the question about int(raw_input()) being a bit verbose, Brian did mention that we can define helper functions to make things less painful. Personal function definitions like this can be very useful: we don't always have to work at a primitive level, but can build on larger concepts. His suggested get_int() function: http://mail.python.org/pipermail/tutor/2005-July/039855.html looks a bit big at first, but we can define it once, store it in a personal library somewhere, and then it'll be available for us from then on. > > By the way, is there any code floating out there that can show how > > many possible mixtures there are, e.g. for x0, x1, x2, x3, and a0, a1, > > a2, and a3 for example. I think people were a little confused what you meant here; can you give us more ideas of what this is for? "Mixture" in English means so many things that it's hard to give concrete answers without seeing more what you mean. Good luck! From jfouhy at paradise.net.nz Thu Jul 28 01:59:15 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu, 28 Jul 2005 11:59:15 +1200 (NZST) Subject: [Tutor] OT: we won't eat VB programmers for lunch [Was: How do I make Python draw?] In-Reply-To: References: Message-ID: <1122508755.42e81fd3a0eb8@www.paradise.net.nz> On Wed, 27 Jul 2005, luke wrote: > VB is not a good language to learn because it is the complete opposite > of every other programming language. If you think that's true, google some time for "esoteric programming languages" :-) Some examples: http://www.muppetlabs.com/~breadbox/bf/ --- an 8 instruction programming language designed with the goal of making the smallest compiler possible. (the AmigaOS compiler was 240 bytes long) http://www.madore.org/~david/programs/unlambda/ --- unLambda: _everything_ is a function. ("Your Functional Programming Language Nightmares Come True") http://en.wikipedia.org/wiki/Malbolge_programming_language --- Malbolge: Designed to be the most horrible programming language conceivable. "Malbolge was so difficult to understand when it arrived that it took two years for the first Malbolge program to appear." http://shakespearelang.sourceforge.net/ --- Programs are in the form of Shakespearean plays. http://compsoc.dur.ac.uk/whitespace/ --- Whitespace: The only legal syntax characters are spaces, tabs and newlines. All other characters are considered comments. There's also one I've seen where your program was an ASCII-art line, and the instructions were given by the angle when your line turned a corner. 180deg was a no-op, so you could make your program as big as you wanted. From alan.gauld at freenet.co.uk Thu Jul 28 02:02:47 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 28 Jul 2005 01:02:47 +0100 Subject: [Tutor] How do I go about this? [was Re: Who uses input()? [wasRe: question on "input"]] References: Message-ID: <000101c59309$9c5ac3f0$8eaa8651@xp> >I first posted my question in this post, but no one seemed to answer >me. Didn't notice because of the subject. A good reason to use meaningful subject lines! >> for example. If there is, show me it, please. I'm getting confused >> writing >> my MasterMind and don't want to screw up bad, e.g. repeat the same >> answer in a different way. This is quite tricky, as I discovered when I wrote the mastermind game code that is on the CD ROM with my book. Here is the approach that I used: # aGuess.value() is the set of 4 numbers. # bulls are black markers, cows are white. # self.goal is the seqience that we are comparing the guess to. def eval(self, aGuess): bulls, cows = 0,0 # create a dictionary of 'what' v 'how many' check = {} for i in aGuess.value(): if check.has_key(i): check[i] = check[i] + 1 else: check[i] = 1 # same for the goal goalchk = {} for i in self.goal: if goalchk.has_key(i): goalchk[i] = goalchk[i] + 1 else: goalchk[i] = 1 # Now total cows = match of guess and goal for i in check.keys(): if i in self.goal: if goalchk[i] > check[i]: cows = cows + check[i] else: cows = cows + goalchk[i] # is it a bull? for i in range(4): item = aGuess.value()[i] if item == self.goal[i]: bulls = bulls + 1 # now reduce cows by number of bulls cows = cows - bulls return (bulls,cows) The full program uses my Games framewoirk as described in the book, but the Target.eval() method is the one that compares the target with the guess. The code above can be optimised quie a bit but I tried to keep it simple enough (and Python v1.5.2 compliant so no True/False values!) for one of my readers to grok it without explanation - its only on the CD ROM not in the text... And if anyone comes up with a simpler algorithm (and I'm sure there is one!) I'll be pleased to see it too. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Jul 28 02:06:19 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 28 Jul 2005 01:06:19 +0100 Subject: [Tutor] I'm stumped. References: Message-ID: <000201c59309$9cb36b40$8eaa8651@xp> Try the split method: >>> '1,2,3,4'.split(',') ['1', '2', '3', '4'] >>> Alan G ----- Original Message ----- From: "Nathan Pinno" To: Sent: Thursday, July 28, 2005 12:17 AM Subject: [Tutor] I'm stumped. How do I split the list members up in the following code? What am I forgetting? lista = [] listb = [] lista = raw_input("Enter lista, separated by commas: ") listb = raw_input("Enter listb, separated by commas: ") print lista print listb for item in lista: for other in listb: print item,other Thanks in advance, Nathan Pinno From alan.gauld at freenet.co.uk Thu Jul 28 02:10:43 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 28 Jul 2005 01:10:43 +0100 Subject: [Tutor] How do I make Python draw? References: <006501c592fb$a5a29770$aa0ca8c0@luke> Message-ID: <000301c59309$9d077eb0$8eaa8651@xp> > Don't ever resort to Visual Basic. > If you think something would be easier in VB then ask us > and we will tell you how to do it in Python. > VB is not a good language to learn because it > is the complete opposite of every other programming language. Not really true anymore. The original VB had a lot of the bad stuff from early BASIC but VB.NET is a very capable modern programming language. I was surprised just how good even the basic VBScript is. Certainly for messing with WSH/COM I find VBScript much easier than Python. > I really can't think of a reason to use VB over Python, C++ or Java. Well VB is much easier to learn than C++ or Java and much safer to use than C++. Python is a better general purpose language than VB but there are places where VB simply gets on with the job where Python needs some nursemaiding Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From falcon3166 at hotmail.com Thu Jul 28 02:16:49 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 18:16:49 -0600 Subject: [Tutor] How do I go about this? [was Re: Who uses input()? [was Re: question on "input"]] References: Message-ID: Here's part of what I'm looking for (got it from a Python program): a b a 2 a 5 a 6 1 b 1 2 1 5 1 6 3 b 3 2 3 5 3 6 4 b 4 2 4 5 4 6 I want to see also !=, ==, and, & nor combos also. 0 != 2 for an example. ----- Original Message ----- From: "Danny Yoo" To: "Nathan Pinno" Cc: "Tutor" Sent: Wednesday, July 27, 2005 5:39 PM Subject: Re: [Tutor] How do I go about this? [was Re: Who uses input()? [was Re: question on "input"]] > > >> I first posted my question in this post, but no one seemed to answer me. >> > >> > It sure did, though I wish there was an easier way of coding it than >> > int(raw_input())! Any ideas would gladly be appreciated. > > Hi Nathan, > > About the question about int(raw_input()) being a bit verbose, Brian did > mention that we can define helper functions to make things less painful. > Personal function definitions like this can be very useful: we don't > always have to work at a primitive level, but can build on larger > concepts. > > His suggested get_int() function: > > http://mail.python.org/pipermail/tutor/2005-July/039855.html > > looks a bit big at first, but we can define it once, store it in a > personal library somewhere, and then it'll be available for us from then > on. > > >> > By the way, is there any code floating out there that can show how >> > many possible mixtures there are, e.g. for x0, x1, x2, x3, and a0, a1, >> > a2, and a3 for example. > > I think people were a little confused what you meant here; can you give us > more ideas of what this is for? "Mixture" in English means so many things > that it's hard to give concrete answers without seeing more what you mean. > > > Good luck! > > From alan.gauld at freenet.co.uk Thu Jul 28 01:47:25 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 28 Jul 2005 00:47:25 +0100 Subject: [Tutor] Why does this NameError appear? References: Message-ID: <000001c59309$9bff0f60$8eaa8651@xp> > Subject: [Tutor] Why does this NameError appear? > lista = [x0, x1, x2, x3] > listb = [a0, a1, a2, a3] So what are x0, x1 etc? You haven't told Python, its never heard of them at this point, so... > lista = [x0, x1, x2, x3] > NameError: name 'x0' is not defined It tells you so. You need to either make the list contents literal values (by making x0, x1 etc strings) or initialise the variables before putting them into the list: x0,x1,x2,x3 = (1,2,3,4) As an example... Alan G. From rabidpoobear at gmail.com Thu Jul 28 02:28:06 2005 From: rabidpoobear at gmail.com (luke) Date: Wed, 27 Jul 2005 19:28:06 -0500 Subject: [Tutor] OT: we won't eat VB programmers for lunch [Was: How do I make Python draw?] References: <1122508755.42e81fd3a0eb8@www.paradise.net.nz> Message-ID: <000e01c5930b$3ab6a9a0$aa0ca8c0@luke> hehe. <3 malbolge. Yeah, I actually learned basic as my first language... I don't mind it. I just don't like it all that much. From falcon3166 at hotmail.com Thu Jul 28 02:33:16 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 18:33:16 -0600 Subject: [Tutor] I'm stumped. References: <000201c59309$9cb36b40$8eaa8651@xp> Message-ID: Thanks. Now it basically works. Now I just have to improve it. ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" ; Sent: Wednesday, July 27, 2005 6:06 PM Subject: Re: [Tutor] I'm stumped. > Try the split method: > >>>> '1,2,3,4'.split(',') > ['1', '2', '3', '4'] >>>> > > Alan G > > ----- Original Message ----- > From: "Nathan Pinno" > To: > Sent: Thursday, July 28, 2005 12:17 AM > Subject: [Tutor] I'm stumped. > > > How do I split the list members up in the following code? What am I > forgetting? > > lista = [] > listb = [] > lista = raw_input("Enter lista, separated by commas: ") > listb = raw_input("Enter listb, separated by commas: ") > print lista > print listb > for item in lista: > for other in listb: > print item,other > > Thanks in advance, > Nathan Pinno > > From falcon3166 at hotmail.com Thu Jul 28 02:36:36 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 18:36:36 -0600 Subject: [Tutor] OT: we won't eat VB programmers for lunch [Was: How doI make Python draw?] References: <1122508755.42e81fd3a0eb8@www.paradise.net.nz> <000e01c5930b$3ab6a9a0$aa0ca8c0@luke> Message-ID: Now that's worth the mention of VB. Glad I have Python, or many of my ideas would stay in my head...hehehe ----- Original Message ----- From: "luke" To: ; "Tutor" Sent: Wednesday, July 27, 2005 6:28 PM Subject: Re: [Tutor] OT: we won't eat VB programmers for lunch [Was: How doI make Python draw?] > hehe. > <3 malbolge. > > Yeah, I actually learned basic as my first language... > I don't mind it. > I just don't like it all that much. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From falcon3166 at hotmail.com Thu Jul 28 02:40:42 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Wed, 27 Jul 2005 18:40:42 -0600 Subject: [Tutor] I'm stumped. References: <000201c59309$9cb36b40$8eaa8651@xp> Message-ID: It works. The program will be found on my webpage at it's new address http://falcon3166.tripod.com in the Downloads page. ----- Original Message ----- From: "Nathan Pinno" To: "Alan G" ; Sent: Wednesday, July 27, 2005 6:33 PM Subject: Re: [Tutor] I'm stumped. > Thanks. Now it basically works. Now I just have to improve it. > ----- Original Message ----- > From: "Alan G" > To: "Nathan Pinno" ; > Sent: Wednesday, July 27, 2005 6:06 PM > Subject: Re: [Tutor] I'm stumped. > > >> Try the split method: >> >>>>> '1,2,3,4'.split(',') >> ['1', '2', '3', '4'] >>>>> >> >> Alan G >> >> ----- Original Message ----- >> From: "Nathan Pinno" >> To: >> Sent: Thursday, July 28, 2005 12:17 AM >> Subject: [Tutor] I'm stumped. >> >> >> How do I split the list members up in the following code? What am I >> forgetting? >> >> lista = [] >> listb = [] >> lista = raw_input("Enter lista, separated by commas: ") >> listb = raw_input("Enter listb, separated by commas: ") >> print lista >> print listb >> for item in lista: >> for other in listb: >> print item,other >> >> Thanks in advance, >> Nathan Pinno >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu Jul 28 12:15:13 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 28 Jul 2005 11:15:13 +0100 Subject: [Tutor] OT: we won't eat VB programmers for lunch [Was: How doImake Python draw?] References: <1122508755.42e81fd3a0eb8@www.paradise.net.nz><000e01c5930b$3ab6a9a0$aa0ca8c0@luke> Message-ID: <007b01c5935d$40967150$8eaa8651@xp> Nathan, I tried to send you a reply about using the 'turtle' module to do your graphics, did you receive it? I sent it from the gane news archive server and its not there and I haven't seen it on the group so I'm wondering if it ever actually went anywhere?... Alan G. ----- Original Message ----- From: "Nathan Pinno" To: "luke" ; ; "Tutor" Sent: Thursday, July 28, 2005 1:36 AM Subject: Re: [Tutor] OT: we won't eat VB programmers for lunch [Was: How doImake Python draw?] > Now that's worth the mention of VB. Glad I have Python, or many of > my ideas would stay in my head...hehehe > ----- Original Message ----- > From: "luke" > To: ; "Tutor" > Sent: Wednesday, July 27, 2005 6:28 PM > Subject: Re: [Tutor] OT: we won't eat VB programmers for lunch [Was: > How doI make Python draw?] > > >> hehe. >> <3 malbolge. >> >> Yeah, I actually learned basic as my first language... >> I don't mind it. >> I just don't like it all that much. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > From cyresse at gmail.com Thu Jul 28 12:23:04 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 28 Jul 2005 22:23:04 +1200 Subject: [Tutor] My first recursive function... Message-ID: Hi all, Spen too much time coding in VBA, so I'm now paranoid about any code I write. Just playing with my first recursive function, and just wanted your experienced opinions on whether it's likely to blow up in my face, as it all seems to work fine out of the gates, and that makes me a little paranoid. For a given list - x = [ ['tag', 'CYP'], ['level', '1.000'], ['value', '3.286'], ['extra', [ ['country', 'CYP'], ['date', [ ['year', '1431'], ['month', 'april'], ['day', '1'] ] ], ['location', '370'], ['success', 'yes'] ] ] ] My data will always be in format [key:info], the question is whether or not value is a list of [key:info]s also. I then want to turn this into a nested dictionary. So, the given function... def isNested(data): dic = {} for (key, info) in data: if isinstance(info], list) and isinstance(info[0], list): dic[key] = isNested(info) else: dic[key] = info return dic ...seems to work alright, but as I've already run astray of the the isNested(data, dic = {} ) gotcha, I'm just covering my bases here. Are there any other pitfalls with recursion I need to watch for? (I'm also expecting the occasional list that is simply a list of strings, hence the and clause in the isinstance check.) If it's all good, then I'm stoked, as I was writing some very unPythonic code before this. (I had one of those moments when you stare at your code, realise it looks ugly and complicated, and realise that means you're doing it the wrong way. File > New time, I call it.) Thanks for any feedback, Liam -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050728/fb0e74e5/attachment.htm From kent37 at tds.net Thu Jul 28 13:04:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Jul 2005 07:04:18 -0400 Subject: [Tutor] My first recursive function... In-Reply-To: References: Message-ID: <42E8BBB2.9020107@tds.net> Liam Clarke wrote: > Just playing with my first recursive function, and just wanted your > experienced opinions on whether it's likely to blow up in my face, > as it all seems to work fine out of the gates, and that makes me a > little paranoid. > > For a given list - > > x = [ ['tag', 'CYP'], > ['level', '1.000'], > ['value', '3.286'], > ['extra', [ ['country', 'CYP'], ['date', [ ['year', '1431'], > ['month', 'april'], ['day', '1'] ] ], ['location', '370'], ['success', > 'yes'] ] ] ] > > My data will always be in format [key:info], the question is whether or > not value is a list of [key:info]s also. I then want to turn this into > a nested dictionary. [key, info] you mean... > So, the given function... > > def isNested(data): > dic = {} > for (key, info) in data: > if isinstance(info], list) and isinstance(info[0], list): > dic[key] = isNested(info) > else: > dic[key] = info > > return dic > > ...seems to work alright, but as I've already run astray of the the > isNested(data, dic = {} ) gotcha, I'm just covering my bases here. Looks good to me other than the name :-) I would call it toDict() or toNestedDict() maybe; IMO a function named isXXX should just return True or False. > Are there any other pitfalls with recursion I need to watch for? > (I'm also expecting the occasional list that is simply a list of > strings, hence the and clause in the isinstance check.) The biggest pitfall I can think of is that you get into an infinite recursion. This can happen when the recursive call for some reason uses the same arguments as were passed to the caller, or when the exit condition is never met. I think you're fine on both counts here. Does this mean you gave up on pyparsing Dict? From project5 at redrival.net Thu Jul 28 13:28:40 2005 From: project5 at redrival.net (Andrei) Date: Thu, 28 Jul 2005 11:28:40 +0000 (UTC) Subject: [Tutor] My first recursive function... References: <42E8BBB2.9020107@tds.net> Message-ID: Liam Clarke gmail.com> writes: > Are there any other pitfalls with recursion I need to watch for? Not just infinite recursion, but recursion that exceeds the maximum recursion depth (1000 on my system). You can add a counter parameter to your recursive function and stop recursing if the function finds it has called itself too many times - helps against infinite recursion too. >>> def a(i): ... i += 1 ... if i < 500: ... a(i) >>> a(0) If you try the function above without the if condition, it will generate a RuntimeError. Yours, Andrei From cyresse at gmail.com Thu Jul 28 13:39:02 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu, 28 Jul 2005 23:39:02 +1200 Subject: [Tutor] My first recursive function... In-Reply-To: <42E8BBB2.9020107@tds.net> References: <42E8BBB2.9020107@tds.net> Message-ID: > [key, info] you mean... Oops. That'd be the one. Looks good to me other than the name :-) I would call it toDict() or > toNestedDict() maybe; IMO a function named isXXX should just return True or > False. Yah, it started off as a boolean return, and then I decided to go for the big one, so to speak, having heard recursion spoken in hushed awe and/or spat out like a swear word. > Are there any other pitfalls with recursion I need to watch for? > > (I'm also expecting the occasional list that is simply a list of > > strings, hence the and clause in the isinstance check.) > > The biggest pitfall I can think of is that you get into an infinite > recursion. This can happen when the recursive call for some reason uses the > same arguments as were passed to the caller, or when the exit condition is > never met. I think you're fine on both counts here. Ah, cool. Now I can run this over my full data set and see what interesting exceptions and errors I get. Does this mean you gave up on pyparsing Dict? To some extent. I could use it, but to be honest, the my limited understanding means the effort:effect ratio doesn't make it worth my while. The author of pyparsing helped me out amazingly, my parse time for a full set of data dropped from nearly 6 hours (!) to 3 minutes once he straightened out my grammar, and I think I've taken enough of his time as it is. My problem is a lot of repeated items like merchant = { tag = LAT,...}so to utilise a pp Dict, I'd have to implement functions into the grammar to pop the the tag name to use as a dictionary key, and I'd rather not mess with the grammar any further, in case I break it, or slow it down. :S My understanding of pyparsing is basic, to say the least, so I'm following the path of least resistance here, as I get a list returned which is (now) simple enough to turn into a dictionary. There's some non-consistent 'special cases' in the data structure, which I can handle a lot simpler when I've written the function which is creating my dictionary. Regards, Liam Clarke _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050728/cdea0643/attachment.htm From davholla2002 at yahoo.co.uk Thu Jul 28 16:38:04 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu, 28 Jul 2005 15:38:04 +0100 (BST) Subject: [Tutor] Select rows and columns in excel In-Reply-To: Message-ID: <20050728143804.31544.qmail@web25401.mail.ukl.yahoo.com> Danny and John, Thanks for the pointers. As I am leaving the project where I need to do this tomorrow, I don't think I will have time to do this, but thanks for the help anyway. David Danny Yoo wrote: On Wed, 27 Jul 2005, David Holland wrote: > I know how to open files in python, however what I want to do is select > some information from an excel spreadsheet and save it as a .dat file. Hi David, Excel spreadsheets are a bit more difficult to work with. They're not plain text files, but have their own internal binary format, so you'll probably need a library to deal with them. Many people deal with Excel by either converting the files to something plain-textish, like the 'csv' format, or they get Python to talk to Excel directly. If you can output your excel spreadsheet in 'csv' format, then Python's 'csv' module should be useful: http://www.python.org/doc/lib/module-csv.html and doing the selection should just be a matter of skipping enough rows, in the file, and then paying attention to the particular column you want. But if you want to go another route --- to talk closely with Excel --- that might take some more involvement, since it's so tightly bound with Windows programming. The book "Python Programming on Win32" has a chapter on how to talk to Excel through Python: http://www.oreilly.com/catalog/pythonwin32/ and if you're interested in this approach, you may want to talk with the python-win32 folks: http://mail.python.org/mailman/listinfo/python-win32 Hope this helps! --------------------------------- How much free photo storage do you get? Store your holiday snaps for FREE with Yahoo! Photos. Get Yahoo! Photos -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050728/e9219b74/attachment-0001.htm From negroup at gmail.com Thu Jul 28 16:48:47 2005 From: negroup at gmail.com (Negroup -) Date: Thu, 28 Jul 2005 16:48:47 +0200 Subject: [Tutor] Basic class inheritance Message-ID: <2fdabf19050728074820c9e1b@mail.gmail.com> I have this class: >>> class A: ... def __init__(self, blank=False, editable=True, name='foo'): ... self.blank = blank ... self.editable = editable ... self.name = name ... >>> a = A() >>> a.blank, a.editable, a.name (False, True, 'foo') All as expected. Now I want that another class, call it B, inherits all behaviours/attributes except for the attribute blank, that now I want to be False. This should be possible overriding __init__ method no? >>> class B(A): ... def __init__(self, blank=True, editable=True, name='foo'): ... self.blank = blank ... self.editable = editable ... self.name = name ... >>> b = B() >>> b.blank, b.editable, b.name (True, True, 'foo') However, is it possible to achieve this without rewrite the whole __init__ method, but just overriding parts of it? For __init__ very long it would be an unuseful duplication of code.., so I'm sure there is a trivial solution! Can you help to figure it out? Thanks From work at infomaniak.ch Thu Jul 28 16:56:43 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Thu, 28 Jul 2005 16:56:43 +0200 Subject: [Tutor] python learning Message-ID: <20050728145643.GB28220@obs.unige.ch> hi, 1)OB I'm learning for almost a year and half python. this is my first language. I'm fine with classes, definition... But now I'm trying to understand better things as: static method class method and the use of metaclass. Does some one of you knows about a compilations of small snippets showing how things works! an url ? because I'm trying to work with sqlobject, and I have to tell my self that I'm far away of a good comprehension of it.. : ( 2) Sometimes, I do think that it will help a lot, to have such compilations. So that people can scan it, test them very easily. Such snippet shall have some use of them (case that work, case that do not work) some explanation in which can we can use them and so on. For example, what I've learned recently. module.py class test(object): def __init__(self): self.dico={} def setname(self,name, value): self.dico[name]=value def dico(self): return printDico testInstance=test() # * setname=testInstance.setname # ** dico=testInstance.dico # *** in the python interpreter. import module module.setname('key1','value1') module.dico() del module # so I've supposed that the garbage collector will destruct this. from module import dico dico() # tintintammm and badaboum there are still there So I imagine, that when you import this module. ``testInstance'' is created in the object space, but it is not assigned to the namespace. So the only way to destruct such module, will be within the module. I found that such module act has a singleton Ced. -- Cedric BRINER Geneva - Switzerland From kent37 at tds.net Thu Jul 28 17:00:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Jul 2005 11:00:48 -0400 Subject: [Tutor] Basic class inheritance In-Reply-To: <2fdabf19050728074820c9e1b@mail.gmail.com> References: <2fdabf19050728074820c9e1b@mail.gmail.com> Message-ID: <42E8F320.8030805@tds.net> Negroup - wrote: > I have this class: > >>>>class A: > > ... def __init__(self, blank=False, editable=True, name='foo'): > ... self.blank = blank > ... self.editable = editable > ... self.name = name > ... > >>>>a = A() >>>>a.blank, a.editable, a.name > > (False, True, 'foo') > > All as expected. > > Now I want that another class, call it B, inherits all > behaviours/attributes except for the attribute blank, that now I want > to be False. > > This should be possible overriding __init__ method no? > >>>>class B(A): > > ... def __init__(self, blank=True, editable=True, name='foo'): > ... self.blank = blank > ... self.editable = editable > ... self.name = name > ... > >>>>b = B() >>>>b.blank, b.editable, b.name > > (True, True, 'foo') > > However, is it possible to achieve this without rewrite the whole > __init__ method, but just overriding parts of it? The usual way to do this is to forward to the __init__() method of the superclass for the common part. In your case you are just specializing the default arguments so all you have to do is pass the args to A.__init__(): class B(A): def __init__(self, blank=True, editable=True, name='foo'): A.__init__(self, blank, editable, name) Kent From work at infomaniak.ch Thu Jul 28 17:26:02 2005 From: work at infomaniak.ch (Cedric BRINER) Date: Thu, 28 Jul 2005 17:26:02 +0200 Subject: [Tutor] Basic class inheritance In-Reply-To: <42E8F320.8030805@tds.net> References: <2fdabf19050728074820c9e1b@mail.gmail.com> <42E8F320.8030805@tds.net> Message-ID: <20050728152602.GE28220@obs.unige.ch> > > However, is it possible to achieve this without rewrite the whole > > __init__ method, but just overriding parts of it? > > The usual way to do this is to forward to the __init__() method of the superclass for the common part. In your case you are just specializing the default arguments so all you have to do is pass the args to A.__init__(): > > class B(A): > def __init__(self, blank=True, editable=True, name='foo'): > A.__init__(self, blank, editable, name) > I thought such kind of thing should be writted like: class A(object): def __init__(self, blank=False, editable=True, name='foo'): self.blank = blank self.editable = editable self.name = name class B(A): def __init__(self, blank=True, editable=True, name='foo'): super(B, self).__init__(blank, editable, name) Ced. -- Cedric BRINER Geneva - Switzerland From kent37 at tds.net Thu Jul 28 17:41:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Jul 2005 11:41:43 -0400 Subject: [Tutor] Basic class inheritance In-Reply-To: <20050728152602.GE28220@obs.unige.ch> References: <2fdabf19050728074820c9e1b@mail.gmail.com> <42E8F320.8030805@tds.net> <20050728152602.GE28220@obs.unige.ch> Message-ID: <42E8FCB7.9030208@tds.net> Cedric BRINER wrote: >>>However, is it possible to achieve this without rewrite the whole >>>__init__ method, but just overriding parts of it? >> >>The usual way to do this is to forward to the __init__() method of the superclass for the common part. In your case you are just specializing the default arguments so all you have to do is pass the args to A.__init__(): >> >>class B(A): >> def __init__(self, blank=True, editable=True, name='foo'): >> A.__init__(self, blank, editable, name) >> > > > I thought such kind of thing should be writted like: > class A(object): > def __init__(self, blank=False, editable=True, name='foo'): > self.blank = blank > self.editable = editable > self.name = name > > class B(A): > def __init__(self, blank=True, editable=True, name='foo'): > super(B, self).__init__(blank, editable, name) Yes, that is the more modern way to do it for new-style classes. In the original example, class A does not inherit from object so I used the older style. Kent From negroup at gmail.com Thu Jul 28 17:52:08 2005 From: negroup at gmail.com (Negroup -) Date: Thu, 28 Jul 2005 17:52:08 +0200 Subject: [Tutor] Basic class inheritance In-Reply-To: <42E8FCB7.9030208@tds.net> References: <2fdabf19050728074820c9e1b@mail.gmail.com> <42E8F320.8030805@tds.net> <20050728152602.GE28220@obs.unige.ch> <42E8FCB7.9030208@tds.net> Message-ID: <2fdabf1905072808522b8a5404@mail.gmail.com> [cut] > > Yes, that is the more modern way to do it for new-style classes. In the original example, class A does not inherit from object so I used the older style. > Thanks guys for your answers, it's clear (even if I wouldn't be able to figure it out by my own). About old style/new style classes, do you suggest some *simple* reading? Documents found here http://www.python.org/doc/newstyle.html are too technical for me now.. TIA From count0.djd at gmail.com Thu Jul 28 18:24:00 2005 From: count0.djd at gmail.com (David Driver) Date: Thu, 28 Jul 2005 11:24:00 -0500 Subject: [Tutor] dictionary question Message-ID: <22803ae205072809245ed23372@mail.gmail.com> The following code: print str(dict(a=1,b=2,c=-1)) print str(dict(a=1,c=-1,b=2)) print str(dict(c=-1,a=1,b=2)) print str(dict(b=2,a=1,c=-1)) print str(dict(b=2,c=-1,a=1)) print print str(dict(a=1,b=2,c=23)) print str(dict(a=1,c=23,b=2)) print str(dict(c=23,a=1,b=2)) print str(dict(b=2,a=1,c=23)) print str(dict(b=2,c=23,a=1)) print print str(dict(a=1,b=2,c='booga')) print str(dict(a=1,c='booga',b=2)) print str(dict(c='booga',a=1,b=2)) print str(dict(b=2,a=1,c='booga')) print str(dict(b=2,c='booga',a=1)) Produces: {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': -1, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 23, 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} {'a': 1, 'c': 'booga', 'b': 2} Could I rely on creating hashes to use as keys in bsddb this way? If I create a dictionary with the same keys, will it str the same way? Thanks! -- *********************************** See there, that wasn't so bad. *********************************** From gsf at panix.com Thu Jul 28 19:12:22 2005 From: gsf at panix.com (Gabriel Farrell) Date: Thu, 28 Jul 2005 13:12:22 -0400 Subject: [Tutor] Problem with pgbd & datetime In-Reply-To: <66926144050727161317a827c8@mail.gmail.com> References: <6692614405072707132ced3a48@mail.gmail.com> <20050727174028.GB1890@panix.com> <66926144050727161317a827c8@mail.gmail.com> Message-ID: <20050728171222.GA18065@panix.com> On Wed, Jul 27, 2005 at 07:13:49PM -0400, Don Parris wrote: > pg/pgdb are both part of the PyGreSQL distribution. You can choose > whichever you want to use, but pgdb supports the 2.0 API, whereas > (according to the readme) pg does not. I will try pg when I get back > to my box tonight, but would prefer to use pgdb. I use pgdb as well, for the same reason. > All of this should have been configured properly when I installed > SUSE Linux 9.2 last Fall. The MySQLdb module works fine - the pgdb > should as well. Perhaps I should post this over on the DB Sig list. Debian lists a package called python-egenix-mxdatetime as a dependency for python-pygresql, and that in turn depends on python-egenix-mxtools. I believe you need to install these modules for pygresql to work, as mxDateTime is not the same as datetime. The site for mxDateTime is http://www.egenix.com/files/python/mxDateTime.html if you need to install it manually, but there should be a SUSE package for it. *Quick look through SUSE site.* Yep, here it is: http://www.novell.com/products/linuxpackages/professional/python-egenix-mx-base.html I hope that gets it working. gsf From kent37 at tds.net Thu Jul 28 19:13:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Jul 2005 13:13:27 -0400 Subject: [Tutor] dictionary question In-Reply-To: <22803ae205072809245ed23372@mail.gmail.com> References: <22803ae205072809245ed23372@mail.gmail.com> Message-ID: <42E91237.8040002@tds.net> David Driver wrote: > If I > create a dictionary with the same keys, will it str the same way? This behaviour is not guaranteed and I wouldn't depend on it. It can break if any other operations have happened on the dict; for example >>> d=dict(a=1,b=2,c=23) >>> str(d) "{'a': 1, 'c': 23, 'b': 2}" >>> for i in range(100): ... d[i]=i ... >>> for i in range(100): ... del d[i] ... >>> str(d) "{'c': 23, 'b': 2, 'a': 1}" The order could also change between Python versions if the internal implementation of dict changes. How about >>> str(sorted(d.items())) "[('a', 1), ('b', 2), ('c', 23)]" Kent From dyoo at hkn.eecs.berkeley.edu Thu Jul 28 19:16:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 28 Jul 2005 10:16:28 -0700 (PDT) Subject: [Tutor] matplotlib (pylab) backends In-Reply-To: Message-ID: On Wed, 27 Jul 2005, Pujo Aji wrote: > I write a program which launch pylab from windows GUI (using wxpython). > I found some problem here. > > If I use the default backends program in matplotlibrc which is TkAgg > I have this result: > 1. I click button the plot is showed > 2. I close the plot > 3. I click the button to show the plot the second time. it shows the > plot but I can't closed it (it hangs. Hi Pujo, Without seeing what you've actually written, I'm not sure how effectively we can help you here. If you can, point us to code that we can use to reliably reproduce your problem. Otherwise, we really can't say at all what's happening here. If I were forced to guess, I guess that some resource is not being properly set to the initial state when the plot is first closed. Since many of us here have little experience with the matplotlib package, you may want to check with someone on the matplotlib-users mailing list to see if someone there can help you: http://lists.sourceforge.net/lists/listinfo/matplotlib-users From alan.gauld at freenet.co.uk Thu Jul 28 19:20:38 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 28 Jul 2005 18:20:38 +0100 Subject: [Tutor] How do I make Python draw? Message-ID: <00c901c59398$acb2fad0$8eaa8651@xp> I found my message to Nathan, looks like I pressed the wrong reply button in the Outlook Express newsreader. I thought I'd forward it to the list since: a) we don't often discuss the turtle module and b) I ask a question at the end that I'd like an answer to! :-) Alan G. ----- Original Message ----- From: "Alan G" To: "Nathan Pinno" Sent: Wednesday, July 27, 2005 10:15 PM Subject: Re: How do I make Python draw? > >> How do I make Python draw a shape? e.g. a triangle Is there a >> specific >> module that I have to call, or what is the command(s)? > > There are several options, most involve using a GUI framework to > create > a Canvas widget and drawing inside that. > > However for your purposes a more interesting route might be to try > the Python turtle module, it does the GUI bits for you and allows > you > to draw graphics by commanding a 'turtle' pen to move on the screen. > > If you know logo or any other turtle implementation it will be easy, > if not an interesting lrearning experience and a fairly easy wauy of > drawing basic geometric shapes... > > You can play with turtle by importing it at a >>> prompt and > issueing > commands. Here is a session to draw an equilateral triangle: > >>>> import turtle as t >>>> p = t.Pen() >>>> p.reset() >>>> p.down() >>>> for side in range(3): > ... p.forward(100) > ... p.left(120) > ... > > And attached is a jpeg of the resultant canvas. > (The righward horizontal line seems to be a buglet in the module > - does anyone know how to get rid of it?) > > HTH, > > Alan G. > -------------- next part -------------- A non-text attachment was scrubbed... Name: turtle.jpg Type: image/jpeg Size: 8279 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050728/2703f30f/turtle.jpg From tpc at csua.berkeley.edu Thu Jul 28 19:45:02 2005 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu, 28 Jul 2005 10:45:02 -0700 (PDT) Subject: [Tutor] try except continue Message-ID: <20050728104324.U38289-100000@localhost.cryptic.com> hey guys, so I've been trying to get my head around the try except statement in Python, and ideally what I'd like is for my procedural program, when it runs through its steps and encounters an error, to log the error and pick up where it left off and keep going. According to this link, 'continue' is allowed within an except or finally: http://python.active-venture.com/ref/continue.html I tried to run the following code, expecting to catch a NameError and continuing on: def someFunc00(): someModulo = 6%2 print someModulus def someFunc01(): print "yeah!" def someFunc02(): print "baby let's go" def someFunc03(): someInt = 2+2 print "someInt is: ", someInt def someProcedure(): someFunc00() someFunc01() someFunc02() someFunc03() # copy and paste the following into IDLE, which on my machine often #crashes for an unknown reason, so I've taken to creating a harness that #imports the required library and then runs the desired programs to test #the desired behavior if __name__ == "__main__": import testTryCatch try: testTryCatch.someProcedure() except: print "encountered error" continue but I get the following error: SyntaxError: 'continue' not properly in loop What am I doing wrong ? From alan.gauld at freenet.co.uk Thu Jul 28 19:48:25 2005 From: alan.gauld at freenet.co.uk (Alan G) Date: Thu, 28 Jul 2005 18:48:25 +0100 Subject: [Tutor] Basic class inheritance References: <2fdabf19050728074820c9e1b@mail.gmail.com> <42E8F320.8030805@tds.net> Message-ID: <00f101c5939c$8e640cf0$8eaa8651@xp> >> Now I want that another class, call it B, inherits all >> behaviours/attributes except for the attribute blank, that now I >> want >> to be False. > class B(A): > def __init__(self, blank=True, editable=True, name='foo'): > A.__init__(self, blank, editable, name) except that instead of passimng blank to A.__init__ you should pass False. That way blank will always be False as required! ie: A.__init__(self, False, editable, name) HTH, Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Jul 28 19:51:58 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 28 Jul 2005 10:51:58 -0700 (PDT) Subject: [Tutor] try except continue In-Reply-To: <20050728104324.U38289-100000@localhost.cryptic.com> Message-ID: On Thu, 28 Jul 2005 tpc at csua.berkeley.edu wrote: > import testTryCatch > try: > testTryCatch.someProcedure() > except: > print "encountered error" > continue > > but I get the following error: > > SyntaxError: 'continue' not properly in loop > > What am I doing wrong ? Hi Tpc, What did you expect to happen when we hit the continue statement? It'll help to know what you wanted to happen, so that we can better understand the problem. According to: http://www.python.org/doc/ref/continue.html 'continue' is only effective if we're in a loop, so the error message is perfectly true. So I think we need to know more about what you are trying to do. Best of wishes! From kent37 at tds.net Thu Jul 28 20:01:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Jul 2005 14:01:11 -0400 Subject: [Tutor] Basic class inheritance In-Reply-To: <00f101c5939c$8e640cf0$8eaa8651@xp> References: <2fdabf19050728074820c9e1b@mail.gmail.com> <42E8F320.8030805@tds.net> <00f101c5939c$8e640cf0$8eaa8651@xp> Message-ID: <42E91D67.9090100@tds.net> Alan G wrote: >>> Now I want that another class, call it B, inherits all >>> behaviours/attributes except for the attribute blank, that now I want >>> to be False. > > >> class B(A): >> def __init__(self, blank=True, editable=True, name='foo'): >> A.__init__(self, blank, editable, name) > > > except that instead of passimng blank to A.__init__ you should pass False. > That way blank will always be False as required! ie: > > A.__init__(self, False, editable, name) It's not really clear what the OP wants - whether blank should always be False, or have a default value of False. Actually the example shows blank having a default value of True for B's which makes more sense than the text since the default value of blank for A's is False. Anyway, if you want to change the default value do it the way I showed originally (above); if you want blank to always be False (or True) you should remove the parameter from the definition of B.__init__() like this: class B(A): def __init__(self, editable=True, name='foo'): A.__init__(self, True, editable, name) Kent From chris at shenton.org Thu Jul 28 19:59:26 2005 From: chris at shenton.org (Chris Shenton) Date: Thu, 28 Jul 2005 13:59:26 -0400 Subject: [Tutor] range()-like function to generate aa, ... az, ..., zz ? Message-ID: <86wtna6cch.fsf@PECTOPAH.shenton.org> I'm looking for a range()-like function which could generate a list of character-oriented tokens, like to iterate over all two-character sequences like: pseudorange('aa', 'zz') would generate: aa, ab, ..., az, ba, ..., za, ..., zz range() doesn't do character iteration, and I'm sure I could write a dumb function to do it, but was wondering if there was something more generic -- e.g., later I might want pseudorange('aaa', 'mmm') Anyway, is there a function to iterate through a range of character strings similar to this? Thanks. From zamb at saudi.net.sa Thu Jul 28 20:40:45 2005 From: zamb at saudi.net.sa (ZIYAD A. M. AL-BATLY) Date: Thu, 28 Jul 2005 21:40:45 +0300 Subject: [Tutor] range()-like function to generate aa, ... az, ..., zz ? In-Reply-To: <86wtna6cch.fsf@PECTOPAH.shenton.org> References: <86wtna6cch.fsf@PECTOPAH.shenton.org> Message-ID: <1122576046.15608.1.camel@localhost.localdomain> On Thu, 2005-07-28 at 13:59 -0400, Chris Shenton wrote: > I'm looking for a range()-like function which could generate a list of > character-oriented tokens, like to iterate over all two-character > sequences like: > > pseudorange('aa', 'zz') would generate: > aa, ab, ..., az, ba, ..., za, ..., zz > > range() doesn't do character iteration, and I'm sure I could write a > dumb function to do it, but was wondering if there was something more > generic -- e.g., later I might want > > pseudorange('aaa', 'mmm') > > Anyway, is there a function to iterate through a range of character > strings similar to this? > > Thanks. My small controbution to PyTuyo: >>> twoLetterSequence = [ "%c%c" % (x, y) for x in range(ord('a'), ord('z')+1) for y in range(ord('a'), ord('z')+1)] Ziyad. From 3dbernard at gmail.com Thu Jul 28 21:08:49 2005 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 28 Jul 2005 15:08:49 -0400 Subject: [Tutor] Regular expression error Message-ID: <61d0e2b405072812081d69b8e6@mail.gmail.com> Hello, I'm using regular expressions to check if arguments of a function are valid. When I run the code below, I get an error. Basically, what the regular expression "should" expect is either an integer, or an integer followed by a letter (string). I convert the tested argument to a string to make sure. Below is the code. # Create regular expression to match oPattern = re.compile( r"(\d+|\d+\D)", re.IGNORECASE ) # Iterate provided arguments for oArg in aArgs: # Attempt to match the argument to the regular expression oMatch = re.match( str( oArg ), 0 ) The error I get is this: #ERROR : Traceback (most recent call last): # File "