From kb1pkl at aim.com Thu Oct 1 03:53:52 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 30 Sep 2009 21:53:52 -0400 Subject: [Tutor] UnboundLocalError and Break Message-ID: <4AC40BB0.1090201@aim.com> Here is my code that is being used/affected by the block that is erroring. The rest is superfluous, and does not affect it: intel = 10 #Define the abilities. strn = 10 con = 10 dex = 10 wis = 10 exp = 0 cha = 10 playHp = 20 melWep = 1 # A sword rngWep = 1 #A bow attack = dex+strn/2 #If they hit! melDmg = strn+1+melWep/2 #Melee damage deff = (con/3)+(dex/2)+6 #Defense rngDmg = dex+1+rngWep/2 #Ranged damage print "You are hiking through the woods one day, and you are jumped by a goblin!" #The beginning of the adventure print "Do you want to 1. Attack w/sword, 2. Attack w/bow, 3. Flee, or 4. Nothing" gob1Hp = 10 #First monsters hitpoints def monsAttk (damage, attack,playHp): #A monsters attack if attack > deff: #Monster hit playHp -= damage #Player takes damage (I think...I will have to work that out) print "You have sustained", damage, "damage, with", damage-playHp, "remaining" #Inform player of their status def gmAttack(monHp, monDef, monAgil) : #A player attack op1 = raw_input("Your choice?") while op1 != "5": #Just a loop that you can break out of (possibly...working that out) if op1 == '1': #Option 1 if attack + 10 > monDef : #If the player hits monHp-= melDmg #Monster takes damage print "you did", melDmg, "damage! It now has", monHp, "health left!" #Inform player how much health it has. monsAttk(4, 15) #Monster attacks elif op1 == '2': #Option 2 if attack + 10 >monDef: #If you hit the monster monHp -= rngDmg #Monster takes damage print "you did", rngDmg, "damage! It now has", monHp, "health left!" #Inform player how much health it has monsAttk(4, 15) #Monster attacks elif op1 == '3' : #Option 3 if attack + dex > monAgil : #If they can escape print "Thou hast fled!" #They have fled! break #Stop the loop (I think. Can someone please inform me as of how this works? I have looked online...it makes no sense to me) elif op1 == '4' : #Option 4...the dumb one monsAttk(4, 15) #Monster attacks monsAttk(4,15) #Monster attacks again, cause they are dumb print "You should attack..." #Inform them of their stupidity else : #Well, what the hell did they pick? print "Unknown option, try again!" #Inform them they didn't pick a valid option while gob1Hp >= 0: #Well it is still alive gmAttack(gob1Hp,13,15) #player attacks if gob1Hp <= 0.5 : #if it dies print "Gratz! You have gotten 5 exp! You only have", 100-exp, "exp left till lv 1!" #print their experience exp += 5 #Give them exp If you catch an error besides what is wrong, please don't point it out, as I would like to work it out myself, unless marked in the comments. But this one is evading me...I have playHp defined at the beginning, and I am getting this error : Traceback (most recent call last): File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", line 183, in gmAttack(gob1Hp,13,15) File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", line 167, in gmAttack monsAttk(4, 15) File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", line 157, in monsAttk playHp -= damage UnboundLocalError: local variable 'playHp' referenced before assignment If you could please help me, that would be great. I'm just trying to get the game engine working, as of now, it is 30% done, with Inventory, Equipment, and a more sophisticated and simpler code to come. It's a bit of a mess now... -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From kb1pkl at aim.com Thu Oct 1 04:00:59 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 30 Sep 2009 22:00:59 -0400 Subject: [Tutor] UnboundLocalError and Break In-Reply-To: References: <4AC40BB0.1090201@aim.com> Message-ID: <4AC40D5B.9050407@aim.com> Luke Paireepinart wrote: > If your code's more than 10 lines long or so, put it on pastebin.com > and send us the link rather than inlining the > whole thing. You could also send it as an attachment. > Your formatting is all screwed up and I can't read the code at all, > but I have an idea about your error. > > Hmmm...thats odd. I didn't do anything different....but I can do > that.http://pastebin.com/m518f612f > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From bgailer at gmail.com Thu Oct 1 04:13:52 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 30 Sep 2009 22:13:52 -0400 Subject: [Tutor] UnboundLocalError and Break In-Reply-To: <4AC40BB0.1090201@aim.com> References: <4AC40BB0.1090201@aim.com> Message-ID: <4AC41060.7030306@gmail.com> Corey Richardson wrote: > Here is my code that is being used/affected by the block that is > erroring. The rest is superfluous, and does not affect it: Something is screwy. def monsAttk (damage, attack,playHp): # function expects 3 arguments monsAttk(4, 15) # passes 2 arguments That should raise TypeError: monsAttk() takes exactly 3 argument (2 given) So something else is awry. BTW the fact that you assigned playHp = 20 has no effect in the function. You redefined playHp as a local variable in the def statement. > > intel = 10 #Define the abilities. > strn = 10 > con = 10 > dex = 10 > wis = 10 > exp = 0 > cha = 10 > playHp = 20 > melWep = 1 # A sword > rngWep = 1 #A bow > attack = dex+strn/2 #If they hit! > melDmg = strn+1+melWep/2 #Melee damage > deff = (con/3)+(dex/2)+6 #Defense > rngDmg = dex+1+rngWep/2 #Ranged damage > print "You are hiking through the woods one day, and you are jumped > by a goblin!" #The beginning of the adventure > print "Do you want to 1. Attack w/sword, 2. Attack w/bow, 3. Flee, > or 4. Nothing" > gob1Hp = 10 #First monsters hitpoints > def monsAttk (damage, attack,playHp): #A monsters attack if > attack > deff: #Monster hit playHp -= damage #Player > takes damage (I think...I will have > to work that out) > print "You have sustained", damage, "damage, with", > damage-playHp, "remaining" #Inform player of their status > def gmAttack(monHp, monDef, monAgil) : #A player attack > op1 = raw_input("Your choice?") > while op1 != "5": #Just a loop that you can break out of > (possibly...working that out) if op1 == '1': #Option 1 > if attack + 10 > monDef : #If the player hits > monHp-= melDmg #Monster takes damage > print "you did", melDmg, "damage! It now has", > monHp, "health left!" #Inform player how much health it has. > monsAttk(4, 15) #Monster attacks elif > op1 == '2': #Option 2 if attack + 10 >monDef: #If you > hit the monster > monHp -= rngDmg #Monster takes damage > print "you did", rngDmg, "damage! It now has", > monHp, "health left!" #Inform player how much health it has > monsAttk(4, 15) #Monster attacks > elif op1 == '3' : #Option 3 > if attack + dex > monAgil : #If they can escape > print "Thou hast fled!" #They have fled! > break #Stop the loop (I think. Can someone please inform > me as of how this works? I have looked online...it makes no sense > to me) > elif op1 == '4' : #Option 4...the dumb one > monsAttk(4, 15) #Monster attacks > monsAttk(4,15) #Monster attacks again, cause they are dumb > print "You should attack..." #Inform them of their > stupidity > else : #Well, what the hell did they pick? > print "Unknown option, try again!" #Inform them they > didn't pick a valid option > while gob1Hp >= 0: #Well it is still alive > gmAttack(gob1Hp,13,15) #player attacks > if gob1Hp <= 0.5 : #if it dies > print "Gratz! You have gotten 5 exp! You only have", 100-exp, > "exp left till lv 1!" #print their experience > exp += 5 #Give them exp > > > If you catch an error besides what is wrong, please don't point it > out, as I would like to work it out myself, unless marked in the > comments. But this one is evading me...I have playHp defined at the > beginning, and I am getting this error : > > Traceback (most recent call last): > File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", > line 183, in > gmAttack(gob1Hp,13,15) > File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", > line 167, in gmAttack > monsAttk(4, 15) > File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", > line 157, in monsAttk > playHp -= damage > UnboundLocalError: local variable 'playHp' referenced before > assignment > > If you could please help me, that would be great. I'm just trying to > get the game engine working, as of now, it is 30% done, with > Inventory, Equipment, and a more sophisticated and simpler code to > come. It's a bit of a mess now... > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From davea at ieee.org Thu Oct 1 05:13:57 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 30 Sep 2009 23:13:57 -0400 Subject: [Tutor] UnboundLocalError and Break In-Reply-To: <4AC40D5B.9050407@aim.com> References: <4AC40BB0.1090201@aim.com> <4AC40D5B.9050407@aim.com> Message-ID: <4AC41E75.2000305@ieee.org> Corey Richardson wrote: > Luke Paireepinart wrote: >> If your code's more than 10 lines long or so, put it on pastebin.com >> and send us the link rather than inlining the >> whole thing. You could also send it as an attachment. >> Your formatting is all screwed up and I can't read the code at all, >> but I have an idea about your error. >> >> Hmmm...thats odd. I didn't do anything different....but I can do >> that.http://pastebin.com/m518f612f > >> >> >> > The pastebin version of the code is substantially different than the original pasted version, and although the error message doesn't correspond to the posted code, at least there's enough to identify the particular error. Line 21: playHp -= damage #Player takes damage (I think...I will have to work that out) in the function monsAttk() is trying to modify a local variable playHp, without initializing it. Nowhere else in the function is that variable referenced or defined. So you get a UnboundLocalError: local variable 'playHp' referenced before assignment What you undoubtedly meant to do is to subtract damage from the *global* variable playHp. But without a global declaration, that's not what happens. It tries instead to adjust a local variable by that name. And of course that local is unbound. The "fix" could be to make the function look like this: 1. def monsAttk (damage, attack): #A monsters attack 2. global playHp #declare that we'll be modifying a global variable by this name, not defining a local 3. if attack > deff: #Monster hit 4. playHp -= damage #Player takes damage (I think...I will have to work that out) 5. print "You have sustained", damage, "damage, with", damage-playHp, "remaining" #Inform player of their statu I have to try hard to resist attacking your indiscriminate use of global variables. But you said to just help on the one problem.... DaveA From rabidpoobear at gmail.com Thu Oct 1 04:12:25 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 30 Sep 2009 21:12:25 -0500 Subject: [Tutor] UnboundLocalError and Break In-Reply-To: <4AC40D5B.9050407@aim.com> References: <4AC40BB0.1090201@aim.com> <4AC40D5B.9050407@aim.com> Message-ID: You're using a global variable (playHP) in a function, but you haven't told the function that playHP is supposed to be a global variable.You're going to want to change your function definition to: def monsAttk (damage, attack): #A monsters attack * global playHP* * On Wed, Sep 30, 2009 at 9:13 PM, bob gailer wrote: > > Something is screwy. > def monsAttk (damage, attack,playHp): # function expects 3 arguments > monsAttk(4, 15) # passes 2 arguments > > That should raise TypeError: monsAttk() takes exactly 3 argument (2 given) > So something else is awry. * That's because Corey originally e-mailed code that he had already modified rather than the code that was generating the error. The pastebin code is different. Corey, I'm not trying to be an ass, but you're making it difficult for us to help you and thus we're less inclined to. On Wed, Sep 30, 2009 at 9:00 PM, Corey Richardson wrote: > Luke Paireepinart wrote: > > If your code's more than 10 lines long or so, put it on pastebin.com and > send us the link rather than inlining the whole thing. You could also send > it as an attachment. > Your formatting is all screwed up and I can't read the code at all, but I > have an idea about your error. > > Hmmm...thats odd. I didn't do anything different....but I can do that. > http://pastebin.com/m518f612f > > > >> >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Fri Oct 2 02:41:37 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 01 Oct 2009 20:41:37 -0400 Subject: [Tutor] help with alternate execution In-Reply-To: <20091001115747.AWZ19213@pepper.merit.edu> References: <20091001115747.AWZ19213@pepper.merit.edu> Message-ID: <4AC54C41.1010203@ieee.org> You top-posted, and sent the mail to me privately (off-list). That's not how mailing lists work. wrobl1rt at cmich.edu wrote: > Thank you for the reply.. I tried putting the print repr(n) > before I defined 'n' with raw_input. My script looks like > this------ > > > def divisible(n): > if n%3 == 0: > print n, "is divisible by 3" > else: > print n, "is not divisible by 3" > n= raw_input("enter a number= ") > print repr(n) > > print divisible(n) > > In the shell, it gives me this error-------- > > Traceback (most recent call last): > File "C:\Users\RY4N\Desktop\CMU > stuff\BIS228\is_divisible_by_3", line 11, in > print divisible(n) > File "C:\Users\RY4N\Desktop\CMU > stuff\BIS228\is_divisible_by_3", line 4, in divisible > if n%3 == 0: > TypeError: not all arguments converted during string formatting > ---------- > I don't understand what the problem is > > You added the print, but you didn't look at the result, did you? So, what was the repr(n) value? In particular, what is the type of n ? Is it what you expected? DaveA From davea at ieee.org Fri Oct 2 02:42:32 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 01 Oct 2009 20:42:32 -0400 Subject: [Tutor] help with alternate execution In-Reply-To: <20091001115747.AWZ19213@pepper.merit.edu> References: <20091001115747.AWZ19213@pepper.merit.edu> Message-ID: <4AC54C78.1070404@ieee.org> You sent the mail to me privately (off-list). That's not how mailing lists work. wrobl1rt at cmich.edu wrote: > Thank you for the reply.. I tried putting the print repr(n) > before I defined 'n' with raw_input. My script looks like > this------ > > > def divisible(n): > if n%3 == 0: > print n, "is divisible by 3" > else: > print n, "is not divisible by 3" > n= raw_input("enter a number= ") > print repr(n) > > print divisible(n) > > In the shell, it gives me this error-------- > > Traceback (most recent call last): > File "C:\Users\RY4N\Desktop\CMU > stuff\BIS228\is_divisible_by_3", line 11, in > print divisible(n) > File "C:\Users\RY4N\Desktop\CMU > stuff\BIS228\is_divisible_by_3", line 4, in divisible > if n%3 == 0: > TypeError: not all arguments converted during string formatting > ---------- > I don't understand what the problem is > > You added the print, but you didn't look at the result, did you? So, what was the repr(n) value? In particular, what is the type of n ? Is it what you expected? DaveA From ziniatinklis at gmail.com Thu Oct 1 13:31:38 2009 From: ziniatinklis at gmail.com (Andrius) Date: Thu, 1 Oct 2009 12:31:38 +0100 Subject: [Tutor] small program Message-ID: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> Hi! There are interesting online course http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/LectureVideos/index.htm where I'm trying to learn Python. Looks quite interesting and I would like to create a program which should repeat a simply string several times with list number before. Like "1. Wanna more. 2. Wanna more. ..." Suppose to a loop here repeating, say x times. Should it look like that: y="Wanna more. " x=1 x=x+d: d=<100 print d+y How to create a program for such kind of task? Regards, Andrius From transmogribenno at gmail.com Fri Oct 2 10:29:14 2009 From: transmogribenno at gmail.com (Benno Lang) Date: Fri, 2 Oct 2009 17:29:14 +0900 Subject: [Tutor] small program In-Reply-To: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> Message-ID: <9b00d1a90910020129i1ee8852ey21b53745d094579a@mail.gmail.com> On Thu, Oct 1, 2009 at 8:31 PM, Andrius wrote: > Hi! > > There are interesting online course > http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/LectureVideos/index.htm > where I'm trying to learn Python. > Looks quite interesting and I would like to create a program which > should repeat a simply string several times with list number before. > Like "1. Wanna more. 2. Wanna more. ..." > Suppose to a loop here repeating, say x times. Should it look like that: > > y="Wanna more. " > x=1 > x=x+d: > d=<100 > print d+y > > How to create a program for such kind of task? [Forgot to reply-all the first time:] Something like this should do the trick, if I get what you're trying to do: x = 10 for i in range (1, x + 1): print i, "whee" HTH, benno From rabidpoobear at gmail.com Thu Oct 1 03:57:33 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 30 Sep 2009 20:57:33 -0500 Subject: [Tutor] UnboundLocalError and Break In-Reply-To: <4AC40BB0.1090201@aim.com> References: <4AC40BB0.1090201@aim.com> Message-ID: If your code's more than 10 lines long or so, put it on pastebin.com and send us the link rather than inlining the whole thing. You could also send it as an attachment.Your formatting is all screwed up and I can't read the code at all, but I have an idea about your error. On Wed, Sep 30, 2009 at 8:53 PM, Corey Richardson wrote: > Here is my code that is being used/affected by the block that is erroring. > The rest is superfluous, and does not affect it: > > intel = 10 #Define the abilities. > strn = 10 > con = 10 > dex = 10 > wis = 10 > exp = 0 > cha = 10 > playHp = 20 > melWep = 1 # A sword > rngWep = 1 #A bow > attack = dex+strn/2 #If they hit! > melDmg = strn+1+melWep/2 #Melee damage > deff = (con/3)+(dex/2)+6 #Defense > rngDmg = dex+1+rngWep/2 #Ranged damage > print "You are hiking through the woods one day, and you are jumped > by a goblin!" #The beginning of the adventure > print "Do you want to 1. Attack w/sword, 2. Attack w/bow, 3. Flee, > or 4. Nothing" > gob1Hp = 10 #First monsters hitpoints > def monsAttk (damage, attack,playHp): #A monsters attack if > attack > deff: #Monster hit playHp -= damage #Player takes > damage (I think...I will have > to work that out) > print "You have sustained", damage, "damage, with", > damage-playHp, "remaining" #Inform player of their status > def gmAttack(monHp, monDef, monAgil) : #A player attack > op1 = raw_input("Your choice?") > while op1 != "5": #Just a loop that you can break out of > (possibly...working that out) if op1 == '1': #Option 1 > if attack + 10 > monDef : #If the player hits > monHp-= melDmg #Monster takes damage > print "you did", melDmg, "damage! It now has", > monHp, "health left!" #Inform player how much health it has. > monsAttk(4, 15) #Monster attacks elif op1 == > '2': #Option 2 if attack + 10 >monDef: #If you hit the > monster > monHp -= rngDmg #Monster takes damage > print "you did", rngDmg, "damage! It now has", > monHp, "health left!" #Inform player how much health it has > monsAttk(4, 15) #Monster attacks > elif op1 == '3' : #Option 3 > if attack + dex > monAgil : #If they can escape > print "Thou hast fled!" #They have fled! > break #Stop the loop (I think. Can someone please inform > me as of how this works? I have looked online...it makes no sense to me) > elif op1 == '4' : #Option 4...the dumb one > monsAttk(4, 15) #Monster attacks > monsAttk(4,15) #Monster attacks again, cause they are dumb > print "You should attack..." #Inform them of their stupidity > else : #Well, what the hell did they pick? > print "Unknown option, try again!" #Inform them they > didn't pick a valid option > while gob1Hp >= 0: #Well it is still alive > gmAttack(gob1Hp,13,15) #player attacks > if gob1Hp <= 0.5 : #if it dies > print "Gratz! You have gotten 5 exp! You only have", 100-exp, > "exp left till lv 1!" #print their experience > exp += 5 #Give them exp > > > If you catch an error besides what is wrong, please don't point it out, as > I would like to work it out myself, unless marked in the comments. But this > one is evading me...I have playHp defined at the beginning, and I am getting > this error : > > Traceback (most recent call last): > File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", > line 183, in > gmAttack(gob1Hp,13,15) > File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", > line 167, in gmAttack > monsAttk(4, 15) > File "C:\Users\Quick-Start\Documents\Python Doc's\Game_File.py", > line 157, in monsAttk > playHp -= damage > UnboundLocalError: local variable 'playHp' referenced before assignment > > If you could please help me, that would be great. I'm just trying to get > the game engine working, as of now, it is 30% done, with Inventory, > Equipment, and a more sophisticated and simpler code to come. It's a bit of > a mess now... > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lead.expression at gmail.com Fri Oct 2 11:47:17 2009 From: lead.expression at gmail.com (Nicola De Quattro) Date: Fri, 2 Oct 2009 11:47:17 +0200 Subject: [Tutor] New to python: some advises for image processing tool Message-ID: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> Hi, I'm a 26 years old Italian engineer. Because to the fact that I'm an astrophile and astronomical tool (expecially under Linux) are not so common, I would like to develop some simple tool for some purposes. Well, I'm not knew to software development but I've never used python. So I want to list you my needed for the first tool, so you can tell me if Python could be a good choice and how to begin the develop. First of all, I need a software running both under Windows and Linux at least (it would be better if running either under MacOS). This is a first reason to choose Python. Secondly, I want a OpenSource tool The software shall be a tool for Star Analyzer (spectroscopic analyzer) images. A similar software already exists, it can be seen at this link (I'm sorry, it is in Italian, but you can understand from the images what is the input and the output) http://www.astropix.it/software/astrospectrum.html So I've to open an image (various formats, first I could need only .fits), to process the image in order to select the interesting strip containing the star and the spectrum (first image of the link posted, but I hope I can select the strip not only in the horizontal line but I will rotate the image), to obtain a graph like the second and third image (this may be simple, it plots the value of luminosity of each point), calibrate the image using periodical table of elements as shown in 6th image in order to color the graph. Well, I know that many people doesn't understand the problem :) I hope you can be able, with the elements reported above, how I have to proceed, remembering that I've no problem programming in Matlab and C but I've never worked with graphical interfaces and with image processing (only under Matlab). I've learned most of python commands. I think I've to start with some library? Thank you very much and sorry for the poem (and for my english)! PS: If the question is "Why don't you use Astrospectrum?" the answer is: it is only for Linux and is not opensource :( -- Nicola De Quattro Mobile: (+39)3292964937 Web: http://nikde4.altervista.org Skype: lead_expression MSNetwork: lead_expression at hotmail.com From patrick.just4fun at gmail.com Fri Oct 2 12:34:09 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Fri, 02 Oct 2009 12:34:09 +0200 Subject: [Tutor] help with alternate execution In-Reply-To: <4AC54C78.1070404@ieee.org> References: <20091001115747.AWZ19213@pepper.merit.edu> <4AC54C78.1070404@ieee.org> Message-ID: <4AC5D721.1060305@gmail.com> wrobl1rt at cmich.edu wrote: > Thank you for the reply.. I tried putting the print repr(n) > before I defined 'n' with raw_input. My script looks like > this------ > > > def divisible(n): > if n%3 == 0: > print n, "is divisible by 3" > else: > print n, "is not divisible by 3" > n= raw_input("enter a number= ") > print repr(n) > > print divisible(n) > I don't understand what the problem is The problem is raw_input gives you a string. So in your example n is a string and when it comes to n%3 python tries to format your string, but since you haven't any formating symbols in it, it fails. To fix your program, convert the n to int: divisible(int(n)) - Patrick From gopcos at gmail.com Fri Oct 2 09:24:33 2009 From: gopcos at gmail.com (goooogi goooogi) Date: Fri, 2 Oct 2009 12:54:33 +0530 Subject: [Tutor] how to run php scripts in pylons framework? Message-ID: Dear All, I have some php scripts which I don't want to rewrite in python. How can I run php Scripts in python? Thanks in advance Googi G -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Fri Oct 2 15:44:57 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 02 Oct 2009 15:44:57 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> Message-ID: Nicola De Quattro wrote: > So I've to open an image (various formats, first I could need only > .fits), to process the image in order to select the interesting strip > containing the star and the spectrum (first image of the link posted, > but I hope I can select the strip not only in the horizontal line but > I will rotate the image), to obtain a graph like the second and third > image (this may be simple, it plots the value of luminosity of each > point), calibrate the image using periodical table of elements as > shown in 6th image in order to color the graph. Without looking further into your problem, there are two (main) general purpose image manipulation libraries for Python (that I know of) that you may want to look at: PIL and ImageMagick. At least ImageMagick supports FITS. Stefan From srilyk at gmail.com Fri Oct 2 16:27:48 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 2 Oct 2009 09:27:48 -0500 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> Message-ID: <333efb450910020727r7a1fcd5dma654b7ba924efe14@mail.gmail.com> On Fri, Oct 2, 2009 at 8:44 AM, Stefan Behnel wrote: > Nicola De Quattro wrote: > > So I've to open an image (various formats, first I could need only > > .fits), to process the image in order to select the interesting strip > > containing the star and the spectrum (first image of the link posted, > > but I hope I can select the strip not only in the horizontal line but > > I will rotate the image), to obtain a graph like the second and third > > image (this may be simple, it plots the value of luminosity of each > > point), calibrate the image using periodical table of elements as > > shown in 6th image in order to color the graph. > > Without looking further into your problem, there are two (main) general > purpose image manipulation libraries for Python (that I know of) that you > may want to look at: PIL and ImageMagick. At least ImageMagick supports > FITS. This is definitely a project you could do with python. It might take a fair amount of programming, but it should certainly take less with python than most other languages. Especially with the implementation of a GUI. I'd suggest PyGTK+ simply because of the rather extensive documentation. I've used both Tkinter and PyGTK and the latter is much easier to deal with when using images, though YMMV. The most difficult task would be analyzing the image and possibly some of the graph generation. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Fri Oct 2 16:32:17 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 2 Oct 2009 08:32:17 -0600 Subject: [Tutor] how to run php scripts in pylons framework? In-Reply-To: References: Message-ID: <1e53c510910020732w51fe1cat56eec420f866f954@mail.gmail.com> On Fri, Oct 2, 2009 at 1:24 AM, goooogi goooogi wrote: > > Dear All, > > I have some php scripts which I don't want to rewrite in python. How can I > run php Scripts in python? > > Thanks in advance > Googi G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Although rewriting is a better option, you can use the subprocess module to make system calls to the php interpreter import subprocess #simple caller, disguard output subprocess.call("php /path/to/my/old/script.php") # if you want output proc = subprocess.Popen("php /path/to/my/script.php", shell=True, stdout=subprocess.PIPE) script_response = proc.stdout.read() Hope that helps, Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Oct 2 16:35:15 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 2 Oct 2009 16:35:15 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> Message-ID: 2009/10/2 Stefan Behnel : > Without looking further into your problem, there are two (main) general > purpose image manipulation libraries for Python (that I know of) that you > may want to look at: PIL and ImageMagick. At least ImageMagick supports FITS. There is a python module for fits files. Never used it so the usual caveats apply here ;-) http://www.stsci.edu/resources/software_hardware/pyfits Greets Sander From bgailer at gmail.com Fri Oct 2 17:38:35 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 Oct 2009 11:38:35 -0400 Subject: [Tutor] small program In-Reply-To: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> Message-ID: <4AC61E7B.5010902@gmail.com> Andrius wrote: > Hi! > > There are interesting online course > http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/LectureVideos/index.htm > where I'm trying to learn Python. > Looks quite interesting and I would like to create a program which > should repeat a simply string several times with list number before. > Like "1. Wanna more. 2. Wanna more. ..." > Suppose to a loop here repeating, say x times. Should it look like that: > > y="Wanna more. " > x=1 > x=x+d: > d=<100 > print d+y > > How to create a program for such kind of task? > Pardon my skepticism - I'm guessing you are taking the course and this is homework. We prefer not to do your homework for you. If it is not homework - we prefer not to write programs for you. Unfortunately Benno gave you a solution. If you want to learn Python read on: In regard to the above code - did you try to run it? That is step one. Try to run it. See if you can figure out why it fails. Hint there are 2 syntax errors. At python.org there are links to several tutorials which will show you how to repeat operations. To repeat things in Python we can use a loop. What Python statements are used for loops? -- Bob Gailer Chapel Hill NC 919-636-4239 From eike.welk at gmx.net Fri Oct 2 23:04:07 2009 From: eike.welk at gmx.net (Eike Welk) Date: Fri, 02 Oct 2009 23:04:07 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> Message-ID: <200910022304.08324.eike.welk@gmx.net> Hello Nicola! For scientific computing there are the Numpy and Scipy libraries: http://www.scipy.org/ For making graphs there is Matplotlib: http://matplotlib.sourceforge.net/ You should join the mailing lists of these projects. For the GUI I would use QT4: http://doc.trolltech.com/4.5/index.html The Python bindings are called PyQt4: http://www.riverbankcomputing.co.uk/news You should also look at Enthought's Traits UI, which is specially dedicated to scientist, but I don't know if it can be installed on Linux. http://code.enthought.com/projects/traits/ Maybe Python's built in GUI might be good enough for you. http://wiki.python.org/moin/TkInter However you should definitely write a command line program first, and start with the GUI when the program more or less works. GUI programming is a lot of work for a relatively small gain in usability. Good luck with your project, Eike. From rudiger.wolf at throughputfocus.com Fri Oct 2 23:45:25 2009 From: rudiger.wolf at throughputfocus.com (=?ISO-8859-1?Q?R=FCdiger=20Wolf?=) Date: Fri, 02 Oct 2009 22:45:25 +0100 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> Message-ID: <1254519925.11010.1337802651@webmail.messagingengine.com> I remember reading some Python tutorials that where written specifically for Astronomers. Did a search on Google. This is not the tutorial I originally read but maybe you will find it to be useful. http://www.stsci.edu/hst/training/events/Python/readManDispImages_WU.pdf Regards Rudiger On Fri, 02 Oct 2009 11:47 +0200, "Nicola De Quattro" wrote: > Hi, > I'm a 26 years old Italian engineer. Because to the fact that I'm an > astrophile and astronomical tool (expecially under Linux) are not so > common, I would like to develop some simple tool for some purposes. > Well, I'm not knew to software development but I've never used python. > So I want to list you my needed for the first tool, so you can tell me > if Python could be a good choice and how to begin the develop. > First of all, I need a software running both under Windows and Linux > at least (it would be better if running either under MacOS). This is a > first reason to choose Python. From didar.hossain at gmail.com Sat Oct 3 07:56:14 2009 From: didar.hossain at gmail.com (Didar Hossain) Date: Sat, 3 Oct 2009 11:26:14 +0530 Subject: [Tutor] How to perform variable assignment and Message-ID: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> Hi, I am currently learning Python and I was wondering is there a shorter way to do the following - import os homedir = os.environ.get('HOME') if homedir: print "My home directory is %s" % homedir I do this in Perl - my $home; if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; } Can I do a similar shortcut statement like the above in Python? Regards, Didar From moron.oxy at gmail.com Sat Oct 3 08:14:54 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Sat, 3 Oct 2009 16:14:54 +1000 Subject: [Tutor] How to perform variable assignment and In-Reply-To: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> References: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> Message-ID: <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> Hello, On Sat, Oct 3, 2009 at 3:56 PM, Didar Hossain wrote: > homedir = os.environ.get('HOME') > > if homedir: > print "My home directory is %s" % homedir > > > I do this in Perl - > > my $home; > > if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; } > > Can I do a similar shortcut statement like the above in Python? > > There are probably various syntactic tricks to achieve the same, however, the main reason you can't do it is that assignment in Python is a statement rather than an expression, i.e. it does not return a value that the if statement can evaluate. While having an assignment as an expression could be convenient in places (I have had my moments where I wish it was!), that particular usage is also a source of common bugs. Often in conditional statements people want to do a comparison using the == operator rather than an assignment (=) + eval. Marking assignment as a statement rather than an expression prevents this bug, since it is now a syntax error in this case - an if statement cannot work on something that doesn't return anything. My Perl is rusty at best! Not sure if there's an == operator, if there isn't then the decision to allow this is probably more justified since comparison and assignment are sufficiently different syntax-wise that the intent is clear. -- Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sat Oct 3 08:44:04 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 2 Oct 2009 23:44:04 -0700 Subject: [Tutor] How to perform variable assignment and In-Reply-To: <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> References: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> Message-ID: <78b3a9580910022344x2eb141e6i3e43b1b8db36d926@mail.gmail.com> On Fri, Oct 2, 2009 at 11:14 PM, Oxymoron wrote: > Hello, > > On Sat, Oct 3, 2009 at 3:56 PM, Didar Hossain > wrote: >> >> homedir = os.environ.get('HOME') >> >> if homedir: >> ? ?print "My home directory is %s" % homedir >> >> >> I do this in Perl - >> >> my $home; >> >> if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; } >> >> Can I do a similar shortcut statement like the above in Python? > > There are probably various syntactic tricks to achieve the same, however, > the main reason you can't do it is that assignment in Python is a statement > rather than an expression, i.e. it does not return a value that the if > statement can evaluate. kamal is correct. you cannot do it in Python because assignments are not expressions, and when they are, it leads to problems, i.e., code readability, bugs, etc. Python fights hard to prevent those from "interrupting your problem-solving," and there's a cost to it -- hopefully the benefits outweigh the minor costs. as far as your solution goes, it is one of the cleanest solution you can come up with. however, there is a tiny bug: if the $HOME environment variable is *not* set, you will get a KeyError exception. one solution is to add a default value to your get() method call so that it returns an object with a Boolean False value: import os homedir = os.environ.get('HOME', '') # or False or None if homedir: print "My home directory is %s" % homedir hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From roadierich at googlemail.com Sat Oct 3 10:04:07 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 3 Oct 2009 09:04:07 +0100 Subject: [Tutor] How to perform variable assignment and In-Reply-To: <78b3a9580910022344x2eb141e6i3e43b1b8db36d926@mail.gmail.com> References: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> <78b3a9580910022344x2eb141e6i3e43b1b8db36d926@mail.gmail.com> Message-ID: 2009/10/3 wesley chun : > On Fri, Oct 2, 2009 at 11:14 PM, Oxymoron wrote: >> Hello, >> >> On Sat, Oct 3, 2009 at 3:56 PM, Didar Hossain >> wrote: >>> >>> homedir = os.environ.get('HOME') >>> >>> if homedir: >>> ? ?print "My home directory is %s" % homedir >>> >>> >>> I do this in Perl - >>> >>> my $home; >>> >>> if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; } >>> >>> Can I do a similar shortcut statement like the above in Python? >> >> There are probably various syntactic tricks to achieve the same, however, >> the main reason you can't do it is that assignment in Python is a statement >> rather than an expression, i.e. it does not return a value that the if >> statement can evaluate. > > kamal is correct. you cannot do it in Python because assignments are > not expressions, and when they are, it leads to problems, i.e., code > readability, bugs, etc. Python fights hard to prevent those from > "interrupting your problem-solving," and there's a cost to it -- > hopefully the benefits outweigh the minor costs. > > as far as your solution goes, it is one of the cleanest solution you > can come up with. however, there is a tiny bug: if the $HOME > environment variable is *not* set, you will get a KeyError exception. > one solution is to add a default value to your get() method call so > that it returns an object with a Boolean False value: > > import os > > homedir = os.environ.get('HOME', '') # or False or None > > if homedir: > ? print "My home directory is %s" % homedir > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > ? ?http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > This message mentions, but skips over one of the differences in the mindsets of perl and python. Perl is designed to "Look Before You Leap", hence the if-statement in your example. Python is designed with the mindset that "It's easier to ask forgivness than permission". This is commonly known as LBYL vs. EAFP So whilst the perl would be if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; } the congruent Python would probably would be something like try: home = os.environ['HOME'] except KeyError: home = None else: print "My home directory is", home Admittedly, I don't know what the value of $home would be after executing the snippet above, but I'm assuming nil or null or whatever the perl equivalent is. In a sort of summary: LBYL means lots of if-statements: Is there a chance value X won't work in this function, if so, let's not try. EAFP means lots of exception handling: Let's try X in this function, and if it goes wrong, we'll deal with it then. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From ziniatinklis at gmail.com Fri Oct 2 18:44:26 2009 From: ziniatinklis at gmail.com (Andrius) Date: Fri, 2 Oct 2009 17:44:26 +0100 Subject: [Tutor] small program In-Reply-To: <4AC61E7B.5010902@gmail.com> References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> <4AC61E7B.5010902@gmail.com> Message-ID: <1d0897be0910020944i3b554a5fjaefb964256563dd3@mail.gmail.com> Ok ok, smarty! Don't be very cool! Nobody asks you a favor, nobody asks your advices as well. There are plenty 'advisers' to say where to see, but not too much able to explain. Keep quiet. Regards, Andrius On 02/10/2009, bob gailer wrote: > Andrius wrote: >> Hi! >> >> There are interesting online course >> http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/LectureVideos/index.htm >> where I'm trying to learn Python. >> Looks quite interesting and I would like to create a program which >> should repeat a simply string several times with list number before. >> Like "1. Wanna more. 2. Wanna more. ..." >> Suppose to a loop here repeating, say x times. Should it look like that: >> >> y="Wanna more. " >> x=1 >> x=x+d: >> d=<100 >> print d+y >> >> How to create a program for such kind of task? >> > > Pardon my skepticism - I'm guessing you are taking the course and this > is homework. We prefer not to do your homework for you. If it is not > homework - we prefer not to write programs for you. > > Unfortunately Benno gave you a solution. > > If you want to learn Python read on: > > In regard to the above code - did you try to run it? That is step one. > Try to run it. See if you can figure out why it fails. Hint there are 2 > syntax errors. > > At python.org there are links to several tutorials which will show you > how to repeat operations. > > To repeat things in Python we can use a loop. What Python statements are > used for loops? > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > From didar.hossain at gmail.com Sat Oct 3 11:47:45 2009 From: didar.hossain at gmail.com (Didar Hossain) Date: Sat, 3 Oct 2009 15:17:45 +0530 Subject: [Tutor] How to perform variable assignment and In-Reply-To: References: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> <78b3a9580910022344x2eb141e6i3e43b1b8db36d926@mail.gmail.com> Message-ID: <62d32bf20910030247q6f610a3ai888edfc3f9ca31f8@mail.gmail.com> On Sat, Oct 3, 2009 at 1:34 PM, Rich Lovely wrote: > 2009/10/3 wesley chun : >> On Fri, Oct 2, 2009 at 11:14 PM, Oxymoron wrote: >>> Hello, >>> >>> On Sat, Oct 3, 2009 at 3:56 PM, Didar Hossain >>> wrote: >>>> >>>> homedir = os.environ.get('HOME') >>>> >>>> if homedir: >>>> ? ?print "My home directory is %s" % homedir >>>> >>>> >>>> I do this in Perl - >>>> >>>> my $home; >>>> >>>> if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; } >>>> >>>> Can I do a similar shortcut statement like the above in Python? >>> >>> There are probably various syntactic tricks to achieve the same, however, >>> the main reason you can't do it is that assignment in Python is a statement >>> rather than an expression, i.e. it does not return a value that the if >>> statement can evaluate. Ok, this is what I understood as the difference between "expression" and "statement": statement => directive to do something expression => check for truth value or "evaluatable" code Am I correct? >> >> kamal is correct. you cannot do it in Python because assignments are >> not expressions, and when they are, it leads to problems, i.e., code >> readability, bugs, etc. Python fights hard to prevent those from >> "interrupting your problem-solving," and there's a cost to it -- >> hopefully the benefits outweigh the minor costs. >> >> as far as your solution goes, it is one of the cleanest solution you >> can come up with. however, there is a tiny bug: if the $HOME >> environment variable is *not* set, you will get a KeyError exception. >> one solution is to add a default value to your get() method call so >> that it returns an object with a Boolean False value: >> >> import os >> >> homedir = os.environ.get('HOME', '') # or False or None This is neat - didn't know I could do that! :-) >> >> if homedir: >> ? print "My home directory is %s" % homedir > > This message mentions, but skips over one of the differences in the > mindsets of perl and python. > > Perl is designed to "Look Before You Leap", hence the if-statement in > your example. ?Python is designed with the mindset that "It's easier > to ask forgivness than permission". ?This is commonly known as LBYL > vs. EAFP > > So whilst the perl would be > if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; } > > the congruent Python would probably would be something like > > try: > ? ?home = os.environ['HOME'] > except KeyError: > ? ?home = None > else: > ? ?print "My home directory is", home This is nice, will take some getting used to. > Admittedly, I don't know what the value of $home would be after > executing the snippet above, but I'm assuming nil or null or whatever > the perl equivalent is. "undef" ;-) > In a sort of summary: ?LBYL means lots of if-statements: Is there a > chance value X won't work in this function, if so, let's not try. > EAFP means lots of exception handling: Let's try X in this function, > and if it goes wrong, we'll deal with it then. Hmmm, seems like I have a lot of unlearning to do. I have to do C as part of my homework and use Perl for hacking up small scripts, so this kind of tendency will be a little difficult to curb. Thank you to all of you, Didar From moron.oxy at gmail.com Sat Oct 3 12:39:12 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Sat, 3 Oct 2009 20:39:12 +1000 Subject: [Tutor] How to perform variable assignment and In-Reply-To: <62d32bf20910030247q6f610a3ai888edfc3f9ca31f8@mail.gmail.com> References: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> <78b3a9580910022344x2eb141e6i3e43b1b8db36d926@mail.gmail.com> <62d32bf20910030247q6f610a3ai888edfc3f9ca31f8@mail.gmail.com> Message-ID: <2096a7260910030339y17782083u3d2978ffb4ff3087@mail.gmail.com> (Did not reply to list earlier, apologies) On Sat, Oct 3, 2009 at 7:47 PM, Didar Hossain wrote: > >>> There are probably various syntactic tricks to achieve the same, > however, > >>> the main reason you can't do it is that assignment in Python is a > statement > >>> rather than an expression, i.e. it does not return a value that the if > >>> statement can evaluate. > > Ok, this is what I understood as the difference between "expression" > and "statement": > > statement => directive to do something > expression => check for truth value or "evaluatable" code > > Am I correct? > > Expressions do stuff too (e.g. function calls with side effects) and can direct "doing", so I'm a bit reluctant to agree with your definition, which gives that privilege only to statements :-). In my view, the crucial thing to note is what happens post-execution of either a statement or an expression. A statement will not return any value - in C it's like a void function, you cannot assign the result to anything else - because well, there's no result returned. An expression always returns a value which in turn can be a simple expression, a more complex expression, even None, etc. In the case of the if statement, if was in fact a statement, however, the condition part: if : , is expected to be an expression that's convertible to a boolean value, true or false. I say convertible, because the following is legal: if None: print "bar" All types have implicit True or False values within the context of conditionals: >>> if []: print "bar" ... >>> if [1]: print "bar" ... bar In the above example, an empty list is considered as False, but a non-empty one is True. This in turn allows you to write concise and often reusable code (though you need to be sure the semantics make sense for your use case) since you do not need to check explicitly every time. I'll leave you to further research these implicit conversions of types. Playing a bit with the interactive interpreter gives you a feel for statements vs. expressions: >>> a = 1 >>> a 1 >>> a + a + a 3 >>> "foo" 'foo' >>> a = "foo" >>> a 'foo' >>> After a = 1, the interpreter had nothing interesting to say - no value returned, a = "foo" also nothing, but the remaining yielded values, so the interpreter output those. There's one caveat though with the above, the use of 'None' - a null/nil/NULL on (mild?) steroids since it is a real type (hint: dir(None)), this is definitely a valid value to return, it is assignable to something else, or returned from a function, and as we saw in the case of 'if None: ...', it certainly can be evaluated, it is as real as "foo". However, in the interpreter: >>> None >>> a = None >>> a >>> Hmm, quiet. It's also implicitly returned by functions. >>> def foo(): ... return ... >>> x = foo() >>> x >>> x is None True >>> def foo(): ... pass ... >>> x = foo() >>> x is None True In my view, None should possibly be printed... perhaps it could get annoying, but it would be explicit - so I put forth my question, if None not important enough to display? ;-) -- Kamal PS. I've heard the phrase "expression statement" used where a function call returns None (implicitly or explicitly) ... sounds highly oxymoronic to me! -- There is more to life than increasing its speed. -- Mahatma Gandhi -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Oct 1 04:32:26 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 1 Oct 2009 04:32:26 +0200 Subject: [Tutor] Fwd: UnboundLocalError and Break In-Reply-To: <4AC410DF.3010408@aim.com> References: <4AC40BB0.1090201@aim.com> <4AC40D5B.9050407@aim.com> <4AC410DF.3010408@aim.com> Message-ID: Corey, please reply on list (use reply-all). I know it's annoying to have to remember that. ---------- Forwarded message ---------- From: Corey Richardson Date: Thu, Oct 1, 2009 at 4:15 AM Subject: Re: [Tutor] UnboundLocalError and Break To: Luke Paireepinart Luke Paireepinart wrote: You're using a global variable (playHP) in a function, but you haven't told the function that playHP is supposed to be a global variable. You're going to want to change your function definition to: def monsAttk (damage, attack): #A monsters attack * global playHP* * On Wed, Sep 30, 2009 at 9:13 PM, bob gailer wrote: > > Something is screwy. > def monsAttk (damage, attack,playHp): # function expects 3 arguments > monsAttk(4, 15) # passes 2 arguments > > That should raise TypeError: monsAttk() takes exactly 3 argument (2 given) > So something else is awry. * That's because Corey originally e-mailed code that he had already modified rather than the code that was generating the error. The pastebin code is different. Corey, I'm not trying to be an ass, but you're making it difficult for us to help you and thus we're less inclined to. Yes...As I was running the code a final time to make sure nothing else was happening until then before I posted it on pastebin, It came up with that, so i changed it. Sorry for the inconvenience. I also realize that, but I'm working on it. And I don't see it as ass-ery, I see it as advice : ) So does that global modifier make sure that, in the function, you are using the variable assigned outside of the function? Thanks for the help, ~Corey My reply: Yep, that's exactly right. You are generally discouraged from using global variables in programming languages (you can read about the various reasons online) but yeah, you have to tell python whether you're using the global scope or the local scope. -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Sun Oct 4 00:05:36 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 3 Oct 2009 15:05:36 -0700 Subject: [Tutor] How to perform variable assignment and References: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com><2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> <78b3a9580910022344x2eb141e6i3e43b1b8db36d926@mail.gmail.com> Message-ID: "wesley chun" wrote in message [snip] > ... however, there is a tiny bug: if the $HOME > environment variable is *not* set, you will get a KeyError exception. > one solution is to add a default value to your get() method call so > that it returns an object with a Boolean False value: No KeyError. Default on missing is to return None. >>> help(os.environ.get) Help on method get in module os: get(self, key, failobj=None) method of os._Environ instance -Mark From steve at alchemy.com Sun Oct 4 01:55:27 2009 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 03 Oct 2009 16:55:27 -0700 Subject: [Tutor] How to perform variable assignment and In-Reply-To: <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> References: <62d32bf20910022256m17a06782kc807a37ae9208dc3@mail.gmail.com> <2096a7260910022314t683ceab0obbe0a76d1170cf41@mail.gmail.com> Message-ID: <4AC7E46F.9040406@alchemy.com> Oxymoron wrote: > While having an assignment as an expression could be convenient in > places (I have had my moments where I wish it was!), that particular > usage is also a source of common bugs. Often in conditional statements Me, too. I grumble every time I have to take two separate statements to assign then test, but this is an explicit design decision in Python and I have to admit this *is* a frequent source of bugs. Even in your code, does if ($home = $ENV{HOME}) { ... } mean to assign the value to $home and continue with the block if that's a true value, or did you intend to do the block if some existing variable $home is equal to $HOME in the environment? The answer to that is really non-obvious without reading a bit of the surrounding context. Something more explicit like if (($home = $ENV{HOME}) ne '') { ...} or if (defined($home = $ENV{HOME})) { ... } is much more obvious that you knew what you were doing in putting the assignment in there. Even so, this seems to be a pitfall for many programmers, particularly novices, and our BDFL decided to just make it a non-issue in Python, so you have to be a tad more explicit, which in the bigger picture of code maintainability, isn't really such a bad thing. > My Perl is rusty at best! Not sure if there's an == operator, if there Yes there is, although it would be incorrect to use here. Now if you want an even better example at why being explicit, and being strongly typed, leads to more clarity in your code, this aspect of Perl is a good one. Since it's weakly typed, the operator used implicitly casts the operands' types, so ($home == $ENV{HOME}) would silently force both variables to *numeric* and return true if they returned the same numeric value, so most strings (which evaluate to 0) would look "equal" there. You need to say ($home eq $ENV{HOME}) would force both to be strings and compare them for string equality. Not trying to start a language war (I like and regularly use both Python and Perl), but it shows some of the differences you see when one language is specifically designed to make code very clear and explicit and another wasn't. --steve From wescpy at gmail.com Fri Oct 2 10:33:53 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 2 Oct 2009 01:33:53 -0700 Subject: [Tutor] small program In-Reply-To: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> Message-ID: <78b3a9580910020133p7d49b836m1ed11b3ab17924ae@mail.gmail.com> > I would like to create a program which > should repeat a simply string several times with list number before. > Like "1. Wanna more. 2. Wanna more. ..." > Suppose to a loop here repeating, say x times. Should it look like that: > > y="Wanna more. " > x=1 > x=x+d: > d=<100 > print d+y > > How to create a program for such kind of task? hi Andrius, welcome to Python! interesting course you're taking. before proceeding with this homework exercise, i would first rewatch lecture 2, as this is where loops are covered... you will need one of Python's two looping mechanisms to complete this exercise with. your pseudocode is a good start, but you need to turn it into Python. i would suggest also having some sort of reference where you can lookup basic constructs where you need it. finally, when you get started, if you are running into errors you cannot explain nor look up online, then cut-n-paste your entire program as well as the erroneous output in full here, and we can help you further. best of luck! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rabidpoobear at gmail.com Sun Oct 4 06:23:36 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 4 Oct 2009 06:23:36 +0200 Subject: [Tutor] small program In-Reply-To: <1d0897be0910020944i3b554a5fjaefb964256563dd3@mail.gmail.com> References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> <4AC61E7B.5010902@gmail.com> <1d0897be0910020944i3b554a5fjaefb964256563dd3@mail.gmail.com> Message-ID: Bob's a very highly respected member of this group, and I suggest you try not to insult the people you're asking for help.He's spot-on with the intention of this mailing list. We aren't here to do work for you. I, for one, am making it a point not to answer any of your queries in the future. So there's at least one "adviser" who chooses not to explain to people who join their mailing list and act like rude jerks. Regards, -Luke On Fri, Oct 2, 2009 at 6:44 PM, Andrius wrote: > Ok ok, smarty! Don't be very cool! Nobody asks you a favor, nobody > asks your advices as well. There are plenty 'advisers' to say where to > see, but not too much able to explain. Keep quiet. > > Regards, > Andrius > > > On 02/10/2009, bob gailer wrote: > > Andrius wrote: > >> Hi! > >> > >> There are interesting online course > >> > http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2008/LectureVideos/index.htm > >> where I'm trying to learn Python. > >> Looks quite interesting and I would like to create a program which > >> should repeat a simply string several times with list number before. > >> Like "1. Wanna more. 2. Wanna more. ..." > >> Suppose to a loop here repeating, say x times. Should it look like that: > >> > >> y="Wanna more. " > >> x=1 > >> x=x+d: > >> d=<100 > >> print d+y > >> > >> How to create a program for such kind of task? > >> > > > > Pardon my skepticism - I'm guessing you are taking the course and this > > is homework. We prefer not to do your homework for you. If it is not > > homework - we prefer not to write programs for you. > > > > Unfortunately Benno gave you a solution. > > > > If you want to learn Python read on: > > > > In regard to the above code - did you try to run it? That is step one. > > Try to run it. See if you can figure out why it fails. Hint there are 2 > > syntax errors. > > > > At python.org there are links to several tutorials which will show you > > how to repeat operations. > > > > To repeat things in Python we can use a loop. What Python statements are > > used for loops? > > > > > > -- > > Bob Gailer > > Chapel Hill NC > > 919-636-4239 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From warren at wantonhubris.com Sun Oct 4 15:51:12 2009 From: warren at wantonhubris.com (Warren) Date: Sun, 4 Oct 2009 09:51:12 -0400 Subject: [Tutor] __mul__ for different variable types? Message-ID: I'm a little confused on this one. I have a Vector class that I want to be able to multiply by either another vector or by a single float value. How would I implement this in my override of __mul__ within that class? Do you check the variable type with a stack of "if isinstance" statements or something? What is the preferred Python way of doing this? - Warren (warren at wantonhubris.com) From rabidpoobear at gmail.com Sun Oct 4 14:40:00 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 4 Oct 2009 14:40:00 +0200 Subject: [Tutor] small program In-Reply-To: <1d0897be0910040459kcad08a2ra85633ae8cac348d@mail.gmail.com> References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> <4AC61E7B.5010902@gmail.com> <1d0897be0910020944i3b554a5fjaefb964256563dd3@mail.gmail.com> <1d0897be0910040459kcad08a2ra85633ae8cac348d@mail.gmail.com> Message-ID: On Sun, Oct 4, 2009 at 1:59 PM, Andrius wrote: > Very good. Nice to hear that from another 'untouchable'. Must to > confirm for your that I'm usually left wing fella, so, if you have > nothing what to say for my in my case - please, fuck off. Re: http://catb.org/~esr/faqs/smart-questions.html#not_losing Good luck, -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From timmichelsen at gmx-topmail.de Sun Oct 4 20:41:56 2009 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Sun, 4 Oct 2009 18:41:56 +0000 (UTC) Subject: [Tutor] =?utf-8?q?using_easy=5Finstall_to_download_eggs?= Message-ID: Hello, I would like to use easy_install to cache packages registered at PyPi locally. How can I do this for packages? I tried the hints from: http://peak.telecommunity.com/DevCenter/EasyInstall#installing-on-un-networked-machines It worked for some packages. But for others, the command easy_install -zxad. mercurial just creates a subdirectory and not an *.egg file. How can I 1) use easy_install to download packages from PyPi to a locally saved egg-file? 2) use easy_install to download archinves (*.tar.gz / *.zip) to download the respective software package from the link indicated on PyPi? Thanks in advance, Timmie From afith13 at gmail.com Sun Oct 4 00:33:47 2009 From: afith13 at gmail.com (afith13 at gmail.com) Date: Sat, 3 Oct 2009 22:33:47 +0000 Subject: [Tutor] Using a list comp in place of a for loop Message-ID: <1426984540-1254609221-cardhu_decombobulator_blackberry.rim.net-1699972136-@bda932.bisx.prod.on.blackberry> Hi tutors, I've got a loop and a comprehension that do the same thing (as far as I can tell): for i in range(N): someList.append.newObject(i) ...and... [someList.append.newObject(i) for i in range(N)] I'm tempted to write this as a list comp because it's a big list and I've read that list comps are faster than for loops in general. I'm hesitating because I'm not sure if building a big list of "None" objects and then throwing it away has any drawbacks. Thanks in advance, From roadierich at googlemail.com Sun Oct 4 23:31:53 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 4 Oct 2009 22:31:53 +0100 Subject: [Tutor] __mul__ for different variable types? In-Reply-To: References: Message-ID: 2009/10/4 Warren : > > I'm a little confused on this one. > > I have a Vector class that I want to be able to multiply by either another > vector or by a single float value. ?How would I implement this in my > override of __mul__ within that class? > > Do you check the variable type with a stack of "if isinstance" statements or > something? ?What is the preferred Python way of doing this? > > - Warren > (warren at wantonhubris.com) > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I think isinstance is probably the most pythonic way of doing this, and don't forget to add __rmul__ as well, for floats: try: from numbers import Real except NameError: Real = (int, long, float) class Vector(object): #__init__ and other methods ommitted. def __mul__(self, other): """self * other""" if isinstance(other, Vector): # code for Vector * Vector elif isinstance(other, Number): # code for Vector * number else: return NotImplemented def __rmul__(self, other): """other * self""" return self.__mul__(other) Note that I've got no type checking in __rmul__, because if only Vector * Vector has a different value if the terms are swapped, and other * self will use other.__mul__ if other is a Vector. Also note the import at the top: numbers.Real is an Abstract Base Class use for all real number types, introduced in Python 2.6, so simplifies testing types. See http://docs.python.org/library/numbers.html for info. If it's not there, the code demos another feature of isinstance most people don't notice: the type argument can be a sequence of types, so I set Real to a tuple of all the builtin real number types (that I can remember off the top of my head) if the import fails. If you want multiplication to be defined for complex numbers, change all occurances of Real to Number, and add complex to the tuple. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From warren at wantonhubris.com Sun Oct 4 23:44:31 2009 From: warren at wantonhubris.com (Warren) Date: Sun, 4 Oct 2009 17:44:31 -0400 Subject: [Tutor] __mul__ for different variable types? In-Reply-To: References: Message-ID: <03326347-6AD2-4914-8E12-720B202ACEC5@wantonhubris.com> Awesome, Rich, thanks! - Warren (warren at wantonhubris.com) On Oct 4, 2009, at 5:31 PM, Rich Lovely wrote: > 2009/10/4 Warren : >> >> I'm a little confused on this one. >> >> I have a Vector class that I want to be able to multiply by either >> another >> vector or by a single float value. How would I implement this in my >> override of __mul__ within that class? >> >> Do you check the variable type with a stack of "if isinstance" >> statements or >> something? What is the preferred Python way of doing this? >> >> - Warren >> (warren at wantonhubris.com) >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > I think isinstance is probably the most pythonic way of doing this, > and don't forget to add __rmul__ as well, for floats: > > try: > from numbers import Real > except NameError: > Real = (int, long, float) > > class Vector(object): > #__init__ and other methods ommitted. > def __mul__(self, other): > """self * other""" > if isinstance(other, Vector): > # code for Vector * Vector > elif isinstance(other, Number): > # code for Vector * number > else: > return NotImplemented > def __rmul__(self, other): > """other * self""" > return self.__mul__(other) > > Note that I've got no type checking in __rmul__, because if only > Vector * Vector has a different value if the terms are swapped, and > other * self will use other.__mul__ if other is a Vector. > > Also note the import at the top: numbers.Real is an Abstract Base > Class use for all real number types, introduced in Python 2.6, so > simplifies testing types. See > http://docs.python.org/library/numbers.html for info. If it's not > there, the code demos another feature of isinstance most people don't > notice: the type argument can be a sequence of types, so I set Real > to a tuple of all the builtin real number types (that I can remember > off the top of my head) if the import fails. > > If you want multiplication to be defined for complex numbers, change > all occurances of Real to Number, and add complex to the tuple. > > -- > Rich "Roadie Rich" Lovely > > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. From roadierich at googlemail.com Mon Oct 5 00:17:53 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 4 Oct 2009 23:17:53 +0100 Subject: [Tutor] Using a list comp in place of a for loop In-Reply-To: <1426984540-1254609221-cardhu_decombobulator_blackberry.rim.net-1699972136-@bda932.bisx.prod.on.blackberry> References: <1426984540-1254609221-cardhu_decombobulator_blackberry.rim.net-1699972136-@bda932.bisx.prod.on.blackberry> Message-ID: 2009/10/3 afith13 : > Hi tutors, > > I've got a loop and a comprehension that do the same thing (as far as I can tell): > > for i in range(N): > ?someList.append.newObject(i) > > ...and... > > [someList.append.newObject(i) for i in range(N)] > > I'm tempted to write this as a list comp because it's a big list and I've read that list comps are faster than for loops in general. I'm hesitating because I'm not sure if building a big list of "None" objects and then throwing it away has any drawbacks. > > Thanks in advance, > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If you want a list comprehension to do the same as your original code, you need to write it as someList = [newObject(i) for i in range(N)] This avoids building the list of Nones, and only differs if someList already has values in it, in which case you can use: someList.extend(newObject(i) for i in range(N)) which will do exactly what your original code does, except using a list comp (actually a generator, which is pretty much the same thing), and won't generate and then throw away a list of Nones. I prefer list comprehensions over for-loops wherever possible because they're easier to read (IMHO). As for speed, let's take a look: >>> t_for = Timer("""l = [] ... for i in range(100): ... l.append(i)""") >>> t_slowComp = Timer("""l = [] ... [l.append(i) for i in range(100)] ... """) >>> t_comp = Timer("""l = [i for i in range(100)""") >>> t_addComp = Timer("""l = [] ... l += [i for i in range(100)]""") >>> t_extend = Timer("""l = [] ... l.extend(i for i in range(100))""") >>> min(t_for.repeat(3,10000)) 0.8266444478279027 >>> min(t_slowComp.repeat(3,10000)) 0.95501802603394026 >>> min(t_comp.repeat(3,10000)) 0.35897579161587601 >>> min(t_addComp.repeat(3,10000)) 0.37727895584498583 >>> min(t_extend.repeat(3,10000)) 0.59708203137552118 >>> As you can see, list comprehensions are better than twice the speed (in this simple example) of a regular for loop. With an existing list, adding a comprehension is surprisingly fast (I was expecting extend to be faster). I wasn't expecting the slow comprehension to be as slow as it is, but as you can see, it is slower than a standard for loop. Hope something in here has helped you, and has answered your question(s). -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. P.S. In case you're wondering, I feel the minimum of Timer.repeat() results is more applicable than an average, as I feel - and the docs agree - that it's a sort of "best speed", ignoring as many other drains of processing power as possible.) From rudiger.wolf at throughputfocus.com Mon Oct 5 11:57:13 2009 From: rudiger.wolf at throughputfocus.com (=?ISO-8859-1?Q?R=FCdiger=20Wolf?=) Date: Mon, 05 Oct 2009 10:57:13 +0100 Subject: [Tutor] using easy_install to download eggs In-Reply-To: References: Message-ID: <1254736633.7133.1338074787@webmail.messagingengine.com> http://stackoverflow.com/questions/529425/easyinstall-cache-downloaded-files pip (http://pypi.python.org/pypi/pip/) is a drop-in replacement for the easy_install tool and can do that. Just run easy_install pip and set an environment variable PIP_DOWNLOAD_CACHE to the path you want pip to store the files. Note that the cache won't work with dependencies that checkout from a source code repository (like svn/git/hg/bzr). Then use pip install instead of easy_install On Sun, 04 Oct 2009 18:41 +0000, "Tim Michelsen" wrote: > Hello, > I would like to use easy_install to cache packages registered at PyPi > locally. > > How can I do this for packages? > > I tried the hints from: > http://peak.telecommunity.com/DevCenter/EasyInstall#installing-on-un-networked-machines > > It worked for some packages. > But for others, the command > > easy_install -zxad. mercurial > > just creates a subdirectory and not an *.egg file. > > How can I > 1) use easy_install to download packages from PyPi to a locally saved > egg-file? > 2) use easy_install to download archinves (*.tar.gz / *.zip) to download > the > respective software package from the link indicated on PyPi? > From timmichelsen at gmx-topmail.de Mon Oct 5 14:28:50 2009 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Mon, 5 Oct 2009 12:28:50 +0000 (UTC) Subject: [Tutor] =?utf-8?q?using_easy=5Finstall_to_download_eggs?= References: <1254736633.7133.1338074787@webmail.messagingengine.com> Message-ID: Hi, thanks for the hint. > pip (http://pypi.python.org/pypi/pip/) is a drop-in replacement for the > easy_install tool and can do that. > > Just run easy_install pip and set an environment variable > PIP_DOWNLOAD_CACHE to the path you want pip to store the files. Note > that the cache won't work with dependencies that checkout from a source > code repository (like svn/git/hg/bzr). I tried this. It saves the downloaded packages in a form of: http%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2FB%2FBareNecessities% 2FBareNecessities-0.2.2.tar.gz.content-type http%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2FB%2FBareNecessities% 2FBareNecessities-0.2.2.tar.gz I was looking for *.egs or *.exe pachages. Any ideas? Regards, Timmie From rudiger.wolf at throughputfocus.com Mon Oct 5 15:06:13 2009 From: rudiger.wolf at throughputfocus.com (=?ISO-8859-1?Q?R=FCdiger=20Wolf?=) Date: Mon, 05 Oct 2009 14:06:13 +0100 Subject: [Tutor] using easy_install to download eggs In-Reply-To: References: <1254736633.7133.1338074787@webmail.messagingengine.com> Message-ID: <1254747973.891.1338096413@webmail.messagingengine.com> Snip from PIP http://pypi.python.org/pypi/pip/0.4 Differences From easy_install pip cannot install some packages. Specifically: * It cannot install from eggs. It only installs from source. (Maybe this will be changed sometime, but it's low priority.) If you want to download eggs then you might try basketweaver? http://pypi.python.org/pypi/basketweaver/ basketweaver is a tool for creating your own package index out of a directory full of eggs. You can then point to this index with e.g. zc.buildout or setuptools and thus be independant of PyPI. Cheers Rudiger On Mon, 05 Oct 2009 12:28 +0000, "Tim Michelsen" wrote: > Hi, > thanks for the hint. > > > pip (http://pypi.python.org/pypi/pip/) is a drop-in replacement for the > > easy_install tool and can do that. > > > > Just run easy_install pip and set an environment variable > > PIP_DOWNLOAD_CACHE to the path you want pip to store the files. Note > > that the cache won't work with dependencies that checkout from a source > > code repository (like svn/git/hg/bzr). > > I tried this. > > It saves the downloaded packages in a form of: > http%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2FB%2FBareNecessities% > 2FBareNecessities-0.2.2.tar.gz.content-type > http%3A%2F%2Fpypi.python.org%2Fpackages%2Fsource%2FB%2FBareNecessities% > 2FBareNecessities-0.2.2.tar.gz > > I was looking for *.egs or *.exe pachages. > > Any ideas? > > Regards, > Timmie > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From oltarasenko at gmail.com Mon Oct 5 16:22:43 2009 From: oltarasenko at gmail.com (Oleg Oltar) Date: Mon, 5 Oct 2009 17:22:43 +0300 Subject: [Tutor] Using command line tool with python script Message-ID: Hi! I want to try to use a command line script with my python application. The task is the following, my database stores some initial data for the script and I need to execute a command line application in a following way: $ application -parameter1 -file1 where file 1 is a file which contains my initial data, and parameter1 is unrelated parameter the workflow as I see it know is following initial_data = get_initial_data_from_db() file = open('temp.txt', 'w+') file.write(initial_data) file.save() os.popen4("application -parameter1 -file temp.txt") I wonder if that possible to execute this script (called application) without writing the file with initial data to the hard disk? Thanks, Oleg -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Oct 5 16:32:14 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 05 Oct 2009 10:32:14 -0400 Subject: [Tutor] Using command line tool with python script In-Reply-To: References: Message-ID: <4ACA036E.4090001@gmail.com> Oleg Oltar wrote: > Hi! > > I want to try to use a command line script with my python application. > The task is the following, my database stores some initial data for > the script and > I need to execute a command line application in a following way: > > $ application -parameter1 -file1 > > where file 1 is a file which contains my initial data, and parameter1 > is unrelated parameter > > the workflow as I see it know is following > > initial_data = get_initial_data_from_db() > file = open('temp.txt', 'w+') > file.write(initial_data) > file.save() > os.popen4("application -parameter1 -file temp.txt") > > I wonder if that possible to execute this script (called application) > without writing the file with initial data to the hard disk? Take a look at os.system() -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Mon Oct 5 18:59:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 5 Oct 2009 12:59:50 -0400 Subject: [Tutor] Using command line tool with python script In-Reply-To: References: Message-ID: <1c2a2c590910050959y7432ba21r86328d46627a96c7@mail.gmail.com> On Mon, Oct 5, 2009 at 10:22 AM, Oleg Oltar wrote: > os.popen4("application -parameter1 -file temp.txt") > > I wonder if that possible to execute this script (called application) > without writing the file with initial data to the hard disk? If "application" can take its input from stdin then you can use the subprocess module to launch it and pipe data to it. If "application" requires a file for input then I think you have to write a file. Kent From ziniatinklis at gmail.com Sun Oct 4 15:21:57 2009 From: ziniatinklis at gmail.com (Andrius) Date: Sun, 4 Oct 2009 14:21:57 +0100 Subject: [Tutor] small program In-Reply-To: References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> <4AC61E7B.5010902@gmail.com> <1d0897be0910020944i3b554a5fjaefb964256563dd3@mail.gmail.com> <1d0897be0910040459kcad08a2ra85633ae8cac348d@mail.gmail.com> Message-ID: <1d0897be0910040621y5eac295ak65dfbfdcd2a57a08@mail.gmail.com> Bye bye. Regards, Andrius On 04/10/2009, Luke Paireepinart wrote: > On Sun, Oct 4, 2009 at 1:59 PM, Andrius wrote: > >> Very good. Nice to hear that from another 'untouchable'. Must to >> confirm for your that I'm usually left wing fella, so, if you have >> nothing what to say for my in my case - please, fuck off. > > > Re: http://catb.org/~esr/faqs/smart-questions.html#not_losing > Good luck, > -Luke > From sander.sweers at gmail.com Mon Oct 5 21:28:56 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 05 Oct 2009 21:28:56 +0200 Subject: [Tutor] if n == 0 vs if not n Message-ID: <1254770936.5925.5.camel@infirit.lan> Hi Tutors, I am going through someone's python script and I am seeing a lot of the following boolean checks. if not s == "" if not n == 0 if b == True if not b == True etc.. All of these can be written without the == notation like "if n", "if s" etc. Now in this case where it is only used as boolean checks which would be the most pythonic way if writing these checks? Thanks Sander From vceder at canterburyschool.org Mon Oct 5 21:47:15 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Mon, 05 Oct 2009 15:47:15 -0400 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <1254770936.5925.5.camel@infirit.lan> References: <1254770936.5925.5.camel@infirit.lan> Message-ID: <4ACA4D43.1000407@canterburyschool.org> Hi Sander, PEP 8, the "Style Guide for Python Code" http://www.python.org/dev/peps/pep-0008/ is pretty clear that the shorter version is preferable: if s: if n: if b: if not b: and so on... Cheers, Vern Sander Sweers wrote: > Hi Tutors, > > I am going through someone's python script and I am seeing a lot of the > following boolean checks. > > if not s == "" > > if not n == 0 > > if b == True > > if not b == True > > etc.. > > All of these can be written without the == notation like "if n", "if s" > etc. > > Now in this case where it is only used as boolean checks which would be > the most pythonic way if writing these checks? > > Thanks > Sander > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From rudiger.wolf at throughputfocus.com Mon Oct 5 21:56:59 2009 From: rudiger.wolf at throughputfocus.com (=?ISO-8859-1?Q?R=FCdiger=20Wolf?=) Date: Mon, 05 Oct 2009 20:56:59 +0100 Subject: [Tutor] Using command line tool with python script In-Reply-To: <1c2a2c590910050959y7432ba21r86328d46627a96c7@mail.gmail.com> References: <1c2a2c590910050959y7432ba21r86328d46627a96c7@mail.gmail.com> Message-ID: <1254772619.16034.1338174655@webmail.messagingengine.com> On Mon, 05 Oct 2009 12:59 -0400, "Kent Johnson" wrote: > On Mon, Oct 5, 2009 at 10:22 AM, Oleg Oltar > wrote: > > > os.popen4("application -parameter1 -file temp.txt") > > > > I wonder if that possible to execute this script (called application) > > without writing the file with initial data to the hard disk? > > If "application" can take its input from stdin then you can use the > subprocess module to launch it and pipe data to it. If "application" > requires a file for input then I think you have to write a file. Matt Harrison have some notes and a video of a talk about good python scripting practices. He describes some patterns that enable you to write python scripts that can be chained together as they process data from one and send it to the next. See the following links for more info. http://panela.blog-city.com/oscon_scripting_with_python_handout.htm http://en.oreilly.com/oscon2009/public/schedule/detail/8317 He created a tool called poachplate so that it is easier to create these kind of scripts. http://pypi.python.org/pypi?%3Aaction=search&term=poachplate Regards Rudiger From dperlman at wisc.edu Mon Oct 5 22:41:08 2009 From: dperlman at wisc.edu (David Perlman) Date: Mon, 5 Oct 2009 15:41:08 -0500 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <333efb450909101915g625ff27ejca19fc6849b6be2d@mail.gmail.com> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> <81121468-12AE-4284-A587-229532722698@wisc.edu> <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> <65DFA0CC-43A7-41E3-9B3F-E343FC952064@wisc.edu> <333efb450909101915g625ff27ejca19fc6849b6be2d@mail.gmail.com> Message-ID: <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> OK, I thought I had this one fixed but it was weirder than I thought. I think I understand what's going on, but I wanted to check with the experts here. I have the following class definition, which does not subclass anything: class oneStim: def __init__(self, time, mods=[], dur=None, format='%1.2f'): self.time=time self.mods=mods self.dur=dur self.format=format def __cmp__(self,other): return cmp(self.time,other.time) def __repr__(self): timestr=self.format % self.time if self.mods == []: modstr='' else: modstr = '*' + ','.join(self.format % i for i in self.mods) if self.dur == None: durstr = '' else: durstr = ':' + (self.format % self.dur) return timestr + modstr + durstr def __len__(self): return len(self.__repr__()) >>> a=oneStim(40) >>> a 40.00 >>> a.mods.append(3) >>> a 40.00*3.00 >>> a.dur=10 >>> a 40.00*3.00:10.00 >>> a.mods.append(1) >>> a 40.00*3.00,1.00:10.00 So far so good, that's exactly what it's supposed to do. But now look: >>> b=oneStim(50) >>> b 50.00*3.00,1.00 The mods that were added to the first instance of oneStim also appear in the second, newly created instance! It appears that what is happening here is that the __init__() method is being parsed by the interpreter once at initial run, and at that time the statement "mods=[]" is being parsed, which means that the [] object is being instantiated once there at the beginning. So every instantiation of class oneStim ends up sharing a reference to the same list object, instead of each one having its own. I fixed this by changing it to "mods=None" and then setting it in the body of the __init__ method. Works fine now. My question is, is this just a quirky misbehavior, or is there a principled reason why the code I have shown above only instantiates the empty list in the arguments once? Thanks for any insight. As I said, I got it to work fine now, so this isn't critical, but I'm curious to understand why things work the way they do. :) -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From sander.sweers at gmail.com Mon Oct 5 22:37:21 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 05 Oct 2009 22:37:21 +0200 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: References: <1254770936.5925.5.camel@infirit.lan> Message-ID: <1254775041.5450.27.camel@infirit.lan> Thanks Wesly/Vern for the replies. On Mon, 2009-10-05 at 21:56 +0200, Luke Paireepinart wrote: > if not n == 0 > > if b == True can be written as if b. > > > However, > if not n == 0 can be written as if n != 0 but NOT as if n. > The reason why is that 0 is not equivalent to False even though it > evaluates to False. > So > if not n: > would be true for n = 0 and for n = "" and for n = None > but > if n != 0: > would be true for n = "" and n = None but not n = 0. Ah, have not thought about this one. In this case it checks the return code of a subprocess command which if not zero means build failure. I am leaving these as they are because in my opinion "if not returncode == 0" shows clearer what is going on than "if returncode". > Whoever wrote your code probably thinks he knows the types of the > variables beforehand so he's just making assumptions as to whether a > variable is an int / string / etc. So you can probably safely assume > that they're boolean checks, but I take no responsibility if you break > something :) When I make the changes and send in a patch it will be reviewed. So any siliness I come up with will be shot down quickly ;-) Thanks Sander From srilyk at gmail.com Mon Oct 5 22:20:21 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 5 Oct 2009 15:20:21 -0500 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <4ACA20F3.3050408@gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> <333efb450910020727r7a1fcd5dma654b7ba924efe14@mail.gmail.com> <4ACA20F3.3050408@gmail.com> Message-ID: <333efb450910051320l3006ea16pb9f5a887a3dfadc3@mail.gmail.com> I think you forgot to hit Reply-all, so forwarding on to the list with my response On Mon, Oct 5, 2009 at 11:38 AM, Nicola De Quattro < lead.expression at gmail.com> wrote: > Wayne ha scritto: > >> The most difficult task would be analyzing the image and possibly some of >> the graph generation. >> > > > Yes I has thought so. Probably it is the same for every language. > > Now I think I could begin with some simple script to come into the Python > world, so I'll start building the easiest components of final tool (perhaps > opening the image and rotate it). > That one should be fairly simple - my guess is it should take < 5 lines to do something like that with PIL or ImageMagick > > Another question I did'nt ask to the list is about the IDE. There's > something like this in Python or not? I've used NetBeans for C. I'm not so > expert with IDE but I think it might be useful something like this in order > to share the same platform on both Linux and Windows (I think to develop on > two different computers). > There are /many/ IDEs available, ranging from free (IDLE, included with python) to over a hundred dollars (the super version of Wing IDE). > If you suggest to use no IDE, the solution I've adopted since now is to use > gedit and python bash program under Linux (it recognizes python sintax) and > notepad++ with... what? under Windows (I think there's something like > "python" package under Windows). > My suggestion is this: Work with what you're comfortable with. If you want to use gedit and python interpreter, go ahead. My personal preference (on any/all systems) is vi/vim in one terminal window for the actual coding, and IPython in another window for testing snippets of code. I have some fairly extensive python-centric modifications to my .vimrc and other scripts and plugins. I'm sure you'll find many different workflows that people use and several folks will probably offer their setups for consideration. I hope you find something comfortable for you, and feel free to ask any questions if you get stuck. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Oct 5 00:07:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 4 Oct 2009 18:07:13 -0400 Subject: [Tutor] small program In-Reply-To: References: <1d0897be0910010431t2a8aea1ew4f6bfdf155e3350c@mail.gmail.com> <4AC61E7B.5010902@gmail.com> <1d0897be0910020944i3b554a5fjaefb964256563dd3@mail.gmail.com> <1d0897be0910040459kcad08a2ra85633ae8cac348d@mail.gmail.com> Message-ID: <1c2a2c590910041507r457fb313m1522275719f701c4@mail.gmail.com> This language is not appropriate for this list and I'm sorry to see it used even in a private reply. Let's keep the discussions here polite and respectful. Thanks, Kent On Sun, Oct 4, 2009 at 8:40 AM, Luke Paireepinart wrote: > > > On Sun, Oct 4, 2009 at 1:59 PM, Andrius wrote: >> >> Very good. Nice to hear that from another 'untouchable'. Must to >> confirm for your that I'm usually left wing fella, so, if you have >> nothing what to say for my in my case - please, f--- off. > > Re:?http://catb.org/~esr/faqs/smart-questions.html#not_losing > Good luck, > -Luke > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From bgailer at gmail.com Mon Oct 5 23:25:06 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 05 Oct 2009 17:25:06 -0400 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> <81121468-12AE-4284-A587-229532722698@wisc.edu> <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> <65DFA0CC-43A7-41E3-9B3F-E343FC952064@wisc.edu> <333efb450909101915g625ff27ejca19fc6849b6be2d@mail.gmail.com> <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> Message-ID: <4ACA6432.7020003@gmail.com> An HTML attachment was scrubbed... URL: From nrhird at gmail.com Mon Oct 5 23:24:39 2009 From: nrhird at gmail.com (Nick Hird) Date: Mon, 5 Oct 2009 17:24:39 -0400 Subject: [Tutor] Which version to start with? Message-ID: What is the best version of python to start out with? I see some discussions on the net about not going to 3.1 but staying with the 2.x releases. But then i see that 3.1 is better if your just starting. Thanks for any insight on which version to go with. -Nick From srilyk at gmail.com Mon Oct 5 23:39:38 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 5 Oct 2009 16:39:38 -0500 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> <81121468-12AE-4284-A587-229532722698@wisc.edu> <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> <65DFA0CC-43A7-41E3-9B3F-E343FC952064@wisc.edu> <333efb450909101915g625ff27ejca19fc6849b6be2d@mail.gmail.com> <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> Message-ID: <333efb450910051439k45514495rf13d25d6918f9b17@mail.gmail.com> On Mon, Oct 5, 2009 at 3:41 PM, David Perlman wrote: > OK, I thought I had this one fixed but it was weirder than I thought. I > think I understand what's going on, but I wanted to check with the experts > here. > > I have the following class definition, which does not subclass anything: > > class oneStim: > def __init__(self, time, mods=[], dur=None, format='%1.2f'): > self.time=time > self.mods=mods > I think this is where the fun occurs (AFAIK, I'm not an expert on how the python lists/namespaces work by any means) You are familiar with the following concept/behavior, correct? def f1(mylist): mylist.append(3) a = [1,2] >>> f1(a) >>> a [1, 2, 3] because python doesn't actually pass a copy, just the reference of the list. So I'm betting that when you say self.mods = mods the second time you call the function you're creating a reference to the self.mods that's in the oneStim object namespace. Ahhh... After some experimentation, I think I see what's going on. class A: def __init__(self, mylist = []): self.mylist = mylist a = A() b = A() In [69]: a.__init__.im_func Out[69]: In [70]: A.__init__.im_func Out[70]: In [71]: b.__init__.im_func Out[71]: The function is at the same address for the parent class and each instance of the class, so I think the reference it creates is to the list in the same location as well. Ah... some enlightenment has struck with what bob posted. The "initial value" of that function is the /exact same/ each time the function is called. When you pass a parameter to the function it will be re-evaluated, but until then the pre-stored reference is used. I'm not sure if that's terribly clear or makes much sense, it's a bit of a difficult concept to wrap my head around, but I *think* I've got it. Hopefully you can get it, too, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Mon Oct 5 23:43:22 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 5 Oct 2009 22:43:22 +0100 Subject: [Tutor] Which version to start with? In-Reply-To: References: Message-ID: 2009/10/5 Nick Hird : > What is the best version of python to start out with? I see some > discussions on the net about not going to 3.1 but staying with the 2.x > releases. But then i see that 3.1 is better if your just starting. > Thanks for any insight on which version to go with. > -Nick > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I've got to say I think version 2.6 is the one to go with. Yes, 3.1 has been out for a while now, so support for it is getting better, but 2.6 code is very much the same as 2.5, so support has been around for much longer, and therefore will be much more stable. The same applies to tutorials: As code has changed very little since 2.0, there are likely to be less errors, and a much larger archive of questions asked previously - most of the posts to this list, archived at http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor (among a few other places), are about 2.x code. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From srilyk at gmail.com Mon Oct 5 23:46:36 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 5 Oct 2009 16:46:36 -0500 Subject: [Tutor] Which version to start with? In-Reply-To: References: Message-ID: <333efb450910051446x2a74b0ddu709b3d3e6b4f368@mail.gmail.com> On Mon, Oct 5, 2009 at 4:24 PM, Nick Hird wrote: > What is the best version of python to start out with? I see some > discussions on the net about not going to 3.1 but staying with the 2.x > releases. But then i see that 3.1 is better if your just starting. > Thanks for any insight on which version to go with. > -Nick > It used to be that few tutorials were updated to 3.x, but I know at least Alan's is finished(right?). The big issue with going to 3.1 is that most of the modules haven't been ported yet, so if you want to use any cool 3rd party modules you may have issues. For beginning there's probably nothing wrong with 3.1, but I think I'd recommend sticking with 2.6. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Mon Oct 5 23:10:52 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 5 Oct 2009 14:10:52 -0700 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <78b3a9580910051410h1d98e7rd2d6042969befc2a@mail.gmail.com> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> <81121468-12AE-4284-A587-229532722698@wisc.edu> <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> <65DFA0CC-43A7-41E3-9B3F-E343FC952064@wisc.edu> <333efb450909101915g625ff27ejca19fc6849b6be2d@mail.gmail.com> <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> <78b3a9580910051410h1d98e7rd2d6042969befc2a@mail.gmail.com> Message-ID: <78b3a9580910051410l5f85f567qfc81c8b372c3b66f@mail.gmail.com> > ? ?def __init__(self, time, mods=[], dur=None, format='%1.2f'): > ? ? ? ?: > The mods that were added to the first instance of oneStim also appear in the > second, newly created instance! > > It appears that what is happening here is that the __init__() method is > being parsed by the interpreter once at initial run, and at that time the > statement "mods=[]" is being parsed, which means that the [] object is being > instantiated once there at the beginning. ?So every instantiation of class > oneStim ends up sharing a reference to the same list object, instead of each > one having its own. > > I fixed this by changing it to "mods=None" and then setting it in the body > of the __init__ method. ?Works fine now. > > My question is, is this just a quirky misbehavior, or is there a principled > reason why the code I have shown above only instantiates the empty list in > the arguments once? good eyes david, you pretty much nailed it. what you describe is *exactly* what's going on. you've run into one of the stumbling blocks that catch new and seasoned Python programmers all the time: using a mutable object as a default value... these objects are assigned early, hence the reason why Python behaves the way it does. IOW, they are *not* assigned on a per-call basis. (this is actually a popular interview question.) :-) there is plenty of documentation online about this phenomenon, as it's been with Python since the early days, or one or more of the other tutors can post the appropriate links. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ?http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Mon Oct 5 21:52:20 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 5 Oct 2009 12:52:20 -0700 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <1254770936.5925.5.camel@infirit.lan> References: <1254770936.5925.5.camel@infirit.lan> Message-ID: <78b3a9580910051252i51c64aa5v5fa4c0f6229ecdc0@mail.gmail.com> > I am going through someone's python script and I am seeing a lot of the > following boolean checks. > > if not s == "" > if not n == 0 > if b == True > if not b == True > etc.. > > All of these can be written without the == notation like "if n", "if s" > etc.Now in this case where it is only used as boolean checks which would be > the most pythonic way if writing these checks? it would be the same as what you have already described. checking against Boolean literals follows the same logic, i.e., "if b", "if not b", etc. of course, the reasoning behind what you said and my suggestion is that all Python objects evaluate to some sort of Boolean value. the "== 0" and '== ""' (and their corresponding "not"s) aren't necessary because both 0 and "" have a Boolean False value, as does False. the general rule is that any numeric zero (0, 0.0, 0.0+0.0J, etc.) or empty "container" (i.e., str, list, tuple, dict, set, etc.), are all False. all other values are True. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Mon Oct 5 23:59:31 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 5 Oct 2009 14:59:31 -0700 Subject: [Tutor] Which version to start with? In-Reply-To: References: Message-ID: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> On Mon, Oct 5, 2009 at 2:24 PM, Nick Hird wrote: > What is the best version of python to start out with? I see some > discussions on the net about not going to 3.1 but staying with the 2.x > releases. But then i see that 3.1 is better if your just starting. greetings nick! ironically, i just gave a talk on this very subject yesterday afternoon(!) http://www.siliconvalley-codecamp.com/Sessions.aspx?OnlyOne=true&id=227 basically, if you're starting from scratch as a hobby with no pre-existing code, then learning 3.x is okay. however, since most of the world still runs on Python 2, most printed and online books and tutorials are still on Python 2, and the code at most companies using Python is still on version 2, i would recommended any release 2.6 (and newer). the reason is because 2.6 is the first release that has 3.x-specific features backported to it, so really, it's the first Python 2 release that lets you start coding against a 3.x interpreter. you can learn Python using 2.6+ then absorb the differences and move to Python 3.x quite easily. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Tue Oct 6 00:13:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 5 Oct 2009 18:13:41 -0400 Subject: [Tutor] Poorly understood error involving class inheritance In-Reply-To: <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> References: <5D4B5145-7433-45C6-94D2-73FD649482AD@wisc.edu> <81121468-12AE-4284-A587-229532722698@wisc.edu> <1c2a2c590909101417sd57bea5r23b6002894ffce52@mail.gmail.com> <65DFA0CC-43A7-41E3-9B3F-E343FC952064@wisc.edu> <333efb450909101915g625ff27ejca19fc6849b6be2d@mail.gmail.com> <132718BC-6D08-4B18-9453-A3335F3F5E68@wisc.edu> Message-ID: <1c2a2c590910051513s2e02d5a7s828775551d4d8d74@mail.gmail.com> On Mon, Oct 5, 2009 at 4:41 PM, David Perlman wrote: > I fixed this by changing it to "mods=None" and then setting it in the body > of the __init__ method. ?Works fine now. That is the correct fix. > My question is, is this just a quirky misbehavior, or is there a principled > reason why the code I have shown above only instantiates the empty list in > the arguments once? This is a FA. Default arguments are shared between all uses: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm From nrhird at gmail.com Tue Oct 6 01:25:59 2009 From: nrhird at gmail.com (Nick Hird) Date: Mon, 5 Oct 2009 19:25:59 -0400 Subject: [Tutor] Which version to start with? In-Reply-To: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> References: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> Message-ID: Thanks all! I think i will install the newly released 2.6.3 and go from there. Its a little intimidating but i guess i gotta jump right in and get my feet wet. Thanks again! -Nick On Mon, Oct 5, 2009 at 5:59 PM, wesley chun wrote: > On Mon, Oct 5, 2009 at 2:24 PM, Nick Hird wrote: >> What is the best version of python to start out with? I see some >> discussions on the net about not going to 3.1 but staying with the 2.x >> releases. But then i see that 3.1 is better if your just starting. > > > greetings nick! > > ironically, i just gave a talk on this very subject yesterday afternoon(!) > http://www.siliconvalley-codecamp.com/Sessions.aspx?OnlyOne=true&id=227 > > basically, if you're starting from scratch as a hobby with no > pre-existing code, then learning 3.x is okay. however, since most of > the world still runs on Python 2, most printed and online books and > tutorials are still on Python 2, and the code at most companies using > Python is still on version 2, i would recommended any release 2.6 (and > newer). the reason is because 2.6 is the first release that has > 3.x-specific features backported to it, so really, it's the first > Python 2 release that lets you start coding against a 3.x interpreter. > > you can learn Python using 2.6+ then absorb the differences and move > to Python 3.x quite easily. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > ? ?http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -- --Nick From davea at ieee.org Tue Oct 6 02:23:29 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 05 Oct 2009 20:23:29 -0400 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <4ACA4D43.1000407@canterburyschool.org> References: <1254770936.5925.5.camel@infirit.lan> <4ACA4D43.1000407@canterburyschool.org> Message-ID: <4ACA8E01.2070008@ieee.org> Vern Ceder wrote: >
Hi Sander, > > PEP 8, the "Style Guide for Python Code" > http://www.python.org/dev/peps/pep-0008/ is pretty clear that the > shorter version is preferable: > > if s: > > if n: > > if b: > > if not b: > > and so on... > > Cheers, > Vern > > Sander Sweers wrote: >> Hi Tutors, >> >> I am going through someone's python script and I am seeing a lot of the >> following boolean checks. >> >> if not s == "" >> >> if not n == 0 >> >> if b == True >> >> if not b == True >> >> etc.. >> >> All of these can be written without the == notation like "if n", "if s" >> etc. >> >> Now in this case where it is only used as boolean checks which would be >> the most pythonic way if writing these checks? >> >> Thanks >> Sander >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > The shorter version may be preferable, but it doesn't generally give the same results. Without knowing the possible data, these substitutions are not safe. For example, replacing "if not n == 0" with "if n" will give different results for values of "", [] and so on. It WILL work if you know that n is an int or float, however. DaveA From vceder at canterburyschool.org Tue Oct 6 02:40:25 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Mon, 05 Oct 2009 20:40:25 -0400 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <4ACA8E01.2070008@ieee.org> References: <1254770936.5925.5.camel@infirit.lan> <4ACA4D43.1000407@canterburyschool.org> <4ACA8E01.2070008@ieee.org> Message-ID: <4ACA91F9.8030204@canterburyschool.org> Dave Angel wrote: >>> Now in this case where it is only used as boolean checks which would be >>> the most pythonic way if writing these checks? >>> >> > The shorter version may be preferable, but it doesn't generally give the > same results. Without knowing the possible data, these substitutions > are not safe. > > For example, replacing "if not n == 0" with "if n" > > will give different results for values of "", [] and so on. It > WILL work if you know that n is an int or float, however. > > DaveA True, I took the OP's statement that they were to be used "only as boolean checks" to mean that there was no type mixing going on. Personally, I would say that checking a list or string for equality (or lack thereof) with 0 is even less "preferable". ;) Otherwise, one would at least prefer "if n != 0" to "if not n == 0", I would think. Cheers, Vern -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From rabidpoobear at gmail.com Mon Oct 5 21:56:11 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 5 Oct 2009 21:56:11 +0200 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <1254770936.5925.5.camel@infirit.lan> References: <1254770936.5925.5.camel@infirit.lan> Message-ID: On Mon, Oct 5, 2009 at 9:28 PM, Sander Sweers wrote: > > Hi Tutors, > > I am going through someone's python script and I am seeing a lot of the > following boolean checks. > > if not s == "" > > if not n == 0 > > if b == True > > if not b == True > > etc.. > > All of these can be written without the == notation like "if n", "if s" > No, they cannot. Some of them can be, others cannot. if b == True can be written as if b. However, if not n == 0 can be written as if n != 0 but NOT as if n. The reason why is that 0 is not equivalent to False even though it evaluates to False. So if not n: would be true for n = 0 and for n = "" and for n = None but if n != 0: would be true for n = "" and n = None but not n = 0. The same is true for if not s == "" > Now in this case where it is only used as boolean checks which would be > the most pythonic way if writing these checks? > If you're sure they're boolean checks, "if n:" or "if not n:" is usually how I see it written. Whoever wrote your code probably thinks he knows the types of the variables beforehand so he's just making assumptions as to whether a variable is an int / string / etc. So you can probably safely assume that they're boolean checks, but I take no responsibility if you break something :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Tue Oct 6 14:59:03 2009 From: beachkid at insightbb.com (Ken G.) Date: Tue, 06 Oct 2009 08:59:03 -0400 Subject: [Tutor] Which version to start with? In-Reply-To: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> References: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> Message-ID: <4ACB3F17.1010205@insightbb.com> I am just starting on Python 2.6.2 on Ubuntu 9.04 and I am slightly confused with the numerous tutorials and books available for learning the language. Is there any good recommendation for a good but easy tutorial on the Internet to learn Python? Ken wesley chun wrote: > On Mon, Oct 5, 2009 at 2:24 PM, Nick Hird wrote: > >> What is the best version of python to start out with? I see some >> discussions on the net about not going to 3.1 but staying with the 2.x >> releases. But then i see that 3.1 is better if your just starting. >> > > > greetings nick! > > ironically, i just gave a talk on this very subject yesterday afternoon(!) > http://www.siliconvalley-codecamp.com/Sessions.aspx?OnlyOne=true&id=227 > > basically, if you're starting from scratch as a hobby with no > pre-existing code, then learning 3.x is okay. however, since most of > the world still runs on Python 2, most printed and online books and > tutorials are still on Python 2, and the code at most companies using > Python is still on version 2, i would recommended any release 2.6 (and > newer). the reason is because 2.6 is the first release that has > 3.x-specific features backported to it, so really, it's the first > Python 2 release that lets you start coding against a 3.x interpreter. > > you can learn Python using 2.6+ then absorb the differences and move > to Python 3.x quite easily. > > hope this helps! > -- wesley > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Oct 6 15:04:11 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 6 Oct 2009 08:04:11 -0500 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <1254775041.5450.27.camel@infirit.lan> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> Message-ID: <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> On Mon, Oct 5, 2009 at 3:37 PM, Sander Sweers wrote: > Thanks Wesly/Vern for the replies. > > On Mon, 2009-10-05 at 21:56 +0200, Luke Paireepinart wrote: > > if not n == 0 > > > > if b == True can be written as if b. > > > > > > However, > > if not n == 0 can be written as if n != 0 but NOT as if n. > > The reason why is that 0 is not equivalent to False even though it > > evaluates to False. > > So > > if not n: > > would be true for n = 0 and for n = "" and for n = None > > but > > if n != 0: > > would be true for n = "" and n = None but not n = 0. > > Ah, have not thought about this one. In this case it checks the return > code of a subprocess command which if not zero means build failure. I am > leaving these as they are because in my opinion "if not returncode == 0" > shows clearer what is going on than "if returncode". > If it's checking the returncode against a value, Vern makes a good point: if returncode != 0 makes a whole lot more sense than "if not returncode == 0" Though when dealing with an integer return code, doesn't it make more sense to use the "is" operator? if returncode is 0: #do something if returncode is not 0: #do something -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Oct 6 15:32:52 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 6 Oct 2009 08:32:52 -0500 Subject: [Tutor] Which version to start with? In-Reply-To: <4ACB3F17.1010205@insightbb.com> References: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> <4ACB3F17.1010205@insightbb.com> Message-ID: <333efb450910060632p336a6865h6dff19478422c756@mail.gmail.com> On Tue, Oct 6, 2009 at 7:59 AM, Ken G. wrote: > I am just starting on Python 2.6.2 on Ubuntu 9.04 and I am slightly > confused with the numerous tutorials and books available for learning the > language. Is there any good recommendation for a good but easy tutorial on > the Internet to learn Python? > > Ken > Alan has a good tutorial: www.alan-g.me.uk/ I haven't read it, but a lot of others on here are big fans of Wesley's book: http://python.net/crew/wesc/cpp/ There are several other sources and tutorials around, those are just the first two that popped into my mind :) I kinda hopped around to various tutorials, especially since I've programmed before (and am a CS major), so a lot of the concepts were a bit easier for me to grasp. Alan's tutorial does a great job explaining a lot of concepts behind programming in general and ties them to programming in python. HTH, Wayne > > wesley chun wrote: > > On Mon, Oct 5, 2009 at 2:24 PM, Nick Hird wrote: > > > What is the best version of python to start out with? I see some > discussions on the net about not going to 3.1 but staying with the 2.x > releases. But then i see that 3.1 is better if your just starting. > > > greetings nick! > > ironically, i just gave a talk on this very subject yesterday afternoon(!)http://www.siliconvalley-codecamp.com/Sessions.aspx?OnlyOne=true&id=227 > > basically, if you're starting from scratch as a hobby with no > pre-existing code, then learning 3.x is okay. however, since most of > the world still runs on Python 2, most printed and online books and > tutorials are still on Python 2, and the code at most companies using > Python is still on version 2, i would recommended any release 2.6 (and > newer). the reason is because 2.6 is the first release that has > 3.x-specific features backported to it, so really, it's the first > Python 2 release that lets you start coding against a 3.x interpreter. > > you can learn Python using 2.6+ then absorb the differences and move > to Python 3.x quite easily. > > hope this helps! > -- wesley > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From didar.hossain at gmail.com Tue Oct 6 15:59:41 2009 From: didar.hossain at gmail.com (Didar Hossain) Date: Tue, 6 Oct 2009 19:29:41 +0530 Subject: [Tutor] Checking for Python version Message-ID: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> Hi, I am using the following code to check for the Python version - import os t = os.sys.version_info[0:2] if (t[0] + t[1]) < 6: os.sys.exit("Need at least Python 2.4") del t This snippet is put at the beginning of the single script file before the rest of the code. I need to check for the minimum specific version because I am using the "@staticmethod" directive. Is there a prettier way or is this fine? Regards, Didar From chuang.lewis at gmail.com Tue Oct 6 16:07:05 2009 From: chuang.lewis at gmail.com (Lewis Chuang) Date: Tue, 06 Oct 2009 16:07:05 +0200 Subject: [Tutor] Which version to start with? In-Reply-To: <333efb450910060632p336a6865h6dff19478422c756@mail.gmail.com> References: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> <4ACB3F17.1010205@insightbb.com> <333efb450910060632p336a6865h6dff19478422c756@mail.gmail.com> Message-ID: <4ACB4F09.1000800@gmail.com> As someone who learned (about) programming by copying and pasting code, I really appreciate," Python for software design - how to think like a computer scientist" by Allen Downey. It really talks you through the workflow of programming, rather than just give you a long list of things that you can do if you learn to program in X. A legally free manuscript is available here: http://www.greenteapress.com/thinkpython/ Best wishes, Lewis Wayne wrote: > > > On Tue, Oct 6, 2009 at 7:59 AM, Ken G. > wrote: > > I am just starting on Python 2.6.2 on Ubuntu 9.04 and I am > slightly confused with the numerous tutorials and books available > for learning the language. Is there any good recommendation for a > good but easy tutorial on the Internet to learn Python? > > Ken > > > Alan has a good tutorial: > www.alan-g.me.uk/ > > I haven't read it, but a lot of others on here are big fans of > Wesley's book: > http://python.net/crew/wesc/cpp/ > > There are several other sources and tutorials around, those are just > the first two that popped into my mind :) > > I kinda hopped around to various tutorials, especially since I've > programmed before (and am a CS major), so a lot of the concepts were a > bit easier for me to grasp. > > Alan's tutorial does a great job explaining a lot of concepts behind > programming in general and ties them to programming in python. > > HTH, > Wayne > > > > > wesley chun wrote: >> On Mon, Oct 5, 2009 at 2:24 PM, Nick Hird wrote: >> >>> What is the best version of python to start out with? I see some >>> discussions on the net about not going to 3.1 but staying with the 2.x >>> releases. But then i see that 3.1 is better if your just starting. >>> >> greetings nick! >> >> ironically, i just gave a talk on this very subject yesterday afternoon(!) >> http://www.siliconvalley-codecamp.com/Sessions.aspx?OnlyOne=true&id=227 >> >> basically, if you're starting from scratch as a hobby with no >> pre-existing code, then learning 3.x is okay. however, since most of >> the world still runs on Python 2, most printed and online books and >> tutorials are still on Python 2, and the code at most companies using >> Python is still on version 2, i would recommended any release 2.6 (and >> newer). the reason is because 2.6 is the first release that has >> 3.x-specific features backported to it, so really, it's the first >> Python 2 release that lets you start coding against a 3.x interpreter. >> >> you can learn Python using 2.6+ then absorb the differences and move >> to Python 3.x quite easily. >> >> hope this helps! >> -- wesley >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn?t. - Primo Levi > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From cwitts at compuscan.co.za Tue Oct 6 16:26:23 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 06 Oct 2009 16:26:23 +0200 Subject: [Tutor] Checking for Python version In-Reply-To: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> Message-ID: <4ACB538F.5020107@compuscan.co.za> Didar Hossain wrote: > Hi, > > I am using the following code to check for the Python version - > > import os > > t = os.sys.version_info[0:2] > if (t[0] + t[1]) < 6: > os.sys.exit("Need at least Python 2.4") > del t > > This snippet is put at the beginning of the single script file before > the rest of the code. > I need to check for the minimum specific version because I am using > the "@staticmethod" > directive. > > Is there a prettier way or is this fine? > > Regards, > Didar > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Your version will fail if the person is running Python 3.0, 3.1 up until the 3.3 series which is not good. Neater looking (imo) code below. from sys import version_info, exit if version_info[0] == 1 or (version_info[0] == 2 and version_info[1] < 4): exit("Please upgrade to Python 2.4 or greater.") -- Kind Regards, Christian Witts From srilyk at gmail.com Tue Oct 6 16:42:04 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 6 Oct 2009 09:42:04 -0500 Subject: [Tutor] Checking for Python version In-Reply-To: <4ACB538F.5020107@compuscan.co.za> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> Message-ID: <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> On Tue, Oct 6, 2009 at 9:26 AM, Christian Witts wrote: > Didar Hossain wrote: > >> Hi, >> >> I am using the following code to check for the Python version - >> >> import os >> >> t = os.sys.version_info[0:2] >> if (t[0] + t[1]) < 6: >> os.sys.exit("Need at least Python 2.4") >> del t >> >> This snippet is put at the beginning of the single script file before >> the rest of the code. >> I need to check for the minimum specific version because I am using >> the "@staticmethod" >> directive. >> >> Is there a prettier way or is this fine? > > Is there anything wrong with using this? import sys if sys.version < '2.4': sys.exit("Need at least Python 2.4") AFAIK the string comparison is reliable -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Oct 6 16:46:33 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 6 Oct 2009 07:46:33 -0700 Subject: [Tutor] Checking for Python version In-Reply-To: <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> Message-ID: <20091006144633.GA70558@dragon.alchemy.com> On Tue, Oct 06, 2009 at 09:42:04AM -0500, Wayne wrote: > On Tue, Oct 6, 2009 at 9:26 AM, Christian Witts wrote: > if sys.version < '2.4': > sys.exit("Need at least Python 2.4") > > AFAIK the string comparison is reliable Not quite. What happens when you compare '2.4' and '2.10'? -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From srilyk at gmail.com Tue Oct 6 16:47:43 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 6 Oct 2009 09:47:43 -0500 Subject: [Tutor] Checking for Python version In-Reply-To: <20091006144633.GA70558@dragon.alchemy.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> <20091006144633.GA70558@dragon.alchemy.com> Message-ID: <333efb450910060747x35d3b3eep2d688c2e3018ed58@mail.gmail.com> On Tue, Oct 6, 2009 at 9:46 AM, Steve Willoughby wrote: > On Tue, Oct 06, 2009 at 09:42:04AM -0500, Wayne wrote: > > On Tue, Oct 6, 2009 at 9:26 AM, Christian Witts >wrote: > > if sys.version < '2.4': > > sys.exit("Need at least Python 2.4") > > > > AFAIK the string comparison is reliable > > Not quite. What happens when you compare '2.4' and '2.10'? > >>> '2.4' > '2.10' True > > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Oct 6 16:57:50 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 6 Oct 2009 07:57:50 -0700 Subject: [Tutor] Checking for Python version In-Reply-To: <333efb450910060747x35d3b3eep2d688c2e3018ed58@mail.gmail.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> <20091006144633.GA70558@dragon.alchemy.com> <333efb450910060747x35d3b3eep2d688c2e3018ed58@mail.gmail.com> Message-ID: <20091006145750.GB70558@dragon.alchemy.com> On Tue, Oct 06, 2009 at 09:47:43AM -0500, Wayne wrote: > On Tue, Oct 6, 2009 at 9:46 AM, Steve Willoughby wrote: > > > On Tue, Oct 06, 2009 at 09:42:04AM -0500, Wayne wrote: > > > On Tue, Oct 6, 2009 at 9:26 AM, Christian Witts > >wrote: > > > if sys.version < '2.4': > > > sys.exit("Need at least Python 2.4") > > > > > > AFAIK the string comparison is reliable > > > > Not quite. What happens when you compare '2.4' and '2.10'? > > > > >>> '2.4' > '2.10' > True Exactly. So it doesn't work. In typical software release numbering, 2.10 is the tenth minor version of the 2.x major version series, so 2.10 is later than 2.4, but comparing as ASCII strings, it comes out the other way around. Also note that '10.1' < '5.7' -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From davea at ieee.org Tue Oct 6 16:58:58 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 06 Oct 2009 10:58:58 -0400 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> Message-ID: <4ACB5B32.7000603@ieee.org> Wayne wrote: > On Mon, Oct 5, 2009 at 3:37 PM, Sander Sweers wrote: > > >> Thanks Wesly/Vern for the replies. >> >> On Mon, 2009-10-05 at 21:56 +0200, Luke Paireepinart wrote: >> >>> if not n == 0 >>> >>> if b == True can be written as if b. >>> >>> >>> However, >>> if not n == 0 can be written as if n != 0 but NOT as if n. >>> The reason why is that 0 is not equivalent to False even though it >>> evaluates to False. >>> So >>> if not n: >>> would be true for n = 0 and for n = "" and for n = None >>> but >>> if n != 0: >>> would be true for n = "" and n = None but not n = 0. >>> >> Ah, have not thought about this one. In this case it checks the return >> code of a subprocess command which if not zero means build failure. I am >> leaving these as they are because in my opinion "if not returncode == 0" >> shows clearer what is going on than "if returncode". >> >> > > If it's checking the returncode against a value, Vern makes a good point: > > if returncode != 0 makes a whole lot more sense than "if not returncode == > 0" > > Though when dealing with an integer return code, doesn't it make more sense > to use the "is" operator? > > if returncode is 0: > #do something > > if returncode is not 0: > #do something > > -Wayne > > No, because you're not assured that all integers that are equal are the same object. Python optimizes that for small integers, but there's no documented range that you can count on it. >>> x = 374 >>> y = 374 >>> print id(x), id(y) 12721272 12721296 >>> x==y True >>> x is y False DaveA From tmz at pobox.com Tue Oct 6 17:02:22 2009 From: tmz at pobox.com (Todd Zullinger) Date: Tue, 6 Oct 2009 11:02:22 -0400 Subject: [Tutor] Checking for Python version In-Reply-To: <4ACB538F.5020107@compuscan.co.za> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> Message-ID: <20091006150222.GJ4551@inocybe.localdomain> Christian Witts wrote: > Your version will fail if the person is running Python 3.0, 3.1 up > until the 3.3 series which is not good. Neater looking (imo) code > below. > > from sys import version_info, exit > > if version_info[0] == 1 or (version_info[0] == 2 and version_info[1] < 4): > exit("Please upgrade to Python 2.4 or greater.") This would fail on python < 2.0, as version_info is not available. So you'd want to catch that, if you want to gracefully handle ancient versions of python. You could also just compare the version_info tuple. This is a bit ugly, but it works at least back to 1.5.2: import sys min_version = '2.4' upgrade_msg = 'Please upgrade to Python %s or greater' % min_version try: min = tuple(map(int, min_version.split('.'))) ver = sys.version_info[:3] if ver < min: sys.exit(upgrade_msg) except AttributeError: sys.exit(upgrade_msg) I don't have any python 3.x systems to test though. -- Todd OpenPGP -> KeyID: 0xBEAF0CE3 | URL: www.pobox.com/~tmz/pgp ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose I were a member of Congress, and suppose I were an idiot. But, I repeat myself. -- Mark Twain -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 542 bytes Desc: not available URL: From srilyk at gmail.com Tue Oct 6 17:02:21 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 6 Oct 2009 10:02:21 -0500 Subject: [Tutor] Checking for Python version In-Reply-To: <20091006145750.GB70558@dragon.alchemy.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> <20091006144633.GA70558@dragon.alchemy.com> <333efb450910060747x35d3b3eep2d688c2e3018ed58@mail.gmail.com> <20091006145750.GB70558@dragon.alchemy.com> Message-ID: <333efb450910060802r409d0e0n64fa8a27169c907@mail.gmail.com> On Tue, Oct 6, 2009 at 9:57 AM, Steve Willoughby wrote: > On Tue, Oct 06, 2009 at 09:47:43AM -0500, Wayne wrote: > > On Tue, Oct 6, 2009 at 9:46 AM, Steve Willoughby > wrote: > > > > > On Tue, Oct 06, 2009 at 09:42:04AM -0500, Wayne wrote: > > > > On Tue, Oct 6, 2009 at 9:26 AM, Christian Witts < > cwitts at compuscan.co.za > > > >wrote: > > > > if sys.version < '2.4': > > > > sys.exit("Need at least Python 2.4") > > > > > > > > AFAIK the string comparison is reliable > > > > > > Not quite. What happens when you compare '2.4' and '2.10'? > > > > > > > >>> '2.4' > '2.10' > > True > > Exactly. So it doesn't work. > > In typical software release numbering, 2.10 is the tenth > minor version of the 2.x major version series, so 2.10 is > later than 2.4, but comparing as ASCII strings, it comes > out the other way around. > > Also note that '10.1' < '5.7' > Ah... I see now. A tuple comparison would work against the version though, correct? >>> import sys >>> sys.version_info (2, 6, 2, 'final', 0) >>> sys.version_info > (2, 4, 0) True >>> sys.version_info > (2, 10, 0) False >>> sys.version_info > (1, 10, 0) True Which looks a lot cleaner (at least to me) than the OP... and has the advantage of working for all versions ;) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Oct 6 17:04:02 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 06 Oct 2009 11:04:02 -0400 Subject: [Tutor] Checking for Python version In-Reply-To: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> Message-ID: <4ACB5C62.8040604@ieee.org> Didar Hossain wrote: > Hi, > > I am using the following code to check for the Python version - > > import os > > t = os.sys.version_info[0:2] > if (t[0] + t[1]) < 6: > os.sys.exit("Need at least Python 2.4") > del t > > This snippet is put at the beginning of the single script file before > the rest of the code. > I need to check for the minimum specific version because I am using > the "@staticmethod" > directive. > > Is there a prettier way or is this fine? > > Regards, > Didar > > How about if sys.version_info < (2,4): Incidentally, your particular approach has the problem of failing for 3.1. Perhaps that was intended, but it wasn't obvious. DaveA From cwitts at compuscan.co.za Tue Oct 6 17:08:25 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 06 Oct 2009 17:08:25 +0200 Subject: [Tutor] Checking for Python version In-Reply-To: <20091006150222.GJ4551@inocybe.localdomain> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> <20091006150222.GJ4551@inocybe.localdomain> Message-ID: <4ACB5D69.70509@compuscan.co.za> Todd Zullinger wrote: > Christian Witts wrote: > >> Your version will fail if the person is running Python 3.0, 3.1 up >> until the 3.3 series which is not good. Neater looking (imo) code >> below. >> >> from sys import version_info, exit >> >> if version_info[0] == 1 or (version_info[0] == 2 and version_info[1] < 4): >> exit("Please upgrade to Python 2.4 or greater.") >> > > This would fail on python < 2.0, as version_info is not available. So > you'd want to catch that, if you want to gracefully handle ancient > versions of python. You could also just compare the version_info > tuple. > > This is a bit ugly, but it works at least back to 1.5.2: > > import sys > > min_version = '2.4' > upgrade_msg = 'Please upgrade to Python %s or greater' % min_version > > try: > min = tuple(map(int, min_version.split('.'))) > ver = sys.version_info[:3] > if ver < min: > sys.exit(upgrade_msg) > except AttributeError: > sys.exit(upgrade_msg) > > I don't have any python 3.x systems to test though. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Ah, I've only been using python since 2.2 so was not aware of this. Thanks for the heads-up. -- Kind Regards, Christian Witts From srilyk at gmail.com Tue Oct 6 17:08:46 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 6 Oct 2009 10:08:46 -0500 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <4ACB5B32.7000603@ieee.org> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> <4ACB5B32.7000603@ieee.org> Message-ID: <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> On Tue, Oct 6, 2009 at 9:58 AM, Dave Angel wrote: > No, because you're not assured that all integers that are equal are the same > object. Python optimizes that for small integers, but there's no documented > range that you can count on it. > > But for this specific case - checking a return code against zero, should it still be considered unreliable? The only case that you are looking for correctness is 0 == 0, any other case should evaluate as false, so I guess the question is does python always optimize for zero? Any other optimization is irrelevant, AFAIK. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Tue Oct 6 17:40:06 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 6 Oct 2009 17:40:06 +0200 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> <4ACB5B32.7000603@ieee.org> <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> Message-ID: <6faf39c90910060840o1ad5cd42j1142bd1625263a30@mail.gmail.com> On Tue, Oct 6, 2009 at 5:08 PM, Wayne wrote: > On Tue, Oct 6, 2009 at 9:58 AM, Dave Angel wrote: >> >> >> >> No, because you're not assured that all integers that are equal are the >> same object. ?Python optimizes that for small integers, but there's no >> documented range that you can count on it. >> > > But for this specific case - checking a return code against zero, should it > still be considered unreliable? The only case that you are looking for > correctness is 0 == 0, any other case should evaluate as false, so I guess > the question is does python always optimize for zero? Any other optimization > is irrelevant, AFAIK. Never rely on optimizations like this being done, or on them not being done. The only save way to code is having your code work in both cases. -- Andr? Engels, andreengels at gmail.com From rabidpoobear at gmail.com Tue Oct 6 16:50:10 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 6 Oct 2009 16:50:10 +0200 Subject: [Tutor] Checking for Python version In-Reply-To: <333efb450910060747x35d3b3eep2d688c2e3018ed58@mail.gmail.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> <20091006144633.GA70558@dragon.alchemy.com> <333efb450910060747x35d3b3eep2d688c2e3018ed58@mail.gmail.com> Message-ID: On Tue, Oct 6, 2009 at 4:47 PM, Wayne wrote: > > On Tue, Oct 6, 2009 at 9:46 AM, Steve Willoughby wrote: > >> On Tue, Oct 06, 2009 at 09:42:04AM -0500, Wayne wrote: >> > On Tue, Oct 6, 2009 at 9:26 AM, Christian Witts > >wrote: >> > if sys.version < '2.4': >> > sys.exit("Need at least Python 2.4") >> > >> > AFAIK the string comparison is reliable >> >> Not quite. What happens when you compare '2.4' and '2.10'? >> > > >>> '2.4' > '2.10' > True > That was his point, 2.4 should be a lesser version than 2.10, so it should not ask you to upgrade if you have 2.10, but this code will. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Tue Oct 6 20:26:06 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 6 Oct 2009 14:26:06 -0400 Subject: [Tutor] advice on structuring a project Message-ID: Hi everyone, I was wondering if anyone could offer advice as I try to simplify a project I've been working on. I have a set of classes that I've named models.py (following the Django convention, though it's not technically a Django project or app). Inside that file, I had initially grouped together a number of classes, subclasses and mixin classes. I've broken out the mixins into a separate file and am now importing those as a module, which has helped tame models.py quite a bit. Now I'm left with a number of subclasses that add in certain functionalities that are not central to the models themselves. For instance, I have a class called FilingsParser and then a FilingsParserAuto subclass which just triggers methods on the FilingsParser when an instance is created: class FilingsParserAuto(FilingsParser): """ A subclass of FilingsParser that adds methods for handling House candidate committee filings. """ def __init__(self): super(FilingsParserAuto, self).__init__() self.get_filings() self.purge_dupes() self.extract_committee_ids() self.create_committees() self.add_reports() That subclass is the one I'm using in a separate program that relies on the "autofire" behavior. I have a number of these Auto subclasses and it's resulted in a bit of bloat inside models.py. So to finally ask the question -- would the above subclasses be better defined as part of the program that requires the "auto" behavior? Or is it preferable to create some sort of API or Auto module where these sublasses live? I can see myself needing this behavior for other projects, but again, it really isn't part of the core functionality of the classes defined in models.py. I guess I'm wondering if there's a convention for how to handle this type of thing... Advice is greatly appreciated. Serdar From lead.expression at gmail.com Tue Oct 6 21:11:27 2009 From: lead.expression at gmail.com (Nicola De Quattro) Date: Tue, 06 Oct 2009 21:11:27 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <333efb450910051320l3006ea16pb9f5a887a3dfadc3@mail.gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> <333efb450910020727r7a1fcd5dma654b7ba924efe14@mail.gmail.com> <4ACA20F3.3050408@gmail.com> <333efb450910051320l3006ea16pb9f5a887a3dfadc3@mail.gmail.com> Message-ID: <4ACB965F.5090100@gmail.com> Excuse me for the mistake, this list is a little different with respect to Yahoo Groups. Below my comments: > Now I think I could begin with some simple script to come into the > Python world, so I'll start building the easiest components of final > tool (perhaps opening the image and rotate it). > > > That one should be fairly simple - my guess is it should take < 5 lines > to do something like that with PIL or ImageMagick I've read some documentation about this libraries, for now I think I'll use PIL(*), because it apparentely seems more similar to the approach I have just meet in the other programming language. On the other hand I think that starting with one or the other would be quitely unimportant for now. > My suggestion is this: Work with what you're comfortable with. If you > want to use gedit and python interpreter, go ahead. I'm agree, I'm starting with an automatic-parser editor with IDLE. Thank you very much for your help, I shall return telling you my progression. (*) PIL seems to support FITS file manipulation from release 1.1.5a1 http://effbot.org/zone/pil-changes-115.htm It seems enough for my purposes. Nik From malaclypse2 at gmail.com Tue Oct 6 21:26:04 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 6 Oct 2009 15:26:04 -0400 Subject: [Tutor] Which version to start with? In-Reply-To: <4ACB3F17.1010205@insightbb.com> References: <78b3a9580910051459h389f43edk8e562a58c2db509d@mail.gmail.com> <4ACB3F17.1010205@insightbb.com> Message-ID: <16651e80910061226s35bb6d06tb5bdd00b8cad1786@mail.gmail.com> On Tue, Oct 6, 2009 at 8:59 AM, Ken G. wrote: > I am just starting on Python 2.6.2 on Ubuntu 9.04 and I am slightly confused > with the numerous tutorials and books available for learning the language. > Is there any good recommendation for a good but easy tutorial on the > Internet to learn Python? I'm fond of the official python tutorial: http://docs.python.org/tutorial/ -- Jerry From marky1991 at gmail.com Tue Oct 6 21:39:36 2009 From: marky1991 at gmail.com (Mark Young) Date: Tue, 6 Oct 2009 15:39:36 -0400 Subject: [Tutor] What language should I learn after Python? Message-ID: I'm now fairly familiar with Python, so I'm thinking about starting to learn a second programming language. The problem is, I don't know which to learn. I want a language that will be good for me to learn, but is not so different from python that I will be totally confused. I tried learning C++ and it was a massive failure, so I definitely think I'd like to stay closer to a high-level language. I know that this is a subjective question, but I'd still like to hear some suggestions if anyone has any. Also, I wasn't really sure if it was okay to ask this on tutor, if it's the wrong place, I'm sorry. Mark Young -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Tue Oct 6 22:31:49 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 6 Oct 2009 16:31:49 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: Hi Mark, I recently started dabbling with Java, which has some great texts on object-oriented design and patterns (a skill that I'm finding helps with Python). If you have time on your hands, you might want to consider learning a programming language that has a different philosophy or approach than Python. So instead of Ruby (which I've found is strikingly similar to Python in many respects), you might want to consider a language like Lisp or Erlang. I'm no expert though, so I'll just point you to the article where I first encountered that advice: Teach Yourself Programming in Ten Years http://www.norvig.com/21-days.html And the portion relevant to your question: "Learn at least a half dozen programming languages. Include one language that supports class abstractions (like Java or C++), one that supports functional abstraction (like Lisp or ML), one that supports syntactic abstraction (like Lisp), one that supports declarative specifications (like Prolog or C++ templates), one that supports coroutines (like Icon or Scheme), and one that supports parallelism (like Sisal)." Good luck with the learning! Regards, Serdar From pine508 at hotmail.com Tue Oct 6 22:50:07 2009 From: pine508 at hotmail.com (Che M) Date: Tue, 6 Oct 2009 16:50:07 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: > programming language. The problem is, I don't know which to learn. I want a language > that will be good for me to learn, Good for you in what way? Is there a general "good for you" for programming, or do you need to achieve a certain goal? From a jobs point of view, Java seems pretty in-demand. From a stretching-your-mind point of view, maybe a rather different language would be better? > I tried learning C++ and it was a massive failure, Earlier today today I picked up "C++ for Dummies" for $0.25 at a library sale bin just on the off chance I might try to learn a bit of it. Not sure I will. But I'm curious: why was it a massive failure? Che _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. http://clk.atdmt.com/GBL/go/177141664/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Tue Oct 6 22:54:46 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 06 Oct 2009 22:54:46 +0200 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <6faf39c90910060840o1ad5cd42j1142bd1625263a30@mail.gmail.com> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> <4ACB5B32.7000603@ieee.org> <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> <6faf39c90910060840o1ad5cd42j1142bd1625263a30@mail.gmail.com> Message-ID: <1254862486.5398.16.camel@infirit.lan> Thanks all for the informative discussion. To re-confirm it was mostly for boolean checks like "if b == True". Greets Sander From zstumgoren at gmail.com Tue Oct 6 23:13:53 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 6 Oct 2009 17:13:53 -0400 Subject: [Tutor] advice on structuring a project In-Reply-To: <1c2a2c590910061333lc2cac0l47c045d3185fc78d@mail.gmail.com> References: <1c2a2c590910061333lc2cac0l47c045d3185fc78d@mail.gmail.com> Message-ID: > I don't think there is a "right" answer to this question. It depends > on how the classes are used and related to each other. If the Auto > classes are related or if they are useful to more than one client, > perhaps you should make an auto_models.py to hold them. If they are > only useful to individual projects you might include each one with its > client. > I kinda figured there might not be any one way to do this. I do like the auto_models idea though. Thanks as always for the help. Serdar From marky1991 at gmail.com Tue Oct 6 23:16:50 2009 From: marky1991 at gmail.com (Mark Young) Date: Tue, 6 Oct 2009 17:16:50 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: I have no real need to learn anything for a job, it's just a hobby right now. I mostly just want "a programming language that has a different philosophy or approach than Python". However, you guys are right, if I just learn a language without a reason, it will be worthless. When I tried to learn C++, I just got extremely confused, I didn't even understand the basic "Hello World" script. I may have given up too quickly; maybe I should try again, or maybe I'll try C. I was thinking about Java, and I heard about Lisp, I heard that it would supposedly make you a better programmer or something. I looked at Lisp, but I wasn't sure which one to use, Scheme or Common Lisp. I think I heard the same about Haskell, but I'm not sure if I'm remembering correctly. Thanks for the suggestions so far. I'm thinking about trying to go back to C++ or C, to study a a lower level language, or maybe Lisp, just to see different techniques in a high level language. I guess I have to accept that things will be different in any language, and if I want to learn different methods and gain new abilities, I'll just have suck it up and start reading. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Tue Oct 6 23:25:32 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 6 Oct 2009 17:25:32 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: Well, it's admirable that you're wiling to stick with it and learn something new. One other resource that I've personally been meaning to look into but just haven't had time is Programming from the Ground Up. It teaches computer science using Assembly language, quite literally from the "ground up." Here's the intro graf from the site: "This is an introductory book to programming and computer science using assembly language. It assumes the reader has never programmed before, and introduces the concepts of variables, functions, and flow control. The reason for using assembly language is to get the reader thinking in terms of how the computer actually works underneath. Knowing how the computer works from a "bare-metal" standpoint is often the difference between top-level programmers and programmers who can never quite master their art." Using that as a starting point might help you wrap your brain around some of the concepts in C, C++, etc. (though again, I'd defer to the experts on this list). From zstumgoren at gmail.com Tue Oct 6 23:26:35 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 6 Oct 2009 17:26:35 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: Sorry, forgot the link: Programming from the Ground Up http://savannah.nongnu.org/projects/pgubook/ From rabidpoobear at gmail.com Tue Oct 6 22:30:56 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 6 Oct 2009 22:30:56 +0200 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: On Tue, Oct 6, 2009 at 9:39 PM, Mark Young wrote: > I'm now fairly familiar with Python, so I'm thinking about starting to > learn a second programming language. The problem is, I don't know which to > learn. I want a language that will be good for me to learn, but is not so > different from python that I will be totally confused. I tried learning C++ > and it was a massive failure, so I definitely think I'd like to stay closer > to a high-level language. I know that this is a subjective question, but I'd > still like to hear some suggestions if anyone has any. > > Also, I wasn't really sure if it was okay to ask this on tutor, if it's the > wrong place, I'm sorry. > We generally don't mind questions regarding other programming languages. It's really important for professionals to have multiple languages in their background, and it helps hobbyists too. What sorts of things do you want to write? If you're interested in web development, Ruby may be a good choice. Perl and PHP are common as well, but (IMHO) have some quirks and design issues that always frustrate me. Depending on your requirements, you may not even need to learn another language, but it's definitely helpful if you do want to do it anyway. You may want to look at Java, although I personally do not like Java very much. I think the most useful second language would probably be C++, because you can extend Python with it, and cover Python's only real weakness, the interpreter speed. But if you can't seem to wrap your head around it, that's understandable. It's not a very user-friendly language. Have you tried learning C? That might be easier for you to pick up. Anyway, you really need to learn a language that you can use for something you want to accomplish, otherwise there will be no point in learning the language other than learning it, and you really have to write code to get familiar with a language (not just its syntax), so it would help if it were something you wanted to do. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Oct 6 22:33:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 Oct 2009 16:33:58 -0400 Subject: [Tutor] advice on structuring a project In-Reply-To: References: Message-ID: <1c2a2c590910061333lc2cac0l47c045d3185fc78d@mail.gmail.com> On Tue, Oct 6, 2009 at 2:26 PM, Serdar Tumgoren wrote: > I have a set of classes that I've named models.py (following the > Django convention, though it's not technically a Django project or > app). > > Inside that file, I had initially grouped together a number of > classes, subclasses and mixin classes. I've broken out the mixins into > a separate file and am now importing those as a module, which has > helped tame models.py quite a bit. Now I'm left with a number of > subclasses that add in certain functionalities that are not central to > the models themselves. > > For instance, I have a class called FilingsParser and then a > FilingsParserAuto subclass which just triggers methods on the > FilingsParser when an instance is created: > > class FilingsParserAuto(FilingsParser): > > That subclass is the one I'm using in a separate program that relies > on the "autofire" behavior. I have a number of these Auto subclasses > and it's resulted in a bit of bloat inside models.py. > > So to finally ask the question -- would the above subclasses be better > defined as part of the program that requires the "auto" behavior? Or > is it preferable to create some sort of API or Auto module where these > sublasses live? I don't think there is a "right" answer to this question. It depends on how the classes are used and related to each other. If the Auto classes are related or if they are useful to more than one client, perhaps you should make an auto_models.py to hold them. If they are only useful to individual projects you might include each one with its client. Kent From marc.tompkins at gmail.com Wed Oct 7 00:09:15 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 6 Oct 2009 15:09:15 -0700 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: <40af687b0910061509w7d15e5e0q7efb4d6ac111687@mail.gmail.com> On Tue, Oct 6, 2009 at 12:39 PM, Mark Young wrote: > I'm now fairly familiar with Python, so I'm thinking about starting to > learn a second programming language. The problem is, I don't know which to > learn. I want a language that will be good for me to learn, but is not so > different from python that I will be totally confused. > May I suggest (some dialect of) SQL? It _is_ quite different from Python, but learning it will familiarise you with some concepts that will be very useful if you want to use your Python skillz in a data-driven application. It's true that you can use Python modules to interface with databases, and maybe never write more than a line or two of real SQL - but those modules are a lot easier to understand if you know what they're doing under the hood. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Oct 6 17:34:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 Oct 2009 11:34:06 -0400 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> <4ACB5B32.7000603@ieee.org> <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> Message-ID: <1c2a2c590910060834i25f05befvab7ec8e878ca19bd@mail.gmail.com> On Tue, Oct 6, 2009 at 11:08 AM, Wayne wrote: > On Tue, Oct 6, 2009 at 9:58 AM, Dave Angel wrote: >> >> >> >> No, because you're not assured that all integers that are equal are the >> same object. ?Python optimizes that for small integers, but there's no >> documented range that you can count on it. >> > > But for this specific case - checking a return code against zero, should it > still be considered unreliable? Yes. It is undocumented, implementation-specific behaviour and you should not depend on it without good reason. In this case, there is no reason at all to prefer "if x is 0" to "if x == 0". > The only case that you are looking for > correctness is 0 == 0, any other case should evaluate as false, so I guess > the question is does python always optimize for zero? Any other optimization > is irrelevant, AFAIK. Define "always". In all past and future versions of every implementation of Python? Unlikely and unknowable. In all current versions of CPython? Yes, AFAIK. Kent From kent37 at tds.net Tue Oct 6 16:12:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 Oct 2009 10:12:24 -0400 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> Message-ID: <1c2a2c590910060712m79a50a0cy1b632dcbffb0621f@mail.gmail.com> On Tue, Oct 6, 2009 at 9:04 AM, Wayne wrote: > If it's checking the returncode against a value, Vern makes a good point: > if returncode != 0 makes a whole lot more sense than "if not returncode == > 0" > Though when dealing with an integer return code, doesn't it make more sense > to use the "is" operator? > if returncode is 0: > ?? ?#do something > if returncode is not 0: > ?? ?#do something No! Equality and identity are different. CPython does cache small integers but that is an implementation detail that you should not rely on. For large values you cannot presume that equal numbers are also identical. For example: In [1]: a=1000000000 In [2]: b=1000000000 In [3]: a==b Out[3]: True In [4]: a is b Out[4]: False Kent From alan.gauld at btinternet.com Wed Oct 7 02:52:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 7 Oct 2009 01:52:33 +0100 Subject: [Tutor] What language should I learn after Python? References: Message-ID: "Mark Young" wrote > I have no real need to learn anything for a job, it's just a hobby right > now. I mostly just want "a programming language that has a different > philosophy or approach In that case consider Lisp (probably via Scheme) or SmallTalk. Both are apparemtly different to Python but once you get under the covers you wuill see where a lot of the thought behind Python originated. And there are some very good free books for both. Given a choice I'd recommend Scheme (I'm actually going through a Scheme course myself just now so maybe I'm biased!). One of the best books from a widening horizons perspective is Hiow to Design Programs (HTDP) and then try the slighlty more academic Structure and Interpretation of Computer Programs(SICP). Both are paper books that are also on the web. If they prove too heavy then try and find a library copy of the Little Lisper (or nowadays the Little Schemer). This short book takes a very unusual approach to teaching program but has a lot in common with HTDP in teaching a "formula" for writing well designed functons. > When I tried to learn C++, I just got extremely confused, I didn't even > understand the basic "Hello World" script. I may have given up too > quickly; > maybe I should try again, or maybe I'll try C. I'd definitely go for C before C++. For one thing you can do a lot in Linux and Python without any C++ and for another most of the complexity in C++ stems from the fact it is a very near superset of C and bolting OOP onto C leads to some wierd things happening! > supposedly make you a better programmer or something. I looked at Lisp, > but > I wasn't sure which one to use, Scheme or Common Lisp. I think I heard > the > same about Haskell, but I'm not sure if I'm remembering correctly. Haskell is another interesting option but p[robably too far from mainstream to be worthwhile just yet. THe principles of functional programming can be learned just as well using Lisp. And Lisp crops up a lot more often in real life (in Emacs for one thing!) > things will be different in any language, and if I want to learn > different > methods and gain new abilities, I'll just have suck it up and start > reading. Finally somebody already suggested SQL and thats a must do at some stage. Also if you want to do anything on the Web you will need a minimal JavaScript knowledge and it too has some interesting concepts behind it once you get past doing cut n paste mash ups. (eg protocol based OOP). You can get the basics of JavaScript by comparing it with Python in my tutorial... Pick one and have fun. If its not fun don't bust a gut, try another. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From orsenthil at gmail.com Wed Oct 7 04:27:07 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Wed, 7 Oct 2009 07:57:07 +0530 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: <20091007022707.GA6240@ubuntu.ubuntu-domain> On Tue, Oct 06, 2009 at 03:39:36PM -0400, Mark Young wrote: > I'm now fairly familiar with Python, so I'm thinking about starting to learn a > second programming language. The problem is, I don't know which to learn. I You have already got a lot of healthy advice in this thread. I would like to suggest that you might take up some project which involves a lot of python and little bit of a different language (Java Script, if it's a webbased project). In that way, you will hone your python skills and additionally start learning the new language. Just look around at Google App Engine and see if you can think of any project (simple one), and try implmenting it. You might end up using JavaScript/HTML. I am learning www.alice.org after Python. It is too much fun! -- Senthil Be careful of reading health books, you might die of a misprint. -- Mark Twain From marky1991 at gmail.com Wed Oct 7 04:41:21 2009 From: marky1991 at gmail.com (Mark Young) Date: Tue, 6 Oct 2009 22:41:21 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: <20091007022707.GA6240@ubuntu.ubuntu-domain> References: <20091007022707.GA6240@ubuntu.ubuntu-domain> Message-ID: Ok, thanks alot everybody. I think I'll start with either Scheme or C, I haven't decided yet. I was pleasantly surprised by how Scheme looks, it's much prettier than some other languages I looked at. Contributing to a project actually sounds like a good idea, I've never done a project with other people before, so it would definitely be helpful, for both my Python and for whatever language I pick up. I think I may wait a bit though, so I can actually help someone instead of slowing them down. Anyway, thanks everyone for the input, you've helped alot. Mark Young -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Oct 7 06:47:58 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 07 Oct 2009 00:47:58 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: <4ACC1D7E.7010103@ieee.org> Mark Young wrote: > I have no real need to learn anything for a job, it's just a hobby right > now. I mostly just want "a programming language that has a different > philosophy or approach than > Python". However, you guys are right, if I just learn a language without a > reason, it will be worthless. > > When I tried to learn C++, I just got extremely confused, I didn't even > understand the basic "Hello World" script. I may have given up too quickly; > maybe I should try again, or maybe I'll try C. > > I was thinking about Java, and I heard about Lisp, I heard that it would > supposedly make you a better programmer or something. I looked at Lisp, but > I wasn't sure which one to use, Scheme or Common Lisp. I think I heard the > same about Haskell, but I'm not sure if I'm remembering correctly. > > Thanks for the suggestions so far. I'm thinking about trying to go back to > C++ or C, to study a a lower level language, or maybe Lisp, just to see > different techniques in a high level language. I guess I have to accept that > things will be different in any language, and if I want to learn different > methods and gain new abilities, I'll just have suck it up and start reading. > > One of the problems with C++ is that it insisted on being a superset of C, in order to gain acceptability. And although it evolved away, C started evolving towards it, so they've been chasing each other down an interesting road. And one of the advantages is that you can generally use the same compiler for both, and even link files made with one with ones made with the other. I'd mention that out of the 25+ languages I've used professionally over the years, C++ is one of my top three favorites. On the other hand, perhaps you should learn something that has practically nothing in common with Python. Forth is at a different extreme. The entire interpreter/compiler can be defined in maybe 50 lines of (Forth) code. It essentially has no syntax, and the programmer is free to add things that in other languages would be considered syntax. To put it another way, IF is a library function that changes how the subsequent code gets compiled. And although it's standard (or builtin if you prefer), there's nothing stopping you from building your own language extensions. Symbols have no restrictions on character set, although generally it's tough to have embedded spaces in them. I don't know how the language has evolved since the ANS standard (XJ14 I believe it was 1994); I got into other things. When I used it, extensive libraries were not a strong point. But some of the concepts are mind-blowing. Forth was originally conceived and used for astronomy, where the computer controls for a telescope had to be reprogrammed in minutes for changing weather conditions. It then expanded many places where small execution size was essential, in embedded systems, pda's, etc. There have been a few processors that essentially used Forth as their machine language, and programming was essentially the art of adding instructions to the machine. I have such a machine in storage somewhere, which had 4k of RAM and 4k of Prom. Nearly half of that PROM was unneeded, as the compiler, interpreter, debugger and editor didn't need that much space. The RAM was limiting however, for doing problems involving lots of data. DaveA From iwasroot at gmail.com Wed Oct 7 08:49:29 2009 From: iwasroot at gmail.com (root) Date: Tue, 6 Oct 2009 23:49:29 -0700 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: <6faf99540910062349o1fbd02b8y2a3c521b144ee74@mail.gmail.com> Want another functional language besides scheme? Haskell. It looks pretty cool, and I want to learn it too. Here's some resources: A speach about haskell http://www.infoq.com/interviews/armstrong-peyton-jones-erlang-haskell Beginner's book http://learnyouahaskell.com/introduction Another book http://book.realworldhaskell.org/ From didar.hossain at gmail.com Wed Oct 7 09:22:21 2009 From: didar.hossain at gmail.com (Didar Hossain) Date: Wed, 7 Oct 2009 12:52:21 +0530 Subject: [Tutor] Checking for Python version In-Reply-To: References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> <4ACB538F.5020107@compuscan.co.za> <333efb450910060742r283ff426uaf76697669b878f1@mail.gmail.com> <20091006144633.GA70558@dragon.alchemy.com> <333efb450910060747x35d3b3eep2d688c2e3018ed58@mail.gmail.com> Message-ID: <62d32bf20910070022v493f185ai9165b4af2375bc8f@mail.gmail.com> I like Kent's "try" method to explicitly look for the "staticmethod" call - it is Pythony :-) Todd's graceful handling idea is a good one - will keep that for future use. Christian's input about my kludge failing with the 3.x series is a good catch, I didn't think about that. Thanks to all of you for the other observations. Regards, Didar From ksterling at mindspring.com Wed Oct 7 10:16:28 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Wed, 7 Oct 2009 04:16:28 -0400 (EDT) Subject: [Tutor] What language should I learn after Python? Message-ID: <27705876.1254903388715.JavaMail.root@mswamui-cedar.atl.sa.earthlink.net> -----Original Message----- >From: Dave Angel >Sent: Oct 7, 2009 12:47 AM >To: Mark Young >Cc: tutor at python.org >Subject: Re: [Tutor] What language should I learn after Python? > >> maybe I should try again, or maybe I'll try C. > >On the other hand, perhaps you should learn something that has >practically nothing in common with Python. Forth is at a different >extreme. The entire interpreter/compiler can be defined in maybe 50 >lines of (Forth) code. On dangerous ground here. I always felt Forth was more a religion than a computer language, hehe. . From alan.gauld at btinternet.com Wed Oct 7 13:03:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 7 Oct 2009 12:03:51 +0100 Subject: [Tutor] What language should I learn after Python? References: <4ACC1D7E.7010103@ieee.org> Message-ID: "Dave Angel" wrote > practically nothing in common with Python. Forth is at a different > extreme. The entire interpreter/compiler can be defined in maybe 50 > lines of (Forth) code. It essentially has no syntax, and the programmer > is free to add things that in other languages would be considered syntax. Tcl is a less extreme case of a similar idea. It too allows you to redefine how things like if{}, while{} etc work and add completely new control structures. But it does have a defined syntax and rules around variable names etc. If the OP is interested in Tcl the original version of my tutorial used Tcl as a comparison language to python. Its still available here: http://www.freenetpages.co.uk/hp/alan.gauld/oldtutor/ > have been a few processors that essentially used Forth as their machine > language, and programming was essentially the art of adding instructions > to the machine. ISTR Sun tried to build one of those. Sun still(?) use Forth in their Unix workstations for the boot monitor. If you press the right keys on startup you find yourself at a Forth prompt! > I have such a machine in storage somewhere, which had 4k of RAM and 4k of > Prom. Sounds like the old Atom PC? A little white box similar to the Sinclair/Timex ZX81 etc? There was also one called Oric (named after the computer in the cult "Blake's Seven" TV show?) that ran Forth if I remember corectly? I never owned or used either but I remember reading about them at the time (early-mid '80s). Ah, nostalgia... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From spell_gooder_now at spellingbeewinnars.org Wed Oct 7 14:20:42 2009 From: spell_gooder_now at spellingbeewinnars.org (Patrick) Date: Wed, 07 Oct 2009 08:20:42 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: Message-ID: <4ACC879A.90401@spellingbeewinnars.org> I am not sure if I can add to the excellent advice you have received here but I would like to add my 2 cents. I have learned a few languages over the past couple of years but I still don't think I am a very good programmer. Please don't fall into the trap I am in. I am now trying to learn more about programming strategies not just another language. I have not received the book yet but I ordered software systems development: http://www.abebooks.com/servlet/BookDetailsPL?bi=1386620426&searchurl=isbn%3D0077111036 I am teaching myself UML to understand how to layout a blueprint and I am trying to learn metamodeling concepts. If you can spell really well and your grammar is perfect you still might not be able to write a novel. Just learning a programming language is not enough. Hope this helps, I have certainly received more then my share of help from this list-Patrick From zstumgoren at gmail.com Wed Oct 7 14:57:44 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 7 Oct 2009 08:57:44 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: <4ACC879A.90401@spellingbeewinnars.org> References: <4ACC879A.90401@spellingbeewinnars.org> Message-ID: And in case you hadn't heard enough suggestions yet, here's something I just stumbled into this morning: Programming Paradigms for Dummies, by Peter Norvig http://lambda-the-ultimate.org/node/3465 Here's a portion of the soundbite from the website (where you can download the PDF): "This chapter gives an introduction to all the main programming paradigms, their underlying concepts, and the relationships between them. We give a broad view to help programmers choose the right concepts they need to solve the problems at hand. We give a taxonomy of almost 30 useful programming paradigms and how they are related. Most of them differ only in one or a few concepts, but this can make a world of difference in programming." Having skimmed a few pages, I'm not sure I'd say this is your average "Dummies" book, but it appears to provide a bird's eye view of how different languages are geared to solve different kinds of problems. Might bring the landscape into sharper relief before you settle on that next language. HTH! Serdar From zstumgoren at gmail.com Wed Oct 7 15:16:38 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 7 Oct 2009 09:16:38 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: <4ACC879A.90401@spellingbeewinnars.org> Message-ID: > http://lambda-the-ultimate.org/node/3465 > Sorry - another brain lapse on my part: the correct author is Peter Van Roy From alan.gauld at btinternet.com Wed Oct 7 15:50:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 7 Oct 2009 14:50:39 +0100 Subject: [Tutor] What language should I learn after Python? References: <4ACC879A.90401@spellingbeewinnars.org> Message-ID: "Serdar Tumgoren" wrote > Programming Paradigms for Dummies, by Peter Norvig > http://lambda-the-ultimate.org/node/3465 Thanks for posting the link. I hadn't seen it before but it made interesting reading. Although maybe digging a tad deeper than the OP had in mind! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zebra05 at gmail.com Wed Oct 7 16:16:19 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Wed, 7 Oct 2009 16:16:19 +0200 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: <4ACC879A.90401@spellingbeewinnars.org> Message-ID: Hi everyone, I've watched this discussion grow with great interest, as not too long ago i was asking myself the OP's question. I started with C#.NET when i got into programming, then moved to Java. This is all at work. I taught myself Python, and will soon be tackling C as well as i can use that to write Python and Ruby extensions and target Apple devices. Overall i've chosen to use Python as a general purpose language, C, Java for mobile development (also a good skill to have as it is in demand) and Ruby for web dev. I think it's good to choose a handfull of skills and pursue them systematically, rather than dabbling in everything and mastering nothing. Have a brace of languages that cover your bases. On Wed, Oct 7, 2009 at 3:50 PM, Alan Gauld wrote: > "Serdar Tumgoren" wrote > > Programming Paradigms for Dummies, by Peter Norvig >> http://lambda-the-ultimate.org/node/3465 >> > > Thanks for posting the link. I hadn't seen it before but it made > interesting reading. Although maybe digging a tad deeper than the OP had in > mind! > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Lloyd -------------- next part -------------- An HTML attachment was scrubbed... URL: From yanglizhi at gmail.com Wed Oct 7 15:57:21 2009 From: yanglizhi at gmail.com (Lizhi Yang) Date: Wed, 7 Oct 2009 09:57:21 -0400 Subject: [Tutor] Memory usage Message-ID: <3da557ee0910070657g2870876bq33c35e4138b2cccc@mail.gmail.com> Hi, Confused. If I create some functions using C++ to load the data into memory and use python to call those functions, what is the memory usage then? From stefan_ml at behnel.de Wed Oct 7 16:59:02 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 07 Oct 2009 16:59:02 +0200 Subject: [Tutor] Memory usage In-Reply-To: <3da557ee0910070657g2870876bq33c35e4138b2cccc@mail.gmail.com> References: <3da557ee0910070657g2870876bq33c35e4138b2cccc@mail.gmail.com> Message-ID: Lizhi Yang wrote: > Confused. If I create some functions using C++ to load the data into > memory and use python to call those functions, what is the memory > usage then? First (obvious) question: how do you call those functions? Do you use ctypes? Cython? Some other way? Providing a short code snippet that shows what you are doing will greatly help in understanding your question better. Stefan From jeff at dcsoftware.com Wed Oct 7 17:59:56 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Wed, 07 Oct 2009 08:59:56 -0700 Subject: [Tutor] What language should I learn after Python? In-Reply-To: <40af687b0910061509w7d15e5e0q7efb4d6ac111687@mail.gmail.com> References: <40af687b0910061509w7d15e5e0q7efb4d6ac111687@mail.gmail.com> Message-ID: <4ACCBAFC.5060807@dcsoftware.com> Marc Tompkins wrote: > On Tue, Oct 6, 2009 at 12:39 PM, Mark Young > wrote: > > I'm now fairly familiar with Python, so I'm thinking about starting > to learn a second programming language. The problem is, I don't know > which to learn. I want a language that will be good for me to > learn, but is not so different from python that I will be totally > confused. > > > May I suggest (some dialect of) SQL? It _is_ quite different from > Python, but learning it will familiarise you with some concepts that > will be very useful if you want to use your Python skillz in a > data-driven application. It's true that you can use Python modules to > interface with databases, and maybe never write more than a line or two > of real SQL - but those modules are a lot easier to understand if you > know what they're doing under the hood. > > -- > www.fsrtechnologies.com I like this suggestion. A language is fairly useless without some work to do and for me personally, all of my applications access databases. I have been programming since 1970 and I have used many languages in my work. After you learn a few you notice the similarities and can pick up a new language quicker. Most of the languages suggested use SQL in some form or fashion. So I would recommend installing PostgreSQL and learning to work with it using the Python you already know. I recommend PostgreSQL because of the cost (free), licensing, and ease of use. One other thing that is important to me is packaging an application for distribution and updating existing applications. That "language" would be Inno Setup. HTH FWIW, Python is my favorite language to use for too many reasons to list here! -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From marky1991 at gmail.com Wed Oct 7 21:03:50 2009 From: marky1991 at gmail.com (Mark Young) Date: Wed, 7 Oct 2009 15:03:50 -0400 Subject: [Tutor] What language should I learn after Python? In-Reply-To: References: <4ACC879A.90401@spellingbeewinnars.org> Message-ID: 2009/10/7 Serdar Tumgoren > And in case you hadn't heard enough suggestions yet, here's something > I just stumbled into this morning: > > Programming Paradigms for Dummies, by Peter Norvig > http://lambda-the-ultimate.org/node/3465 > > Here's a portion of the soundbite from the website (where you can > download the PDF): > > "This chapter gives an introduction to all the main programming > paradigms, their underlying concepts, and the relationships between > them. We give a broad view to help programmers choose the right > concepts they need to solve the problems at hand. We give a taxonomy > of almost 30 useful programming paradigms and how they are related. > Most of them differ only in one or a few concepts, but this can make a > world of difference in programming." > > Having skimmed a few pages, I'm not sure I'd say this is your average > "Dummies" book, but it appears to provide a bird's eye view of how > different languages are geared to solve different kinds of problems. > Might bring the landscape into sharper relief before you settle on > that next language. > > HTH! > > Serdar > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > It looks interesting, I'm working on reading it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sotsirh194 at gmail.com Thu Oct 8 01:01:13 2009 From: sotsirh194 at gmail.com (Hristos Giannopoulos) Date: Wed, 7 Oct 2009 19:01:13 -0400 Subject: [Tutor] Sleep Message-ID: <28ed27d90910071601u7699e07crf676c21649d7295e@mail.gmail.com> Is it possible for a python script to make a windows computer sleep or wake from sleep? Preferably in windows? -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Oct 8 01:22:36 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 7 Oct 2009 16:22:36 -0700 Subject: [Tutor] Sleep In-Reply-To: <28ed27d90910071601u7699e07crf676c21649d7295e@mail.gmail.com> References: <28ed27d90910071601u7699e07crf676c21649d7295e@mail.gmail.com> Message-ID: <40af687b0910071622y3138ab24r47b4a47709f43069@mail.gmail.com> On Wed, Oct 7, 2009 at 4:01 PM, Hristos Giannopoulos wrote: > Is it possible for a python script to make a windows computer sleep or wake > from sleep? Preferably in windows? > I think your best bet for controlling Windows power management with Python will be the pywin32 module, at http://sourceforge.net/projects/pywin32/ It wraps the Win32 API so that Python scripts can call it. You'll find there's not much documentation for pywin32, but you won't need much, because what you really need to know is how to use the API to do what you want. Just Google for that - there's a huge body of information available on the Web about using the Win32 API - then use pywin32 to wrap whatever API call you find. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu Oct 8 09:43:58 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 08 Oct 2009 08:43:58 +0100 Subject: [Tutor] Sleep In-Reply-To: <28ed27d90910071601u7699e07crf676c21649d7295e@mail.gmail.com> References: <28ed27d90910071601u7699e07crf676c21649d7295e@mail.gmail.com> Message-ID: <4ACD983E.7060101@timgolden.me.uk> Hristos Giannopoulos wrote: > Is it possible for a python script to make a windows computer sleep or wake > from sleep? Preferably in windows? Nothing built in to the language. You'll need in invoke the relevant Windows API[1] either via pywin32[2] or ctypes[3]: [1] http://msdn.microsoft.com/en-us/library/aa373163%28VS.85%29.aspx http://msdn.microsoft.com/en-us/library/aa373206%28VS.85%29.aspx http://msdn.microsoft.com/en-us/library/aa373201%28VS.85%29.aspx [2] http://sourceforge.net/projects/pywin32/ [3] http://docs.python.org/library/ctypes.html TJG From david.jamieson at gmail.com Thu Oct 8 10:29:06 2009 From: david.jamieson at gmail.com (David Jamieson) Date: Thu, 8 Oct 2009 09:29:06 +0100 Subject: [Tutor] Help or Advice on MySQL, Python and test data storage Message-ID: <4f5a5a4b0910080129o54ea70een628028011fc5b57d@mail.gmail.com> Hi All, looking for some advice on using Python with MySQL for test data storage. What builds of Python work well with MySQL and what modules allow the connection to the database and data transfer activities. I'm thinking about using PhPMyAdmin to set-up and administer my database in the first instance until I get going with the project, though I could create tables using the commandline option. Is there a Python equivalent to PhPMyAdmin? Outline of testing carried out ======================= I use Python to control my test instruments, Spectrum Analyser, Power Meter, Signal Generator and scope using pyvisa. I am just learning wxpython for the gui side of my application (crudely working app to date) and I current dump test data out to a csv file using the csv module. I want my test data stored in a better fashion and in a way where I can compare easily the data from one device to another. Testing involves gathering power data at harmonic frequencies over a set range in one test. Another test involves injecting a signal and observing the effect on specific registers on the device under test. I want to record all the device under test set-up information and the test equipment information (calibration dates instrument type etc) input signal values during the test and the device under test response values. Test data to store is harmonic frequencies v power levels recorded at each frequency per test unit. Unit under test serial number, setup parameters, version. In a way header information for each test run. Registers settings recorded during test run possibly 8 to 10 different register settings to monitor. Screen dumps from the analyser (WMF or BMP file format, roughly 130Kb per image, possibly 250 images per test run)how best to store these in the database, i.e. as a link to a file or as raw data set (glob or blob can't remember the exact phrase used for storing data in this way). Images are important for the tester to be able to look for any sideband issues or areas of broadband noise, as some runs will overnight when no staff are on site. Thanks in advance for any responses to my questions. -- Cheers David. From ansuman.dash at gmail.com Thu Oct 8 10:38:28 2009 From: ansuman.dash at gmail.com (Ansuman Dash) Date: Thu, 8 Oct 2009 14:08:28 +0530 Subject: [Tutor] Package for verify validity of any kind of IP Message-ID: <8c0cfa60910080138k5b1514e6h470c51278c6de448@mail.gmail.com> Hi, Can anybody suggest me a package to verify validity of any kind of IP, i.e. IPv4 or IPv6. Thanks, AD -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at pythontoo.com Thu Oct 8 11:21:30 2009 From: david at pythontoo.com (David) Date: Thu, 08 Oct 2009 05:21:30 -0400 Subject: [Tutor] Help or Advice on MySQL, Python and test data storage In-Reply-To: <4f5a5a4b0910080129o54ea70een628028011fc5b57d@mail.gmail.com> References: <4f5a5a4b0910080129o54ea70een628028011fc5b57d@mail.gmail.com> Message-ID: <4ACDAF1A.5020409@pythontoo.com> David Jamieson wrote: > Hi All, > looking for some advice on using Python with MySQL for test data > storage. What builds of Python work well with MySQL and what modules > allow the connection to the database and data transfer activities. SQLAlchemy is one option; http://www.rmunn.com/sqlalchemy-tutorial/tutorial-0.1.html -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From rabidpoobear at gmail.com Thu Oct 8 08:15:16 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 8 Oct 2009 08:15:16 +0200 Subject: [Tutor] Bounces Message-ID: I keep getting Mail Delivery Subsystem notices from tutor saying my mail is undeliverable. Is that just me or are other people getting this as well? I'm realizing now that a lot of my replies are not getting through. Anyone know why this may be? (even if you don't, someone please reply so I know at least this one got through!) -------------- next part -------------- An HTML attachment was scrubbed... URL: From onyxtic at gmail.com Thu Oct 8 13:34:09 2009 From: onyxtic at gmail.com (Evans Anyokwu) Date: Thu, 8 Oct 2009 12:34:09 +0100 Subject: [Tutor] Bounces In-Reply-To: References: Message-ID: This one seems to have got through though.. On Thu, Oct 8, 2009 at 7:15 AM, Luke Paireepinart wrote: > I keep getting Mail Delivery Subsystem notices from tutor saying my mail is > undeliverable. Is that just me or are other people getting this as well? > I'm realizing now that a lot of my replies are not getting through. Anyone > know why this may be? (even if you don't, someone please reply so I know at > least this one got through!) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Oct 8 13:38:34 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 08 Oct 2009 13:38:34 +0200 Subject: [Tutor] Bounces In-Reply-To: References: Message-ID: <4ACDCF3A.1040608@compuscan.co.za> Luke Paireepinart wrote: > I keep getting Mail Delivery Subsystem notices from tutor saying my > mail is undeliverable. Is that just me or are other people getting > this as well? I'm realizing now that a lot of my replies are not > getting through. Anyone know why this may be? (even if you don't, > someone please reply so I know at least this one got through!) > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > This one came through, I also have 57 emails originating from you since the 8th of July 2009. -- Kind Regards, Christian Witts From zstumgoren at gmail.com Thu Oct 8 14:02:31 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 8 Oct 2009 08:02:31 -0400 Subject: [Tutor] Help or Advice on MySQL, Python and test data storage In-Reply-To: <4f5a5a4b0910080129o54ea70een628028011fc5b57d@mail.gmail.com> References: <4f5a5a4b0910080129o54ea70een628028011fc5b57d@mail.gmail.com> Message-ID: > looking for some advice on using Python with MySQL for test data > storage. What builds of Python work well with MySQL and what modules > allow the connection to the database and data transfer activities. You'll need the MySQLdb module to connect to MySQL from Python. http://sourceforge.net/projects/mysql-python/ According to its sourceforge page, the module supports: MySQL versions 3.23-5.1; and Python versions 2.3-2.5 are supported. One of the reviews on the page says it also works with Python 2.6. > I'm thinking about using PhPMyAdmin to set-up and administer my > database in the first instance until I get going with the project, > though I could create tables using the commandline option. Is there a > Python equivalent to PhPMyAdmin? If you already know how to use phpMyAdmin and it serves your needs, why not just stick with it? Another option is MySQL's database management tools: http://dev.mysql.com/downloads/gui-tools/5.0.html I don't believe these can administer remote databases, but you'll want to check the docs on that to be sure. I've only used them on a local machine, and they worked fine for that purpose. HTH, Serdar From zstumgoren at gmail.com Thu Oct 8 14:10:14 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 8 Oct 2009 08:10:14 -0400 Subject: [Tutor] Bounces In-Reply-To: <4ACDCF3A.1040608@compuscan.co.za> References: <4ACDCF3A.1040608@compuscan.co.za> Message-ID: I got an error bounce too, saying that the bottom portion of a recent message was "ignored" From yanglizhi at gmail.com Thu Oct 8 13:47:21 2009 From: yanglizhi at gmail.com (Lizhi Yang) Date: Thu, 8 Oct 2009 07:47:21 -0400 Subject: [Tutor] Memory usage (Lizhi Yang) Message-ID: <3da557ee0910080447q34a6909bh6f8e82be3c0e1738@mail.gmail.com> Below you see my original post. 1: Say I use boost.python. 2: For example, I allocate a big array with integers using C++ function (4 bytes for each int in C++, but 12 bytes in python), and I use boost.python to call those C++ functions. How is the memory allocation for that array then? My last question: Lizhi Yang wrote: > Confused. If I create some functions using C++ to load the data into > memory and use python to call those functions, what is the memory > usage then? First (obvious) question: how do you call those functions? Do you use ctypes? Cython? Some other way? Providing a short code snippet that shows what you are doing will greatly help in understanding your question better. Stefan From srilyk at gmail.com Thu Oct 8 14:41:58 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 8 Oct 2009 07:41:58 -0500 Subject: [Tutor] Package for verify validity of any kind of IP In-Reply-To: <8c0cfa60910080138k5b1514e6h470c51278c6de448@mail.gmail.com> References: <8c0cfa60910080138k5b1514e6h470c51278c6de448@mail.gmail.com> Message-ID: <333efb450910080541n331f0f12wc73706f2c821d158@mail.gmail.com> On Thu, Oct 8, 2009 at 3:38 AM, Ansuman Dash wrote: > Hi, > > Can anybody suggest me a package to verify validity of any kind of IP, i.e. > IPv4 or IPv6. > > You mean to check if the IP is live, or to check if the IP is in the valid range for IP addresses? For the latter, just use a regex (google can give you explicit examples if you don't want to make your own) hth, wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From gary.littwin at gmail.com Thu Oct 8 14:47:50 2009 From: gary.littwin at gmail.com (gary littwin) Date: Thu, 8 Oct 2009 14:47:50 +0200 Subject: [Tutor] Beginners question Message-ID: Hi all - Just started on "Python Programming for Absolute Beginners" and I've got a question: The program called 'Guess my Number' goes like this: # Guess My Number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is too high, too low # or right on the money #import random print "\tWelcome to 'Guess My Number'!" print "\nI'm thinking of a number between 1 and 15." print "Try to guess it in as few attempts as possible.\n" import random # set the initial values the_number = random.randrange(15) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 # guessing loop while (guess != the_number): if (guess > the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess: ")) tries += 1 print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") So here's the question - the original code has parentheses around the lines of code with *(guess !=the_number)* and *(guess* *> the_number)* . I tried to run the program without the parentheses and it runs just fine. So what are the parentheses for?? Thanks a lot for your time - Gary -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Oct 8 15:40:16 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 08 Oct 2009 15:40:16 +0200 Subject: [Tutor] Beginners question In-Reply-To: References: Message-ID: <4ACDEBC0.3030509@compuscan.co.za> gary littwin wrote: > > Hi all - > > Just started on "Python Programming for Absolute Beginners" and I've > got a question: > > The program called 'Guess my Number' goes like this: > # Guess My Number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > #import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 15." > print "Try to guess it in as few attempts as possible.\n" > > import random > > > # set the initial values > the_number = random.randrange(15) + 1 > guess = int(raw_input("Take a guess: ")) > tries = 1 > > # guessing loop > while (guess != the_number): > if (guess > the_number): > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess: ")) > tries += 1 > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit.") > > So here's the question - the original code has parentheses around the > lines of code with *(guess !=the_number)* and *(guess* *> the_number)* > . I tried to run the program without the parentheses and it runs just > fine. So what are the parentheses for?? > > Thanks a lot for your time - > > Gary > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Some use the parentheses for code clarity as it reads easier when it's grouped by (). Your code as written won't run as it should, your while loop needs to change to include your `guess = int(raw_input("Take a guess: "))` as without it if your first guess is incorrect it would just loop infinitely (it's currently 1 level of indentation out, as well as your `tries += 1`). Welcome to Python and hope you enjoy your stay. :) -- Kind Regards, Christian Witts From jeff at dcsoftware.com Thu Oct 8 15:48:20 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Thu, 08 Oct 2009 06:48:20 -0700 Subject: [Tutor] Beginners question In-Reply-To: References: Message-ID: <4ACDEDA4.7090003@dcsoftware.com> gary littwin wrote: > > Hi all - > > Just started on "Python Programming for Absolute Beginners" and I've got > a question: > > The program called 'Guess my Number' goes like this: > # Guess My Number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is too high, too low > # or right on the money > > #import random > > print "\tWelcome to 'Guess My Number'!" > print "\nI'm thinking of a number between 1 and 15." > print "Try to guess it in as few attempts as possible.\n" > > import random > > > # set the initial values > the_number = random.randrange(15) + 1 > guess = int(raw_input("Take a guess: ")) > tries = 1 > > # guessing loop > while (guess != the_number): > if (guess > the_number): > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess: ")) > tries += 1 > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit.") > > So here's the question - the original code has parentheses around the > lines of code with *(guess !=the_number)* and *(guess* *> the_number)* . > I tried to run the program without the parentheses and it runs just > fine. So what are the parentheses for?? > > Thanks a lot for your time - > > Gary > The parentheses in this procedure are not required but don't do any harm. I often use extra parentheses to clarify what I am doing so it is more readable when going back to look at it a couple of years later. Especially in long calculations or SQL with lots of ands and ors. -- Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From adam.jtm30 at gmail.com Thu Oct 8 15:49:04 2009 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 8 Oct 2009 14:49:04 +0100 Subject: [Tutor] Memory usage (Lizhi Yang) In-Reply-To: <3da557ee0910080643x75e3d514r36ab2fe0dc115384@mail.gmail.com> References: <3da557ee0910080447q34a6909bh6f8e82be3c0e1738@mail.gmail.com> <3da557ee0910080619p6442366byadaa77991d49308e@mail.gmail.com> <3da557ee0910080643x75e3d514r36ab2fe0dc115384@mail.gmail.com> Message-ID: 2009/10/8 Lizhi Yang > Hi Adam, > > One more question, if I want to implement algorithms and load the huge > amount of data using C++, but using Python as the glue language to > implement other functionality such as Gui and txt processing, you > think Boost.python is better or SWIG is better? Have not tried yet, > just need to make decision first, thanks. > > On Thu, Oct 8, 2009 at 9:19 AM, Lizhi Yang wrote: > > Hi Adam, > > > > Thank you so much for your help. I will do a test, and will let you > > know the result. > > > > On Thu, Oct 8, 2009 at 9:15 AM, Adam Bark wrote: > >> 2009/10/8 Lizhi Yang > >>> > >>> Below you see my original post. > >>> > >>> 1: Say I use boost.python. > >>> 2: For example, I allocate a big array with integers using C++ > >>> function (4 bytes for each int in C++, but 12 bytes in python), and I > >>> use boost.python to call those C++ functions. How is the memory > >>> allocation for that array then? > >> > >> If the data is setup in C++ using native types then it will use 4 bytes > per > >> int. I believe boost just creates a wrapper so you can call the C++ > function > >> as if it were a python function it then does all the conversion > internally > >> and will return some python type data. > >> HTH > > > Hi Lizhi, I don't really have much experience with either, personally, and I just realised I didn't reply-all my original response so I'm CC'ing this back to the list, hopefully you'll get a useful response there. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Thu Oct 8 16:15:47 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 8 Oct 2009 08:15:47 -0600 Subject: [Tutor] Package for verify validity of any kind of IP In-Reply-To: <8c0cfa60910080138k5b1514e6h470c51278c6de448@mail.gmail.com> References: <8c0cfa60910080138k5b1514e6h470c51278c6de448@mail.gmail.com> Message-ID: <1e53c510910080715r22bb10f8p4df6e6b4728791e8@mail.gmail.com> On Thu, Oct 8, 2009 at 2:38 AM, Ansuman Dash wrote: > Hi, > > Can anybody suggest me a package to verify validity of any kind of IP, i.e. > IPv4 or IPv6. > > Thanks, > AD > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I have used googles ipaddr package and have found it to work quite well http://code.google.com/p/ipaddr-py/ Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From benshafat at gmail.com Thu Oct 8 17:02:47 2009 From: benshafat at gmail.com (Elisha Rosensweig) Date: Thu, 8 Oct 2009 11:02:47 -0400 Subject: [Tutor] Branch Coverage Tool for Python Message-ID: <7fd42f290910080802o755f180ajb957f39211179a65@mail.gmail.com> Hi All, Is there any Python tool for Branch Coverage (as opposed to Statement Coverage)? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From yanglizhi at gmail.com Thu Oct 8 15:54:47 2009 From: yanglizhi at gmail.com (Lizhi Yang) Date: Thu, 8 Oct 2009 09:54:47 -0400 Subject: [Tutor] Wrapper of C++ Message-ID: <3da557ee0910080654o270e1859x6b21d9c1b20cc404@mail.gmail.com> Since the memory usage for saving huge data using python is not efficent at all(12 bytes per int). if I want to implement algorithms and load the huge amount of data using C++, but using Python as the glue language to implement other functionality such as Gui and txt processing, you think Boost.python is better or SWIG is better? Have not tried yet, just need to make decision first, thanks. From rabidpoobear at gmail.com Tue Oct 6 03:13:40 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 6 Oct 2009 03:13:40 +0200 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <4ACA91F9.8030204@canterburyschool.org> References: <1254770936.5925.5.camel@infirit.lan> <4ACA4D43.1000407@canterburyschool.org> <4ACA8E01.2070008@ieee.org> <4ACA91F9.8030204@canterburyschool.org> Message-ID: On Tue, Oct 6, 2009 at 2:40 AM, Vern Ceder wrote: > Dave Angel wrote: > > Now in this case where it is only used as boolean checks which would be >>>> the most pythonic way if writing these checks? >>>> >>>> >>> The shorter version may be preferable, but it doesn't generally give the >> same results. Without knowing the possible data, these substitutions are >> not safe. >> >> For example, replacing "if not n == 0" with "if n" >> >> will give different results for values of "", [] and so on. It WILL >> work if you know that n is an int or float, however. >> >> DaveA >> > > True, I took the OP's statement that they were to be used "only as boolean > checks" to mean that there was no type mixing going on. Personally, I would > say that checking a list or string for equality (or lack thereof) with 0 is > even less "preferable". ;) > > Otherwise, one would at least prefer "if n != 0" to "if not n == 0", I > would think. > Actually, I just realized that "not" has higher precedence than "==" so this is really checking if (not n) is equal to 0, not if (n == 0) is (not) True. So essentially "not n" is evaluated and is turned into a bool, which is then compared to 0, which is the same as False in a boolean context, but "n != 0" is comparing n to 0, where n may not be the same type (eg. a string). I'm not sure if there's a situation where this difference matters, but I feel like there might be. Anyone have some counter-examples to n != 0 being the same as "not n == 0"? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Oct 8 19:44:34 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 08 Oct 2009 13:44:34 -0400 Subject: [Tutor] Wrapper of C++ In-Reply-To: <3da557ee0910080654o270e1859x6b21d9c1b20cc404@mail.gmail.com> References: <3da557ee0910080654o270e1859x6b21d9c1b20cc404@mail.gmail.com> Message-ID: <4ACE2502.1000908@ieee.org> Lizhi Yang wrote: > Since the memory usage for saving huge data using python is not > efficent at all(12 bytes per int). if I want to implement algorithms > and load the huge amount of data using C++, but using Python as the > glue language to implement other functionality such as Gui and txt > processing, you think Boost.python is better or SWIG is better? Have > not tried yet, > just need to make decision first, thanks. > > arrays of ints don't take 12 bytes per, they take 4. That's the same in C++ or in Python. So if that's the only reason to use C++, stick with Python. Probably you were looking at the overhead of list, which lets you put different types of data in different offsets. If you really have an (huge) array of ints, use array.array() to create it. As for talking between C++ and Python, you have a number of choices. You probably should look at ctypes, since it's built-in, before trying something more complex. DaveA From kent37 at tds.net Thu Oct 8 20:29:43 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 Oct 2009 14:29:43 -0400 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: References: <1254770936.5925.5.camel@infirit.lan> <4ACA4D43.1000407@canterburyschool.org> <4ACA8E01.2070008@ieee.org> <4ACA91F9.8030204@canterburyschool.org> Message-ID: <1c2a2c590910081129i49a5aea8i6071af9127a37b6a@mail.gmail.com> On Mon, Oct 5, 2009 at 9:13 PM, Luke Paireepinart wrote: > Actually, I just realized that "not" has higher precedence than "==" so this > is really checking if (not n) is equal to 0, not if (n == 0) is (not) True. No, "not" is lower precedence than "==". See http://docs.python.org/reference/expressions.html#summary > Anyone have some counter-examples to n != 0 being the same as "not n == 0"? Well, you can create a pathological class where they are different: In [17]: class funky(object): ....: def __eq__(self, other): ....: return True ....: def __ne__(self, other): ....: return True In [18]: f = funky() In [19]: f != 0 Out[19]: True In [20]: f == 0 Out[20]: True In [21]: not f == 0 Out[21]: False For a less contrived example, if n is a numpy array, n==0 is also a numpy array but (not n != 0) gives an error: In [1]: from numpy import * In [2]: a = array( [ 0, 10, 20, 30, 40 ] ) In [3]: a== 0 Out[3]: array([ True, False, False, False, False], dtype=bool) In [5]: not a!= 0 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) C:\Project\MangoLib\ in () ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() Kent From wescpy at gmail.com Thu Oct 8 21:58:22 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 8 Oct 2009 12:58:22 -0700 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <1254862486.5398.16.camel@infirit.lan> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> <4ACB5B32.7000603@ieee.org> <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> <6faf39c90910060840o1ad5cd42j1142bd1625263a30@mail.gmail.com> <1254862486.5398.16.camel@infirit.lan> Message-ID: <78b3a9580910081258v27ca8065w70d62edae24578a2@mail.gmail.com> > Thanks all for the informative discussion. To re-confirm it was mostly > for boolean checks like "if b == True". wow, as the OP, you must have been surprised to see how far we have taken your (seemingly) simple question. we went from boolean checks to interning! commenting on my previous reply, i was addressing only the boolean results when shortening the comparisons. as i mentioned earlier, every Python object has the concept of a boolean value. zeros and empty containers have False values while all others are True. however, what i did *not* mention is that these (abbreviated) comparisons do not work should you care to distinguish between multiple Python objects/values that have the same boolean value. in other words, "if not b" will catch False, None, 0, etc. if your application is using 3 values like None (for unset value), False (bad/errror code), and True (correct behavior), then None and False will both cause the if clause to be executed. in other words, if you care about the actual objects, then you need to use either "==" or "is", rather than just checking their boolean outcomes. now on to the difference between "==" vs. "is" and interning. "==" is the object *value* comparison operator while "is" is the object *identity* comparison operator. although "is 0" does work, it's easier to read and less confusing than "== 0". also as others have already mentioned, it's not a good idea to rely on the undocumented underlying implementation, and for it to stay consistent. for example, back in the earlier 2.x releases, the interned integer range was (-1, 101). when i worked on the 2nd edition of Core Python, i still had that range in the original manuscript. i then discovered that it changed to (-5, 256)... no one warned me ahead of time, and i was not paying enough attention to the python-dev list! again, the bottom line is to *not* rely on the implementation because it is always subject to change, granted not for numbers like -1, 0, 1, but why confuse your fellow Python coder? "is" is better suited for constants that are not numbers and that is always only one instance of: None, True, False. best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From robert.lummis at gmail.com Thu Oct 8 22:03:28 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Thu, 8 Oct 2009 16:03:28 -0400 Subject: [Tutor] Bounces In-Reply-To: References: Message-ID: <71d330f00910081303r71c83ce9w4b07edad25c3c3aa@mail.gmail.com> It probably means that you used "reply all" and one of the addresses was not valid, possibly because it got garbled somehow on an earlier "reply all". On Thu, Oct 8, 2009 at 2:15 AM, Luke Paireepinart wrote: > I keep getting Mail Delivery Subsystem notices from tutor saying my mail is > undeliverable.? Is that just me or are other people getting this as well? > I'm realizing now that a lot of my replies are not getting through.? Anyone > know why this may be? (even if you don't, someone please reply so I know at > least this one got through!) > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Robert Lummis From xboxmuncher at gmail.com Thu Oct 8 22:10:58 2009 From: xboxmuncher at gmail.com (xbmuncher) Date: Thu, 8 Oct 2009 16:10:58 -0400 Subject: [Tutor] Reading individual file from tar file as a file object Message-ID: I have a large tar.bz2 file that I want to extract certain files directly to an FTP path. Since the extract() method doesn't accept ftp paths... I wanted to read the files from the tar file like a file object or file I/O stream. Is there a way to do this? Here's my pseudocode: import tarfile def putThisDataSomewhere(data): #write it to a file in FTP tar = tarfile.open("HUGE_FILE_OVER_5GB.tar.bz2", "r:bz2") readSize = 50 for tarInfo in tar: fileSize = tarInfo.size #prepare for loop to read specific file inside tar if readSize > fileSize readSize = fileSize readIterations = fileSize/readSize #loop & read file for i in range(readIterations): putThisDataSomewhere(tarFile.read(readSize)) #catch remainder of file lastReadSize = fileSize - (readSize * readIterations) if lastReadSize: putThisDataSomewhere(tarFile.read(lastReadSize)) tar.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Thu Oct 8 23:02:27 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 08 Oct 2009 23:02:27 +0200 Subject: [Tutor] if n == 0 vs if not n In-Reply-To: <78b3a9580910081258v27ca8065w70d62edae24578a2@mail.gmail.com> References: <1254770936.5925.5.camel@infirit.lan> <1254775041.5450.27.camel@infirit.lan> <333efb450910060604p7a66b139if0531c514a4106cf@mail.gmail.com> <4ACB5B32.7000603@ieee.org> <333efb450910060808t79e99642w886a55c574f81a80@mail.gmail.com> <6faf39c90910060840o1ad5cd42j1142bd1625263a30@mail.gmail.com> <1254862486.5398.16.camel@infirit.lan> <78b3a9580910081258v27ca8065w70d62edae24578a2@mail.gmail.com> Message-ID: <1255035747.5445.33.camel@infirit.lan> On Thu, 2009-10-08 at 12:58 -0700, wesley chun wrote: > wow, as the OP, you must have been surprised to see how far we have > taken your (seemingly) simple question. Pleasently suprised :-) And I am gratefull to see the heavy weights join in. > however, what i did *not* mention is that these (abbreviated) > comparisons do not work should you care to distinguish between > multiple Python objects/values that have the same boolean value. in > other words, "if not b" will catch False, None, 0, etc. if your > application is using 3 values like None (for unset value), False > (bad/errror code), and True (correct behavior), then None and False > will both cause the if clause to be executed. in other words, if you > care about the actual objects, then you need to use either "==" or > "is", rather than just checking their boolean outcomes. Good one, I have to remember this as it will very likely bite me someday. I really appriciate all the feedback and good advice! Thanks Sander From eduardo.susan at gmail.com Thu Oct 8 22:42:08 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Thu, 8 Oct 2009 14:42:08 -0600 Subject: [Tutor] Troubles with lists and control flow Message-ID: <9356b9f30910081342l5e348eb8u79643d7a58fe72bf@mail.gmail.com> Hello I'm developing a script to compare two files, finding duplicate entries and matching which id of one csv file corresponds to the id of another csv file. The first version was working nice, but I wanted to postpone the writing to a file till the end and also make a correct csv file. The code is not so great and I expect to work with no more than 3000 lines of data in either file: So here is the inicial code. I hope it's not too long or complicated: import csv import re import addrnormalize import difflib import time started = time.time() nobv = open('regnobv.csv', 'wb') yesbv = open('reginbv.csv', 'wb') bv = open(r'\\albertapdc\ESP Data\ESP Main Files\BV_Customersa.csv').read().upper() site = open(r'C:\myscripts\latestregistrants.csv').read().upper() site = re.sub(r'([0-9]{3})-([0-9]{3})-([0-9]{4})', r'\1\2\3', site) bvreader = csv.DictReader(bv.splitlines()) sitelist = csv.DictReader(site.splitlines()) def inbv(yesbv): yesbv.write(item['USER_ID'] + ',') yesbv.write(row['CUS_NO'] + ',') yesbv.write(item['COMPANY'] + ',') yesbv.write(row['BVADDR1'] + ',') yesbv.write(item['ADDRESSLINEONE']+ ',') yesbv.write(row['BVADDRTELNO1'] + ',') yesbv.write(item['PHONE'] + '\n') bvreader = list(bvreader) # or (row['NAME'] in item['COMPANY']) or (row['BVADDREMAIL'] in item['EMAIL']) for item in sitelist: for row in bvreader: if ((row['BVADDRTELNO1'] == item['PHONE'] and row['BVADDRTELNO1']) or (row['BVADDREMAIL'] == item['EMAIL'] and row['BVADDREMAIL'])): inbv(yesbv) break ## this module just makes a few string transformations to standardize both strings. Like STREET -> ST elif addrnormalize.format_address(row['BVADDR1']) == addrnormalize.format_address(item['ADDRESSLINEONE']) and row['BVADDR1'] and row['BVPROVSTATE'] == item['STATE'] and row['BVPROVSTATE']: inbv(yesbv) break ## trying some fuzzy matching here elif (difflib.SequenceMatcher(lambda x: x in " ,.-#" , row['BVADDR1'], item['ADDRESSLINEONE']).quick_ratio() > 0.87) \ and (difflib.SequenceMatcher(lambda x: x in " .-" , row['BVCITY'], item['CITY']).quick_ratio() > 0.87): inbv(yesbv) break else: nobv.write(item['USER_ID']+ ',') nobv.write(item['FIRSTNAME']+ ',') nobv.write(item['LASTNAME']+ ',') nobv.write(item['COMPANY']+ ',') nobv.write(item['EMAIL'].lower()+ ',') nobv.write(item['PHONE']+ ',') nobv.write(item['FAX']+ ',') nobv.write(item['ADDRESSLINEONE']+ ',') nobv.write(item['ADDRESSLINETWO']+ ',') nobv.write(item['CITY']+ ',') nobv.write(item['STATE']+ ',') nobv.write(item['POSTALCODE']+ ',') nobv.write(item['COUNTRY']+ ',') nobv.write('\n') nobv.close() yesbv.close() finished = time.time() print finished - started ---- End of code --- #### When I try with list it does not even print the "print linha" test #### If I uncomment all the conditionals except the first if than I get that written to the final file: reginbv. ### How is the new function with list affecting the results? import csv import re import addrnormalize import difflib import time started = time.time() nobv = open('regnobv.csv', 'wb') bv = open(r'\\albertapdc\ESP Data\ESP Main Files\BV_Customersa.csv').read().upper() site = open(r'C:\myscripts\latestregistrants.csv').read().upper() site = re.sub(r'([0-9]{3})-([0-9]{3})-([0-9]{4})', r'\1\2\3', site) bvreader = csv.DictReader(bv.splitlines()) sitelist = csv.DictReader(site.splitlines()) list2csv = [] list_not_in_bv = [] yesbv = csv.writer(open('reginbv.csv', 'wb'), dialect="excel") nobv = csv.writer(open('regnobv.csv', 'wb'), dialect="excel") def inbv(currentline = None): """writes a line of data when a date is found in BV""" if currentline is None: currentline = [] else: currentline.append(item['USER_ID']) currentline.append(row['CUS_NO']) currentline.append(item['COMPANY']) currentline.append(row['BVADDR1']) currentline.append(item['ADDRESSLINEONE']) currentline.append(row['BVADDRTELNO1']) currentline.append(item['PHONE']) currentline.append(row['BVCITY']) currentline.append(item['CITY']) return currentline def notinbv(currentline): if currentline is None: currentline = [] else: currentline.append(item['USER_ID']) currentline.append(item['FIRSTNAME']) currentline.append(item['LASTNAME']) currentline.append(item['COMPANY']) currentline.append(item['EMAIL']) currentline.append(item['PHONE']) currentline.append(item['FAX']) currentline.append(item['ADDRESSLINEONE']) currentline.append(item['ADDRESSLINETWO']) currentline.append(item['CITY']) currentline.append(item['STATE']) currentline.append(item['POSTALCODE']) currentline.append(item['COUNTRY']) return currentline bvreader = list(bvreader) # or (row['NAME'] in item['COMPANY']) or (row['BVADDREMAIL'] in item['EMAIL']) for item in sitelist: for row in bvreader: if ((row['BVADDRTELNO1'] == item['PHONE'] and row['BVADDRTELNO1']) or (row['BVADDREMAIL'] == item['EMAIL'] and row['BVADDREMAIL'])): lin = [] linha = inbv(lin) list2csv.append(linha) print linha break elif addrnormalize.format_address(row['BVADDR1']) == addrnormalize.format_address(item['ADDRESSLINEONE']) and row['BVADDR1'] and row['BVPROVSTATE'] == item['STATE'] and row['BVPROVSTATE']: lin = [] linha = inbv(lin) list2csv.append(linha) break ## elif (difflib.SequenceMatcher(lambda x: x in " ,.-#" , row['BVADDR1'], item['ADDRESSLINEONE']).quick_ratio() > 0.87) \ and (difflib.SequenceMatcher(lambda x: x in " .-" , row['BVCITY'], item['CITY']).quick_ratio() > 0.87): lin = [] linha = inbv(lin) list2csv.append(linha) break ## ## else: le = [] linha = notinbv(le) list_not_in_bv.append(linha) break print "now printing list2csv" print list2csv print list_not_in_bv for customer in list2csv: yesbv.writerow(customer) for customer in list_not_in_bv: nobv.writerow(customer) finished = time.time() print finished - started From rabidpoobear at gmail.com Thu Oct 8 23:36:49 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 8 Oct 2009 15:36:49 -0600 Subject: [Tutor] Troubles with lists and control flow In-Reply-To: References: <9356b9f30910081342l5e348eb8u79643d7a58fe72bf@mail.gmail.com> Message-ID: Oops, accidentally replied off-list. ---------- Forwarded message ---------- From: Luke Paireepinart Date: Thu, Oct 8, 2009 at 3:36 PM Subject: Re: [Tutor] Troubles with lists and control flow To: Eduardo Vieira On Thu, Oct 8, 2009 at 2:42 PM, Eduardo Vieira wrote: > Hello I'm developing a script to compare two files, finding duplicate > entries and matching which id of one csv file corresponds to the id of > another csv file. > The first version was working nice, but I wanted to postpone the > writing to a file till the end and also make a correct csv file. The > code is not so great and I expect to work with no more than 3000 lines > of data in either file: > So here is the inicial code. I hope it's not too long or complicated: > It's a little long to be in a message body, it'd have been nice if you posted to pastebin and chosen Python so we could have seen it with syntax highlighting and it would guarantee it doesn't mess up your indentation, but it's fine for now. Just keep that in mind for longer code samples. > def inbv(currentline = None): > """writes a line of data when a date is found in BV""" > if currentline is None: > currentline = [] > else: > currentline.append(item['USER_ID']) > currentline.append(row['CUS_NO']) > currentline.append(item['COMPANY']) > currentline.append(row['BVADDR1']) > currentline.append(item['ADDRESSLINEONE']) > currentline.append(row['BVADDRTELNO1']) > currentline.append(item['PHONE']) > currentline.append(row['BVCITY']) > currentline.append(item['CITY']) > > return currentline > You don't want to do it like this. What you're saying is: "if they didn't pass in an argument to my function, create a new list and return an empty list. otherwise, if they did pass in a list, append an item and return the new list." What you really want to do is "if they didn't pass in a list, create a new one. Then append a value and return the new list." There's a subtle difference, do you see it? You want to add an item to the list whether or not they passed in a list in the first place, you just want to initialize a new list first. Think about your code and how you can change it to do that. At least I think that's what your issue is, I don't really understand your code at all. Also: > > def notinbv(currentline): > if currentline is None: > currentline = [] You should go ahead and define this one the same as the previous one (with the optional currentline parameter) unless you left it out on purpose. -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From bobsmith327 at hotmail.com Fri Oct 9 00:04:27 2009 From: bobsmith327 at hotmail.com (bob smith) Date: Thu, 8 Oct 2009 15:04:27 -0700 Subject: [Tutor] Python 3 and tkinter Radiobuttons Message-ID: Hi. I?m using Tkinter to create a new Radiobutton in Python 3. However, when I create the button, it starts off looking selected instead of unselected (though it behaves correctly like an unselected Radiobutton). So this means when I create a group of Radiobuttons they all look selected when my program begins. This happens under both Windows XP and Windows 7. Here?s a super simple example program that produces this result: from tkinter import * root = Tk() root.grid() button = Radiobutton(root, text = "Test RadioButton") button.grid(row = 0, column = 0, sticky = W) root.mainloop() Does anyone know how to solve this issue? Anyone know if this is a bug being worked on? Thanks, --Bob _________________________________________________________________ Hotmail: Powerful Free email with security by Microsoft. http://clk.atdmt.com/GBL/go/171222986/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Oct 9 00:17:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 Oct 2009 18:17:39 -0400 Subject: [Tutor] Reading individual file from tar file as a file object In-Reply-To: References: Message-ID: <1c2a2c590910081517i729f290yaff9f4dde9febf8c@mail.gmail.com> On Thu, Oct 8, 2009 at 4:10 PM, xbmuncher wrote: > I have a large tar.bz2 file that I want to extract certain files directly to > an FTP path. > Since the extract() method doesn't accept ftp paths...? I wanted to read the > files from the tar file like a file object or file I/O stream. > Is there a way to do this? I think tarfile.extractfile() does what you want. The docs are a bit confusing but it returns a file-like object from which the item can be read. Your code would be something like tar = tarfile.open("HUGE_FILE_OVER_5GB.tar.bz2", "r:bz2") for tarInfo in tar: putThisDataSomewhere(tar.extractfile(tarInfo)) putThisDataSomewhere() will read from its argument and write to FTP. Any required blocking or buffering would be in putThisDataSomewhere(). Kent From kent37 at tds.net Tue Oct 6 16:16:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 Oct 2009 10:16:55 -0400 Subject: [Tutor] Checking for Python version In-Reply-To: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> References: <62d32bf20910060659m5b2f605cq1f661c52c288045a@mail.gmail.com> Message-ID: <1c2a2c590910060716v2f8fb28cs64ae413864823a10@mail.gmail.com> On Tue, Oct 6, 2009 at 9:59 AM, Didar Hossain wrote: > Hi, > > I am using the following code to check for the Python version - > > import os > > t = os.sys.version_info[0:2] > if (t[0] + t[1]) < 6: Hmm, what would this give for Python 1.5? How about if t < (2, 4): > ? ?os.sys.exit("Need at least Python 2.4") > del t > > This snippet is put at the beginning of the single script file before > the rest of the code. > I need to check for the minimum specific version because I am using > the "@staticmethod" > directive. You could check for what you actually need rather than checking the version: try: staticmethod except NameError: os.sys.exit("Need at least Python 2.4") Kent From kent37 at tds.net Fri Oct 9 02:43:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 Oct 2009 20:43:21 -0400 Subject: [Tutor] Python 3 and tkinter Radiobuttons In-Reply-To: References: Message-ID: <1c2a2c590910081743t2255d5e8p6d53a61351656149@mail.gmail.com> On Thu, Oct 8, 2009 at 6:04 PM, bob smith wrote: > Hi. ?I?m using Tkinter to create a new Radiobutton in Python 3.? However, > when I create the button, it starts off looking selected instead of > unselected (though it behaves correctly like an unselected Radiobutton).? So > this means when I create a group of Radiobuttons they all look selected when > my program begins. You have to associate the Radiobuttons with a variable, for example: from tkinter import * root = Tk() root.grid() v = IntVar() button = Radiobutton(root, text = "Test RadioButton", variable=v, value=1) button.grid(row = 0, column = 0, sticky = W) button = Radiobutton(root, text = "Test RadioButton2", variable=v, value=2) button.grid(row = 1, column = 0, sticky = W) root.mainloop() Kent From xboxmuncher at gmail.com Fri Oct 9 02:45:55 2009 From: xboxmuncher at gmail.com (Xbox Muncher) Date: Thu, 8 Oct 2009 20:45:55 -0400 Subject: [Tutor] Reading individual file from tar file as a file object In-Reply-To: <1c2a2c590910081517i729f290yaff9f4dde9febf8c@mail.gmail.com> References: <1c2a2c590910081517i729f290yaff9f4dde9febf8c@mail.gmail.com> Message-ID: <3f533e960910081745i4454d6c0wba585c5b79877238@mail.gmail.com> Works perfectly! Thanks. Yet again, I've learned I need to read better. :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Oct 9 03:25:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 Oct 2009 21:25:10 -0400 Subject: [Tutor] Reading individual file from tar file as a file object In-Reply-To: <3f533e960910081745i4454d6c0wba585c5b79877238@mail.gmail.com> References: <1c2a2c590910081517i729f290yaff9f4dde9febf8c@mail.gmail.com> <3f533e960910081745i4454d6c0wba585c5b79877238@mail.gmail.com> Message-ID: <1c2a2c590910081825w76b115du41c9d90a518ca63e@mail.gmail.com> On Thu, Oct 8, 2009 at 8:45 PM, Xbox Muncher wrote: > Works perfectly! Thanks. Yet again, I've learned I need to read better. :) And remember, if the docs are unclear, you can always look at the source, as I did... Kent From cfuller084 at thinkingplanet.net Fri Oct 9 03:16:10 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 9 Oct 2009 02:16:10 +0100 (BST) Subject: [Tutor] Wrapper of C++ Message-ID: <200910090116.n991GAUu004566@mail.authsmtp.com> It might also be a good application for numpy (http://www.numpy.org/) Cheers From christer.edwards at gmail.com Tue Oct 6 21:57:16 2009 From: christer.edwards at gmail.com (Christer Edwards) Date: Tue, 6 Oct 2009 13:57:16 -0600 Subject: [Tutor] list comprehensions Message-ID: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> I've been studying python now for a few weeks and I've recently come into list comprehensions. Some of the examples that I've found make sense, and I find them readable and concise. In particular I'm referring to the python docs on the topic (http://docs.python.org/tutorial/datastructures.html#list-comprehensions). Those make sense to me. The way I understand them is: do something to x for each x in list, with an optional qualifier. On the other hand I've seen a few examples that look similar, but there is no action done to the first x, which confuses me. An example: print sum(x for x in xrange(1,1000) if x%3==0 or x%5==0) In this case is sum() acting as the "action" on the first x? Can anyone shed some light on what it is I'm not quite grasping between the two? Christer From gregor.lingl at aon.at Fri Oct 9 07:03:01 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Fri, 09 Oct 2009 07:03:01 +0200 Subject: [Tutor] list comprehensions In-Reply-To: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> References: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> Message-ID: <4ACEC405.9090801@aon.at> Christer Edwards schrieb: > I've been studying python now for a few weeks and I've recently come > into list comprehensions. Some of the examples that I've found make > sense, and I find them readable and concise. In particular I'm > referring to the python docs on the topic > (http://docs.python.org/tutorial/datastructures.html#list-comprehensions). > Those make sense to me. The way I understand them is: > > do something to x for each x in list, with an optional qualifier. > > On the other hand I've seen a few examples that look similar, but > there is no action done to the first x, which confuses me. An example: > > print sum(x for x in xrange(1,1000) if x%3==0 or x%5==0) > > In this case is sum() acting as the "action" on the first x? No. >>> (x for x in xrange(1,100) if x%3==0 or x%5==0) at 0x011C1990> Is a generator expression. If you want to see what it generates, create e.g. a tuple >>> tuple(x for x in xrange(1,100) if x%3==0 or x%5==0) (3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99) So you see that the generator selects those integers that are divisible by 3 or 5 >>> sum(x for x in xrange(1,100) if x%3==0 or x%5==0) 2318 This calculates the some of those. There are quite a couple of functions in Python that accept generator expressions as arguments Regards, Gregor > > Can > anyone shed some light on what it is I'm not quite grasping between > the two? > > Christer > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From moron.oxy at gmail.com Fri Oct 9 07:17:44 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Fri, 9 Oct 2009 16:17:44 +1100 Subject: [Tutor] list comprehensions In-Reply-To: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> References: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> Message-ID: <2096a7260910082217h75089e0ei11dc34d1b783293d@mail.gmail.com> Hello, On Wed, Oct 7, 2009 at 6:57 AM, Christer Edwards wrote: > > do something to x for each x in list, with an optional qualifier. > To be more precise: http://docs.python.org/tutorial/datastructures.html#list-comprehensions "Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses" > On the other hand I've seen a few examples that look similar, but > there is no action done to the first x, which confuses me. An example: > > print sum(x for x in xrange(1,1000) if x%3==0 or x%5==0) So, it's not an 'action' as such, but an expression, x in this case is a variable containing a number, thus stating 'x' by itself is an expression that yields x's value and adds it to the sequence being generated without doing anything else to it. The built-in function sum (on the interpreter, type: help(sum)) takes a sequence of (numeric) values and returns their... sum :-). > In this case is sum() acting as the "action" on the first x? Can > anyone shed some light on what it is I'm not quite grasping between > the two? Hence, sum does not know about x at all, just about the end result of the generator expression: the generated sequence first evaluated, then passed into it as an argument. -- Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi From wescpy at gmail.com Fri Oct 9 07:21:19 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 8 Oct 2009 22:21:19 -0700 Subject: [Tutor] list comprehensions In-Reply-To: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> References: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> Message-ID: <78b3a9580910082221r328228dcy41d54371b51bb129@mail.gmail.com> > I've been studying python now for a few weeks and I've recently come > into list comprehensions. [...] > Those make sense to me. The way I understand them is: > do something to x for each x in list, with an optional qualifier. that's pretty much correct. > On the other hand I've seen a few examples that look similar, but > there is no action done to the first x, which confuses me. An example: > > print sum(x for x in xrange(1,1000) if x%3==0 or x%5==0) > > In this case is sum() acting as the "action" on the first x? the "do something" can also include "do nothing!" in other words, you can simply just select certain elements that meet your particular criteria. for example, let's say you just want all the odd numbers from 0 to 19: odd = [x for x in range(20) if x % 2 != 0] you just wanted the numbers but not to really do anything with them other than have them as elements in a newly-created list. your question also brought up "generator expressions" which are lazier, more memory-friendly alternative to "listcomps." the syntax is nearly identical, with the only difference being that they're enclosed by parentheses instead of square brackets: odd_gen = (x for x in range(20) if x % 2 != 0) that's the only difference syntactically. however, there is a bigger difference under the covers: >>> odd [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] >>> odd_gen at 0x012F44E0> notice that memory is allocated and the entire list created in memory for the listcomp but just a generic object for the "genexp." they are "lazy" because you iterate over the values one at a time instead of creating the entire list. they are slightly slower but save memory. similar constructs for dicts and sets appear in Python 3: dictionary and set comprehensions. back to your question regarding sum(). sum() just iterates over the genexp and adds up all the individual numbers iterated over. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From stefan at lsd.co.za Fri Oct 9 09:54:24 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Fri, 9 Oct 2009 09:54:24 +0200 Subject: [Tutor] for loop issue Message-ID: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> Hi, This feels like a strange issue, so i hope I formulate this so its understandable. I have some objects. Each object has associated values. I am looping through these objects, working with a value and printing out the value. The issue in this case is that i need to check if the one value superseeds the other, and in that case, not print it out. I think the problem is that when you are in the loop, you dont know about the other object that you havent processed yet, and when you are processing that object, you dont know about the previous one? (not 100% sure if this assumption is correct) eg of my data (im comparing ubuntu -> debian security fixes and the data comes from https://edge.launchpad.net/ubuntu/+source/openswan) You can see what i have so far here - http://people.ubuntu.com/~stefanlsd/synclist.html The Jaunty Jackalope (current stable release) Show details 1:2.4.12+dfsg-1.3+lenny2build0.9.04.1 updates, security (universe) two days ago Show details 1:2.4.12+dfsg-1.3 release (universe) 49 weeks ago In the above case, the first loop goes through 1:2.4.12+dfsg-1.3+lenny2build0.9.04.1. At this point i need it to stop without checking the next entry 1:2.4.12+dfsg-1.3 as the former superseeds it. I understand that I can use a break to exit the loop, but i run a whole bunch of things after this check, so i dont want to break out of it. Is this possible what i'm doing? or have i architected the loop wrong so i 'should' be able to break out of it. Thanks in advance! stefan snippet of code below if its of any use... for app in apps: print('app in apps: %s' % app) for item in series: print('item in series: %s' % item) debian_series = item[0] debian_fullversion = item[2] print('debian_series: %s' % debian_series) print('debian_fullversion: %s' % debian_fullversion) debian_version = re.sub('\+?(etch|lenny|sarge|squeeze|woody)[0-9]+$', '', debian_fullversion) print('debian_version: %s' % debian_version) main_archive = launchpad.distributions['ubuntu'].main_archive #TODO - May be able to use a version check in the publishedsource to increase speed of checking publishedsource = main_archive.getPublishedSources(source_name = app, status='Published', exact_match=True) for source in publishedsource: if source.distro_series.active: print source.distro_series.name, source.source_package_version ubuntu_fullversion = source.source_package_version print('ubuntu fullversion before: %s' % ubuntu_fullversion) ubuntu_version = re.sub('build0.[0-9]+.[0-9][0-9].[0-9]+$', '', ubuntu_fullversion) #ubuntu_version = re.sub('\+?(etch|lenny|sarge|squeeze|woody)[0-9]+$', '', ubuntu_version) print('ubuntu version after: %s' % ubuntu_version) #ubuntu_target = ('%subuntu/+source/%s') % (launchpad._root_uri,app) if debian_fullversion == ubuntu_version: continue if debian_version in ubuntu_fullversion: ubuntu_component = source.component_name ubuntu_series = source.distro_series.name ubuntu_pocket = source.pocket print('ubuntu_pocket: %s' % ubuntu_pocket) print('debian version: %s' % debian_version) #If pocket is Security, no need to check further if ubuntu_pocket == 'Security' or ubuntu_pocket == 'Updates': print('Not Found version in: %s. Continue' % ubuntu_pocket) break if debian_version == ubuntu_version: matchtype = 'Sync Match' else: matchtype = 'MoM Match' ubuntu_changelog = 'Ubuntu Changelog' debian_changelog = 'Debian Changelog' print('cve: %s' % cve) for cveitem in cve: cvestatus, url = cvecheck(cveitem, ubuntu_series, ubuntu_version) print('cvestatus: "%s"' % cvestatus) if cvestatus == 'released' or cvestatus == 'dne' or cvestatus == 'not-affected': pass else: writeweb(date, matchtype, app, ubuntu_series, ubuntu_fullversion, debian_fullversion, ubuntu_changelog, debian_changelog, url, cveitem, cvestatus) From adam.jtm30 at gmail.com Fri Oct 9 11:40:23 2009 From: adam.jtm30 at gmail.com (Adam Bark) Date: Fri, 9 Oct 2009 10:40:23 +0100 Subject: [Tutor] for loop issue In-Reply-To: References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> Message-ID: 2009/10/9 Stefan Lesicnik Hi, > > This feels like a strange issue, so i hope I formulate this so its > understandable. > > I have some objects. Each object has associated values. I am looping > through these objects, working with a value and printing out the > value. > The issue in this case is that i need to check if the one value > superseeds the other, and in that case, not print it out. I think the > problem is that when you are in the loop, you dont know about the > other object that you havent processed yet, and when you are > processing that object, you dont know about the previous one? (not > 100% sure if this assumption is correct) > > eg of my data (im comparing ubuntu -> debian security fixes and the > data comes from https://edge.launchpad.net/ubuntu/+source/openswan) > You can see what i have so far here - > http://people.ubuntu.com/~stefanlsd/synclist.html > > The Jaunty Jackalope (current stable release) > Show details 1:2.4.12+dfsg-1.3+lenny2build0.9.04.1 updates, security > (universe) two days ago > Show details 1:2.4.12+dfsg-1.3 release (universe) 49 weeks ago > > In the above case, the first loop goes through > 1:2.4.12+dfsg-1.3+lenny2build0.9.04.1. At this point i need it to stop > without checking the next entry 1:2.4.12+dfsg-1.3 as the former > superseeds it. > I understand that I can use a break to exit the loop, but i run a > whole bunch of things after this check, so i dont want to break out of > it. > > Is this possible what i'm doing? or have i architected the loop wrong > so i 'should' be able to break out of it. > > Thanks in advance! > > stefan > > > snippet of code below if its of any use... > > > for app in apps: > print('app in apps: %s' % app) > for item in series: > print('item in series: %s' % item) > debian_series = item[0] > debian_fullversion = item[2] > print('debian_series: %s' % debian_series) > print('debian_fullversion: %s' % debian_fullversion) > > debian_version = > re.sub('\+?(etch|lenny|sarge|squeeze|woody)[0-9]+$', '', > debian_fullversion) > print('debian_version: %s' % debian_version) > > main_archive = > launchpad.distributions['ubuntu'].main_archive > #TODO - May be able to use a version check in the > publishedsource to increase speed of checking > publishedsource = > main_archive.getPublishedSources(source_name = app, > status='Published', exact_match=True) > > for source in publishedsource: > > if source.distro_series.active: > print source.distro_series.name, > source.source_package_version > ubuntu_fullversion = source.source_package_version > print('ubuntu fullversion before: %s' % > ubuntu_fullversion) > ubuntu_version = > re.sub('build0.[0-9]+.[0-9][0-9].[0-9]+$', '', ubuntu_fullversion) > #ubuntu_version = > re.sub('\+?(etch|lenny|sarge|squeeze|woody)[0-9]+$', '', > ubuntu_version) > print('ubuntu version after: %s' % ubuntu_version) > #ubuntu_target = ('%subuntu/+source/%s') % > (launchpad._root_uri,app) > > if debian_fullversion == ubuntu_version: > continue > > if debian_version in ubuntu_fullversion: > ubuntu_component = source.component_name > ubuntu_series = source.distro_series.name > ubuntu_pocket = source.pocket > print('ubuntu_pocket: %s' % ubuntu_pocket) > print('debian version: %s' % debian_version) > > #If pocket is Security, no need to check further > if ubuntu_pocket == 'Security' or > ubuntu_pocket == 'Updates': > print('Not Found version in: %s. > Continue' % ubuntu_pocket) > break > > if debian_version == ubuntu_version: > matchtype = 'Sync Match' > else: > matchtype = 'MoM Match' > > ubuntu_changelog = ' href=http://changelogs.ubuntu.com/changelogs/pool/' + ubuntu_component > + '/' + app[:1] + '/' + app + '/' + app + '_' + ubuntu_version + > '/changelog>Ubuntu Changelog' > debian_changelog = ' href=http://packages.debian.org/changelogs/pool/' + 'main' + '/' + > app[:1] + '/' + app + '/' + app + '_' + debian_fullversion + > '/changelog>Debian Changelog' > > print('cve: %s' % cve) > for cveitem in cve: > cvestatus, url = cvecheck(cveitem, > ubuntu_series, ubuntu_version) > print('cvestatus: "%s"' % cvestatus) > if cvestatus == 'released' or > cvestatus == 'dne' or cvestatus == 'not-affected': > pass > else: > writeweb(date, matchtype, app, > ubuntu_series, ubuntu_fullversion, debian_fullversion, > ubuntu_changelog, debian_changelog, url, cveitem, cvestatus) > I'm not sure I fully understand this but you can put the break statement anywhere so you can check whether or not you need to continue then do a bunch of things before finally breaking out of the loop eg. if "something good" == happened: # do stuff # do some more things break HTH -------------- next part -------------- An HTML attachment was scrubbed... URL: From moron.oxy at gmail.com Fri Oct 9 12:35:06 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Fri, 9 Oct 2009 21:35:06 +1100 Subject: [Tutor] for loop issue In-Reply-To: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> Message-ID: <2096a7260910090335k6285d6fdnc2a8b860f5b19489@mail.gmail.com> Hello, On Fri, Oct 9, 2009 at 6:54 PM, Stefan Lesicnik wrote: > The issue in this case is that i need to check if the one value > superseeds the other, and in that case, not print it out. I think the > problem is that when you are in the loop, you dont know about the > other object that you havent processed yet, and when you are > processing that object, you dont know about the previous one? ?(not > 100% sure if this assumption is correct) If I understand correctly, the items are basically in the same collection that you're looping over. And you need to know an item after/before the current one being iterated over. Whether you can do this or not (or do it easily!) really depends on what sort of sequence you are iterating over, if it's something in-memory like a list or a tuple, it's easy, instead of iterating over the actual items in the collection, you iterate their indexes, let's assume your items are inside a list x: x = ['foo', 'bar', 'baz', 'spam'] for i in xrange(0, len(x)-1): print x[i], x[i+1] Thus, you can muck around with x[i] (current item), and x[i+1] (next item), and decide how you want to proceed with the loop. Note the use of len(x) - 1 rather than just len(x) to easily prevent an IndexError or extra special case logic. Now, if what you're looping over is something that just follows the iteration protocol (i.e. something you can iterate over), it may not know or support knowing the length (look up the __len__ special method for more info) of the items in advance, i.e. len(iterable_obj) fails. An example of this is the file handle, which allows you to iterate through lines in the file, but attempting to do a len(handle), e.g.: >>> f = open('foo.txt') >>> len(f) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'file' has no len() fails. In this case, the simplest thing is to first read in the items into an in-memory structure like a list or tuple, then use the index iteration method above. If not all data can fit into memory, then it is time to wrack your brains some more, I suspect you won't have to go that far for now though :-). Ask away if this is unclear or I got your problem description wrong. -- Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi From moron.oxy at gmail.com Fri Oct 9 12:39:42 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Fri, 9 Oct 2009 21:39:42 +1100 Subject: [Tutor] for loop issue In-Reply-To: <2096a7260910090335k6285d6fdnc2a8b860f5b19489@mail.gmail.com> References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> <2096a7260910090335k6285d6fdnc2a8b860f5b19489@mail.gmail.com> Message-ID: <2096a7260910090339i2218ddap3999a5593ae8fe37@mail.gmail.com> On Fri, Oct 9, 2009 at 9:35 PM, Oxymoron wrote: > Thus, you can muck around with x[i] (current item), and x[i+1] (next > item), and decide how you want to proceed with the loop. Note the use > of len(x) - 1 rather than just len(x) to easily prevent an IndexError > or extra special case logic. "easily prevent an IndexError without extra special case logic". It's been a long week. -- Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi From kent37 at tds.net Fri Oct 9 13:57:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Oct 2009 07:57:14 -0400 Subject: [Tutor] list comprehensions In-Reply-To: <78b3a9580910082221r328228dcy41d54371b51bb129@mail.gmail.com> References: <9dbd3d650910061257p7dbd4211jf03c4ebdd8360724@mail.gmail.com> <78b3a9580910082221r328228dcy41d54371b51bb129@mail.gmail.com> Message-ID: <1c2a2c590910090457q5b33353flb8a68da7faf9780c@mail.gmail.com> On Fri, Oct 9, 2009 at 1:21 AM, wesley chun wrote: > [generator expressions] are > "lazy" because you iterate over the values one at a time instead of > creating the entire list. they are slightly slower but save memory. I don't think you can make a blanket statement comparing speed of list comp vs genexp. For example: kent $ py -m timeit 'sum(x for x in xrange(1,1000) if x%3==0 or x%5==0)' 1000 loops, best of 3: 295 usec per loop kent $ py -m timeit 'sum([x for x in xrange(1,1000) if x%3==0 or x%5==0])' 1000 loops, best of 3: 281 usec per loop Here list comp is a bit faster. kent $ py -m timeit 'sum(x for x in xrange(1,10000) if x%3==0 or x%5==0)' 100 loops, best of 3: 2.83 msec per loop kent $ py -m timeit 'sum([x for x in xrange(1,10000) if x%3==0 or x%5==0])' 100 loops, best of 3: 2.85 msec per loop Here they are neck and neck. kent $ py -m timeit 'sum(x for x in xrange(1,100000) if x%3==0 or x%5==0)' 10 loops, best of 3: 28.9 msec per loop kent $ py -m timeit 'sum([x for x in xrange(1,100000) if x%3==0 or x%5==0])' 10 loops, best of 3: 29.4 msec per loop genexp pulls in to the lead. Kent From kent37 at tds.net Fri Oct 9 14:02:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Oct 2009 08:02:28 -0400 Subject: [Tutor] for loop issue In-Reply-To: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> Message-ID: <1c2a2c590910090502w1447b7abk7cf80907d133b9b4@mail.gmail.com> On Fri, Oct 9, 2009 at 3:54 AM, Stefan Lesicnik wrote: > Hi, > > This feels like a strange issue, so i hope I formulate this so its > understandable. > > I have some objects. Each object has associated values. I am looping > through these objects, working with a value and printing out the > value. > The issue in this case is that i need to check if the one value > superseeds the other, and in that case, not print it out. I think the > problem is that when you are in the loop, you dont know about the > other object that you havent processed yet, and when you are > processing that object, you dont know about the previous one? ?(not > 100% sure if this assumption is correct) You can easily keep track of the previous item by assigning it to a variable. For example this shows just the increasing elements of a sequence: In [22]: items = [0, 1, 3, 2, 8, 5, 9 ] In [23]: last = None In [24]: for item in items: ....: if last is None or item > last: ....: print item ....: last = item 0 1 3 8 9 From moron.oxy at gmail.com Fri Oct 9 14:15:13 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Fri, 9 Oct 2009 23:15:13 +1100 Subject: [Tutor] for loop issue In-Reply-To: <1c2a2c590910090502w1447b7abk7cf80907d133b9b4@mail.gmail.com> References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> <1c2a2c590910090502w1447b7abk7cf80907d133b9b4@mail.gmail.com> Message-ID: <2096a7260910090515y52be3b83s310ceac14573224b@mail.gmail.com> On Fri, Oct 9, 2009 at 11:02 PM, Kent Johnson wrote: > On Fri, Oct 9, 2009 at 3:54 AM, Stefan Lesicnik wrote: > > You can easily keep track of the previous item by assigning it to a > variable. For example this shows just the increasing elements of a > sequence: > > In [22]: items = [0, 1, 3, 2, 8, 5, 9 ] > > In [23]: last = None > > In [24]: for item in items: > ? ....: ? ? if last is None or item > last: > ? ....: ? ? ? ? print item > ? ....: ? ? last = item Darn... this is what happens when you're stuck on one solution (referring to my index-only ways in the last post) - you miss other obvious ways, duh * 10. Apologies for the unnecessarily complicated exposition on iterables above. :-( -- There is more to life than increasing its speed. -- Mahatma Gandhi From eduardo.susan at gmail.com Fri Oct 9 17:36:23 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 9 Oct 2009 09:36:23 -0600 Subject: [Tutor] Troubles with lists and control flow In-Reply-To: References: <9356b9f30910081342l5e348eb8u79643d7a58fe72bf@mail.gmail.com> Message-ID: <9356b9f30910090836t7189cbbbv627a55132d23febe@mail.gmail.com> On Thu, Oct 8, 2009 at 3:36 PM, Luke Paireepinart wrote: > Oops, accidentally replied off-list. > > ---------- Forwarded message ---------- > From: Luke Paireepinart > Date: Thu, Oct 8, 2009 at 3:36 PM > Subject: Re: [Tutor] Troubles with lists and control flow > To: Eduardo Vieira > > > > > On Thu, Oct 8, 2009 at 2:42 PM, Eduardo Vieira > wrote: >> >> Hello I'm developing a script to compare two files, finding duplicate >> entries and matching which id of one csv file corresponds to the id of >> another csv file. >> The first version was working nice, but I wanted to postpone the >> writing to a file till the end and also make a correct csv file. The >> code is not so great and I expect to work with no more than 3000 lines >> of data in either file: >> So here is the inicial code. I hope it's not too long or complicated: > > It's a little long to be in a message body, it'd have been nice if you > posted to pastebin and chosen Python so we could have seen it with syntax > highlighting and it would guarantee it doesn't mess up your indentation, but > it's fine for now.? Just keep that in mind for longer code samples. > >> >> def inbv(currentline = None): >> ? ?"""writes a line of data when a date is found in BV""" >> ? ?if currentline is None: >> ? ? ? ?currentline = [] >> ? ?else: >> ? ? ? ?currentline.append(item['USER_ID']) >> ? ? ? ?currentline.append(row['CUS_NO']) >> ? ? ? ?currentline.append(item['COMPANY']) >> ? ? ? ?currentline.append(row['BVADDR1']) >> ? ? ? ?currentline.append(item['ADDRESSLINEONE']) >> ? ? ? ?currentline.append(row['BVADDRTELNO1']) >> ? ? ? ?currentline.append(item['PHONE']) >> ? ? ? ?currentline.append(row['BVCITY']) >> ? ? ? ?currentline.append(item['CITY']) >> >> ? ?return currentline > > You don't want to do it like this. > What you're saying is: > "if they didn't pass in an argument to my function, create a new list and > return an empty list.? otherwise, if they did pass in a list, append an item > and return the new list."? What you really want to do is "if they didn't > pass in a list, create a new one.? Then append a value and return? the new > list."? There's a subtle difference, do you see it? You want to add an item > to the list whether or not they passed in a list in the first place, you > just want to initialize a new list first.? Think about your code and how you > can change it to do that. > > At least I think that's what your issue is, I don't really understand your > code at all. > > Also: >> >> def notinbv(currentline): >> ? ?if currentline is None: >> ? ? ? ?currentline = [] > > You should go ahead and define this one the same as the previous one (with > the optional currentline parameter) unless you left it out on purpose. > > -Luke > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Thanks Luke. I corrected my function, but I didn't have any good result. In other words, the problem wasn't there. The problem was with my control flow... I was using a "break" under the else clause. I often get confused with control flow things... Well, the 'else' clause on a for loop is always executed when there is no "break" triggered in the loop. So, that "break" under the else was not necessary ... and was not present in my first version too... copy and paste error, I guess. Eduardo www.expresssignproducts.com From digitalman66 at gmail.com Fri Oct 9 21:16:54 2009 From: digitalman66 at gmail.com (Glen Zangirolami) Date: Fri, 9 Oct 2009 14:16:54 -0500 Subject: [Tutor] Finding and Inserting missing dates in a date range. Message-ID: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> If i have a list of dates:date_list = ['2008-12-29','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-05'] How do I find the missing dates in the range of dates and insert them into the list so I get? date_list = ['2008-12-29','2008-12-30','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-12-04','2008-01-05'] Hopefully the case is that I haven't found the correct python module that does it ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Oct 9 22:29:16 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 9 Oct 2009 15:29:16 -0500 Subject: [Tutor] Finding and Inserting missing dates in a date range. In-Reply-To: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> References: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> Message-ID: <333efb450910091329g17b78263p571f3e7ca2a8de5b@mail.gmail.com> On Fri, Oct 9, 2009 at 2:16 PM, Glen Zangirolami wrote: > If i have a list of dates:date_list = > ['2008-12-29','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-05'] > > How do I find the missing dates in the range of dates and insert them into > the list so I get? > date_list = > ['2008-12-29','2008-12-30','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-12-04','2008-01-05'] > > Hopefully the case is that I haven't found the correct python module that > does it ;) > The datetime module exists... you could easily write a function that does something along the lines of: def date_range(startdate, enddate): #do something here to make a range of dates though you may want to write a function that checks for a missing date first. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Oct 9 22:41:06 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 09 Oct 2009 21:41:06 +0100 Subject: [Tutor] Finding and Inserting missing dates in a date range. In-Reply-To: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> References: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> Message-ID: <4ACF9FE2.9050306@timgolden.me.uk> Glen Zangirolami wrote: > If i have a list of dates:date_list = > ['2008-12-29','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-05'] > > How do I find the missing dates in the range of dates and insert them into > the list so I get? > date_list = > ['2008-12-29','2008-12-30','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-12-04','2008-01-05'] > > Hopefully the case is that I haven't found the correct python module that > does it ;) I'd be inclined to combine datetime.strptime with a date-ranging function and some set work. TJG From kent37 at tds.net Fri Oct 9 22:43:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Oct 2009 16:43:53 -0400 Subject: [Tutor] Finding and Inserting missing dates in a date range. In-Reply-To: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> References: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> Message-ID: <1c2a2c590910091343l549d05an2fad4033f3707f58@mail.gmail.com> On Fri, Oct 9, 2009 at 3:16 PM, Glen Zangirolami wrote: > If i have a list of dates: > date_list = > ['2008-12-29','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-05'] > How do I find the missing dates in the range of dates and insert them into > the list so I get? > date_list = > ['2008-12-29','2008-12-30','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-12-04','2008-01-05'] I would do something like the following using datetime.datetime and datetime.timedelta: - convert each list item to a datetime object using datetime.strptime() - find the min and max datetimes in the list (use min() and max() - create a new list by incrementing the min date by timedelta(days=1) until it hits the max date - convert the new list to strings using datetime.strftime() Kent From rudiger.wolf at throughputfocus.com Sat Oct 10 00:11:28 2009 From: rudiger.wolf at throughputfocus.com (=?ISO-8859-1?Q?R=FCdiger=20Wolf?=) Date: Fri, 09 Oct 2009 23:11:28 +0100 Subject: [Tutor] Finding and Inserting missing dates in a date range. In-Reply-To: <1c2a2c590910091343l549d05an2fad4033f3707f58@mail.gmail.com> References: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> <1c2a2c590910091343l549d05an2fad4033f3707f58@mail.gmail.com> Message-ID: <1255126288.8112.1339240893@webmail.messagingengine.com> Ah! but are we sure that the max and min dates are actually in the list? If there are 'missing dates' it might just be possible that it is the max or min date that is missing. On Fri, 09 Oct 2009 16:43 -0400, "Kent Johnson" wrote: > On Fri, Oct 9, 2009 at 3:16 PM, Glen Zangirolami > wrote: > > If i have a list of dates: > > date_list = > > ['2008-12-29','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-05'] > > How do I find the missing dates in the range of dates and insert them into > > the list so I get? > > date_list = > > ['2008-12-29','2008-12-30','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-12-04','2008-01-05'] > > I would do something like the following using datetime.datetime and > datetime.timedelta: > - convert each list item to a datetime object using datetime.strptime() > - find the min and max datetimes in the list (use min() and max() > - create a new list by incrementing the min date by timedelta(days=1) > until it hits the max date > - convert the new list to strings using datetime.strftime() > > Kent From digitalman66 at gmail.com Sat Oct 10 00:15:37 2009 From: digitalman66 at gmail.com (Glen Zangirolami) Date: Fri, 9 Oct 2009 17:15:37 -0500 Subject: [Tutor] Finding and Inserting missing dates in a date range. In-Reply-To: <1255126288.8112.1339240893@webmail.messagingengine.com> References: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> <1c2a2c590910091343l549d05an2fad4033f3707f58@mail.gmail.com> <1255126288.8112.1339240893@webmail.messagingengine.com> Message-ID: <24a9d1f30910091515n429141e5l418dac1f06259d20@mail.gmail.com> Thats for all the responses. I'm going to use Kents method. I'll let you know what I work out. Rudiger - I did think about that. Luckily I am generating the list with a start datetime and end datetime so if those don't exist in either end if the list I can insert them after I check the dates between. On Fri, Oct 9, 2009 at 5:11 PM, R?diger Wolf < rudiger.wolf at throughputfocus.com> wrote: > Ah! but are we sure that the max and min dates are actually in the list? > If there are 'missing dates' it might just be possible that it is the > max or min date that is missing. > > On Fri, 09 Oct 2009 16:43 -0400, "Kent Johnson" wrote: > > On Fri, Oct 9, 2009 at 3:16 PM, Glen Zangirolami > > > wrote: > > > If i have a list of dates: > > > date_list = > > > > ['2008-12-29','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-05'] > > > How do I find the missing dates in the range of dates and insert them > into > > > the list so I get? > > > date_list = > > > > ['2008-12-29','2008-12-30','2008-12-31','2008-01-01','2008-01-02','2008-01-03','2008-12-04','2008-01-05'] > > > > I would do something like the following using datetime.datetime and > > datetime.timedelta: > > - convert each list item to a datetime object using datetime.strptime() > > - find the min and max datetimes in the list (use min() and max() > > - create a new list by incrementing the min date by timedelta(days=1) > > until it hits the max date > > - convert the new list to strings using datetime.strftime() > > > > Kent > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From xboxmuncher at gmail.com Sat Oct 10 06:20:45 2009 From: xboxmuncher at gmail.com (xbmuncher) Date: Sat, 10 Oct 2009 00:20:45 -0400 Subject: [Tutor] If you don't close file when writing, do bytes stay in memory? Message-ID: Which piece of code will conserve more memory? I think that code #2 will because I close the file more often, thus freeing more memory by closing it. Am I right in this thinking... or does it not save me any more bytes in memory by closing the file often? Sure I realize that in my example it doesn't save much if it does... but I'm dealing with writing large files.. so every byte freed in memory counts. Thanks. CODE #1: def getData(): return '12345' #5 bytes f = open('file.ext', 'wb') for i in range(2000): f.write(getData()) f.close() CODE #2: def getData(): return '12345' #5 bytes f = open('file.ext', 'wb') for i in range(2000): f.write(getData()) if i == 5: f.close() f = open('file.ext', 'ab') i = 1 i = i + 1 f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From moron.oxy at gmail.com Sat Oct 10 08:17:10 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Sat, 10 Oct 2009 17:17:10 +1100 Subject: [Tutor] If you don't close file when writing, do bytes stay in memory? In-Reply-To: References: Message-ID: <2096a7260910092317l4f185179kebb7f0e84e4b1ded@mail.gmail.com> (Did not do a reply-all earlier) On Sat, Oct 10, 2009 at 3:20 PM, xbmuncher wrote: > Which piece of code will conserve more memory? > ?I think that code #2 will because I close the file more often, thus freeing > more memory by closing it. > Am I right in this thinking... or does it not save me any more bytes in > memory by closing the file often? In general, you should only close a file once you're done with writing all the data you need. Opening and closing after each write within a loop is unnecessarily costly, as it usually translates to multiple system calls. Thus the general pattern is: open file while have stuff to do: do stuff, read/write file finally close file (As an aside, you can also check out the 'with' statement in Python 2.5+ that'll handle the closing.) With regard to memory consumption, there are 2 issues to be considered: 1. An open file handle obviously takes up some memory space, but this is (usually) insignificant in comparison to actual data being read/written, in your example the actual bytes. Not that you shouldn't worry about keeping too many file descriptors open, there are limits per process/user depending on the OS on the number of file descriptors/handles that can be open at any one time. 2. The data itself, if the data is in memory, say from a list, etc. obviously that takes up space, adding to the memory consumed by your program. This is where Python's garbage collection (GC) comes in handy. I am not familiar with the exact type of GC the CPython interpreter uses, but as a general rule, if you scope your data to just where it's needed, e.g. within functions, etc. and it is not accidentally referred to from somewhere else for reference-able types (e.g. lists), then once the function or code block is complete, the memory will be reclaimed by Python. This is also a good reason to avoid global variables, or limit them to things like constants, or overall configuration, or items that are reused many times across the application (e.g. caching). Otherwise, the memory remains for the lifetime of the program even if your code does not use the data. So point 2, the actual data items, lists, variables etc. are more significant in terms of memory, in comparison to file handles. In your example, the data is produced by getData(), so is only created as necessary, but let's say you did: x = getData() x is a global, and is no longer ever used except maybe once - since it is in scope, the memory remains. (Strings are of course immutable and often cached by Python once created so this may be a moot point for string data.) Hope that helps. -- Kamal -- There is more to life than increasing its speed. -- Mahatma Gandhi From didar.hossain at gmail.com Sat Oct 10 11:31:54 2009 From: didar.hossain at gmail.com (Didar Hossain) Date: Sat, 10 Oct 2009 15:01:54 +0530 Subject: [Tutor] [OT] Secure coding guidelines Message-ID: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> Hi, This is a little off-topic, but, I though I might put this question in. Since I am learning Python, I was wondering if there are any good references on secure coding practices. Books, guides or even any howtos would suffice. Security seems to be almost always an after-thought rather than being ingrained into any course that I have come across including the ones that they have in college degrees. If this question is inappropriate for this list then please let me know and accept my apologies (EAFP) ;-) Regards, Didar From davea at ieee.org Sat Oct 10 13:02:08 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 10 Oct 2009 07:02:08 -0400 Subject: [Tutor] If you don't close file when writing, do bytes stay in memory? In-Reply-To: References: Message-ID: <4AD069B0.7020906@ieee.org> xbmuncher wrote: > Which piece of code will conserve more memory? > I think that code #2 will because I close the file more often, thus freeing > more memory by closing it. > Am I right in this thinking... or does it not save me any more bytes in > memory by closing the file often? > Sure I realize that in my example it doesn't save much if it does... but I'm > dealing with writing large files.. so every byte freed in memory counts. > Thanks. > > CODE #1: > def getData(): return '12345' #5 bytes > f = open('file.ext', 'wb') > for i in range(2000): > f.write(getData()) > > f.close() > > > CODE #2: > def getData(): return '12345' #5 bytes > f = open('file.ext', 'wb') > for i in range(2000): > f.write(getData()) > if i == 5: > f.close() > f = open('file.ext', 'ab') > i = 1 > i = i + 1 > > f.close() > > You don't save a noticeable amount of memory usage by closing and immediately reopening the file. The amount that the system buffers probably wouldn't depend on file size, in any case. When dealing with large files, the thing to watch is how much of the data you've got in your own lists and dictionaries, not how much the file subsystem and OS are using. But you have other issues in your code. 1) you don't say what version of Python you're using. So I'll assume it's version 2.x. If so, then range is unnecessarily using a lot of memory. It builds a list of ints, when an iterator would do just as well. Use xrange(). ( In Python 3.x, xrange() was renamed to be called range(). ) This may not matter for small values, but as the number gets bigger, so would the amount of wastage. 2) By using the same local for the for loop as for your "should I close" counter, you're defeating the logic. As it stands, it'll only do the close() once. Either rename one of these, or do the simpler test, of if i%5 == 0: f.close() f = open.... 3) Close and re-open has three other effects. One, it's slow. Two, append-mode isn't guaranteed by the C standard to always position at the end (!). And three, it flushes the data. That can be a very useful result, in case the computer crashes while spending a long time updating a file. I'd suggest sometimes doing a flush() call on the file, if you know you'll be spending a long time updating it. But I wouldn't bother closing it. DaveA From xboxmuncher at gmail.com Sat Oct 10 16:32:09 2009 From: xboxmuncher at gmail.com (Xbox Muncher) Date: Sat, 10 Oct 2009 10:32:09 -0400 Subject: [Tutor] If you don't close file when writing, do bytes stay in memory? In-Reply-To: <4AD069B0.7020906@ieee.org> References: <4AD069B0.7020906@ieee.org> Message-ID: <3f533e960910100732u9fab96ke50873e5dd1ed905@mail.gmail.com> What does flush do technically? "Flush the internal buffer, like stdio?s fflush(). This may be a no-op on some file-like objects." The reason I thought that closing the file after I've written about 500MB file data to it, was smart -> was because I thought that python stores that data in memory or keeps info about it somehow and only deletes this memory of it when I close the file. When I write to a file in 'wb' mode at 500 bytes at a time.. I see that the file size changes as I continue to add more data, maybe not in exact 500 byte sequences as my code logic but it becomes bigger as I make more iterations still. Seeing this, I know that the data is definitely being written pretty immediately to the file and not being held in memory for very long. Or is it...? Does it still keep it in this "internal buffer" if I don't close the file. If it does, then flush() is exactly what I need to free the internal buffer, which is what I was trying to do when I closed the file anyways... However, from your replies I take it that python doesn't store this data in an internal buffer and DOES immediately dispose of the data into the file itself (of course it still exists in variables I put it in). So, closing the file doesn't free up any more memory. On Sat, Oct 10, 2009 at 7:02 AM, Dave Angel wrote: > xbmuncher wrote: > >> Which piece of code will conserve more memory? >> I think that code #2 will because I close the file more often, thus >> freeing >> more memory by closing it. >> Am I right in this thinking... or does it not save me any more bytes in >> memory by closing the file often? >> Sure I realize that in my example it doesn't save much if it does... but >> I'm >> dealing with writing large files.. so every byte freed in memory counts. >> Thanks. >> >> CODE #1: >> def getData(): return '12345' #5 bytes >> f = open('file.ext', 'wb') >> for i in range(2000): >> f.write(getData()) >> >> f.close() >> >> >> CODE #2: >> def getData(): return '12345' #5 bytes >> f = open('file.ext', 'wb') >> for i in range(2000): >> f.write(getData()) >> if i == 5: >> f.close() >> f = open('file.ext', 'ab') >> i = 1 >> i = i + 1 >> >> f.close() >> >> >> > You don't save a noticeable amount of memory usage by closing and > immediately reopening the file. The amount that the system buffers probably > wouldn't depend on file size, in any case. When dealing with large files, > the thing to watch is how much of the data you've got in your own lists and > dictionaries, not how much the file subsystem and OS are using. > > But you have other issues in your code. > > 1) you don't say what version of Python you're using. So I'll assume it's > version 2.x. If so, then range is unnecessarily using a lot of memory. It > builds a list of ints, when an iterator would do just as well. Use > xrange(). ( In Python 3.x, xrange() was renamed to be called range(). ) > This may not matter for small values, but as the number gets bigger, so > would the amount of wastage. > > 2) By using the same local for the for loop as for your "should I close" > counter, you're defeating the logic. As it stands, it'll only do the > close() once. Either rename one of these, or do the simpler test, of > if i%5 == 0: > f.close() > f = open.... > > 3) Close and re-open has three other effects. One, it's slow. Two, > append-mode isn't guaranteed by the C standard to always position at the end > (!). And three, it flushes the data. That can be a very useful result, in > case the computer crashes while spending a long time updating a file. > > I'd suggest sometimes doing a flush() call on the file, if you know you'll > be spending a long time updating it. But I wouldn't bother closing it. > > DaveA > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From xboxmuncher at gmail.com Sat Oct 10 16:34:55 2009 From: xboxmuncher at gmail.com (Xbox Muncher) Date: Sat, 10 Oct 2009 10:34:55 -0400 Subject: [Tutor] If you don't close file when writing, do bytes stay in memory? In-Reply-To: <3f533e960910100732u9fab96ke50873e5dd1ed905@mail.gmail.com> References: <4AD069B0.7020906@ieee.org> <3f533e960910100732u9fab96ke50873e5dd1ed905@mail.gmail.com> Message-ID: <3f533e960910100734r621f03caofaf0d14641f3334d@mail.gmail.com> Oh yea, it's python 2.6. On Sat, Oct 10, 2009 at 10:32 AM, Xbox Muncher wrote: > What does flush do technically? > "Flush the internal buffer, like stdio?s fflush(). This may be a no-op on > some file-like objects." > > The reason I thought that closing the file after I've written about 500MB > file data to it, was smart -> was because I thought that python stores that > data in memory or keeps info about it somehow and only deletes this memory > of it when I close the file. > When I write to a file in 'wb' mode at 500 bytes at a time.. I see that the > file size changes as I continue to add more data, maybe not in exact 500 > byte sequences as my code logic but it becomes bigger as I make more > iterations still. > > Seeing this, I know that the data is definitely being written pretty > immediately to the file and not being held in memory for very long. Or is > it...? Does it still keep it in this "internal buffer" if I don't close the > file. If it does, then flush() is exactly what I need to free the internal > buffer, which is what I was trying to do when I closed the file anyways... > > However, from your replies I take it that python doesn't store this data in > an internal buffer and DOES immediately dispose of the data into the file > itself (of course it still exists in variables I put it in). So, closing the > file doesn't free up any more memory. > > > On Sat, Oct 10, 2009 at 7:02 AM, Dave Angel wrote: > >> xbmuncher wrote: >> >>> Which piece of code will conserve more memory? >>> I think that code #2 will because I close the file more often, thus >>> freeing >>> more memory by closing it. >>> Am I right in this thinking... or does it not save me any more bytes in >>> memory by closing the file often? >>> Sure I realize that in my example it doesn't save much if it does... but >>> I'm >>> dealing with writing large files.. so every byte freed in memory counts. >>> Thanks. >>> >>> CODE #1: >>> def getData(): return '12345' #5 bytes >>> f = open('file.ext', 'wb') >>> for i in range(2000): >>> f.write(getData()) >>> >>> f.close() >>> >>> >>> CODE #2: >>> def getData(): return '12345' #5 bytes >>> f = open('file.ext', 'wb') >>> for i in range(2000): >>> f.write(getData()) >>> if i == 5: >>> f.close() >>> f = open('file.ext', 'ab') >>> i = 1 >>> i = i + 1 >>> >>> f.close() >>> >>> >>> >> You don't save a noticeable amount of memory usage by closing and >> immediately reopening the file. The amount that the system buffers probably >> wouldn't depend on file size, in any case. When dealing with large files, >> the thing to watch is how much of the data you've got in your own lists and >> dictionaries, not how much the file subsystem and OS are using. >> >> But you have other issues in your code. >> >> 1) you don't say what version of Python you're using. So I'll assume it's >> version 2.x. If so, then range is unnecessarily using a lot of memory. It >> builds a list of ints, when an iterator would do just as well. Use >> xrange(). ( In Python 3.x, xrange() was renamed to be called range(). ) >> This may not matter for small values, but as the number gets bigger, so >> would the amount of wastage. >> >> 2) By using the same local for the for loop as for your "should I close" >> counter, you're defeating the logic. As it stands, it'll only do the >> close() once. Either rename one of these, or do the simpler test, of >> if i%5 == 0: >> f.close() >> f = open.... >> >> 3) Close and re-open has three other effects. One, it's slow. Two, >> append-mode isn't guaranteed by the C standard to always position at the end >> (!). And three, it flushes the data. That can be a very useful result, in >> case the computer crashes while spending a long time updating a file. >> >> I'd suggest sometimes doing a flush() call on the file, if you know you'll >> be spending a long time updating it. But I wouldn't bother closing it. >> >> DaveA >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent3737 at gmail.com Sat Oct 10 17:26:48 2009 From: kent3737 at gmail.com (Kent Johnson) Date: Sat, 10 Oct 2009 11:26:48 -0400 Subject: [Tutor] If you don't close file when writing, do bytes stay in memory? In-Reply-To: <3f533e960910100732u9fab96ke50873e5dd1ed905@mail.gmail.com> References: <4AD069B0.7020906@ieee.org> <3f533e960910100732u9fab96ke50873e5dd1ed905@mail.gmail.com> Message-ID: <1c2a2c590910100826i51cc0cc8j7c496408c29572ad@mail.gmail.com> 2009/10/10 Xbox Muncher : > What does flush do technically? > "Flush the internal buffer, like stdio?s fflush(). This may be a no-op on some file-like objects." > > The reason I thought that closing the file after I've written about 500MB file data to it, was smart -> was because I thought that python stores that data in memory or keeps info about it somehow and only deletes this memory of it when I close the file. > When I write to a file in 'wb' mode at 500 bytes at a time.. I see that the file size changes as I continue to add more data, maybe not in exact 500 byte sequences as my code logic but it becomes bigger as I make more iterations still. > > Seeing this, I know that the data is definitely being written pretty immediately to the file and not being held in memory for very long. Or is it...? Does it still keep it in this "internal buffer" if I don't close the file. If it does, then flush() is exactly what I need to free the internal buffer, which is what I was trying to do when I closed the file anyways... > > However, from your replies I take it that python doesn't store this data in an internal buffer and DOES immediately dispose of the data into the file itself (of course it still exists in variables I put it in). So, closing the file doesn't free up any more memory. Python file I/O is buffered. That means that there is a memory buffer that is used to hold a small amount of the file as it is read or written. You original example writes 5 bytes at a time. With unbuffered I/O, this would write to the disk on every call to write(). (The OS also has some buffering, I'm ignoring that.) With buffered writes, there is a memory buffer allocated to hold the data. The write() call just puts data into the buffer; when it is full, the buffer is written to the disk. This is a flush. Calling flush() forces the buffer to be written. So, a few points about your questions: - calling flush() after each write() will cause a disk write. This is probably not what you want, it will slow down the output considerably. - calling flush() does not de-allocate the buffer, it just writes its contents. So calling flush() should not change the amount of memory used. - the buffer is pretty small, maybe 8K or 32K. You can specify the buffer size as an argument to open() but really you probably want the system default. Kent From roadierich at googlemail.com Sat Oct 10 19:07:15 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 10 Oct 2009 18:07:15 +0100 Subject: [Tutor] for loop issue In-Reply-To: <2096a7260910090515y52be3b83s310ceac14573224b@mail.gmail.com> References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> <1c2a2c590910090502w1447b7abk7cf80907d133b9b4@mail.gmail.com> <2096a7260910090515y52be3b83s310ceac14573224b@mail.gmail.com> Message-ID: 2009/10/9 Oxymoron : > On Fri, Oct 9, 2009 at 11:02 PM, Kent Johnson wrote: >> On Fri, Oct 9, 2009 at 3:54 AM, Stefan Lesicnik wrote: >> >> You can easily keep track of the previous item by assigning it to a >> variable. For example this shows just the increasing elements of a >> sequence: >> >> In [22]: items = [0, 1, 3, 2, 8, 5, 9 ] >> >> In [23]: last = None >> >> In [24]: for item in items: >> ? ....: ? ? if last is None or item > last: >> ? ....: ? ? ? ? print item >> ? ....: ? ? last = item > > Darn... this is what happens when you're stuck on one solution > (referring to my index-only ways in the last post) - you miss other > obvious ways, duh * 10. Apologies for the unnecessarily complicated > exposition on iterables above. :-( > > > > -- > There is more to life than increasing its speed. > ?-- Mahatma Gandhi > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Another way, if you just want to track two consecutive items (which probably won't help in this case, but is useful to know), is to zip together two iters over the list, one omitting the first item, the other omitting the last: >>> lst = range(5) >>> for v1, v2 in zip(lst[:-1], lst[1:]): ... print v1, v2 ... 0 1 1 2 2 3 3 4 4 5 If you're concerned about memory usage (zip generates an intermediate list, twice the size of the original), you can use itertools.izip, which is the same except it doen't generate the list: it's xrange to zip's range. Also, rather than mucking around with xrange() and len(), I'd always recommend using enumerate: e.g. Your example of for i in xrange(0, len(x)-1): print x[i], x[i+1] becomes for i, v in enumerate(x[:-1]): #omitting last value in list to avoid IndexError print v, x[i+1] I've got to say that of the two, I prefer the zip method: it looks cleaner, at least to my eyes. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From davea at ieee.org Sat Oct 10 19:36:09 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 10 Oct 2009 13:36:09 -0400 Subject: [Tutor] If you don't close file when writing, do bytes stay in memory? In-Reply-To: <1c2a2c590910100826i51cc0cc8j7c496408c29572ad@mail.gmail.com> References: <4AD069B0.7020906@ieee.org> <3f533e960910100732u9fab96ke50873e5dd1ed905@mail.gmail.com> <1c2a2c590910100826i51cc0cc8j7c496408c29572ad@mail.gmail.com> Message-ID: <4AD0C609.9060603@ieee.org> Kent Johnson wrote: > 2009/10/10 Xbox Muncher : > >> What does flush do technically? >> "Flush the internal buffer, like stdio?s fflush(). This may be a no-op on some file-like objects." >> >> The reason I thought that closing the file after I've written about 500MB file data to it, was smart -> was because I thought that python stores that data in memory or keeps info about it somehow and only deletes this memory of it when I close the file. >> When I write to a file in 'wb' mode at 500 bytes at a time.. I see that the file size changes as I continue to add more data, maybe not in exact 500 byte sequences as my code logic but it becomes bigger as I make more iterations still. >> >> Seeing this, I know that the data is definitely being written pretty immediately to the file and not being held in memory for very long. Or is it...? Does it still keep it in this "internal buffer" if I don't close the file. If it does, then flush() is exactly what I need to free the internal buffer, which is what I was trying to do when I closed the file anyways... >> >> However, from your replies I take it that python doesn't store this data in an internal buffer and DOES immediately dispose of the data into the file itself (of course it still exists in variables I put it in). So, closing the file doesn't free up any more memory. >> > > Python file I/O is buffered. That means that there is a memory buffer > that is used to hold a small amount of the file as it is read or > written. > > You original example writes 5 bytes at a time. With unbuffered I/O, > this would write to the disk on every call to write(). (The OS also > has some buffering, I'm ignoring that.) > > With buffered writes, there is a memory buffer allocated to hold the > data. The write() call just puts data into the buffer; when it is > full, the buffer is written to the disk. This is a flush. Calling > flush() forces the buffer to be written. > > So, a few points about your questions: > - calling flush() after each write() will cause a disk write. This is > probably not what you want, it will slow down the output considerably. > - calling flush() does not de-allocate the buffer, it just writes its > contents. So calling flush() should not change the amount of memory > used. > - the buffer is pretty small, maybe 8K or 32K. You can specify the > buffer size as an argument to open() but really you probably want the > system default. > > Kent > > What Kent said. I brought up flush(), not because you should do it on every write, but because you might want to do it on a file that's open a long time, either because it's very large, or because you're doing other things while keeping the file open. A flush() pretty much assures that this portion of the file is recoverable, in case of subsequent crash. The operating system itself is also doing some buffering. After all, the disk drive writes sectors in multiples of at least 512 bytes, so if you write 12 bytes and flush, it needs at least to know about the other 504 bytes in the one sector. The strategy of this buffering varies depending on lots of things outside of the control of your Python program. For example, a removable drive can be mounted either for "fast access" or for "most likely to be recoverable if removed unexpectedly." These parameters (OS specific, and even version specific) will do much more buffering than Python or the C runtime library will ever do. Incidentally, just because you can see that the file has grown, that doesn't mean the disk drive itself has been updated. It just means that the in-memory version of the directory entries has been updated. Those are buffered as well, naturally. If they weren't, then writing performance would be truly horrendous. Anyway, don't bother closing and re-opening, unless it's to let some other process get access to the file. And use flush() judiciously, if at all, considering the tradeoffs. Did you follow my comment about using the modulo operator to do something every nth time through a loop? DaveA From moron.oxy at gmail.com Sat Oct 10 19:43:35 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Sun, 11 Oct 2009 04:43:35 +1100 Subject: [Tutor] for loop issue In-Reply-To: References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> <1c2a2c590910090502w1447b7abk7cf80907d133b9b4@mail.gmail.com> <2096a7260910090515y52be3b83s310ceac14573224b@mail.gmail.com> Message-ID: <2096a7260910101043k66d11247q6aa3c5dfd45a1d61@mail.gmail.com> On Sun, Oct 11, 2009 at 4:07 AM, Rich Lovely wrote: > for i, v in enumerate(x[:-1]): ?#omitting last value in list to avoid IndexError > ? print v, x[i+1] Thanks for the tip on enumerate, escaped me. Much like Kent's simply using a temporary var escaped me despite having done similar things often... never reply on a tiring Friday. On the bright side this blunder with indexes, iterators, and lengths has made me more aware of other contexts for using additional (zip, enumerate) facilities. I hope the original poster learnt as much as I did from feebly attempting to answer! > > I've got to say that of the two, I prefer the zip method: it looks > cleaner, at least to my eyes. It's an elegant usage :-), zipping up slices of the same list to compare consecutive elems in it, hmm neat. -- Kamal > > -- > Rich "Roadie Rich" Lovely > > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. > -- There is more to life than increasing its speed. -- Mahatma Gandhi From srilyk at gmail.com Sun Oct 11 00:04:56 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 10 Oct 2009 17:04:56 -0500 Subject: [Tutor] [OT] Secure coding guidelines In-Reply-To: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> References: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> Message-ID: <333efb450910101504k1d99f482pe86dfd9ff2fe9889@mail.gmail.com> On Sat, Oct 10, 2009 at 4:31 AM, Didar Hossain wrote: > Since I am learning Python, I was wondering if there are any good > references on secure > coding practices. Books, guides or even any howtos would suffice. > I'm not sure of any references, but I know of a few things. First, for versions < 3.0 use raw_input (ref: http://docs.python.org/library/functions.html#raw_input ) It's a lot more secure than input() Data validation is also a good thing: rather than a function like this: def mysum(n1, n2): return n1 + n2 validate your data: def mysum(n1, n2): try: n1 = int(n1) n2 = int(n2) except ValueError: print "Error! Cannot convert values to int!" return n1+n2 Or do something similar. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Oct 11 00:28:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Oct 2009 23:28:05 +0100 Subject: [Tutor] [OT] Secure coding guidelines References: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> <333efb450910101504k1d99f482pe86dfd9ff2fe9889@mail.gmail.com> Message-ID: "Wayne" wrote > Data validation is also a good thing: I agree with this bit but... > def mysum(n1, n2): > try: > n1 = int(n1) > n2 = int(n2) > except ValueError: > print "Error! Cannot convert values to int!" > > return n1+n2 > > Or do something similar. In a dynamic language like Python this kind of data validation - which is actually type validation - is not necessary. It would be better to do: def mysum(n1,n2): try: return n1+n2 except TypeError: print "Cannot add %s and %s" % (n1,n2) One of the most powerful features of Python is that you can use "Duck Typing" to create powerful polymorphic functions like this that can add two objects, regardless of type, provided they support addition. Limiting it to integers would be a big limitation. In Python data validaton should normally be restricted to catching invalid data *values* not invalid data types. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Sun Oct 11 02:52:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Oct 2009 20:52:21 -0400 Subject: [Tutor] [OT] Secure coding guidelines In-Reply-To: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> References: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> Message-ID: <1c2a2c590910101752l406a3ad1xbf947da7217958ab@mail.gmail.com> On Sat, Oct 10, 2009 at 5:31 AM, Didar Hossain wrote: > Hi, > > This is a little off-topic, but, I though I might put this question in. > > Since I am learning Python, I was wondering if there are any good > references on secure > coding practices. Books, guides or even any howtos would suffice. I don't know any references, but a few tips: - don't use eval or exec on untrusted code - don't unpickle data from an untrusted source - don't use string formatting to create SQL statements - use the two-argument form of execute() to pass args as a sequence - AFAIK there is no generally accepted, secure sandbox for running untrusted Python code (other than Google App Engine I guess) so don't run untrusted code Kent From bobsmith327 at hotmail.com Sun Oct 11 06:44:07 2009 From: bobsmith327 at hotmail.com (bob smith) Date: Sat, 10 Oct 2009 21:44:07 -0700 Subject: [Tutor] Python 3 and tkinter Radiobuttons In-Reply-To: <1c2a2c590910081743t2255d5e8p6d53a61351656149@mail.gmail.com> References: Message-ID: Thanks for the reply. Unfortunately, even when I include a variable, all of the buttons start out selected. I noticed that this is the case when I create a StringVar (rather than an IntVar, where the buttons start out correctly unselected). So, here's another simple example where all of the radio buttons start out incorrectly selected: from tkinter import * root = Tk() root.grid() v = StringVar() Radiobutton(root, text = "Test RadioButton 1", variable=v, value="1").grid(row = 0, column = 0, sticky = W) Radiobutton(root, text = "Test RadioButton 2", variable=v, value="2").grid(row = 1, column = 0, sticky = W) root.mainloop() Any ideas on how to have a StringVar() associated with a group of Radiobutton objects where all of the radio buttons start off unselected? --Bob > Date: Thu, 8 Oct 2009 20:43:21 -0400 > Subject: Re: [Tutor] Python 3 and tkinter Radiobuttons > From: kent37 at tds.net > To: bobsmith327 at hotmail.com > CC: tutor at python.org > > On Thu, Oct 8, 2009 at 6:04 PM, bob smith wrote: > > Hi. I?m using Tkinter to create a new Radiobutton in Python 3. However, > > when I create the button, it starts off looking selected instead of > > unselected (though it behaves correctly like an unselected Radiobutton). So > > this means when I create a group of Radiobuttons they all look selected when > > my program begins. > > You have to associate the Radiobuttons with a variable, for example: > > from tkinter import * > > root = Tk() > root.grid() > v = IntVar() > button = Radiobutton(root, text = "Test RadioButton", variable=v, value=1) > button.grid(row = 0, column = 0, sticky = W) > > button = Radiobutton(root, text = "Test RadioButton2", variable=v, value=2) > button.grid(row = 1, column = 0, sticky = W) > > root.mainloop() > > > Kent _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. http://clk.atdmt.com/GBL/go/177141664/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Oct 11 08:04:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Oct 2009 07:04:16 +0100 Subject: [Tutor] Python 3 and tkinter Radiobuttons References: Message-ID: "bob smith" wrote > So, here's another simple example where all of the radio buttons > start out incorrectly selected: v = StringVar() Radiobutton(root, text = "Test RadioButton 1", variable=v, value="1").grid(row = 0, column = 0, sticky = W) Radiobutton(root, text = "Test RadioButton 2", variable=v, value="2").grid(row = 1, column = 0, sticky = W) root.mainloop() > > Any ideas on how to have a StringVar() associated with a > group of Radiobutton objects where all of the radio buttons start off > unselected? Don't you need to assign a value to the StringVar? Othewise how does Python know which of your buttons is supposed to be the selected option? But I'm no expert, I rarely use radio buttons... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Sun Oct 11 13:00:57 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 11 Oct 2009 07:00:57 -0400 Subject: [Tutor] Python 3 and tkinter Radiobuttons In-Reply-To: References: Message-ID: <4AD1BAE9.1070002@ieee.org> (Don't top-post. It confuses everything. Put your reply at the bottom, or maybe inline) bob smith wrote: > > Thanks for the reply. Unfortunately, even when I include a variable, all of the buttons start out selected. I noticed that this is the case when I create a StringVar (rather than an IntVar, where the buttons start out correctly unselected). So, here's another simple example where all of the radio buttons start out incorrectly selected: > > from tkinter import * > > root = Tk() > root.grid() > > v = StringVar() > Radiobutton(root, text = "Test RadioButton 1", variable=v, value="1").grid(row = 0, column = 0, sticky = W) > Radiobutton(root, text = "Test RadioButton 2", variable=v, value="2").grid(row = 1, column = 0, sticky = W) > > root.mainloop() > > > Any ideas on how to have a StringVar() associated with a group of Radiobutton objects where all of the radio buttons start off unselected? > > --Bob > > > >> Date: Thu, 8 Oct 2009 20:43:21 -0400 >> Subject: Re: [Tutor] Python 3 and tkinter Radiobuttons >> From: kent37 at tds.net >> To: bobsmith327 at hotmail.com >> CC: tutor at python.org >> >> On Thu, Oct 8, 2009 at 6:04 PM, bob smith wrote: >> >>> Hi. I?m using Tkinter to create a new Radiobutton in Python 3. However, >>> when I create the button, it starts off looking selected instead of >>> unselected (though it behaves correctly like an unselected Radiobutton). So >>> this means when I create a group of Radiobuttons they all look selected when >>> my program begins. >>> >> You have to associate the Radiobuttons with a variable, for example: >> >> from tkinter import * >> >> root = Tk() >> root.grid() >> v = IntVar() >> button = Radiobutton(root, text = "Test RadioButton", variable=v, value=1) >> button.grid(row = 0, column = 0, sticky = W) >> >> button = Radiobutton(root, text = "Test RadioButton2", variable=v, value=2) >> button.grid(row = 1, column = 0, sticky = W) >> >> root.mainloop() >> >> >> Kent >> > I think Kent forgot to include the v.set(), to set the initial state of that group of radiobuttons. To go to your example, just add one line: from tkinter import * root = Tk() root.grid() v = StringVar() v.set("1") Radiobutton(root, text = "Test RadioButton 1", variable=v, value="1").grid(row = 0, column = 0, sticky = W) Radiobutton(root, text = "Test RadioButton 2", variable=v, value="2").grid(row = 1, column = 0, sticky = W) root.mainloop() This will select button 1, and leave button 2 unselected. DaveA From kent37 at tds.net Sun Oct 11 14:38:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 11 Oct 2009 08:38:39 -0400 Subject: [Tutor] Python 3 and tkinter Radiobuttons In-Reply-To: <4AD1BAE9.1070002@ieee.org> References: <4AD1BAE9.1070002@ieee.org> Message-ID: <1c2a2c590910110538n1fccac6l670a733264d5e5b2@mail.gmail.com> On Sun, Oct 11, 2009 at 7:00 AM, Dave Angel wrote: > bob smith wrote: >> >> ? ? ? ? ? ? ? ? ?Thanks for the reply. Unfortunately, even when I include >> a variable, all of the buttons start out selected. What version of Python 3 are you using? What platform? If you are not using the latest version, try upgrading. My example works as shown using Python 3.1 on Mac OSX. The initial state of the buttons is "all off". > I think Kent forgot to include the v.set(), to set the initial state of that > group of radiobuttons. Without the v.set() it starts with no button selected. With v.set() it starts with one button selected. Either way it satisfies the OP's requirement; which one is correct depends on his needs. Kent From livinglif3 at gmail.com Sun Oct 11 14:40:07 2009 From: livinglif3 at gmail.com (Utkarsh "") Date: Sun, 11 Oct 2009 18:10:07 +0530 Subject: [Tutor] Extracting columns from CSV Message-ID: <68e4cf240910110540g68e38134h147867415f0f0576@mail.gmail.com> Hello, I have a CSV file, from which I want to extract data. The CSV file is arranged like this: Time, InSec, Open, High, Low, Close, Qty 09:55:17,35717,41.95,41.95,41.95,41.95,105 09:56:03,35763,41.75,41.75,41.75,41.75,20785 09:56:40,35800,41.75,41.75,41.75,41.75,8950 I wanted to extract each column, and put the data in a list, with a list for each column. I'm using the following code to perform this action: Time, InSec, Open, High, Low, Close, Volume = [], [], [], [], [], [], [] thefile = open('somefile.CSV', 'r') linelist = thefile.readline() while linelist != '': b = linelist.split(',') Time.append(b[0]) InSec.append(b[1]) Open.append(b[2]) High.append(b[3]) Low.append(b[4]) Close.append(b[5]) Volume.append(b[6]) linelist = thefile.readline() Is there any other, better and more pythonic way to do this ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dextrous85 at gmail.com Sun Oct 11 14:46:25 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Sun, 11 Oct 2009 18:16:25 +0530 Subject: [Tutor] Extracting columns from CSV In-Reply-To: <68e4cf240910110540g68e38134h147867415f0f0576@mail.gmail.com> References: <68e4cf240910110540g68e38134h147867415f0f0576@mail.gmail.com> Message-ID: <5487b3060910110546j3473ef98v879c2c33639d50b9@mail.gmail.com> On Sun, Oct 11, 2009 at 6:10 PM, Utkarsh "" wrote: > Hello, I have a CSV file, from which I want to extract data. > The CSV file is arranged like this: > > Time, InSec, Open, High, Low, Close, Qty > 09:55:17,35717,41.95,41.95,41.95,41.95,105 > 09:56:03,35763,41.75,41.75,41.75,41.75,20785 > 09:56:40,35800,41.75,41.75,41.75,41.75,8950 > > I wanted to extract each column, and put the data in a list, with a list > for each column. > I'm using the following code to perform this action: > > Time, InSec, Open, High, Low, Close, Volume = [], [], [], [], [], [], > [] > thefile = open('somefile.CSV', 'r') > linelist = thefile.readline() > while linelist != '': > b = linelist.split(',') > Time.append(b[0]) > InSec.append(b[1]) > Open.append(b[2]) > High.append(b[3]) > Low.append(b[4]) > Close.append(b[5]) > Volume.append(b[6]) > linelist = thefile.readline() > > Is there any other, better and more pythonic way to do this ? > > you can take a look at csv module http://docs.python.org/library/csv.html > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vishwajeet Singh +91-9657702154 | dextrous85 at gmail.com | http://singhvishwajeet.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Oct 11 15:02:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 11 Oct 2009 09:02:21 -0400 Subject: [Tutor] Extracting columns from CSV In-Reply-To: <68e4cf240910110540g68e38134h147867415f0f0576@mail.gmail.com> References: <68e4cf240910110540g68e38134h147867415f0f0576@mail.gmail.com> Message-ID: <1c2a2c590910110602w5699b0d2jf1a22f4b267fabf2@mail.gmail.com> On Sun, Oct 11, 2009 at 8:40 AM, Utkarsh "" wrote: > Hello, I have a CSV file, from which I want to extract data. > The CSV file is arranged like this: > Time, InSec, Open, High, Low, Close, Qty > 09:55:17,35717,41.95,41.95,41.95,41.95,105 > 09:56:03,35763,41.75,41.75,41.75,41.75,20785 > 09:56:40,35800,41.75,41.75,41.75,41.75,8950 > I wanted to extract each column, and put the data in a list, with a list for > each column. > I'm using the following code to perform this action: > ?? ?Time, InSec, Open, High, Low, Close, Volume = [], [], [], [], [], [], [] > ?? ?thefile = open('somefile.CSV', 'r') > ?? ?linelist = thefile.readline() > ?? ?while linelist != '': > ?? ? ? ?b = linelist.split(',') > ?? ? ? ?Time.append(b[0]) > ?? ? ? ?InSec.append(b[1]) > ?? ? ? ?Open.append(b[2]) > ?? ? ? ?High.append(b[3]) > ?? ? ? ?Low.append(b[4]) > ?? ? ? ?Close.append(b[5]) > ?? ? ? ?Volume.append(b[6]) > ?? ? ? ?linelist = thefile.readline() > Is there any other, better and more pythonic way to do this ? First, you should use the csv module to read CSV files, it will do the splitting for you and correctly handle any quoted values. Second, a simple way to transpose a list of list is to use zip(*list_of_lists). Putting these together gives import csv f = csv.reader(open('somefile.CSV')) Time, InSec, Open, High, Low, Close, Volume = zip(*f) (Pretty cool BTW that *f works, I wasn't sure if it could take an iterable instead of a sequence.) Kent From lie.1296 at gmail.com Sun Oct 11 18:23:41 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 12 Oct 2009 03:23:41 +1100 Subject: [Tutor] [OT] Secure coding guidelines In-Reply-To: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> References: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> Message-ID: Didar Hossain wrote: > Hi, > > This is a little off-topic, but, I though I might put this question in. > > Since I am learning Python, I was wondering if there are any good > references on secure > coding practices. Books, guides or even any howtos would suffice. > > Security seems to be almost always an after-thought rather than being > ingrained into > any course that I have come across including the ones that they have > in college degrees. > > If this question is inappropriate for this list then please let me > know and accept my apologies > (EAFP) ;-) Common tips for python: 1. Don't trust the user! Any data from raw_input() (py2.x) or input() (py3.x), etc must be validated. 2. Don't trust files! Data coming from open(), urlopen(), etc must go through the same rigorous process as user input. 3. Use extreme caution when dynamically generating code. This includes python's built-in eval/exec, SQL statements, shell call, etc. Prefer APIs. 4. In some cases, don't trust the environment! A malicious user or virus could attach themselves to the OS's stdin/stdout/file-read/write/shell. (Don't take this seriously, a program with no input and no output is a waste of space and time) 5. In extreme situation, don't even trust external modules or even the standard library. 6. And finally, in any case, don't assume that Guido don't have a hidden agenda. From alan.gauld at btinternet.com Sun Oct 11 20:32:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Oct 2009 19:32:20 +0100 Subject: [Tutor] Python 3 and tkinter Radiobuttons References: <4AD1BAE9.1070002@ieee.org> <1c2a2c590910110538n1fccac6l670a733264d5e5b2@mail.gmail.com> Message-ID: "Kent Johnson" wrote > Without the v.set() it starts with no button selected. With v.set() it > starts with one button selected. Either way it satisfies the OP's > requirement; which one is correct depends on his needs. Unfortunately on Windows it seems to set them all selected without the var set. At least it does for me using Python 3.1 Alan G. From lie.1296 at gmail.com Sun Oct 11 20:39:09 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 12 Oct 2009 05:39:09 +1100 Subject: [Tutor] Extracting columns from CSV In-Reply-To: <1c2a2c590910110602w5699b0d2jf1a22f4b267fabf2@mail.gmail.com> References: <68e4cf240910110540g68e38134h147867415f0f0576@mail.gmail.com> <1c2a2c590910110602w5699b0d2jf1a22f4b267fabf2@mail.gmail.com> Message-ID: Kent Johnson wrote: > (Pretty cool BTW that *f works, I wasn't sure if it could take an > iterable instead of a sequence.) Just be careful not to use zip(*f) on an infinite iterable... From lie.1296 at gmail.com Sun Oct 11 20:44:55 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 12 Oct 2009 05:44:55 +1100 Subject: [Tutor] Finding and Inserting missing dates in a date range. In-Reply-To: <24a9d1f30910091515n429141e5l418dac1f06259d20@mail.gmail.com> References: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> <1c2a2c590910091343l549d05an2fad4033f3707f58@mail.gmail.com> <1255126288.8112.1339240893@webmail.messagingengine.com> <24a9d1f30910091515n429141e5l418dac1f06259d20@mail.gmail.com> Message-ID: Glen Zangirolami wrote: > Thats for all the responses. I'm going to use Kents method. I'll let you > know what I work out. > > Rudiger - I did think about that. Luckily I am generating the list with > a start datetime and end datetime so if those don't exist > in either end if the list I can insert them after I check the dates between. > > If you can safely assume that the list of dates are always sorted, you can simply write something like range_date(date_list[0], date_list[-1]). From shellcom3 at juno.com Sun Oct 11 21:42:38 2009 From: shellcom3 at juno.com (shellcom3 at juno.com) Date: Sun, 11 Oct 2009 19:42:38 GMT Subject: [Tutor] class with objects Message-ID: <20091011.154238.18610.0@webmail19.dca.untd.com> I want to display the ship default value for zero and display the ship's initial fuel level. Also have a method called status that displays an object's name and fuel values. I want to have several Ship objects and call their status() methods to test various aspects of the class constructor. Here's my code: class Ship(object): """A spaceship""" total = 0 def __init__(self, name, fuel = 0): print "My spaceship has arrived! The",name self.name = name self.fuel = fuel print "My fuel level is", fuel def status(): Ship.total += 1 print "The total number of objects is", Ship.total status = staticmethod(status) #main ship = Ship("Galaxia") print "\nCreating objects." ship1 = Ship("object 1") ship2 = Ship("object 2") ship3 = Ship("object 3") Ship.status() ____________________________________________________________ Find Top-Rated Pavers Get competing bids on any driveway, patio or walk need. Free quotes! http://thirdpartyoffers.juno.com/TGL2141/c?cp=mcvPp46j2ooOnKJe4-1LngAAJ1CmHaRKpeX3s0f3JfT8odq8AAQAAAAFAAAAALpJjD0AAANSAAAAAAAAAAAAAAAAABIXaQAAAAA= From srilyk at gmail.com Sun Oct 11 22:00:01 2009 From: srilyk at gmail.com (Wayne) Date: Sun, 11 Oct 2009 15:00:01 -0500 Subject: [Tutor] class with objects In-Reply-To: <20091011.154238.18610.0@webmail19.dca.untd.com> References: <20091011.154238.18610.0@webmail19.dca.untd.com> Message-ID: <333efb450910111300t70db4b35o5a038e8f6e30b4c6@mail.gmail.com> On Sun, Oct 11, 2009 at 2:42 PM, shellcom3 at juno.com wrote: > I want to display the ship default value for zero and display the ship's > initial fuel level. Also have a method called status that displays an > object's name and fuel values. I want to have several Ship objects and call > their status() methods to test various aspects of the class constructor. > And what problems have you run into? What would you like from us? This sounds vaguely like homework which we don't do here. We are, however, more than happy to offer pointers in the right direction if you get stuck. For an explanation of /how/ to ask a good question, check out this: http://catb.org/~esr/faqs/smart-questions.html#examples HTH, Wayne > > Here's my code: > > class Ship(object): > """A spaceship""" > total = 0 > def __init__(self, name, fuel = 0): > > print "My spaceship has arrived! The",name > self.name = name > self.fuel = fuel > > print "My fuel level is", fuel > > def status(): > Ship.total += 1 > print "The total number of objects is", Ship.total > status = staticmethod(status) > > #main > ship = Ship("Galaxia") > > print "\nCreating objects." > ship1 = Ship("object 1") > ship2 = Ship("object 2") > ship3 = Ship("object 3") > Ship.status() > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bobsmith327 at hotmail.com Sun Oct 11 23:16:53 2009 From: bobsmith327 at hotmail.com (bob smith) Date: Sun, 11 Oct 2009 14:16:53 -0700 Subject: [Tutor] Python 3 and tkinter Radiobuttons In-Reply-To: References: <4AD1BAE9.1070002@ieee.org> <1c2a2c590910110538n1fccac6l670a733264d5e5b2@mail.gmail.com> Message-ID: > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 11 Oct 2009 19:32:20 +0100 > Subject: Re: [Tutor] Python 3 and tkinter Radiobuttons > > > "Kent Johnson" wrote > > > Without the v.set() it starts with no button selected. With v.set() it > > starts with one button selected. Either way it satisfies the OP's > > requirement; which one is correct depends on his needs. > > Unfortunately on Windows it seems to set them all selected > without the var set. At least it does for me using Python 3.1 > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Yes, on Windows with Python 3.1 and using a StringVar(), the initial state is that all radio buttons look selected when the program first begins. I'm able to work around it so that no radio buttons look selected when the program first begins with: v.set(None) But this seems a bit like a hack. I know back in Python 2.x on Windows, I didn't need to do this. Is this a bug in tkinter for Python 3? (I know when using an IntVar, you don't need to do this). Is this the best solution for now? Thanks, --Bob _________________________________________________________________ Hotmail: Trusted email with powerful SPAM protection. http://clk.atdmt.com/GBL/go/177141665/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Oct 12 00:58:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 11 Oct 2009 18:58:58 -0400 Subject: [Tutor] Python 3 and tkinter Radiobuttons In-Reply-To: References: <4AD1BAE9.1070002@ieee.org> <1c2a2c590910110538n1fccac6l670a733264d5e5b2@mail.gmail.com> Message-ID: <1c2a2c590910111558s49a3bf8fx434e5cc744771243@mail.gmail.com> On Sun, Oct 11, 2009 at 5:16 PM, bob smith wrote: > Yes, on Windows with Python 3.1 and using a StringVar(), the initial state > is that all radio buttons look selected when the program first begins.? I'm > able to work around it so that no radio buttons look selected when the > program first begins with: > > v.set(None) > > But this seems a bit like a hack.? I know back in Python 2.x on Windows, I > didn't need to do this.? Is this a bug in tkinter for Python 3? I don't see anything in the issue tracker. You could add one. http://bugs.python.org/ Kent From alan.gauld at btinternet.com Mon Oct 12 01:05:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Oct 2009 00:05:57 +0100 Subject: [Tutor] class with objects References: <20091011.154238.18610.0@webmail19.dca.untd.com> Message-ID: wrote >I want to display the ship default value for zero and display the ship's > initial fuel level. Also have a method called status that displays an > object's name and fuel values. So far so good. > I want to have several Ship objects and call their status() methods > to test various aspects of the class constructor. Now I'm confused. Does status "test various aspects of the class constructor" or does it "display an objects name and fuel values"? These are not the same thing... > Here's my code: > > class Ship(object): > """A spaceship""" > total = 0 > def __init__(self, name, fuel = 0): > > print "My spaceship has arrived! The",name > self.name = name > self.fuel = fuel > > print "My fuel level is", fuel > > def status(): > Ship.total += 1 What is the puropse of thoe above line? Why is it part of status()? > print "The total number of objects is", Ship.total > status = staticmethod(status) And why is it a staticmethod? > ship = Ship("Galaxia") > print "\nCreating objects." > ship1 = Ship("object 1") > ship2 = Ship("object 2") > ship3 = Ship("object 3") > Ship.status() What do you expect the output to be? And what is it really? Are they different? Why? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From vineet.kothari at gmail.com Mon Oct 12 05:33:37 2009 From: vineet.kothari at gmail.com (Vineet Kothari) Date: Sun, 11 Oct 2009 20:33:37 -0700 Subject: [Tutor] Carriage return Message-ID: Hi Everyone I see that python IDLE add ^M as carriage return while programming in windows machine. How can I set IDLE not to do so. I don't see any option & neither do I see any option to check for carriage return. Can anyone help me as I use IDLE & I need to remove ^M from the end of every line. Though it is not shown while programming but I can see that when I run my scripts on debian linux environment & thus get errors. Thanks -- Regards, Vineet Kothari 248-821-8105 http://www.vineetkothari.in ----- Its NICE 2 be IMPORTANT, but whats more IMPORTANT is 2 be NICE. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Oct 12 05:38:38 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 11 Oct 2009 23:38:38 -0400 Subject: [Tutor] Carriage return In-Reply-To: References: Message-ID: <4AD2A4BE.70909@gmail.com> Vineet Kothari wrote: > Hi Everyone > > I see that python IDLE add ^M as carriage return while programming in > windows machine. How can I set IDLE not to do so. I don't see any > option & neither do I see any option to check for carriage return. > > Can anyone help me as I use IDLE & I need to remove ^M from the end of > every line. Though it is not shown while programming but I can see > that when I run my scripts on debian linux environment & thus get errors. I don't understand. Please explain. -- Bob Gailer Chapel Hill NC 919-636-4239 From srilyk at gmail.com Mon Oct 12 05:38:10 2009 From: srilyk at gmail.com (Wayne) Date: Sun, 11 Oct 2009 22:38:10 -0500 Subject: [Tutor] Carriage return In-Reply-To: References: Message-ID: <333efb450910112038t28fc7525lc956b9a67f628951@mail.gmail.com> On Sun, Oct 11, 2009 at 10:33 PM, Vineet Kothari wrote: > Hi Everyone > > I see that python IDLE add ^M as carriage return while programming in > windows machine. How can I set IDLE not to do so. I don't see any option & > neither do I see any option to check for carriage return. > > Can anyone help me as I use IDLE & I need to remove ^M from the end of > every line. Though it is not shown while programming but I can see that when > I run my scripts on debian linux environment & thus get errors. > > That's not an issue with IDLE so much as windows/linux. IIRC, Linux only uses a newline, while windows uses a CRLF. There's the dos2unix util: http://linuxcommand.org/man_pages/dos2unix1.html that may help. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 12 09:52:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Oct 2009 08:52:16 +0100 Subject: [Tutor] Carriage return References: Message-ID: "Vineet Kothari" wrote > I see that python IDLE add ^M as carriage return while programming in > windows machine. Thats just the Windows line ending. If you want to use the same file on both Windowscand Linux then you will need to either get used to it or run the DOS2Unix tool (and UNIX2DOS going back to Windows). > Can anyone help me as I use IDLE & I need to remove ^M from the end of > every > line. Though it is not shown while programming but I can see that when I > run > my scripts on debian linux environment & thus get errors. It shouldn't cause any faults in the programs when they run, it is just a nuisance when working in the editor. Some editors are intelligent enough to deal with this transparently - eg. I think vim and Scite both do this. If you regularly edit on both OS then it might be worth moving from IDLE to one of those editors. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kp8 at mac.com Mon Oct 12 11:01:25 2009 From: kp8 at mac.com (kevin parks) Date: Mon, 12 Oct 2009 18:01:25 +0900 Subject: [Tutor] Automaton/transitional grammar query Message-ID: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> I posted about this a couple weeks back, but then got horribly ill and dropped the ball so i was hoping to revisit. I am not sure if this is and example of Finite Automaton or a Finite State Machine or perhaps it is related to a transition table or markov process. I think some one here told me it is called a transitional grammar? I am not sure. I am not a math person but i would love to know exactly what this is. I googled around and got lots of super complicated gobbledegoo all with knotty regex stuff, but what i want to do is much more simple. I am trying to use a table to define a bunch of moves like so: 1 --> 2 5 2 --> 1 4 3 --> 3 4 --> 1 5 --> 4 3 so that i can generate a sequence that, given an initial value, that will continue to grow according to these rules. Starting with 1 we then go to 2 & 5, 2 leads us too 1 & 4, the 5 leads us to 4 & 3, then we iterate over 1 4 4 and 3 to get 2 5 1 1 and 3.... Like so: 1 2 5 1 4 4 3 2 5 1 1 3 1 4 4 3 2 5 2 5 3 ..... etc. Essentially, iterating over the last added items to the list, applying the table, appending those new items to the list, applying the table again... etc, until the sequence reaches some predetermined number of iterations and quits. [ [1], [2, 5], [1, 4] , [4, 3], [2, 5], [1], [1], [3], [1, 4], [4, 3], [2, 5], [2, 5], [3] ] First, as i mentioned I would like to know what, precisely, this kind of process is called so that i can look it up. Second, i would l like to add to what i have, which seems to work. But first here is the code, where we left off below: #!/usr/bin/env python rules = {1: (2, 5), 2: (1, 4), 3: (3,), 4: (1,), 5: (4, 3)} def apply_rules(sequence): for element in sequence: # look it up in the global rules values = rules[element] # yield each of those in turn for value in values: yield value def flatten(l, ltypes=(list, tuple)): ltype = type(l) l = list(l) i = 0 while i < len(l): while isinstance(l[i], ltypes): if not l[i]: l.pop(i) i -= 1 break else: l[i:i + 1] = l[i] i += 1 return ltype(l) def test(): data = [1] outlist = [] for i in range(10): outlist.append(data) gen = apply_rules(data) data = list(gen) outlist.append(data) # one more to get the final result print '\n\n', outlist, '\n\n' flat = flatten(outlist) count = 0 for item in flat: print count, ',', item, ';' count += 1 print '\n\n' if __name__ == "__main__": test() This all appears to work. I am not sure if this is the best way to do it, but for the size lists i have been generating it seems zippy. So what? You are asking a question you already know the answer to? Well now I would like to have this set of rules contain some probabilistic branching. Instead of having my "go to" rules or grammar hard wired it would be good if some steps could also have weighted choices. So that maybe 1 --> 2 5 70% of the time but maybe it goes 1 -- > 2 4 every once in a while (as in 30%). So i am not sure how to do that... also, it occurs to me that i could define a grammar that got stuck in an infinite loop if not careful. I wonder if i should add some mechanism to check the dictionary defined rules before execution.... or if that is just too hard to do and i should just be careful. Meanwhile I have my trusty old weighted random func all ready to go: import random def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair''' wtotal = sum([x[1] for x in lst]) n = random.uniform(0, wtotal) for item, weight in lst: if n < weight: break n = n - weight return item My question is how to apply this since i am setting up my rules in a dictionary, so I am confused as to how all these pieces, which work in isolation, would fit together. Lastly, if i add the probabilities... is this just a super roundabout way to make a quasi markov table? i dunno. But it seems like a cool way to make patterns. From stefan at lsd.co.za Mon Oct 12 11:40:08 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Mon, 12 Oct 2009 11:40:08 +0200 Subject: [Tutor] for loop issue In-Reply-To: <2096a7260910101043k66d11247q6aa3c5dfd45a1d61@mail.gmail.com> References: <5cb309e70910090054r168f6ce3j29e83dd4a740be61@mail.gmail.com> <1c2a2c590910090502w1447b7abk7cf80907d133b9b4@mail.gmail.com> <2096a7260910090515y52be3b83s310ceac14573224b@mail.gmail.com> <2096a7260910101043k66d11247q6aa3c5dfd45a1d61@mail.gmail.com> Message-ID: <5cb309e70910120240k617d453du5d20505d1e48c87d@mail.gmail.com> > Thanks for the tip on enumerate, escaped me. Much like Kent's simply > using a temporary var escaped me despite having done similar things > often... never reply on a tiring Friday. On the bright side this > blunder with indexes, iterators, and lengths has made me more aware of > other contexts for using additional (zip, enumerate) facilities. I > hope the original poster learnt as much as I did from feebly > attempting to answer! Thanks everybody for the responses. I've asked some other questions before that have been responded too equally well and I learnt a whole bunch of information, some of it was still over my head, but its getting easier every time :) Stefan From davea at ieee.org Mon Oct 12 12:41:03 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 12 Oct 2009 06:41:03 -0400 Subject: [Tutor] Carriage return In-Reply-To: References: Message-ID: <4AD307BF.1080009@ieee.org> Alan Gauld wrote: >
> "Vineet Kothari" wrote > >> I see that python IDLE add ^M as carriage return while programming in >> windows machine. > > Thats just the Windows line ending. > If you want to use the same file on both Windowscand Linux then > you will need to either get used to it or run the DOS2Unix tool > (and UNIX2DOS going back to Windows). > >> Can anyone help me as I use IDLE & I need to remove ^M from the end >> of every >> line. Though it is not shown while programming but I can see that >> when I run >> my scripts on debian linux environment & thus get errors. > > It shouldn't cause any faults in the programs when they run, it is > just a nuisance when working in the editor. Some editors are intelligent > enough to deal with this transparently - eg. I think vim and Scite > both do this. > If you regularly edit on both OS then it might be worth moving from IDLE > to one of those editors. > > HTH, > But the other problem I've seen when copying a DOS-formatted python script to Unix environment is that the shebang line is misinterpreted. (Some?) Unix shell will refuse to find the python interpreter if the file name seems to have a 0x0d in it. From davea at ieee.org Mon Oct 12 13:02:47 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 12 Oct 2009 07:02:47 -0400 Subject: [Tutor] Automaton/transitional grammar query In-Reply-To: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> Message-ID: <4AD30CD7.5070000@ieee.org> kevin parks wrote: >
I posted > about this a couple weeks back, but then got horribly ill and dropped > the ball so i was hoping to revisit. > > I am not sure if this is and example of Finite Automaton or a Finite > State Machine or perhaps it is related to a transition table or markov > process. I think some one here told me it is called a transitional > grammar? I am not sure. I am not a math person but i would love to > know exactly what this is. I googled around and got lots of super > complicated gobbledegoo all with knotty regex stuff, but what i want > to do is much more simple. I am trying to use a table to define a > bunch of moves like so: > > 1 --> 2 5 > 2 --> 1 4 > 3 --> 3 > 4 --> 1 > 5 --> 4 3 > > so that i can generate a sequence that, given an initial value, that > will continue to grow according to these rules. Starting with 1 we > then go to 2 & 5, 2 leads us too 1 & 4, the 5 leads us to 4 & 3, then > we iterate over 1 4 4 and 3 to get 2 5 1 1 and 3.... Like so: > > 1 > 2 5 > 1 4 4 3 > 2 5 1 1 3 > 1 4 4 3 2 5 2 5 3 > > ..... etc. > > Essentially, iterating over the last added items to the list, applying > the table, appending those new items to the list, applying the table > again... etc, until the sequence reaches some predetermined number of > iterations and quits. > > [ [1], [2, 5], [1, 4] , [4, 3], [2, 5], [1], [1], [3], [1, 4], [4, 3], > [2, 5], [2, 5], [3] ] > > First, as i mentioned I would like to know what, precisely, this kind > of process is called so that i can look it up. Second, i would l like > to add to what i have, which seems to work. But first here is the > code, where we left off below: > > #!/usr/bin/env python > > rules = {1: (2, 5), 2: (1, 4), 3: (3,), 4: (1,), 5: (4, 3)} > > def apply_rules(sequence): > for element in sequence: > # look it up in the global rules > values = rules[element] > # yield each of those in turn > for value in values: > yield value > > def flatten(l, ltypes=(list, tuple)): > ltype = type(l) > l = list(l) > i = 0 > while i < len(l): > while isinstance(l[i], ltypes): > if not l[i]: > l.pop(i) > i -= 1 > break > else: > l[i:i + 1] = l[i] > i += 1 > return ltype(l) > > def test(): > data = [1] > outlist = [] > for i in range(10): > outlist.append(data) > gen = apply_rules(data) > data = list(gen) > outlist.append(data) # one more to get the final result > print '\n\n', outlist, '\n\n' > flat = flatten(outlist) > count = 0 > for item in flat: > print count, ',', item, ';' > count += 1 > print '\n\n' > > if __name__ == "__main__": > test() > > > This all appears to work. I am not sure if this is the best way to do > it, but for the size lists i have been generating it seems zippy. > > So what? You are asking a question you already know the answer to? > Well now I would like to have this set of rules contain some > probabilistic branching. Instead of having my "go to" rules or grammar > hard wired it would be good if some steps could also have weighted > choices. So that maybe 1 --> 2 5 70% of the time but maybe it goes 1 > --> 2 4 every once in a while (as in 30%). So i am not sure how to do > that... also, it occurs to me that i could define a grammar that got > stuck in an infinite loop if not careful. I wonder if i should add > some mechanism to check the dictionary defined rules before > execution.... or if that is just too hard to do and i should just be > careful. > > Meanwhile I have my trusty old weighted random func all ready to go: > > import random > > def windex(lst): > '''an attempt to make a random.choose() function that makes > weighted choices > > accepts a list of tuples with the item and probability as a pair''' > > wtotal = sum([x[1] for x in lst]) > n = random.uniform(0, wtotal) > for item, weight in lst: > if n < weight: > break > n = n - weight > return item > > My question is how to apply this since i am setting up my rules in a > dictionary, so I am confused as to how all these pieces, which work in > isolation, would fit together. Lastly, if i add the probabilities... > is this just a super roundabout way to make a quasi markov table? i > dunno. But it seems like a cool way to make patterns. > > > >
> Often, when a combination of existing stdlib collection types gets too confusing, it's time to consider classes and objects. Not necessarily to make the program "object oriented," but to make the program data structure understandable. You have a dictionary mapping from ints to tuples of ints. You want to keep the same dictionary keys, but make the values more complex. Each value, instead of being a tuple, needs to be a list of tuples, with a probability assigned to each. So create a class for that "list of tuples," and modify windex to work on an object of such a class. And in apply_rules, change the values= line to call windex() after doing the lookup. I don't see where an infinite loop is possible. But it'd be useful to do some error checking for the class items, such as validating that the probabilities add up to 100% (within a tolerance factor). DaveA From mazher_ana66 at hotmail.com Mon Oct 12 08:15:52 2009 From: mazher_ana66 at hotmail.com (mazher ahmad) Date: Mon, 12 Oct 2009 12:15:52 +0600 Subject: [Tutor] python help needed Message-ID: i wana make ToC/headings for any PDF documents ,PDFminer solves the my problem if ToC are given.i came across many files where there is no Toc. Does any one know ,how to extract ToC/headings from such files. thanx _________________________________________________________________ Windows Live Hotmail: Your friends can get your Facebook updates, right from Hotmail?. http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_4:092009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Oct 12 13:58:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Oct 2009 07:58:57 -0400 Subject: [Tutor] Carriage return In-Reply-To: <333efb450910112038t28fc7525lc956b9a67f628951@mail.gmail.com> References: <333efb450910112038t28fc7525lc956b9a67f628951@mail.gmail.com> Message-ID: <1c2a2c590910120458r2746101bh7b711da019e8b80c@mail.gmail.com> On Sun, Oct 11, 2009 at 11:38 PM, Wayne wrote: > That's not an issue with IDLE so much as windows/linux. IIRC, Linux only > uses a newline, while windows uses a CRLF. There's the dos2unix util: > http://linuxcommand.org/man_pages/dos2unix1.html > that may help. There is also a crlf.py script distributed with Python (in the scripts folder) that removes CR. Some version control systems will handle this for you - Subversion, Mercurial and git, at least - so you could use a VCS to transfer the files and convert the line endings. This would also give the benefit of having the files in the VCS. Kent From dotancohen at gmail.com Mon Oct 12 14:17:16 2009 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 12 Oct 2009 14:17:16 +0200 Subject: [Tutor] Porting PHP web app to Python GUI Message-ID: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> I have a simple PHP web application with a form, which enter the information entered into the form into a database. However, I will be several weeks without internet access so I now have two choices: 1) Run the script locally on my Kubuntu box 2) Port it to Python and make a real app out of it. I prefer the second route, but I want to know if this seems reasonable in Python: 1) GUI with several input areas which are analogous to the HTML Select, Input=Text, and Textarea fields. 2) insert the data collected into an sqlite database 3) Retrieve and display data from the database using predefined queries. I am familiar with the SQL language, some PHP and some C programing. I have never done GUI programming other than HTML. Does PyQt seem to have a reasonable learning curve for this application? Thanks! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il From kent37 at tds.net Mon Oct 12 14:44:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Oct 2009 08:44:33 -0400 Subject: [Tutor] Automaton/transitional grammar query In-Reply-To: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> Message-ID: <1c2a2c590910120544n38aa2e42h48d7422083c8ef18@mail.gmail.com> On Mon, Oct 12, 2009 at 5:01 AM, kevin parks wrote: > First, as i mentioned I would like to know what, precisely, this kind of > process is called so that i can look it up. It looks like a simple cellular automaton where a cell's neighborhood includes only the cell itself. You might be interested in Steven Wolfram's book, "A New Kind of Science" and the many examples on his web site: http://www.wolframscience.com/ See Wikipedia as well. This is a very rich area. Your set of rules is a simple context-free grammar. Generally a context-free grammar is non-deterministic, though - there are multiple productions from a given term - so you may not find much relevant info by searching for this. When you introduce the random element you are generating Markov chains. > Second, i would l like to add to > what i have, which seems to work. But first here is the code, where we left > off below: > > #!/usr/bin/env python > > rules = {1: (2, 5), 2: (1, 4), 3: (3,), 4: (1,), 5: (4, 3)} > > def apply_rules(sequence): > ? ?for element in sequence: > ? ? ? ?# look it up in the global rules > ? ? ? ?values = rules[element] > ? ? ? ?# yield each of those in turn > ? ? ? ?for value in values: > ? ? ? ? ? ?yield value Since you want a list at the end, rather than yielding each item you could just build the final list using extend: def apply_rules(sequence): result = [] for element in sequence: result.extent(rules[element]) return result > def flatten(l, ltypes=(list, tuple)): > ? ? ? ?ltype = type(l) > ? ? ? ?l = list(l) > ? ? ? ?i = 0 > ? ? ? ?while i < len(l): > ? ? ? ? ? ? ? ?while isinstance(l[i], ltypes): > ? ? ? ? ? ? ? ? ? ? ? ?if not l[i]: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?l.pop(i) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?i -= 1 > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break > ? ? ? ? ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?l[i:i + 1] = l[i] > ? ? ? ? ? ? ? ?i += 1 > ? ? ? ?return ltype(l) I don't understand why you want to flatten outlist; when I run your program I get one number per line, not one generation per line as you show above. I don't understand your flatten function, either...To flatten a single level, which is all you need, you can use this recipe from itertools: def flatten(listOfLists): return list(chain.from_iterable(listOfLists)) or use extend() again: def flatten(sequence): result = [] for element in sequence: result.extent(element) return result > > def test(): > ? ? ? ?data = [1] > ? ? ? ?outlist = [] > ? ? ? ?for i in range(10): > ? ? ? ? ? ? ? ?outlist.append(data) > ? ? ? ? ? ? ? ?gen = apply_rules(data) > ? ? ? ? ? ? ? ?data = list(gen) > ? ? ? ?outlist.append(data) ?# one more to get the final result > ? ? ? ?print '\n\n', outlist, '\n\n' > ? ? ? ?flat = flatten(outlist) > ? ? ? ?count = 0 > ? ? ? ?for item in flat: > ? ? ? ? ? ? ? ?print count, ',', item, ';' > ? ? ? ? ? ? ? ?count += 1 enumerate() is simpler: for count, item in enumerate(flat): print count, ',', item, ';' > ? ? ? ?print '\n\n' > > if __name__ == "__main__": > ? ? ? ?test() > > > So what? You are asking a question you already know the answer to? Well now > I would like to have this set of rules contain some probabilistic branching. > Instead of having my "go to" rules or grammar hard wired it would be good if > some steps could also have weighted choices. So that maybe 1 --> 2 5 70% of > the time but maybe it goes 1 --> 2 4 ?every once in a while (as in 30%). So > i am not sure how to do that... also, it occurs to me that i could define a > grammar that got stuck in an infinite loop if not careful. I wonder if i > should add some mechanism to check the dictionary defined rules before > execution.... or if that is just too hard to do and i should just be > careful. I don't think you will get an infinite loop. You may have a grammar that generates a stable or repeating pattern but I don't think you will be able to detect that without trying it. > > Meanwhile I have my trusty old weighted random func all ready to go: > > My question is how to apply this since i am setting up my rules in a > dictionary, so I am confused as to how all these pieces, which work in > isolation, would fit together. Lastly, if i add the probabilities... is this > just a super roundabout way to make a quasi markov table? i dunno. But it > seems like a cool way to make patterns. Your rules, instead of being just a list of numbers, become a list of probability mappings. I think you want to apply the probabilities to the whole sequence, so a single rule might be (using your example) 1: [ ((2. 5), .7), ((2. 4), .3) ] Then change the apply_rules function to choose one of the possibilites using your windex() function. Kent From kent37 at tds.net Mon Oct 12 14:45:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Oct 2009 08:45:56 -0400 Subject: [Tutor] python help needed In-Reply-To: References: Message-ID: <1c2a2c590910120545j4d175c31g43833135f2da8bf2@mail.gmail.com> On Mon, Oct 12, 2009 at 2:15 AM, mazher ahmad wrote: > i wana make ToC/headings for any PDF documents ,PDFminer solves the my > problem if ToC? are given.i came across many files where there > is no Toc. > Does any one know ,how to extract ToC/headings from such files. I guess you will have to construct the ToC from the headings. Does dumppdf (from PDFminer) show the information you want to collect? If so, it should give you a starting point for collecting the data. Kent From rudiger.wolf at throughputfocus.com Mon Oct 12 15:14:11 2009 From: rudiger.wolf at throughputfocus.com (=?ISO-8859-1?Q?R=FCdiger=20Wolf?=) Date: Mon, 12 Oct 2009 14:14:11 +0100 Subject: [Tutor] Porting PHP web app to Python GUI In-Reply-To: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> References: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> Message-ID: <1255353251.5976.1339606783@webmail.messagingengine.com> On Mon, 12 Oct 2009 14:17 +0200, "Dotan Cohen" wrote: > I prefer the second route, but I want to know if this seems reasonable > in Python: > 1) GUI with several input areas which are analogous to the HTML > Select, Input=Text, and Textarea fields. > 2) insert the data collected into an sqlite database > 3) Retrieve and display data from the database using predefined queries. > > I am familiar with the SQL language, some PHP and some C programing. I > have never done GUI programming other than HTML. Does PyQt seem to > have a reasonable learning curve for this application? > EasyGUI makes it simple to add GUI to python app. http://easygui.sourceforge.net/ From chaoticslacker at gmail.com Mon Oct 12 15:33:31 2009 From: chaoticslacker at gmail.com (Jason Willis) Date: Mon, 12 Oct 2009 09:33:31 -0400 Subject: [Tutor] complete neophyte question here Message-ID: I've recently been going through "Python Programming, for the Absolute Beginner" Second Edition, By Michael Dawson I'm running python 2.5.4 on a windows xp home machine. So my question boils down to this: At the end of one of his chapters there is a challenge to write a program that flips a "coin" 100 times then outputs the number of heads or tails it hit. I wrote this: import random flip = 0 head = 0 tails = 0 while flip != 100: ????flip += 1 ????coin = random.randrange(2) ????if coin == 0 ????????head += 1 ????elif coin == 1 ????????tails += 1 print head, tails raw_input("\n") I honestly don't know how code works and would appreciate someone explaining it to me? Using logic, I shouldn't be able to write the program due to my limited skills so i don't know how to explain HOW i wrote it because it just sort of happened. I was sitting home one night and it just came out itself. I know that's not much of an explanation but there it is. Thanks in advance, Slacker -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Mon Oct 12 15:36:35 2009 From: jfabiani at yolo.com (John) Date: Mon, 12 Oct 2009 06:36:35 -0700 Subject: [Tutor] Porting PHP web app to Python GUI In-Reply-To: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> References: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> Message-ID: <200910120636.35710.jfabiani@yolo.com> On Monday 12 October 2009 05:17:16 am Dotan Cohen wrote: > I have a simple PHP web application with a form, which enter the > information entered into the form into a database. However, I will be > several weeks without internet access so I now have two choices: > > 1) Run the script locally on my Kubuntu box > 2) Port it to Python and make a real app out of it. > > I prefer the second route, but I want to know if this seems reasonable > in Python: > 1) GUI with several input areas which are analogous to the HTML > Select, Input=Text, and Textarea fields. > 2) insert the data collected into an sqlite database > 3) Retrieve and display data from the database using predefined queries. > > I am familiar with the SQL language, some PHP and some C programing. I > have never done GUI programming other than HTML. Does PyQt seem to > have a reasonable learning curve for this application? > > Thanks! Take a look at Dabo www.dabodev.com. Dabo works with SQLite, MySQL, MsSQL, Firebird, and Postgres. Use the ClassDesigner to create simple forms in a visual way. Johnf From kp8 at mac.com Mon Oct 12 16:09:24 2009 From: kp8 at mac.com (kevin parks) Date: Mon, 12 Oct 2009 23:09:24 +0900 Subject: [Tutor] Automaton/transitional grammar query In-Reply-To: <1c2a2c590910120544n38aa2e42h48d7422083c8ef18@mail.gmail.com> References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> <1c2a2c590910120544n38aa2e42h48d7422083c8ef18@mail.gmail.com> Message-ID: <56987A26-1558-49D0-9B7C-30C4F4FC7C91@mac.com> > > You might be interested in Steven Wolfram's book, "A New Kind of > > Science" and the many examples on his web site: > > http://www.wolframscience.com/ See Wikipedia as well. This is a very > > rich area. Thanks. That was just the kind of reference I was looking for. Fantastic. I am sure i wont be able to grok the math bits but maybe i can begin to understand thsese ideas on a conceptual level. I will look for this in the book store. > > When you introduce the random element you are generating Markov > chains. That's what i thought. I would be interested in playing with some simple, 1st and 2nd order markov chains too, but i just want to define the transition tables with the elements and their probabilities and generate. Most of the Markov stuff i see out there is big and knotty and way more than i need. > > I don't understand why you want to flatten outlist; when I run your > > program I get one number per line, not one generation per line as > you > > show above. That's odd. Anyway in my program I am printing the list twice. The first time outlist is printed it is nested one level deep. That is just scaffolding. Then i pick through it one item per line having flattened it and print it in a format that my other program can read. I been using that flatten function since 1970. Prolly pilfered from Tim Peters or Effbot. Remember them guys? Awesome dudes. I wonder if they even use python anymore. Anyway that is from way before itertools was even a glimmer. Additionally, your flatten function doesn't work for me actually. I get: NameError: global name 'chain' is not defined > >> enumerate() is simpler: Thanks. enumerate is also still somewhat new to me. > > I don't think you will get an infinite loop. You may have a grammar > > that generates a stable or repeating pattern but I don't think you > > will be able to detect that without trying it. Yeah i don't mean an infinite loop, but more like a perpetual dance back and forth between to items that point to each other. I think I need to be careful when i define the rules that i don't get something like that... say if 1 goes to 4 but 4's rule is go to 1, for example. > > our rules, instead of being just a list of numbers, become a list of > > probability mappings. I think you want to apply the probabilities to > > the whole sequence, so a single rule might be (using your example) > > 1: [ ((2. 5), .7), ((2. 4), .3) ] > > > > Then change the apply_rules function to choose one of the > possibilites > > using your windex() function. I'll roll this around in my pea sized brain and see if i can put this suggestion to work. Thanks Kent! Hopefully I will get this going and my psudo-markov thingy happening too. These things are fun for making patterns. I like these powerful little pea shooters. -kevin From kp8 at mac.com Mon Oct 12 16:12:02 2009 From: kp8 at mac.com (kevin parks) Date: Mon, 12 Oct 2009 23:12:02 +0900 Subject: [Tutor] Automaton/transitional grammar query In-Reply-To: <4AD30CD7.5070000@ieee.org> References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> <4AD30CD7.5070000@ieee.org> Message-ID: <51EB2946-7380-40AB-9B08-43DDEED8119F@mac.com> On Oct 12, 2009, at 8:02 PM, Dave Angel wrote: > Often, when a combination of existing stdlib collection types gets > too confusing, it's time to consider classes and objects. Not > necessarily to make the program "object oriented," but to make the > program data structure understandable. That's sage advice.... I just dislike and resist OO. But i do eventually need to make steps in that direction. From alan.gauld at btinternet.com Mon Oct 12 16:18:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Oct 2009 15:18:03 +0100 Subject: [Tutor] complete neophyte question here References: Message-ID: "Jason Willis" wrote > So my question boils down to this: > > At the end of one of his chapters there is a challenge to write a program > that flips a "coin" 100 times then outputs the number of heads or tails > it > hit. > > I wrote this: > < ... snipped code ....> > > I honestly don't know how code works and would appreciate someone > explaining > it to me? What do you want us to explain? How you were able to write a working program without actually kowing how it works? That's probably due to osmosis. You saw enough similar code that you just coped and modified till it worked - or seemed to. Or how the program that you wrote works? Thats more tricky. What do you not understand? The book should be explaining how all the individuall bits work. Your program basically initialises some variables - do you understand what variables are? It then repeatedly generates either 0 or 1 for 100 repetitions. If the number generated is 0 it increments heads. If it is 1 it increments tails. Then it prints the two stored results. Which bit of it do you not understand? > Using logic, I shouldn't be able to write the program due to my limited > skills so i don't know how to explain HOW i wrote it because it just > sort > of happened. I was sitting home one night and it just came out itself. I > know that's not much of an explanation but there it is. Just like great art... :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Mon Oct 12 16:21:12 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 12 Oct 2009 09:21:12 -0500 Subject: [Tutor] complete neophyte question here In-Reply-To: References: Message-ID: <333efb450910120721o365bdd7asb18ad30d70fcf876@mail.gmail.com> On Mon, Oct 12, 2009 at 8:33 AM, Jason Willis wrote: > I honestly don't know how code works and would appreciate someone > explaining it to me? > > Using logic, I shouldn't be able to write the program due to my limited > skills so i don't know how to explain HOW i wrote it because it just sort > of happened. I was sitting home one night and it just came out itself. I > know that's not much of an explanation but there it is. > Asking is the first step to understanding. Of course, rather than just explaining, I'll ask you some questions because if you can explain it you really know it. import random flip = 0 head = 0 tails = 0 What is going on here? What does import random do, and why are you doing it? while flip != 100: What is this? What does it do? Is there any other way to do this? ????flip += 1 What's happening here? Why? ????coin = random.randrange(2) What does this do? Why is it important? ????if coin == 0 ????????head += 1 ????elif coin == 1 ????????tails += 1 What are you doing here? Why are you doing it? > print head, tails > raw_input("\n") And what are these for? I haven't read the book, but I'm sure Dawson gives a good explanation of if statements and loops. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 12 16:22:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Oct 2009 15:22:16 +0100 Subject: [Tutor] Porting PHP web app to Python GUI References: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> <200910120636.35710.jfabiani@yolo.com> Message-ID: "John" wrote >> 1) GUI with several input areas which are analogous to the HTML >> Select, Input=Text, and Textarea fields. >> 2) insert the data collected into an sqlite database >> 3) Retrieve and display data from the database using predefined queries. >> >> I am familiar with the SQL language, some PHP and some C programing. I >> have never done GUI programming other than HTML. Does PyQt seem to >> have a reasonable learning curve for this application? > > Take a look at Dabo www.dabodev.com. Dabo works with SQLite, MySQL, > MsSQL, > Firebird, and Postgres. Use the ClassDesigner to create simple forms in > a > visual way. Dabo would be a good choice for this kind of app. It has a visual GUI designer and is optimised for working with databases. But any Python GUI framework would be suitable from Tkinter through wxPython to PyQt etc. This is very much bread and butter GUI programming. The learning curve for any GUI is prettty high though, and Dabo's visual designer will take one part of that pain away. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Mon Oct 12 16:25:02 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 12 Oct 2009 09:25:02 -0500 Subject: [Tutor] Porting PHP web app to Python GUI In-Reply-To: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> References: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> Message-ID: <333efb450910120725o27b2573dmeaf56f5ec8168f60@mail.gmail.com> On Mon, Oct 12, 2009 at 7:17 AM, Dotan Cohen wrote: > I have a simple PHP web application with a form, which enter the > information entered into the form into a database. However, I will be > several weeks without internet access so I now have two choices: > > 1) Run the script locally on my Kubuntu box > 2) Port it to Python and make a real app out of it. > > I prefer the second route, but I want to know if this seems reasonable > in Python: > 1) GUI with several input areas which are analogous to the HTML > Select, Input=Text, and Textarea fields. > 2) insert the data collected into an sqlite database > 3) Retrieve and display data from the database using predefined queries. > Very easy/reasonable > > I am familiar with the SQL language, some PHP and some C programing. I > have never done GUI programming other than HTML. Does PyQt seem to > have a reasonable learning curve for this application? > I've never used PyQT so I don't know about that. I mainly use PyGTK+, but for something this simple I'd just use Tkinter. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 12 16:24:48 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Oct 2009 15:24:48 +0100 Subject: [Tutor] Porting PHP web app to Python GUI References: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> <1255353251.5976.1339606783@webmail.messagingengine.com> Message-ID: "R?diger Wolf" wrote >> 1) GUI with several input areas which are analogous to the HTML >> Select, Input=Text, and Textarea fields. >> 3) Retrieve and display data from the database using predefined queries. > > EasyGUI makes it simple to add GUI to python app. > http://easygui.sourceforge.net/ EasyGui makes it easy to capture data via simple dialog boxes and display simple output the same way, but its not really a GUI application its more like a GUI alternative to raw_input and print. As such its very useful but... You can't, so far as I can tell, design a multi part GUI form using EasyGUI so I don;t think it would be a good choice here. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Mon Oct 12 16:32:13 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 13 Oct 2009 01:32:13 +1100 Subject: [Tutor] complete neophyte question here In-Reply-To: References: Message-ID: Jason Willis wrote: > I've recently been going through "Python Programming, for the Absolute > Beginner" Second Edition, By Michael Dawson > > I'm running python 2.5.4 on a windows xp home machine. > > So my question boils down to this: > > At the end of one of his chapters there is a challenge to write a > program that flips a "coin" 100 times then outputs the number of heads > or tails it hit. > > I wrote this: > Let's break the program down: > import random on this line you're importing an external module. In python (and in practically all languages), the random module is used to generate random numbers. In practically all languages, there are mechanisms to use codes written in another file, probably written by someone else. random is one such external code. In python, this external code is called a module, and the import mechanism allows you to use whatever code is in the random module. The random module is part of python's standard library and comes together when you installed python. Later, you will learn how to create your own modules and how to import modules you've written yourself. But how precisely the import mechanism works is not really important right now. > flip = 0 > head = 0 > tails = 0 Here you created some variables and assigned values to them; specifically 0s. > while flip != 100: while-loop will repeat the block of code below it until "flip != 100" evaluates to false. "flip != 100" evaluates to false when the value of flip is 100. > flip += 1 the flip is your loop counter; you increment (add by one) every time the block is run. > coin = random.randrange(2) you call a function in the random module called randrange(). A function is a piece of code that is meant for reuse; you can write your own function like this: def add(argument1, argument2): sum = argument1 + argument2 return sum and later in your code you could call add(3, 2) to get 5. random.randrange() is one such functions that is defined by the random module. randrange(n) returns a random number between 0 and n-1 (i.e. in your case between 0 and 1). There are various advantages on returning between 0 and n-1 instead of between 0 and n, but the justifications are not important now. > if coin == 0 > head += 1 > elif coin == 1 > tails += 1 That code does the main work that increment head by 1 when when coin is 0 or tails when coin is 1. > print head, tails and finally you printed the result to the screen. > raw_input("\n") > > > I honestly don't know how code works and would appreciate someone > explaining it to me? > > Using logic, I shouldn't be able to write the program due to my limited > skills so i don't know how to explain HOW i wrote it because it just > sort of happened. I was sitting home one night and it just came out > itself. I know that's not much of an explanation but there it is. > Why the pessimism? You have written a correct code (except for a few minor syntactical issue). Congratulations for your first program. From kent37 at tds.net Mon Oct 12 16:47:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Oct 2009 10:47:47 -0400 Subject: [Tutor] Automaton/transitional grammar query In-Reply-To: <56987A26-1558-49D0-9B7C-30C4F4FC7C91@mac.com> References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> <1c2a2c590910120544n38aa2e42h48d7422083c8ef18@mail.gmail.com> <56987A26-1558-49D0-9B7C-30C4F4FC7C91@mac.com> Message-ID: <1c2a2c590910120747j3d1ddec0q1e0fb8528ad73db9@mail.gmail.com> On Mon, Oct 12, 2009 at 10:09 AM, kevin parks wrote: >> > I don't understand why you want to flatten outlist; when I run your >> > program I get one number per line, not one generation per line as you >> > show above. > > > That's odd. Anyway in my program I am printing the list twice. The first > time outlist is printed it is nested one level deep. That is just > scaffolding. Then i pick through it one item per line having flattened it > and print it in a format that my other program can read. In the program you posted, outlist is a list of lists where each sub-list is a list of integers representing one generation of the automaton. When outlist is flattened, the result is a single list of integers. Maybe what you posted and what you tried are different? > I been using that flatten function since 1970. Prolly pilfered from Tim > Peters or Effbot. Remember them guys? Awesome dudes. I wonder if they even > use python anymore. Yes; Tim Peters lurks on this list; Fredrik Lundh still maintains PIL, at least. > Anyway that is from way before itertools was even a > glimmer. Additionally, your flatten function doesn't work for me actually. I > get: > > NameError: global name 'chain' is not defined from itertools import chain >> > I don't think you will get an infinite loop. You may have a grammar >> > that generates a stable or repeating pattern but I don't think you >> > will be able to detect that without trying it. > > Yeah i don't mean an infinite loop, but more like a perpetual dance back and > forth between to items > that point to each other. I think I need to be careful when i define the > rules that i don't get something like that... say if 1 goes to 4 but 4's > rule is go to 1, for example. That can clearly happen. There are several cases: - every rule maps to a single symbol. In this case, each generation is the same size as the previous generation and the pattern must repeat at some point, as the number of patterns is limited - all rules map to more than one symbol. In this case each generation is longer than the previous so there can not be a repeat. - at least one rule, but not all, maps to more than one symbol. In this case either outcome is possible, depending on whether the expanding rule is repeatedly hit. Kent From davea at ieee.org Mon Oct 12 17:06:50 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 12 Oct 2009 11:06:50 -0400 Subject: [Tutor] Automaton/transitional grammar query In-Reply-To: <51EB2946-7380-40AB-9B08-43DDEED8119F@mac.com> References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> <4AD30CD7.5070000@ieee.org> <51EB2946-7380-40AB-9B08-43DDEED8119F@mac.com> Message-ID: <4AD3460A.8040408@ieee.org> kevin parks wrote: > > On Oct 12, 2009, at 8:02 PM, Dave Angel wrote: > >> Often, when a combination of existing stdlib collection types gets >> too confusing, it's time to consider classes and objects. Not >> necessarily to make the program "object oriented," but to make the >> program data structure understandable. > > > That's sage advice.... I just dislike and resist OO. But i do > eventually need to make steps in that direction. > > > Well, an object is just a container, and a class is standardized way to make similar objects. But in Python, there are few restrictions on what you can do with such objects. So just start with data and without inheritance, which makes it very simple to understand. Then C++ would commonly call it struct, instead of class, and in fact struct already existed in C, which is not object oriented. class ProbableValue(object): def __init__(self, probability, newvalues): """probability is a float 0.0<=prob < 1.0. newvalues is a tuple of one or more values""" self.probability = probability self.newvalues= newvalues Is all you really need. Now you can create objects of this class by simply saying: val1 = ProbableValue(.3, (1, 4)) val2 = ProbableValue(.5, (12,)) and you can access the data by val1.probability, or val2.newvalues Now you can initialize the original rules table by something like: rules = {} val1 = ProbableValue(.3, (1,4)) val2 = ProbableValue(.25, (5)) val3 = ProbableValue(.45, (1,3,5)) #note that .3 + .25 + .45 == 1 rules[1] = (val1, val2, val3) #one dictionary rule and repeat those last four lines as needed to build up the dictionary Can you see where you might go from here? DaveA From alan.gauld at btinternet.com Mon Oct 12 18:43:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Oct 2009 17:43:44 +0100 Subject: [Tutor] Automaton/transitional grammar query References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com><1c2a2c590910120544n38aa2e42h48d7422083c8ef18@mail.gmail.com> <56987A26-1558-49D0-9B7C-30C4F4FC7C91@mac.com> Message-ID: "kevin parks" wrote > I been using that flatten function since 1970. Prolly pilfered from > Tim Peters or Effbot. Are you sure about that date? If you did get it from Tim or F/ it certainly wouldn't have been in Python back then! :-) Alan G From kent37 at tds.net Mon Oct 12 19:13:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Oct 2009 13:13:44 -0400 Subject: [Tutor] Automaton/transitional grammar query In-Reply-To: <1c2a2c590910120747j3d1ddec0q1e0fb8528ad73db9@mail.gmail.com> References: <37F38FFA-AB72-4375-944F-81F535A90513@mac.com> <1c2a2c590910120544n38aa2e42h48d7422083c8ef18@mail.gmail.com> <56987A26-1558-49D0-9B7C-30C4F4FC7C91@mac.com> <1c2a2c590910120747j3d1ddec0q1e0fb8528ad73db9@mail.gmail.com> Message-ID: <1c2a2c590910121013m7d7e5946wc41a8d14b305226e@mail.gmail.com> On Mon, Oct 12, 2009 at 10:47 AM, Kent Johnson wrote: > On Mon, Oct 12, 2009 at 10:09 AM, kevin parks wrote: >> Yeah i don't mean an infinite loop, but more like a perpetual dance back and >> forth between to items >> that point to each other. I think I need to be careful when i define the >> rules that i don't get something like that... say if 1 goes to 4 but 4's >> rule is go to 1, for example. > > That can clearly happen. There are several cases: > - at least one rule, but not all, maps to more than one symbol. In > this case either outcome is possible, depending on whether the > expanding rule is repeatedly hit. If you consider the set of rules as a directed graph, the question becomes something like, does the graph contain any cycles which - contain rules that map to more than one symbol, and - are reachable from the start symbol I'm not sure but I think there are probably standard methods of graph theory to answer this question. Kent From vic_prof at hotmail.com Mon Oct 12 20:21:30 2009 From: vic_prof at hotmail.com (Victor Binns) Date: Mon, 12 Oct 2009 14:21:30 -0400 Subject: [Tutor] Help on python file extension windows vista recognition Message-ID: Please, I need help. I installed python on my gateway windows vista laptop computer. This is with the latest version of python (Python 2.6.3 Windows installer) Python 2.6.3 Windows installer I have some python code files I placed on my desktop and tried placing it in a folder containing python program. The files still appears on the computer as a text file. Even though I placed the .py file extension on the file. The .py is on the file but the icon image appears as a notepad file. I need help in resolving this issue. Thanks _________________________________________________________________ Hotmail: Trusted email with Microsoft?s powerful SPAM protection. http://clk.atdmt.com/GBL/go/177141664/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From amosanderson at gmail.com Mon Oct 12 21:01:51 2009 From: amosanderson at gmail.com (Amos Anderson) Date: Mon, 12 Oct 2009 14:01:51 -0500 Subject: [Tutor] Help on python file extension windows vista recognition In-Reply-To: References: Message-ID: You probably have the true extension hidden. Try this... 1. Start->Control Panel->Appearance and Personalization->Folder Options2. Click the View tab 3. Uncheck Hide Extensions for Known File Types 4. Hit apply. Now check the file. You probably will notice the .txt extension is still there. You can remove it by renaming now. On Mon, Oct 12, 2009 at 1:21 PM, Victor Binns wrote: > > Please, > I need help. I installed python on my gateway windows vista laptop > computer. > > This is with the latest version of python (Python 2.6.3 Windows installer > ) > Python 2.6.3 Windows installer > > I have some python code files I placed on my desktop and tried placing it > in a folder containing > python program. > > The files still appears on the computer as a text file. Even though I > placed the .py file extension on the file. > > The .py is on the file but the icon image appears as a notepad file. > > I need help in resolving this issue. > > Thanks > > > ------------------------------ > Hotmail: Trusted email with Microsoft?s powerful SPAM protection. Sign up > now. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lead.expression at gmail.com Mon Oct 12 21:55:04 2009 From: lead.expression at gmail.com (Nicola De Quattro) Date: Mon, 12 Oct 2009 21:55:04 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> Message-ID: <4AD38998.10706@gmail.com> Hi all I'm starting with my project (rather slowly...) and I want to give you a little update (and do some trivial questions). I've started to write something about input image loading and rotation. My goal is that, from graphical interface, the user will be able to rotate an image at steps (perhaps using two buttons) or by entering the amount of degree the image has to be rotated. I've writed the following "main" that will call some functions for rotating, saving, etc. ------------------------------------------------ def tipsy_imp "Tests of Tipsy Imp input management" import Image, os, sys print """ ******************************* Tipsy Imp - Alpha version 0.0.1 by Nicola De Quattro ******************************* """ var = 0 while(var !=q0) print """ Please select an action from the menu below: -------------------------------------- o) Open an image +) Rotate the image of 1? clockwise -) Rotate the image of -1? clockwise r) Rotate the image of an input degree s) Show the image a) Save the image q) Quit Tipsy Imp -------------------------------------- """ var = raw_input("Make a choice: "); ------------------------------------------------ I've some questions: 1) Is there a switch-case statement in Python? It seems to me not. How do you suggest to proceed in order to switch into var values? 2) If I want this script to automatically load a image that I give him as argument, I obtain filename by simply using the instruction: import sys input= sys.argv[1:] image=Image.open(input) So under Linux I type, from commandline $ python main.py It can be the same under Windows? Thank you for your advices. Nik Nicola De Quattro ha scritto: > Hi, > I'm a 26 years old Italian engineer. Because to the fact that I'm an > astrophile and astronomical tool (expecially under Linux) are not so > common, I would like to develop some simple tool for some purposes. > Well, I'm not knew to software development but I've never used python. > So I want to list you my needed for the first tool, so you can tell me > if Python could be a good choice and how to begin the develop. > First of all, I need a software running both under Windows and Linux > at least (it would be better if running either under MacOS). This is a > first reason to choose Python. > Secondly, I want a OpenSource tool > The software shall be a tool for Star Analyzer (spectroscopic > analyzer) images. A similar software already exists, it can be seen at > this link (I'm sorry, it is in Italian, but you can understand from > the images what is the input and the output) > > http://www.astropix.it/software/astrospectrum.html > > So I've to open an image (various formats, first I could need only > .fits), to process the image in order to select the interesting strip > containing the star and the spectrum (first image of the link posted, > but I hope I can select the strip not only in the horizontal line but > I will rotate the image), to obtain a graph like the second and third > image (this may be simple, it plots the value of luminosity of each > point), calibrate the image using periodical table of elements as > shown in 6th image in order to color the graph. > > Well, I know that many people doesn't understand the problem :) I hope > you can be able, with the elements reported above, how I have to > proceed, remembering that I've no problem programming in Matlab and C > but I've never worked with graphical interfaces and with image > processing (only under Matlab). > > I've learned most of python commands. I think I've to start with some library? > > Thank you very much and sorry for the poem (and for my english)! > > PS: If the question is "Why don't you use Astrospectrum?" the answer > is: it is only for Linux and is not opensource :( > From davea at ieee.org Mon Oct 12 22:32:30 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 12 Oct 2009 16:32:30 -0400 Subject: [Tutor] Help on python file extension windows vista recognition In-Reply-To: References: Message-ID: <4AD3925E.5030400@ieee.org> Victor Binns wrote: > > > Please, > I need help. I installed python on my gateway windows vista laptop computer. > > This is with the latest version of python (Python 2.6.3 Windows installer) > Python 2.6.3 Windows installer > It's not the latest, but no problem. It's probably a good choice. > > I have some python code files I placed on my desktop and tried placing it in a folder containing > python program. > Which? On the desktop, or in a folder containing python programs? > > The files still appears on the computer as a text file. Even though I placed the .py file extension on the file. > > The .py is on the file but the icon image appears as a notepad file. > > I need help in resolving this issue. > > Thanks > > > > Are you familiar with your system, and with Vista in particular? One thing that's been wrong for the last few implementations of Windows is that by default Explorer hides the extension of files. So you have to believe in icons to guess what the file extension is. When I get each new system, one of the first things I change is "hide file extensions for known types". Don't hide anything. There are a number of other foolish settings which ought to be switched, but this is one of the most important. Most likely, your base problem is that your file is called myprogram.py.txt Notepad loves to add a txt extension to files, and by default Windows Explorer obscures that fact. If you must use Notepad to edit the files, then when doing the SaveAs, make sure you change the "Save as file type" from "Text Documents" to "All files" Otherwise Notepad will add an extra .txt to whatever extension you try to use. You will also need to get comfortable with the DOS box (Command Prompt, whatever Vista calls it. It's probably in Start->Accessories). In a DOS box, you could do a DIR of that directory, and see exactly what the file is called. You also could invoke python or pythonw explicitly on the file, with extra option switches. And when the program finishes, the window with the result wouldn't automatically vanish. And you can scroll back and see what's been happening in previous runs. And you can actually type arguments to your script. And ... DaveA From kb1pkl at aim.com Mon Oct 12 22:34:04 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 12 Oct 2009 16:34:04 -0400 Subject: [Tutor] Switching to other version of Python Message-ID: <4AD392BC.3080506@aim.com> My school has python 2.4. I have python 2.6, and I find it perfectly wonderful. However, I am contemplating the switch, and am wondering, what is your personal opinion on why or why not to use 3.x? Thanks for the help in advance, ~Corey -------------- next part -------------- A non-text attachment was scrubbed... Name: kb1pkl.vcf Type: text/x-vcard Size: 55 bytes Desc: not available URL: From srilyk at gmail.com Mon Oct 12 22:45:02 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 12 Oct 2009 15:45:02 -0500 Subject: [Tutor] Switching to other version of Python In-Reply-To: <4AD392BC.3080506@aim.com> References: <4AD392BC.3080506@aim.com> Message-ID: <333efb450910121345v38e46feewa994ddd9892ebcc8@mail.gmail.com> On Mon, Oct 12, 2009 at 3:34 PM, Corey Richardson wrote: > My school has python 2.4. I have python 2.6, and I find it perfectly > wonderful. However, I am contemplating the switch, and am wondering, what is > your personal opinion on why or why not to use 3.x? Few 3rd party modules have been ported to 3.x If you're using the standard bits-n-pieces, and have no desire to use anything else... there's probably no reason to hold off on learning 3.x I'm waiting around for a few more modules & things to be ported over. I'll probably start looking a bit more aggressively come summer of '10. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Mon Oct 12 22:59:11 2009 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 12 Oct 2009 22:59:11 +0200 Subject: [Tutor] Porting PHP web app to Python GUI In-Reply-To: References: <880dece00910120517u1f8ce52bj80aaf0050fa60e85@mail.gmail.com> <200910120636.35710.jfabiani@yolo.com> Message-ID: <880dece00910121359q7ceee549qc41f418dae253488@mail.gmail.com> Thanks, all, I have subscribed to the Dabo list and I will almost certainly bug both lists in the near future. Thank you! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il From the_only_katala at verizon.net Mon Oct 12 23:57:01 2009 From: the_only_katala at verizon.net (Katt) Date: Mon, 12 Oct 2009 14:57:01 -0700 Subject: [Tutor] What is Curses and why do they call it that. References: Message-ID: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> Hello all, In my search for ways to change the color of text printed to the screen I came across discussions about curses. Some documentation indicate it as a module that will translate commands to control screen output. Is this right? Also, why do they call it curses? Thanks in advance, Katt From steve at alchemy.com Tue Oct 13 00:09:55 2009 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 12 Oct 2009 15:09:55 -0700 Subject: [Tutor] What is Curses and why do they call it that. In-Reply-To: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> References: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> Message-ID: <20091012220955.GA70541@dragon.alchemy.com> On Mon, Oct 12, 2009 at 02:57:01PM -0700, Katt wrote: > In my search for ways to change the color of text printed to the screen I > came across discussions about curses. > > Some documentation indicate it as a module that will translate commands to > control screen output. Is this right? Also, why do they call it curses? Curses is an ancient library for handling full-screen control easily. This is from back in the days when you typically connected to the computer using some sort of ASCII terminal, and graphical user interfaces were far from common. The name is a humorous reference to the "cursor" on the screen which this package controls for the application, moving it around (and curses even contains some pretty sophisticated code for calculating how to retraw fields, windows, etc. in ASCII characters using the least possible transmitted characters in each case--a boon when using a slow modem). If you want to change text attributes or set up data entry screens (or information displays) on a plain text terminal window or system console, it's worth looking at curses. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From rabidpoobear at gmail.com Tue Oct 13 00:13:27 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 12 Oct 2009 17:13:27 -0500 Subject: [Tutor] What is Curses and why do they call it that. In-Reply-To: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> References: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> Message-ID: Not sure what curses means but that module only works on Unix. It does do what you want though. On 10/12/09, Katt wrote: > Hello all, > > In my search for ways to change the color of text printed to the screen I > came across discussions about curses. > > Some documentation indicate it as a module that will translate commands to > control screen output. Is this right? Also, why do they call it curses? > > Thanks in advance, > > Katt > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sent from my mobile device From mzanfardino at gmail.com Tue Oct 13 00:37:24 2009 From: mzanfardino at gmail.com (Mark K. Zanfardino) Date: Mon, 12 Oct 2009 15:37:24 -0700 Subject: [Tutor] What is Curses and why do they call it that. In-Reply-To: References: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> Message-ID: <1255387044.26993.4.camel@mycroft64.Hormann> Curses is a pun on the term "cursor optimization". It is a library of functions that manage an application's display on character-cell terminals (e.g., VT100). On Mon, 2009-10-12 at 17:13 -0500, Luke Paireepinart wrote: > Not sure what curses means but that module only works on Unix. It does > do what you want though. > > On 10/12/09, Katt wrote: > > Hello all, > > > > In my search for ways to change the color of text printed to the screen I > > came across discussions about curses. > > > > Some documentation indicate it as a module that will translate commands to > > control screen output. Is this right? Also, why do they call it curses? > > > > Thanks in advance, > > > > Katt > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > From the_only_katala at verizon.net Mon Oct 12 23:49:34 2009 From: the_only_katala at verizon.net (Katt) Date: Mon, 12 Oct 2009 14:49:34 -0700 Subject: [Tutor] First line of a python program References: Message-ID: <7641F1CA3F934786AD39A75CC6CD142F@COMPUTER01> Hello all, Numerous times I see the following as the first line of a python program: #! /usr/bin/python What is this for or do for the program? Thanks in advance, Katt From mzanfardino at gmail.com Tue Oct 13 01:05:04 2009 From: mzanfardino at gmail.com (Mark K. Zanfardino) Date: Mon, 12 Oct 2009 16:05:04 -0700 Subject: [Tutor] First line of a python program In-Reply-To: <7641F1CA3F934786AD39A75CC6CD142F@COMPUTER01> References: <7641F1CA3F934786AD39A75CC6CD142F@COMPUTER01> Message-ID: <1255388704.26993.6.camel@mycroft64.Hormann> >From http://en.wikipedia.org/wiki/Shebang_(Unix): In computing, a shebang (also called a hashbang, hashpling, pound bang, or crunchbang) refers to the characters "#!" when they are the first two characters in a text file. In a Unix-like operating system, the program loader takes the presence of these two characters as an indication that the file is a script, and tries to execute that script using the interpreter specified by the rest of the first line in the file. Mark On Mon, 2009-10-12 at 14:49 -0700, Katt wrote: > Hello all, > > Numerous times I see the following as the first line of a python program: > > #! /usr/bin/python > > What is this for or do for the program? > > Thanks in advance, > > Katt > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Tue Oct 13 01:07:27 2009 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 12 Oct 2009 16:07:27 -0700 Subject: [Tutor] First line of a python program In-Reply-To: <7641F1CA3F934786AD39A75CC6CD142F@COMPUTER01> References: <7641F1CA3F934786AD39A75CC6CD142F@COMPUTER01> Message-ID: <20091012230727.GB70541@dragon.alchemy.com> On Mon, Oct 12, 2009 at 02:49:34PM -0700, Katt wrote: > Hello all, > > Numerous times I see the following as the first line of a python program: > > #! /usr/bin/python As far as Python is concerned, it is a comment. Anything from the # character to the end of the line is a comment. If you want to execute this script, you need to run the Python interpreter and tell it to load the script file and run it for you: $ /usr/bin/python myscript You could just set your script to be executable (by setting the right permission bits) and then you can run it as a command without naming python yourself: $ myscript (that assumes it's in a directory in your PATH, of course, or you'd have to type the path to the script as well.) That allows you to write scripts which act like any other command on your system. In order to do that, though, the system needs to know what interpreter to use to actually run your script. Unix uses the convention of looking at the first few bytes of the program file. If they start with "#!" then the remainder of the first line is assumed to be the name of the interpreter program, so with "#!/usr/bin/python" at the top of your file, Unix will know to run it as "/usr/bin/python myscript". If you use an operating system other than Unix, or invoke the interpreter yourself (typing "python myscript"), then this line is completely ignored. HTH HAND > > What is this for or do for the program? > > Thanks in advance, > > Katt > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From markus.flatscher at virginia.edu Tue Oct 13 00:54:46 2009 From: markus.flatscher at virginia.edu (Markus Flatscher ) Date: Mon, 12 Oct 2009 18:54:46 -0400 Subject: [Tutor] First line of a python program In-Reply-To: <7641F1CA3F934786AD39A75CC6CD142F@COMPUTER01> References: <7641F1CA3F934786AD39A75CC6CD142F@COMPUTER01> Message-ID: The short answer is, it's a shebang: http://en.wikipedia.org/wiki/Shebang_(Unix) Let us know if this clarifies anything. M. On Mon, 12 Oct 2009 14:49:34 -0700 "Katt" wrote: >Hello all, > >Numerous times I see the following as the first line of a python program: > >#! /usr/bin/python > >What is this for or do for the program? > >Thanks in advance, > >Katt >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor -- Markus Flatscher, Project Editor ROTUNDA, The University of Virginia Press PO Box 801079, Charlottesville, VA 22904-4318 USA Courier: 310 Old Ivy Way, Suite 302, Charlottesville VA 22903 Email: markus.flatscher at virginia.edu From alan.gauld at btinternet.com Tue Oct 13 01:36:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 00:36:39 +0100 Subject: [Tutor] Switching to other version of Python References: <4AD392BC.3080506@aim.com> Message-ID: "Corey Richardson" wrote > My school has python 2.4. I have python 2.6, and I find it perfectly > wonderful. However, I am contemplating the switch, and am wondering, > what is your personal opinion on why or why not to use 3.x? Thanks for > the help in advance, Well your Python 3 programs won't run as expected on your school v2.4 and your schoool programs won;t run at all on your python v3. So I'd stay well clear of v3 for now. There is no compelling reason to switch yet. You could keep 2.6 on your own PC and use v3 of course but most of the v3 stuff is available in 2.6. Also you could upgrade to 2.7 for even more 3 compatibility but still better with 2.4 than using 3 would be. Resist the urge to upgrade just for the sake of it. (Advice I fail to follow in HiFi but try to follow in everything else! :-) Alan G. From alan.gauld at btinternet.com Tue Oct 13 01:48:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 00:48:16 +0100 Subject: [Tutor] What is Curses and why do they call it that. References: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> Message-ID: "Katt" wrote > Some documentation indicate it as a module that will translate commands > to control screen output. Is this right? Also, why do they call it > curses? Thats right, it provides a way to draw GUI like "windows" on the screen using graphics characters if they are available or plain ASCII if not, thus it offers a degree of terminal independance. It was popular in the period before GUIs became normal but after they became desirable - ie around 1985-1995. A curses screen field will look something like (use monospace font for this bit) +-------------------------+ Name | | +-------------------------+ And you could define the box as a window and position the cursor inside it. You could then clear the window, read its contents, change its colour, even resize it etc. Just like an Edit box in a GUI. Nowadays most usage is to deliver cursor control to console mode programs rather than building multi-windowed displays etc. The default window is the full screen. See the Event Driven Programming topic of my tutorial for a very simple demo of curses in use. The name curses is a pun on the word cursor and the typical reaction of programmers forced to use curses to build a "GUI"! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bill at celestial.net Tue Oct 13 01:57:44 2009 From: bill at celestial.net (Bill Campbell) Date: Mon, 12 Oct 2009 16:57:44 -0700 Subject: [Tutor] What is Curses and why do they call it that. In-Reply-To: References: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> Message-ID: <20091012235743.GA29963@ayn.mi.celestial.com> On Tue, Oct 13, 2009, Alan Gauld wrote: > > "Katt" wrote > >> Some documentation indicate it as a module that will translate commands >> to control screen output. Is this right? Also, why do they call it >> curses? > > Thats right, it provides a way to draw GUI like "windows" on the screen > using graphics characters if they are available or plain ASCII if not, thus > it offers a degree of terminal independance. It was popular in the period > before GUIs became normal but after they became desirable - ie > around 1985-1995. And should be more desirable today for applications that require efficient, heads-down data entry where one does not want to take fingers off of home keys or numeric keypads. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 What this country needs are more unemployed politicians. -- Edward L angley, Artist (1928 - 1995) From stefan_ml at behnel.de Tue Oct 13 09:09:02 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 13 Oct 2009 09:09:02 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <4AD38998.10706@gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> <4AD38998.10706@gmail.com> Message-ID: Nicola De Quattro wrote: > while(var !=q0) > print """ > Please select an action from the menu below: > -------------------------------------- > o) Open an image > +) Rotate the image of 1? clockwise > -) Rotate the image of -1? clockwise > r) Rotate the image of an input degree > s) Show the image > a) Save the image > q) Quit Tipsy Imp > -------------------------------------- > """ > var = raw_input("Make a choice: "); "var" is a rather meaningless name for a variable. Something like "choice" might be better here. BTW, you might want to look into a GUI toolkit. There's tkinter that comes with Python, and there are many others that aren't hard to use either. http://wiki.python.org/moin/FrontPage?action=fullsearch&context=180&value=gui&titlesearch=Titel > ------------------------------------------------ > > I've some questions: > 1) Is there a switch-case statement in Python? It seems to me not. How > do you suggest to proceed in order to switch into var values? Use a dict that maps characters to functions and then lookup_dispatch_function = { 'o' : open_image, ... }.get def error_fallback(): print("Invalid input, try again") # ... choice = raw_input("Make a choice: ") handle_input = lookup_dispatch_function( choice.strip(), error_fallback) handle_input() Stefan From fomcl at yahoo.com Tue Oct 13 09:29:30 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 13 Oct 2009 00:29:30 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <777107.59195.qm@web110707.mail.gq1.yahoo.com> Hi, I'm using Tkinter to program my very frist GUI. Each button grays out after it has been used so the user knows what next steps to take. Now I want to define a Reset button to 'ungray' all buttons (state='normal'). How can I programmatically create a list of all available buttons? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before you criticize someone, walk a mile in their shoes, that way when you do criticize them, you're a mile away and you have their shoes! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From the_only_katala at verizon.net Tue Oct 13 09:11:50 2009 From: the_only_katala at verizon.net (Katt) Date: Tue, 13 Oct 2009 00:11:50 -0700 Subject: [Tutor] Curses - What does it do and why is it called this? References: Message-ID: <658BAD57AED04708975EE68925F05848@COMPUTER01> > From: Steve Willoughby > To: Katt > The name is a humorous reference to the "cursor" on the screen which this > package controls for the application, moving it around (and curses even Now I understand. Makes sense. If "Curses" is for UNIX what would I use on a Windows XP system using Python 2.6.2? Thanks to all for the help. Being new to python I am confused by some of the vocabulary that is being used. Thanks also to Luke P. and Mark Z. for your responses Katt From the_only_katala at verizon.net Tue Oct 13 09:19:49 2009 From: the_only_katala at verizon.net (Katt) Date: Tue, 13 Oct 2009 00:19:49 -0700 Subject: [Tutor] Shebang (#!) in the first line of a python script References: Message-ID: <6B96A488DDB946FFB2308068DB3CCC56@COMPUTER01> > From: "Mark K. Zanfardino" > To: Katt > Cc: tutor at python.org > Subject: Re: [Tutor] First line of a python program > In computing, a shebang (also called a hashbang, hashpling, pound bang, > or crunchbang) refers to the characters "#!" when they are the first two > characters in a text file. In a Unix-like operating system, the program > > #! /usr/bin/python > > If you want to execute this script, you need to run the Python > interpreter and tell it to load the script file and run it > for you: > > $ /usr/bin/python myscript > > You could just set your script to be executable (by setting the > right permission bits) and then you can run it as a command > without naming python yourself: > > $ myscript > Okay. So if I were to place the following in my Windows XP py v.2.6.2 : $ (name of python script) Then as long as python was in my path I would be able to type the name of the script like a Dos batch file (ex: lowertoupper.py or lowertoupper) instead of having to type python lowertoupper.py? And it will run as normal? Thanks also to Steve W. Thanks in advance, Katt From mail at timgolden.me.uk Tue Oct 13 09:48:36 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 13 Oct 2009 08:48:36 +0100 Subject: [Tutor] Help on python file extension windows vista recognition In-Reply-To: <4AD3925E.5030400@ieee.org> References: <4AD3925E.5030400@ieee.org> Message-ID: <4AD430D4.2060909@timgolden.me.uk> Dave Angel wrote: > You will also need to get comfortable with the DOS box (Command Prompt, > whatever Vista calls it. It's probably in Start->Accessories). In a > DOS box, you could do a DIR of that directory, and see exactly what the > file is called. You also could invoke python or pythonw explicitly on > the file, with extra option switches. And when the program finishes, > the window with the result wouldn't automatically vanish. And you can > scroll back and see what's been happening in previous runs. And you can > actually type arguments to your script. And ... If you haven't already, check out the "Using Python on..." section of the docs. This is an online link: http://docs.python.org/using/windows.html but the docs are included in the standard Windows install. TJG From alan.gauld at btinternet.com Tue Oct 13 09:53:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 08:53:58 +0100 Subject: [Tutor] What is Curses and why do they call it that. References: <598F4EEE61CF406B98D491ADD4CEED99@COMPUTER01> <20091012235743.GA29963@ayn.mi.celestial.com> Message-ID: "Bill Campbell" wrote >> it offers a degree of terminal independance. It was popular in the >> period >> before GUIs became normal but after they became desirable - ie >> around 1985-1995. > > And should be more desirable today for applications that require > efficient, heads-down data entry where one does not want to take > fingers off of home keys or numeric keypads. That is entirely possible in a pure GUI, its only bad design that prevents it! Default focus and tab order settings are available on virtually every GUI toolkit, its just that the designers often don't give much thought to it. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 13 09:58:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 08:58:04 +0100 Subject: [Tutor] Curses - What does it do and why is it called this? References: <658BAD57AED04708975EE68925F05848@COMPUTER01> Message-ID: "Katt" wrote > Now I understand. Makes sense. If "Curses" is for UNIX what would I use > on > a Windows XP system using Python 2.6.2? It does exist for DOS too but the Python bindings don;t sem to work well. However for most simple terminal handling you can use the msvcrt module (msvcrt = MicroSoft Visual C RunTime). There is also a conio module (based on Borland's I/O library) which provides a bit more in the way of cursor control. And I think Fred Lundh has a Terminal module that is OS independant. But for creating actual forms etc I'f just go with a GUI in Tkinter or somesuch. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 13 10:01:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 09:01:52 +0100 Subject: [Tutor] Shebang (#!) in the first line of a python script References: <6B96A488DDB946FFB2308068DB3CCC56@COMPUTER01> Message-ID: "Katt" wrote > Okay. So if I were to place the following in my Windows XP py v.2.6.2 : > > $ (name of python script) > > Then as long as python was in my path I would be able to type the name of > the script like a Dos batch file (ex: lowertoupper.py or lowertoupper) > instead of having to type python lowertoupper.py? And it will run as > normal? The shebang line does nothing on Windows, it is just a comment. Windows uses the file extension so, provided you end the file in .py, you can just type in the name of the script and Windows will use the file association to find the interpreter. This is a somewhat fragile mechanism and if you have two versions of Python installed or the associations get broken it may fail but most of the time it works fine. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 13 10:06:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 09:06:50 +0100 Subject: [Tutor] GUI Buttons References: <777107.59195.qm@web110707.mail.gq1.yahoo.com> Message-ID: Please provide a subject when sending mail to the list. And please create a new message so it doesn't get lost in an old thread... "Albert-Jan Roskam" wrote in message > I'm using Tkinter to program my very frist GUI. > Each button grays out after it has been used so the user knows what next > steps to take. > Now I want to define a Reset button to 'ungray' all buttons > (state='normal'). > How can I programmatically create a list of all available buttons? Just add your buttons to a list when you create them Then in your reset method do for button in ButtonList: button['state'] = NORMAL HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From the_only_katala at verizon.net Tue Oct 13 10:43:43 2009 From: the_only_katala at verizon.net (Katt) Date: Tue, 13 Oct 2009 01:43:43 -0700 Subject: [Tutor] Changing text colors on WinXP py2.6.2 References: Message-ID: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> Hello All, Is it possible to change text color on a WinXP system by just using the Ansi escape codes. I have tried, but it just shows the start and end text of the code, but it doesn't change the color. I have tried placing the following before and aft the variable I wish to change: print "\x1B[31;46m",variable,"[0m" print "\033[31;46m",variable,"[0m" In both cases no change has happened. From davea at ieee.org Tue Oct 13 12:24:42 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Oct 2009 06:24:42 -0400 Subject: [Tutor] Shebang (#!) in the first line of a python script In-Reply-To: References: <6B96A488DDB946FFB2308068DB3CCC56@COMPUTER01> Message-ID: <4AD4556A.2020406@ieee.org> Alan Gauld wrote: > "Katt" wrote > >> Okay. So if I were to place the following in my Windows XP py v.2.6.2 : >> >> $ (name of python script) >> >> Then as long as python was in my path I would be able to type the >> name of the script like a Dos batch file (ex: lowertoupper.py or >> lowertoupper) instead of having to type python lowertoupper.py? And >> it will run as normal? > > The shebang line does nothing on Windows, it is just a comment. > Windows uses the file extension so, provided you end the file in .py, > you can just type in the name of the script and Windows will use the > file association to find the interpreter. > > This is a somewhat fragile mechanism and if you have two versions > of Python installed or the associations get broken it may fail but most > of the time it works fine. > As Alan says, the default shells in Windows ignore the shebang line. So unless you have a custom shell installed, you need to understand the Windows pattern. They have another mechanism, which involves two registry entries and an environment variable. The registry entries can easily be manipulated using the utility programs assoc.exe and ftype.exe. However, as long as you have a single Python installation, these are probably already setup for you. If you have more than one Python version installed, you might need to use ftype to switch which one is your default. As long as you're using this mechanism, python.exe does *not* have to be on your PATH. The full path location of python.exe is set up by ftype. You may want your script(s) to be on your PATH of course. The environment variable is used to avoid the need to type the extension. This is *not* set up by default in the Python installation, at least in my experience. But you can easily do it yourself. The environment variable PATHEXT has a list of extensions that it will search for. Mine looks like: PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.PYW Yours probably doesn't yet have the last two entries, and the others might be somewhat different as well. With .py in this variable, you can type lowertoupper instead of lowertoupper.py DaveA From mail at timgolden.me.uk Tue Oct 13 12:34:15 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 13 Oct 2009 11:34:15 +0100 Subject: [Tutor] Changing text colors on WinXP py2.6.2 In-Reply-To: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> References: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> Message-ID: <4AD457A7.5030301@timgolden.me.uk> Katt wrote: > Is it possible to change text color on a WinXP system by just using the Ansi > escape codes. I have tried, but it just shows the start and end text of the > code, but it doesn't change the color. No. ANSI escapes don't work on Windows. Depending on where you want to go, you can look at the win32console module [1] of the pywin32 package [2] or Fredrik Lundh's console [3] module or Chris Gonnerman's wconio [4]. TJG [1] http://timgolden.me.uk/pywin32-docs/win32console.html [2] http://sourceforge.net/projects/pywin32/ [3] http://effbot.org/zone/console-index.htm [4] http://newcenturycomputers.net/projects/wconio.html From kent37 at tds.net Tue Oct 13 13:01:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Oct 2009 07:01:36 -0400 Subject: [Tutor] (no subject) In-Reply-To: <777107.59195.qm@web110707.mail.gq1.yahoo.com> References: <777107.59195.qm@web110707.mail.gq1.yahoo.com> Message-ID: <1c2a2c590910130401s212d9808nde885e26bd9b0518@mail.gmail.com> On Tue, Oct 13, 2009 at 3:29 AM, Albert-Jan Roskam wrote: > Hi, > > I'm using Tkinter to program my very frist GUI. Each button grays out after it has been used so the user knows what next steps to take. > Now I want to define a Reset button to 'ungray' all buttons (state='normal'). How can I programmatically create a list of all available buttons? When you create the buttons, add them to a list. Keep the list as a member of the class that handles the buttons so it is available to the Reset button handler. Kent From eike.welk at gmx.net Tue Oct 13 13:39:50 2009 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 13 Oct 2009 13:39:50 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <4AD38998.10706@gmail.com> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> <4AD38998.10706@gmail.com> Message-ID: <200910131339.51569.eike.welk@gmx.net> On Monday 12 October 2009, Nicola De Quattro wrote: > I've started to write something about input image loading and > rotation. My goal is that, from graphical interface, the user will > be able to rotate an image at steps (perhaps using two buttons) or > by entering the amount of degree the image has to be rotated. I've > writed the following "main" that will call some functions for > rotating, saving, etc. I think you shouldn't write text based menus either. You should just write a library of Python functions. To use your software you call these functions from the Python prompt. IPython, an extension for the standard Python interpreter, is good for it. You then work with Python similar to Matlab. http://ipython.scipy.org/moin/ Only when the functions work, then you start to write more simple user interfaces. Your mail illustrates my point: You currently think about user interface stuff and not about the real problem, analyzing spectra of stars. A session with your software would then look like this: ~> ipython In [1]: from analyze_spectra import * In [2]: im1 = load_image("astro/spectra/13-10-2009/im1.fits") In [3]: display_image(im1) In [4]: im1rot = rotate_image(im1, 20, degrees=True) .... And so on. This is much more flexible than Graphical or menu driven user interfaces, and it is much more comfortable for software development. You can write test scripts, instead of clicking around in your unfinished user interface. The added flexibility lets you do odd tasks, that a GUI can't do. And you get automation if you have many similar images for free. If you have Windows users, they can install Python XY. This is a Package that contains a Python interpreter and many libraries for scientists. It contains the libraries that I have recommended, but unfortunately not Pyfits. It also contains Eclipse as a development environment. (I think it is even better than any repository for Suse Linux.) http://www.pythonxy.com/foreword.php Kind regards, Eike. From alan.gauld at btinternet.com Tue Oct 13 14:12:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 13:12:11 +0100 Subject: [Tutor] Changing text colors on WinXP py2.6.2 References: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> <4AD457A7.5030301@timgolden.me.uk> Message-ID: "Tim Golden" wrote > No. ANSI escapes don't work on Windows. Wouldn't the ANSI codes work if ANSI.SYS were loaded? I thought you could still load ANSI.SYS it just wasn't normally there? The help system says you should load it in config.nt with: device=c:\winnt\system32\ansi.sys But I admit I've never tried it - I didn't even like ANSI.SYS when I was using DOS! Alan G. From mail at timgolden.me.uk Tue Oct 13 14:26:14 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 13 Oct 2009 13:26:14 +0100 Subject: [Tutor] Changing text colors on WinXP py2.6.2 In-Reply-To: References: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> <4AD457A7.5030301@timgolden.me.uk> Message-ID: <4AD471E6.7050304@timgolden.me.uk> Alan Gauld wrote: > "Tim Golden" wrote > >> No. ANSI escapes don't work on Windows. > > Wouldn't the ANSI codes work if ANSI.SYS were loaded? > I thought you could still load ANSI.SYS it just wasn't > normally there? The help system says you should load it > in config.nt with: > > device=c:\winnt\system32\ansi.sys > > But I admit I've never tried it - I didn't even like ANSI.SYS > when I was using DOS! (from memory). I'm fairly sure that even that no longer works. When this question last came up I think we went round that loop and discovered that it didn't. Happy to be wrong. :) TJG From lead.expression at gmail.com Tue Oct 13 14:47:41 2009 From: lead.expression at gmail.com (Nicola De Quattro) Date: Tue, 13 Oct 2009 14:47:41 +0200 Subject: [Tutor] New to python: some advises for image processing tool In-Reply-To: <200910131339.51569.eike.welk@gmx.net> References: <83afd1db0910020247m59c446efy8e9117535345f88b@mail.gmail.com> <4AD38998.10706@gmail.com> <200910131339.51569.eike.welk@gmx.net> Message-ID: <83afd1db0910130547r37a1cdbfr8087377aa3e4b269@mail.gmail.com> > You currently think about > user interface stuff and not about the real problem, analyzing > spectra of stars. Well, I think is exactly as you say. I've never developed entirely a tool, so I started with the container rather then the content. Thanks for the very useful (however simple) observation > This is much more flexible than Graphical or menu driven user > interfaces, and it is much more comfortable for software development. It isn't completely clear to me the difference and advantages about standard Python Interpreter (you can execute commands and test script like Matlab, can't you?) but I think I try to install it and take a look. > If you have Windows users, they can install Python XY. This is a > Package that contains a Python interpreter and many libraries for > scientists. It contains the libraries that I have recommended, but > unfortunately not Pyfits. It also contains Eclipse as a development > environment. (I think it is even better than any repository for Suse > Linux.) > http://www.pythonxy.com/foreword.php Very good, this seems good for my purposes, 'cause for now I don't use Pyfits. Thank you very much for your help. I'll start to write and test single modules as you advice. -- Nicola De Quattro Mobile: (+39)3292964937 Web: http://nikde4.altervista.org Skype: lead_expression MSNetwork: lead_expression at hotmail.com From metolone+gmane at gmail.com Tue Oct 13 16:11:53 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 13 Oct 2009 07:11:53 -0700 Subject: [Tutor] Changing text colors on WinXP py2.6.2 References: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> <4AD457A7.5030301@timgolden.me.uk> <4AD471E6.7050304@timgolden.me.uk> Message-ID: "Tim Golden" wrote in message news:4AD471E6.7050304 at timgolden.me.uk... > Alan Gauld wrote: >> "Tim Golden" wrote >>> No. ANSI escapes don't work on Windows. >> >> Wouldn't the ANSI codes work if ANSI.SYS were loaded? >> I thought you could still load ANSI.SYS it just wasn't normally there? >> The help system says you should load it in config.nt with: >> >> device=c:\winnt\system32\ansi.sys But I admit I've never tried it - I >> didn't even like ANSI.SYS when I was using DOS! > > > (from memory). I'm fairly sure that even that > no longer works. When this question last came > up I think we went round that loop and discovered > that it didn't. Happy to be wrong. :) That still works, but it only ever worked for command.com (the 16-bit command interpreter that still comes with Windows XP). A 16-bit DOS program or a batch file explicitly run under command.com can still use ANSI excapes. -Mark From mail at timgolden.me.uk Tue Oct 13 16:19:09 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 13 Oct 2009 15:19:09 +0100 Subject: [Tutor] Changing text colors on WinXP py2.6.2 In-Reply-To: References: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> <4AD457A7.5030301@timgolden.me.uk> <4AD471E6.7050304@timgolden.me.uk> Message-ID: <4AD48C5D.7060009@timgolden.me.uk> Mark Tolonen wrote: > "Tim Golden" wrote in message > news:4AD471E6.7050304 at timgolden.me.uk... >> Alan Gauld wrote: >>> "Tim Golden" wrote >>>> No. ANSI escapes don't work on Windows. >>> Wouldn't the ANSI codes work if ANSI.SYS were loaded? >>> I thought you could still load ANSI.SYS it just wasn't normally there? >>> The help system says you should load it in config.nt with: >>> >>> device=c:\winnt\system32\ansi.sys But I admit I've never tried it - I >>> didn't even like ANSI.SYS when I was using DOS! >> >> (from memory). I'm fairly sure that even that >> no longer works. When this question last came >> up I think we went round that loop and discovered >> that it didn't. Happy to be wrong. :) > > That still works, but it only ever worked for command.com (the 16-bit > command interpreter that still comes with Windows XP). A 16-bit DOS program > or a batch file explicitly run under command.com can still use ANSI excapes. Thanks for the info; hopefully I'll remember it the next time this question gets asked! TJG From RWeidner at ea.com Tue Oct 13 16:28:40 2009 From: RWeidner at ea.com (Weidner, Ronald) Date: Tue, 13 Oct 2009 07:28:40 -0700 Subject: [Tutor] [OT] Secure coding guidelines In-Reply-To: <1c2a2c590910101752l406a3ad1xbf947da7217958ab@mail.gmail.com> References: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> <1c2a2c590910101752l406a3ad1xbf947da7217958ab@mail.gmail.com> Message-ID: In reference to this tip, my question is why? - don't use string formatting to create SQL statements - use the two-argument form of execute() to pass args as a sequence -- Ronald Weidner -----Original Message----- From: tutor-bounces+rweidner=ea.com at python.org [mailto:tutor-bounces+rweidner=ea.com at python.org] On Behalf Of Kent Johnson Sent: Saturday, October 10, 2009 8:52 PM To: Didar Hossain Cc: tutor at python.org Subject: Re: [Tutor] [OT] Secure coding guidelines On Sat, Oct 10, 2009 at 5:31 AM, Didar Hossain wrote: > Hi, > > This is a little off-topic, but, I though I might put this question in. > > Since I am learning Python, I was wondering if there are any good > references on secure > coding practices. Books, guides or even any howtos would suffice. I don't know any references, but a few tips: - don't use eval or exec on untrusted code - don't unpickle data from an untrusted source - don't use string formatting to create SQL statements - use the two-argument form of execute() to pass args as a sequence - AFAIK there is no generally accepted, secure sandbox for running untrusted Python code (other than Google App Engine I guess) so don't run untrusted code Kent _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From zstumgoren at gmail.com Tue Oct 13 17:49:18 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 13 Oct 2009 11:49:18 -0400 Subject: [Tutor] [OT] Secure coding guidelines In-Reply-To: References: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> <1c2a2c590910101752l406a3ad1xbf947da7217958ab@mail.gmail.com> Message-ID: > In reference to this tip, ?my question is why? > - don't use string formatting to create SQL statements - use the > two-argument form of execute() to pass args as a sequence > SQL injection is the primary reason: http://en.wikipedia.org/wiki/SQL_injection If you are going to "manually" hit a database by constructing your own SQL calls, it's generally safer to pass in a tuple of parameters. The below is an excerpt from the Python Docs for sqlite3: http://docs.python.org/library/sqlite3.html <> Usually your SQL operations will need to use values from Python variables. You shouldn?t assemble your query using Python?s string operations because doing so is insecure; it makes your program vulnerable to an SQL injection attack. Instead, use the DB-API?s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor?s execute() method. (Other database modules may use a different placeholder, such as %s or :1.) For example: # Never do this -- insecure! symbol = 'IBM' c.execute("... where symbol = '%s'" % symbol) # Do this instead t = (symbol,) c.execute('select * from stocks where symbol=?', t) # Larger example for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ]: c.execute('insert into stocks values (?,?,?,?,?)', t) <> You're other option is to use some type of object relational mapper, such as SQL Alchemy or Django's ORM, to hit the database. You use that language's database-query language, which in turn constructs the SQL calls for you in a (hopefully) safe manner. From davea at ieee.org Tue Oct 13 17:50:56 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Oct 2009 11:50:56 -0400 Subject: [Tutor] Changing text colors on WinXP py2.6.2 In-Reply-To: <4AD471E6.7050304@timgolden.me.uk> References: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> <4AD457A7.5030301@timgolden.me.uk> <4AD471E6.7050304@timgolden.me.uk> Message-ID: <4AD4A1E0.4060807@ieee.org> Tim Golden wrote: >
Alan > Gauld wrote: >> "Tim Golden" wrote >>> No. ANSI escapes don't work on Windows. >> >> Wouldn't the ANSI codes work if ANSI.SYS were loaded? >> I thought you could still load ANSI.SYS it just wasn't normally >> there? The help system says you should load it in config.nt with: >> >> device=c:\winnt\system32\ansi.sys >> But I admit I've never tried it - I didn't even like ANSI.SYS when I >> was using DOS! > > > (from memory). I'm fairly sure that even that > no longer works. When this question last came > up I think we went round that loop and discovered > that it didn't. Happy to be wrong. :) > > TJG > > (Also from memory). ANSI.SYS is still available in XP, but only for 16 bit DOS apps. See: http://support.microsoft.com/kb/101875 So it wouldn't be useful for Python apps like the OP had. In particular, you can load a COMMAND.COM shell with ANSI.SYS driver in that (16bit) process. What ought to work is a 3rd party console replacement. One example of such a replacement (from an old established company) is "Take Command" (formerly 4NT) from http://www.jpsoft.com/ However, it appears that they only support ANSI sequences in output from their built-in commands, such as TYPE. See: http://www.jpsoft.com/help/index.htm?ansisupport.htm Other things to consider: cygwin http://www.softpedia.com/get/System/System-Miscellaneous/ANSICON.shtml http://www.codeplex.com/poshconsole/ I make no promises as to compatibility, safety, or performance, though. I haven't used any of these, except older versions of 4NT. To change text colors in a standard console, you need to use the Console API. Of course, you can change them for the entire console with the Properties dialog. DaveA From alan.gauld at btinternet.com Tue Oct 13 18:36:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Oct 2009 17:36:55 +0100 Subject: [Tutor] Changing text colors on WinXP py2.6.2 References: <0B0688DA463B4FEDB4F3C878014EE426@COMPUTER01> <4AD457A7.5030301@timgolden.me.uk> <4AD471E6.7050304@timgolden.me.uk> <4AD4A1E0.4060807@ieee.org> Message-ID: "Dave Angel" wrote > Other things to consider: > > cygwin curses works on cygwin too so a much wider set of choices there. Alan G From ciik13 at gmail.com Tue Oct 13 20:01:31 2009 From: ciik13 at gmail.com (David Eric) Date: Tue, 13 Oct 2009 14:01:31 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory Message-ID: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> doing a python tutorial and one of the assignments says to develop a program that backsup files to zip files into a backup directory im using Darwin 10.0.0 unix version: this is what i came up with thus far, i did copy the sample program given but made changes for my unix OS: #!/usr/bin/env python # Filename : backup_prog.py import os import time source = '/Users/davidteboul/bin/python' target_dir = '/Users/davidteboul/backups' target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.gz' zip_command = "gzip -qr {0} {1}".format(target, ' '.join(source)) if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup FAILED') i ran it and my computer went nuts!..its started trying to gzip every file on my computer...luckily it said access denied oneverything but i dont understand why it would zip files that i didnt even specify..is it the 'r' comman in the gzip command line that prompted this? ill cut and paste partial piece of what came up in terminal: gzip: /Users/davidteboul/backups/20091013134804.gz: No such file or directory gzip: //.file: Permission denied gzip: //.fseventsd: Permission denied gzip: //.hotfiles.btree: Permission denied gzip: //.Spotlight-V100: Permission denied gzip: //.Trashes: Permission denied gzip: //Applications/Address Book.app/Contents/_CodeSignature/CodeResources.gz: Permission denied gzip: //Applications/Address Book.app/Contents/CodeResources: Too many levels of symbolic links gzip: //Applications/Address Book.app/Contents/Info.plist.gz: Permission denied gzip: //Applications/Address Book.app/Contents/MacOS/Address Book.gz: Permission denied gzip: //Applications/Address Book.app/Contents/PkgInfo.gz: Permission denied gzip: //Applications/Address Book.app/Contents/Resources/AB16.png.gz: Permission denied gzip: //Applications/Address Book.app/Contents/Resources/ABAccountsPreferencesModule.png.gz: Permission denied gzip: //Applications/Address Book.app/Contents/Resources/ABCertificate.tiff.gz: Permission denied gzip: //Applications/Address Book.app/Contents/Resources/AddButton.tif.gz: Permission denied but it went on for about 1000 lines if not more -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Oct 13 20:31:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Oct 2009 14:31:54 -0400 Subject: [Tutor] [OT] Secure coding guidelines In-Reply-To: References: <62d32bf20910100231o51187307sde4bb4099f3ee505@mail.gmail.com> <1c2a2c590910101752l406a3ad1xbf947da7217958ab@mail.gmail.com> Message-ID: <1c2a2c590910131131q511b0v2e67a4d25ae6d1fe@mail.gmail.com> On Tue, Oct 13, 2009 at 11:49 AM, Serdar Tumgoren wrote: >> In reference to this tip, ?my question is why? > >> - don't use string formatting to create SQL statements - use the >> two-argument form of execute() to pass args as a sequence >> > > SQL injection is the primary reason: > > http://en.wikipedia.org/wiki/SQL_injection And the classic xkcd: http://xkcd.com/327/ I'm not sure about this, but I think there is also a possible performance boost if you are executing the same SQL with different parameters; if the parameters are not part of the SQL then there is some pre-processing that can be cached and re-used. Kent From kent37 at tds.net Tue Oct 13 20:42:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Oct 2009 14:42:35 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> Message-ID: <1c2a2c590910131142y41939727j1c0214d39daa51b3@mail.gmail.com> On Tue, Oct 13, 2009 at 2:01 PM, David Eric wrote: > doing a python tutorial and one of the assignments says to develop a program > that backsup files to zip files into a backup directory > > im using Darwin 10.0.0 unix version: > > this is what i came up with thus far, i did copy the sample program given > but made changes for my unix OS: > > #!/usr/bin/env python > # Filename : backup_prog.py > > > import os > import time > > source = '/Users/davidteboul/bin/python' > > target_dir = '/Users/davidteboul/backups' > > target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.gz' > > zip_command = "gzip -qr {0} {1}".format(target, ' '.join(source)) Two problems: - gzip operates on single files, if you want to gzip multiple files you should tar them first. That is why it gives you the initial file not found. From 'man gzip': Whenever possible, each file is replaced by one with the extension .gz, while keeping the same ownership modes, access and modification times. - the ' '.join(source) shouldn't be there In [25]: source = '/Users/davidteboul/bin/python' In [26]: ' '.join(source) Out[26]: '/ U s e r s / d a v i d t e b o u l / b i n / p y t h o n' Here is zip_command: 'gzip -qr /Users/davidteboul/backups\\20091013143741.gz / U s e r s / d a v i d t e b o u l / b i n / p y t h o n' > i ran it and my computer went nuts!..its started trying to gzip every file > on my computer...luckily it said access denied oneverything but i dont > understand why it would zip files that i didnt even specify..is it the 'r' > comman in the gzip command line that prompted this? The incorrect command line combined with -r Next time, you might want to print the command line before going live with it ;-) Kent From the_only_katala at verizon.net Tue Oct 13 20:44:47 2009 From: the_only_katala at verizon.net (Katt) Date: Tue, 13 Oct 2009 11:44:47 -0700 Subject: [Tutor] Shebang (#!) in the first line of a python script References: Message-ID: > Message: 2 > Date: Tue, 13 Oct 2009 06:24:42 -0400 > From: Dave Angel > To: Alan Gauld > Cc: tutor at python.org, Katt > Subject: Re: [Tutor] Shebang (#!) in the first line of a python script > Message-ID: <4AD4556A.2020406 at ieee.org> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Alan Gauld wrote: >> "Katt" wrote >> >>> Okay. So if I were to place the following in my Windows XP py v.2.6.2 : >>> >>> $ (name of python script) >>> >>> Then as long as python was in my path I would be able to type the >>> name of the script like a Dos batch file (ex: lowertoupper.py or >>> lowertoupper) instead of having to type python lowertoupper.py? And >>> it will run as normal? >> >> The shebang line does nothing on Windows, it is just a comment. >> Windows uses the file extension so, provided you end the file in .py, >> you can just type in the name of the script and Windows will use the >> file association to find the interpreter. >> > As Alan says, the default shells in Windows ignore the shebang line. So > unless you have a custom shell installed, you need to understand the > Windows pattern. > > They have another mechanism, which involves two registry entries and an > environment variable. The registry entries can easily be manipulated > using the utility programs assoc.exe and ftype.exe. However, as long as > you have a single Python installation, these are probably already setup > for you. If you have more than one Python version installed, you might > need to use ftype to switch which one is your default. > > As long as you're using this mechanism, python.exe does *not* have to be > on your PATH. The full path location of python.exe is set up by ftype. > You may want your script(s) to be on your PATH of course. > > The environment variable is used to avoid the need to type the > extension. This is *not* set up by default in the Python installation, > at least in my experience. But you can easily do it yourself. The > environment variable PATHEXT has a list of extensions that it will > search for. > > Mine looks like: > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.PY;.PYW > > Yours probably doesn't yet have the last two entries, and the others > might be somewhat different as well. > > With .py in this variable, you can type lowertoupper instead of > lowertoupper.py > > DaveA > You were right. I did not have .PY/.PYW in my PATHEXT. I have put it in as suggested. I do have python.exe in my path so that should take care of things. Messing around with the windows registry isn't something I want to tackle just yet so I will save that for later. Thank you for your help, Katt From davea at ieee.org Tue Oct 13 21:23:11 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Oct 2009 15:23:11 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> Message-ID: <4AD4D39F.5060101@ieee.org> David Eric wrote: > doing a python tutorial and one of the assignments says to develop a program > that backsup files to zip files into a backup directory > > im using Darwin 10.0.0 unix version: > > this is what i came up with thus far, i did copy the sample program given > but made changes for my unix OS: > > #!/usr/bin/env python > # Filename : backup_prog.py > > > import os > import time > > source = '/Users/davidteboul/bin/python' > > target_dir = '/Users/davidteboul/backups' > > target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.gz' > > zip_command = "gzip -qr {0} {1}".format(target, ' '.join(source)) > > if os.system(zip_command) == 0: > print('Successful backup to', target) > else: print('Backup FAILED') > > > When launching external programs you're not familiar with, you really need to do a dry-run test, just to be sure. It wouldn't have been hard to come up with something that trashes your system. (Ask me, I issued a Unix command once that was deleting all files in a valuable tree, and the only thing that saved my bacon was that Unix file I/O was so slow. It only did about two files per second, so I was able to Ctrl-C after only losing about 5 files, all of which were quickly recoverable. The next directory down would have been a disaster, however, and had it completed, we would have had to restore from the previous night's nightly backup, effectively wasting the day for most employees.) I see two problems, but since I don't know gzip, there may very well be more. The -r switch on nearly all Unix utilities means "recurse" which means to process all subdirectories of the starting location. The ' '.join(source) takes your source string, and puts spaces as every second character. The only thing I can think of you might have meant was to pass it a list of strings. So if source were source = ['/Users/davidteboul/bin/python', '/Users/davidteboul/bin/perl'] then it'd make sense. Anyway, I'd launch some innocuous script, that echoes its arguments, rather than trying it directly on gzip. And of course, I'd look at the man page for gzip, to see just what its arguments are supposed to look like. DaveA From the_only_katala at verizon.net Tue Oct 13 21:55:58 2009 From: the_only_katala at verizon.net (Katt) Date: Tue, 13 Oct 2009 12:55:58 -0700 Subject: [Tutor] Changing colors using WinXP py2.6.2 References: Message-ID: <079D76EF8528488C9E424899A1C7D500@COMPUTER01> > Message: 3 > Date: Tue, 13 Oct 2009 11:34:15 +0100 > From: Tim Golden > Cc: tutor at python.org > Subject: Re: [Tutor] Changing text colors on WinXP py2.6.2 > Message-ID: <4AD457A7.5030301 at timgolden.me.uk> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Katt wrote: >> Is it possible to change text color on a WinXP system by just using the >> Ansi >> escape codes. I have tried, but it just shows the start and end text of >> the >> code, but it doesn't change the color. > > No. ANSI escapes don't work on Windows. Depending on where > you want to go, you can look at the win32console module [1] > of the pywin32 package [2] or Fredrik Lundh's console [3] > module or Chris Gonnerman's wconio [4]. > > TJG > > [1] http://timgolden.me.uk/pywin32-docs/win32console.html > [2] http://sourceforge.net/projects/pywin32/ > [3] http://effbot.org/zone/console-index.htm > [4] http://newcenturycomputers.net/projects/wconio.html > > Thanks Tim G. and Alan G. I will check these four options out. Hopefully they won't be to difficult to incorporate into my beginner level programming :) Thanks to all for your help. It definitely makes a difference having this great support. Katt From davea at ieee.org Tue Oct 13 22:14:31 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Oct 2009 16:14:31 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <46e9bd9b0910131232i3a71a9eg79b51e6efa94f6c6@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> <4AD4D39F.5060101@ieee.org> <46e9bd9b0910131232i3a71a9eg79b51e6efa94f6c6@mail.gmail.com> Message-ID: <4AD4DFA7.7000207@ieee.org> (You top-posted, instead of adding your part to the end. That's frowned upon in a mailing list, at least in this one.) (You replied privately, and forgot to CC the tutor list. I'm forwarding it there with my response) David Eric wrote: > wow thank you > yes...youre right i did want to pass a list of strings > im copying the sample program and adding my own directories, i missed what > the example was trying to show in that instance. > as far as the recursive option, you mean the -r would process all > subdirectories under /Users? > im sorry for being so ignorant on this but what would be an example of an > innoucuous script? > > > > On Tue, Oct 13, 2009 at 3:23 PM, Dave Angel wrote: > > >> David Eric wrote: >> >> >>> doing a python tutorial and one of the assignments says to develop a >>> program >>> that backsup files to zip files into a backup directory >>> >>> im using Darwin 10.0.0 unix version: >>> >>> this is what i came up with thus far, i did copy the sample program given >>> but made changes for my unix OS: >>> >>> #!/usr/bin/env python >>> # Filename : backup_prog.py >>> >>> >>> import os >>> import time >>> >>> source = '/Users/davidteboul/bin/python' >>> >>> target_dir = '/Users/davidteboul/backups' >>> >>> target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.gz' >>> >>> zip_command = "gzip -qr {0} {1}".format(target, ' '.join(source)) >>> >>> if os.system(zip_command) == 0: >>> print('Successful backup to', target) >>> else: print('Backup FAILED') >>> >>> >>> >>> >>> >> When launching external programs you're not familiar with, you really need >> to do a dry-run test, just to be sure. It wouldn't have been hard to come >> up with something that trashes your system. (Ask me, I issued a Unix >> command once that was deleting all files in a valuable tree, and the only >> thing that saved my bacon was that Unix file I/O was so slow. It only did >> about two files per second, so I was able to Ctrl-C after only losing about >> 5 files, all of which were quickly recoverable. The next directory down >> would have been a disaster, however, and had it completed, we would have had >> to restore from the previous night's nightly backup, effectively wasting the >> day for most employees.) >> >> >> I see two problems, but since I don't know gzip, there may very well be >> more. >> >> The -r switch on nearly all Unix utilities means "recurse" which means to >> process all subdirectories of the starting location. >> >> The ' '.join(source) takes your source string, and puts spaces as every >> second character. The only thing I can think of you might have meant was to >> pass it a list of strings. So if source were >> source = ['/Users/davidteboul/bin/python', '/Users/davidteboul/bin/perl'] >> >> then it'd make sense. >> >> Anyway, I'd launch some innocuous script, that echoes its arguments, rather >> than trying it directly on gzip. And of course, I'd look at the man page >> for gzip, to see just what its arguments are supposed to look like. >> >> DaveA >> >> >> I haven't used Unix in over 15 years, so I don't remember. But I think it had something like 'echo' that simply echoed its arguments to stdout. In Windows, I'd make a one-line batch file like: Echo Running %0 script, with parameters %* or Echo Running %0 script, with parameters %1, %2, %3, %4, %5 The script could also display things like the current directory, maybe some environment variables. Whatever might be relevant to help see what's going on. The -r switch should mean to process all files in /Users/davidteboul/bin/python, plus all files in any of its subdirectories. Not starting at /Users, just starting in that ...../python directory. HTH DaveA From ciik13 at gmail.com Tue Oct 13 22:25:28 2009 From: ciik13 at gmail.com (David Eric) Date: Tue, 13 Oct 2009 16:25:28 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <4AD4DFA7.7000207@ieee.org> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> <4AD4D39F.5060101@ieee.org> <46e9bd9b0910131232i3a71a9eg79b51e6efa94f6c6@mail.gmail.com> <4AD4DFA7.7000207@ieee.org> Message-ID: <46e9bd9b0910131325n3e622fc8ob6737383cc4b26f1@mail.gmail.com> On Tue, Oct 13, 2009 at 4:14 PM, Dave Angel wrote: > (You top-posted, instead of adding your part to the end. That's frowned > upon in a mailing list, at least in this one.) > (You replied privately, and forgot to CC the tutor list. I'm forwarding it > there with my response) > > > David Eric wrote: > >> wow thank you >> yes...youre right i did want to pass a list of strings >> im copying the sample program and adding my own directories, i missed what >> the example was trying to show in that instance. >> as far as the recursive option, you mean the -r would process all >> subdirectories under /Users? >> im sorry for being so ignorant on this but what would be an example of an >> innoucuous script? >> >> >> >> On Tue, Oct 13, 2009 at 3:23 PM, Dave Angel wrote: >> >> >> >>> David Eric wrote: >>> >>> >>> >>>> doing a python tutorial and one of the assignments says to develop a >>>> program >>>> that backsup files to zip files into a backup directory >>>> >>>> im using Darwin 10.0.0 unix version: >>>> >>>> this is what i came up with thus far, i did copy the sample program >>>> given >>>> but made changes for my unix OS: >>>> >>>> #!/usr/bin/env python >>>> # Filename : backup_prog.py >>>> >>>> >>>> import os >>>> import time >>>> >>>> source = '/Users/davidteboul/bin/python' >>>> >>>> target_dir = '/Users/davidteboul/backups' >>>> >>>> target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.gz' >>>> >>>> zip_command = "gzip -qr {0} {1}".format(target, ' '.join(source)) >>>> >>>> if os.system(zip_command) == 0: >>>> print('Successful backup to', target) >>>> else: print('Backup FAILED') >>>> >>>> >>>> >>>> >>>> >>>> >>> When launching external programs you're not familiar with, you really >>> need >>> to do a dry-run test, just to be sure. It wouldn't have been hard to >>> come >>> up with something that trashes your system. (Ask me, I issued a Unix >>> command once that was deleting all files in a valuable tree, and the only >>> thing that saved my bacon was that Unix file I/O was so slow. It only >>> did >>> about two files per second, so I was able to Ctrl-C after only losing >>> about >>> 5 files, all of which were quickly recoverable. The next directory down >>> would have been a disaster, however, and had it completed, we would have >>> had >>> to restore from the previous night's nightly backup, effectively wasting >>> the >>> day for most employees.) >>> >>> >>> I see two problems, but since I don't know gzip, there may very well be >>> more. >>> >>> The -r switch on nearly all Unix utilities means "recurse" which means to >>> process all subdirectories of the starting location. >>> >>> The ' '.join(source) takes your source string, and puts spaces as every >>> second character. The only thing I can think of you might have meant was >>> to >>> pass it a list of strings. So if source were >>> source = ['/Users/davidteboul/bin/python', >>> '/Users/davidteboul/bin/perl'] >>> >>> then it'd make sense. >>> >>> Anyway, I'd launch some innocuous script, that echoes its arguments, >>> rather >>> than trying it directly on gzip. And of course, I'd look at the man >>> page >>> for gzip, to see just what its arguments are supposed to look like. >>> >>> DaveA >>> >>> >>> >>> >> I haven't used Unix in over 15 years, so I don't remember. But I think it > had something like 'echo' that simply echoed its arguments to stdout. In > Windows, I'd make a one-line batch file like: > > Echo Running %0 script, with parameters %* > > or > > Echo Running %0 script, with parameters %1, %2, %3, %4, %5 > > The script could also display things like the current directory, maybe some > environment variables. Whatever might be relevant to help see what's going > on. > > The -r switch should mean to process all files in > /Users/davidteboul/bin/python, plus all files in any of its subdirectories. > Not starting at /Users, just starting in that ...../python directory. > > HTH > DaveA > > Sorry about the top posting and not CC'ing tutor at python.org > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kreglet at gmail.com Tue Oct 13 22:10:39 2009 From: kreglet at gmail.com (kreglet) Date: Tue, 13 Oct 2009 13:10:39 -0700 (PDT) Subject: [Tutor] Dialogs Message-ID: <25879937.post@talk.nabble.com> I am having a problem with GtkDialogs. Ref: http://faq.pygtk.org/index.py?req=show&file=faq10.011.htp http://faq.pygtk.org/index.py?req=show&file=faq10.011.htp I want to add a treeview to the dialog. The first time btnDialog is pressed the dialog shows with the treeview in it. If I press btnDialog a second time the app closes and I get a "Segmentation fault" error. Without adding the treeview, the dialog works as expected. Do you have to destroy the widgets added to a dialog when you destroy the dialog? If so how? #!/usr/bin/env python import pygtk import gtk btnDialog = gtk.Button("Dialog") # list of items to display plist = gtk.ListStore(int, str) plist.append( (0, "Item 1",) ) plist.append( (1, "Item 2",) ) plist.append( (2, "Item 3",) ) # the Treeview treeview = gtk.TreeView() model = treeview.get_selection() model.set_mode(gtk.SELECTION_SINGLE) r = gtk.CellRendererText() treeview.insert_column_with_attributes(-1, "Items", r, text=1) treeview.set_model(plist) class NewWindow(gtk.Window): def btnDialogClick(self, widget): dialog = gtk.Dialog('Choose Item', self, # the window that spawned this dialog gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, ("Play Now", 77, gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) dialog.vbox.pack_start(gtk.Label('Do you want to play a game?')) dialog.vbox.pack_start(treeview) dialog.show_all() result = dialog.run() if result == 77: print "Play Button Clicked" elif result == gtk.RESPONSE_CLOSE: print "Close Button Clicked" dialog.destroy() #---------------------------------------------------------------- def __init__(self): super(NewWindow, self).__init__() self.set_title("test") self.set_size_request(1024, 768) self.set_keep_above(True) self.set_position(gtk.WIN_POS_CENTER) self.set_modal(True) fixed = gtk.Layout() fixed.put(btnDialog, 400, 5) btnDialog.connect("clicked", self.btnDialogClick) self.add(fixed) self.connect("destroy", gtk.main_quit) self.show_all() NewWindow() gtk.main() -- View this message in context: http://www.nabble.com/Dialogs-tp25879937p25879937.html Sent from the Python - tutor mailing list archive at Nabble.com. From yam at nerd.cx Tue Oct 13 22:22:15 2009 From: yam at nerd.cx (William Witteman) Date: Tue, 13 Oct 2009 16:22:15 -0400 Subject: [Tutor] Recursive user input collection problem Message-ID: <20091013202215.GA15650@yam.witteman.ca> I need to collect a couple of integers from a user, but I want to make sure that I actually get integers. I tried this, but subsequent calls to the function don't update variable. I'm not sure this is terribly clear - here's the code: num_of_articles = 0 num_of_reviewers = 0 def getinput(variable,prompt): """ Get the input by prompting the user and collecting the response - if it is a non-integer, try again. """ variable = 0 variable = raw_input(prompt) try: int(variable) return variable except ValueError: print("We need an integer (number) here.") getinput(variable,prompt) num_of_articles = getinput(num_of_articles,"Enter number of articles: ") num_of_reviewers = getinput(num_of_reviewers,"Enter number of reviewers: ") print(num_of_articles) print(num_of_reviewers) This works fine if I put in good input, but not if I pass in a bad value. Can anyone show me where I have gone astray? Thanks. -- yours, William From ciik13 at gmail.com Tue Oct 13 22:38:24 2009 From: ciik13 at gmail.com (David Eric) Date: Tue, 13 Oct 2009 16:38:24 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <1c2a2c590910131302y58c9c5e5na6950bb554658cae@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> <1c2a2c590910131142y41939727j1c0214d39daa51b3@mail.gmail.com> <46e9bd9b0910131158x5ddbf2a4iaf5447051327061e@mail.gmail.com> <1c2a2c590910131302y58c9c5e5na6950bb554658cae@mail.gmail.com> Message-ID: <46e9bd9b0910131338y71e8795ctcfac4481c18e06d8@mail.gmail.com> On Tue, Oct 13, 2009 at 4:02 PM, Kent Johnson wrote: > On Tue, Oct 13, 2009 at 2:58 PM, David Eric wrote: > > printing the command line, > > would it be > > print('gzip {0} {1}'.format(target, ' '.join(source))? > > Yes, or just > print zip_command > > > and as far as using the tar command, > > i have three files, > > file1,file2,file3 > > i wanted to preserve that structure, doesnt tar combine everything into > one > > file? > > Yes, tar makes a single file. Do you want to preserve the individual > files? Why did you have the .gz argument in your command line? Is that > supposed to be a directory name or a file name? > > My understanding of the man page is that gzip *replaces* files with > their gzipped version, so I guess if you want to back up a directory > to gzipped files you would have to first copy the directory, then > gzip. > > BTW you might like to look at the zipfile module as an alternative to gzip. > > Kent > > PS Please Reply All to reply to the list. > yes Dave told me to stop top posting and CC tutor at python.org..sorry about that i didnt know. as far as print zip_command, i would add that to the program however, doesnt just declaring it actually trigger it..thus it would executed and the command line would get printed as well? the actual program i was looking to write would take: file1,file2,and file3, in /Users/davidteboul/bin/python and condense them into individual files; file1.gz, file2.gz and file3.gz and save them in a directory already made - (/Users/davidteboul/backups) ps..did i post and reply all corretly? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Oct 13 22:02:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Oct 2009 16:02:31 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <46e9bd9b0910131158x5ddbf2a4iaf5447051327061e@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> <1c2a2c590910131142y41939727j1c0214d39daa51b3@mail.gmail.com> <46e9bd9b0910131158x5ddbf2a4iaf5447051327061e@mail.gmail.com> Message-ID: <1c2a2c590910131302y58c9c5e5na6950bb554658cae@mail.gmail.com> On Tue, Oct 13, 2009 at 2:58 PM, David Eric wrote: > printing the command line, > would it be > ?print('gzip {0} {1}'.format(target, ' '.join(source))? Yes, or just print zip_command > and as far as using the tar command, > i have three files, > file1,file2,file3 > i wanted to preserve that structure, doesnt tar combine everything into one > file? Yes, tar makes a single file. Do you want to preserve the individual files? Why did you have the .gz argument in your command line? Is that supposed to be a directory name or a file name? My understanding of the man page is that gzip *replaces* files with their gzipped version, so I guess if you want to back up a directory to gzipped files you would have to first copy the directory, then gzip. BTW you might like to look at the zipfile module as an alternative to gzip. Kent PS Please Reply All to reply to the list. From eike.welk at gmx.net Tue Oct 13 22:45:03 2009 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 13 Oct 2009 22:45:03 +0200 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> Message-ID: <200910132245.03386.eike.welk@gmx.net> Hello David! This is meant as an addition to Kent's remarks that 'gzip' is inappropriate, and you should use tar to create the archive. The 'tar' program can additionally use 'gzip' to compress the archive. A useful command would be: tar cvzf archive_name.tgz file_or_dir_1 file_or_dir_2 and_so_on tar czf .... does not print the filenames. See the manpage here: http://gd.tuwien.ac.at/linuxcommand.org/man_pages/tar1.html Ahem... I'm assuming that Mac OS X uses GNU tar, and not some other version of the program. In this case you must read its manpage and maybe need to use a pipe: tar c all_files_of_the_archive | gzip > archive_name.tgz Kind regards, Eike. From RWeidner at ea.com Tue Oct 13 22:52:32 2009 From: RWeidner at ea.com (Weidner, Ronald) Date: Tue, 13 Oct 2009 13:52:32 -0700 Subject: [Tutor] Recursive user input collection problem In-Reply-To: <20091013202215.GA15650@yam.witteman.ca> References: <20091013202215.GA15650@yam.witteman.ca> Message-ID: I didn't test this but shouldn't you have a line like this... return getinput(variable,prompt) -- Ronald Weidner -----Original Message----- From: tutor-bounces+rweidner=ea.com at python.org [mailto:tutor-bounces+rweidner=ea.com at python.org] On Behalf Of William Witteman Sent: Tuesday, October 13, 2009 4:22 PM To: tutor at python.org Subject: [Tutor] Recursive user input collection problem I need to collect a couple of integers from a user, but I want to make sure that I actually get integers. I tried this, but subsequent calls to the function don't update variable. I'm not sure this is terribly clear - here's the code: num_of_articles = 0 num_of_reviewers = 0 def getinput(variable,prompt): """ Get the input by prompting the user and collecting the response - if it is a non-integer, try again. """ variable = 0 variable = raw_input(prompt) try: int(variable) return variable except ValueError: print("We need an integer (number) here.") getinput(variable,prompt) num_of_articles = getinput(num_of_articles,"Enter number of articles: ") num_of_reviewers = getinput(num_of_reviewers,"Enter number of reviewers: ") print(num_of_articles) print(num_of_reviewers) This works fine if I put in good input, but not if I pass in a bad value. Can anyone show me where I have gone astray? Thanks. -- yours, William _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From christopher.henk at allisontransmission.com Tue Oct 13 22:54:16 2009 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Tue, 13 Oct 2009 16:54:16 -0400 Subject: [Tutor] Recursive user input collection problem In-Reply-To: <20091013202215.GA15650@yam.witteman.ca> Message-ID: > I need to collect a couple of integers from a user, but I want to make > sure that I actually get integers. I tried this, but subsequent calls > to the function don't update variable. I'm not sure this is terribly > clear - here's the code: > > num_of_articles = 0 > num_of_reviewers = 0 > > def getinput(variable,prompt): > """ > Get the input by prompting the user and collecting the response - if it is > a non-integer, try again. > """ > variable = 0 > variable = raw_input(prompt) > > try: > int(variable) > return variable > > except ValueError: > print("We need an integer (number) here.") > getinput(variable,prompt) > > > num_of_articles = getinput(num_of_articles,"Enter number of articles: ") > num_of_reviewers = getinput(num_of_reviewers,"Enter number of reviewers: ") > > print(num_of_articles) > print(num_of_reviewers) > > > This works fine if I put in good input, but not if I pass in a bad > value. Can anyone show me where I have gone astray? Thanks. > -- > > yours, > > William When the exception is thrown the "return variable" line is not executed. The path jumps down to the except block and runs that. Thus when you are unrolling the recursion the first getinput() does not return a value. A finally block after the exception block will execute whether or not the exception is thrown after the other code runs. You also need to assign the return value of getinput() within your except block. Finally there is no need to pass variable into the function as you immediately change it to zero. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Oct 13 22:54:32 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Oct 2009 16:54:32 -0400 Subject: [Tutor] Shebang (#!) in the first line of a python script In-Reply-To: References: Message-ID: <4AD4E908.8030709@ieee.org> Katt wrote: > > You were right. I did not have .PY/.PYW in my PATHEXT. I have put it > in as > suggested. I do have python.exe in my path so that should take care > of things. > > Messing around with the windows registry isn't something I want to > tackle just yet so I will save that for later. > > Thank you for your help, > > Katt You don't have to directly mess with the registry. But if you just enter the script name, you are causing the registry lookups just the same. As I said, the install took care of it for you, and you shouldn't have to change till you have two installs. But to re-iterate: When you run a script this way, the PATH is *not* used to look up the Python.exe, but only to search for the script. DaveA From davea at ieee.org Tue Oct 13 23:02:32 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Oct 2009 17:02:32 -0400 Subject: [Tutor] Recursive user input collection problem In-Reply-To: <20091013202215.GA15650@yam.witteman.ca> References: <20091013202215.GA15650@yam.witteman.ca> Message-ID: <4AD4EAE8.2080103@ieee.org> William Witteman wrote: > I need to collect a couple of integers from a user, but I want to make > sure that I actually get integers. I tried this, but subsequent calls > to the function don't update variable. I'm not sure this is terribly > clear - here's the code: > > num_of_articles = 0 > num_of_reviewers = 0 > > def getinput(variable,prompt): > """ > Get the input by prompting the user and collecting the response - if it is > a non-integer, try again. > """ > variable = 0 > variable = raw_input(prompt) > > try: > int(variable) > return variable > > except ValueError: > print("We need an integer (number) here.") > getinput(variable,prompt) > > > num_of_articles = getinput(num_of_articles,"Enter number of articles: ") > num_of_reviewers = getinput(num_of_reviewers,"Enter number of reviewers: ") > > print(num_of_articles) > print(num_of_reviewers) > > > This works fine if I put in good input, but not if I pass in a bad > value. Can anyone show me where I have gone astray? Thanks. > You called getinput() from inside getinput(), which is a recursive call. So what happens is whenever the user makes a mistake, you have two copies of the function running. And they get their own copies of variables, which isn't what you want in this case. What you want instead is to loop back to the beginning, not to call. In this simple case, you can simply enclose the entire function in a while True: loop. And when the exception happens, you loop around back to the beginning. DaveA From kent37 at tds.net Tue Oct 13 23:17:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Oct 2009 17:17:08 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <46e9bd9b0910131338y71e8795ctcfac4481c18e06d8@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> <1c2a2c590910131142y41939727j1c0214d39daa51b3@mail.gmail.com> <46e9bd9b0910131158x5ddbf2a4iaf5447051327061e@mail.gmail.com> <1c2a2c590910131302y58c9c5e5na6950bb554658cae@mail.gmail.com> <46e9bd9b0910131338y71e8795ctcfac4481c18e06d8@mail.gmail.com> Message-ID: <1c2a2c590910131417g1f559d38j66037de11e818bbb@mail.gmail.com> On Tue, Oct 13, 2009 at 4:38 PM, David Eric wrote: > as far as print zip_command, i would add that to the program however, doesnt > just declaring it actually trigger it..thus it would executed and the > command line would get printed as well? I'm not sure what you mean by "declaring", but assigning a value to zip_command, as you do, and printing it, as I suggest, do just that - assign and print. It is the call to os.system() that executes the command. > the actual program i was looking to write would take: > ?file1,file2,and file3, in /Users/davidteboul/bin/python > and condense them into individual files; file1.gz, file2.gz and file3.gz and > save them in a directory already made - (/Users/davidteboul/backups) I think that doing this with gzip, you have to first copy the files to the backup directory, then run gzip on the backup. > ps..did i post and reply all corretly? You can intersperse your comments with the original email, as I have done above, rather than putting your entire reply at the end. The reply all is fine. Kent From ciik13 at gmail.com Tue Oct 13 23:38:10 2009 From: ciik13 at gmail.com (David Eric) Date: Tue, 13 Oct 2009 17:38:10 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <1c2a2c590910131417g1f559d38j66037de11e818bbb@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> <1c2a2c590910131142y41939727j1c0214d39daa51b3@mail.gmail.com> <46e9bd9b0910131158x5ddbf2a4iaf5447051327061e@mail.gmail.com> <1c2a2c590910131302y58c9c5e5na6950bb554658cae@mail.gmail.com> <46e9bd9b0910131338y71e8795ctcfac4481c18e06d8@mail.gmail.com> <1c2a2c590910131417g1f559d38j66037de11e818bbb@mail.gmail.com> Message-ID: <46e9bd9b0910131438p21f8c5oe3f1ac10df924362@mail.gmail.com> On Tue, Oct 13, 2009 at 5:17 PM, Kent Johnson wrote: > On Tue, Oct 13, 2009 at 4:38 PM, David Eric wrote: > > > as far as print zip_command, i would add that to the program however, > doesnt > > just declaring it actually trigger it..thus it would executed and the > > command line would get printed as well? > > I'm not sure what you mean by "declaring", but assigning a value to > zip_command, as you do, and printing it, as I suggest, do just that - > assign and print. It is the call to os.system() that executes the > command. > > oh i see the if os.sytem() command in the program is what ran the > zip_command > > > the actual program i was looking to write would take: > > file1,file2,and file3, in /Users/davidteboul/bin/python > > and condense them into individual files; file1.gz, file2.gz and file3.gz > and > > save them in a directory already made - (/Users/davidteboul/backups) > > I think that doing this with gzip, you have to first copy the files to > the backup directory, then run gzip on the backup. > > > > ps..did i post and reply all corretly? > > You can intersperse your comments with the original email, as I have > done above, rather than putting your entire reply at the end. The > reply all is fine. > > Kent > thanks for the help, ill try some stuff and see if i can get it to work -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Oct 14 01:53:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Oct 2009 00:53:29 +0100 Subject: [Tutor] Recursive user input collection problem References: <20091013202215.GA15650@yam.witteman.ca> Message-ID: "William Witteman" wrote > I want to make sure that I actually get integers. > num_of_articles = 0 > num_of_reviewers = 0 > > def getinput(variable,prompt): > """ > Get the input by prompting the user and collecting the response - if it > is > a non-integer, try again. > """ > variable = 0 > variable = raw_input(prompt) > > try: > int(variable) > return variable The normal way in Python would be to combine this with try: return int(raw_input(....)) except ValueError: blah... > except ValueError: > print("We need an integer (number) here.") > getinput(variable,prompt) You don;t return the value from getinput(). Just add a return in front of the call... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mystylplx at gmail.com Wed Oct 14 02:29:57 2009 From: mystylplx at gmail.com (Scott Markwell) Date: Tue, 13 Oct 2009 17:29:57 -0700 Subject: [Tutor] Shebang (#!) in the first line of a python script In-Reply-To: <4AD4E908.8030709@ieee.org> References: <4AD4E908.8030709@ieee.org> Message-ID: On Tue, Oct 13, 2009 at 1:54 PM, Dave Angel wrote: > Katt wrote: > >> >> You were right. I did not have .PY/.PYW in my PATHEXT. I have put it in >> as >> suggested. I do have python.exe in my path so that should take care of >> things. >> >> Messing around with the windows registry isn't something I want to tackle >> just yet so I will save that for later. >> >> Thank you for your help, >> >> Katt >> > You don't have to directly mess with the registry. But if you just enter > the script name, you are causing the registry lookups just the same. As I > said, the install took care of it for you, and you shouldn't have to change > till you have two installs. > > But to re-iterate: When you run a script this way, the PATH is *not* used > to look up the Python.exe, but only to search for the script. > > DaveA > > You can do it strictly through the explorer. Right click on any .py or .pyw file and select 'properties.' Where it says 'open with' click 'change.' In the dialog select 'other' and browse to python.exe. Make sure it's the python.exe from the version you want to use. I just installed python 2.6 and had to do that and set the paths manually as for some reason the installer didn't do it for me. (oops hit "reply" the first time instead of "reply all." New to this mailing list thing.) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- This just goes to show that there's nothing an agnostic can't do if he really doesn't know if he believes in anything or not. ~Monty Python -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Oct 14 03:31:57 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 13 Oct 2009 21:31:57 -0400 Subject: [Tutor] Shebang (#!) in the first line of a python script In-Reply-To: References: <4AD4E908.8030709@ieee.org> Message-ID: <4AD52A0D.70300@ieee.org> Scott Markwell wrote: > On Tue, Oct 13, 2009 at 1:54 PM, Dave Angel wrote: > > >> Katt wrote: >> >> >>> >>> You were right. I did not have .PY/.PYW in my PATHEXT. I have put it in >>> as >>> suggested. I do have python.exe in my path so that should take care of >>> things. >>> >>> Messing around with the windows registry isn't something I want to tackle >>> just yet so I will save that for later. >>> >>> Thank you for your help, >>> >>> Katt >>> >>> >> You don't have to directly mess with the registry. But if you just enter >> the script name, you are causing the registry lookups just the same. As I >> said, the install took care of it for you, and you shouldn't have to change >> till you have two installs. >> >> But to re-iterate: When you run a script this way, the PATH is *not* used >> to look up the Python.exe, but only to search for the script. >> >> DaveA >> >> >> > You can do it strictly through the explorer. Right click on any .py or .pyw > file and select 'properties.' Where it says 'open with' click 'change.' In > the dialog select 'other' and browse to python.exe. Make sure it's the > python.exe from the version you want to use. > > I just installed python 2.6 and had to do that and set the paths manually as > for some reason the installer didn't do it for me. > > (oops hit "reply" the first time instead of "reply all." New to this mailing > list thing.) > > >> _ Presumably the reason your python upgrade didn't change them is you told the installer that you didn't want it to be the default installation. As you say, you can fix that in Explorer. But you can also use assoc.exe and ftype.exe The reason I prefer assoc and ftype is that they're command line utilities that fix the associations. Thus simple batch files of pythons scripts can switch things back and forth once you need the extra flexibility. DaveA From fomcl at yahoo.com Wed Oct 14 09:42:02 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 14 Oct 2009 00:42:02 -0700 (PDT) Subject: [Tutor] GUI Buttons In-Reply-To: Message-ID: <872737.68591.qm@web110709.mail.gq1.yahoo.com> Hi Alan and Kent, Thank you for helping me. This is a lot simpler than the solution I had in mind. The button names in my program always start with "button_", so I wanted to use locals() in a list comprehension to compile a list of the buttons. But then I'd still have the names and not the instances. But when is the configure() method more appropriate to change e.g. the button status? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before you criticize someone, walk a mile in their shoes, that way when you do criticize them, you're a mile away and you have their shoes! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Tue, 10/13/09, Alan Gauld wrote: > From: Alan Gauld > Subject: [Tutor] GUI Buttons > To: tutor at python.org > Date: Tuesday, October 13, 2009, 10:06 AM > Please provide a subject when sending > mail to the list. > And please create a new message so it doesn't get lost in > an old thread... > > "Albert-Jan Roskam" > wrote in message > > > I'm using Tkinter to program my very frist GUI. > > Each button grays out after it has been used so the > user knows what next steps to take. > > Now I want to define a Reset button to 'ungray' all > buttons (state='normal'). > > How can I programmatically create a list of all > available buttons? > > Just add your buttons to a list when you create them > Then in your reset method do > > for button in ButtonList: > ???button['state'] = NORMAL > > HTH, > > > -- Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Wed Oct 14 09:49:26 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 14 Oct 2009 07:49:26 +0000 (GMT) Subject: [Tutor] GUI Buttons In-Reply-To: <872737.68591.qm@web110709.mail.gq1.yahoo.com> References: <872737.68591.qm@web110709.mail.gq1.yahoo.com> Message-ID: <259567.49064.qm@web86708.mail.ird.yahoo.com> > But when is the configure() method more appropriate to change e.g. the button > status? configure is better when you need to change more than one attribute of a widget at a time. The dictionary style access is just a convenience feature. If you prefer you can use configure() all the time. Alan G. > > > How can I programmatically create a list of all > > available buttons? > > > > Just add your buttons to a list when you create them > > Then in your reset method do > > > > for button in ButtonList: > > button['state'] = NORMAL > > From david at pythontoo.com Wed Oct 14 10:43:52 2009 From: david at pythontoo.com (David) Date: Wed, 14 Oct 2009 04:43:52 -0400 Subject: [Tutor] writing sample program that zips files and saves in a backup directory In-Reply-To: <46e9bd9b0910131438p21f8c5oe3f1ac10df924362@mail.gmail.com> References: <46e9bd9b0910131101p13070e3ekaead9485c1f9645@mail.gmail.com> <1c2a2c590910131142y41939727j1c0214d39daa51b3@mail.gmail.com> <46e9bd9b0910131158x5ddbf2a4iaf5447051327061e@mail.gmail.com> <1c2a2c590910131302y58c9c5e5na6950bb554658cae@mail.gmail.com> <46e9bd9b0910131338y71e8795ctcfac4481c18e06d8@mail.gmail.com> <1c2a2c590910131417g1f559d38j66037de11e818bbb@mail.gmail.com> <46e9bd9b0910131438p21f8c5oe3f1ac10df924362@mail.gmail.com> Message-ID: <4AD58F48.5000003@pythontoo.com> David Eric wrote: > > > On Tue, Oct 13, 2009 at 5:17 PM, Kent Johnson > wrote: > > On Tue, Oct 13, 2009 at 4:38 PM, David Eric > wrote: > > > as far as print zip_command, i would add that to the program > however, doesnt > > just declaring it actually trigger it..thus it would executed and the > > command line would get printed as well? > > I'm not sure what you mean by "declaring", but assigning a value to > zip_command, as you do, and printing it, as I suggest, do just that - > assign and print. It is the call to os.system() that executes the > command. > > > > oh i see the if os.sytem() command in the program is what ran the > zip_command > > > > > the actual program i was looking to write would take: > > file1,file2,and file3, in /Users/davidteboul/bin/python > > and condense them into individual files; file1.gz, file2.gz and > file3.gz and > > save them in a directory already made - (/Users/davidteboul/backups) > > I think that doing this with gzip, you have to first copy the files to > the backup directory, then run gzip on the backup. > > > > > ps..did i post and reply all corretly? > > You can intersperse your comments with the original email, as I have > done above, rather than putting your entire reply at the end. The > reply all is fine. > > Kent > > > thanks for the help, ill try some stuff and see if i can get it to work > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Has anyone mentioned the module zipfile; http://www.doughellmann.com/PyMOTW/zipfile/index.html -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From lie.1296 at gmail.com Wed Oct 14 10:54:01 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 14 Oct 2009 19:54:01 +1100 Subject: [Tutor] Switching to other version of Python In-Reply-To: References: <4AD392BC.3080506@aim.com> Message-ID: Alan Gauld wrote: > > "Corey Richardson" wrote >> My school has python 2.4. I have python 2.6, and I find it perfectly >> wonderful. However, I am contemplating the switch, and am wondering, >> what is your personal opinion on why or why not to use 3.x? Thanks for >> the help in advance, > > Well your Python 3 programs won't run as expected on your school v2.4 > and your schoool programs won;t run at all on your python v3. > > So I'd stay well clear of v3 for now. There is no compelling reason to > switch yet. > > You could keep 2.6 on your own PC and use v3 of course but most of the > v3 stuff is available in 2.6. Also you could upgrade to 2.7 for even > more 3 compatibility but still better with 2.4 than using 3 would be. > > Resist the urge to upgrade just for the sake of it. > (Advice I fail to follow in HiFi but try to follow in everything else! :-) > You also have the option to install both and ignore one. It's not like a black-or-white choice. From lie.1296 at gmail.com Wed Oct 14 11:11:59 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 14 Oct 2009 20:11:59 +1100 Subject: [Tutor] Recursive user input collection problem In-Reply-To: <20091013202215.GA15650@yam.witteman.ca> References: <20091013202215.GA15650@yam.witteman.ca> Message-ID: William Witteman wrote: > I need to collect a couple of integers from a user, but I want to make > sure that I actually get integers. I tried this, but subsequent calls > to the function don't update variable. I'm not sure this is terribly > clear - here's the code: > > > def getinput(variable,prompt): > """ > Get the input by prompting the user and collecting the response - if it is > a non-integer, try again. > """ > variable = 0 the source of your confusion is misunderstanding of python's calling model. Here is an article: http://effbot.org/zone/call-by-object.htm From ljmamoreira at gmail.com Wed Oct 14 13:26:22 2009 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Wed, 14 Oct 2009 12:26:22 +0100 Subject: [Tutor] namespaces and global Message-ID: <200910141226.22567.ljmamoreira@gmail.com> Hello I'm new to this list. I tried to find the answer to my question but found nothing I could really use. I'm sorry if this is a FAQ. I want to use a variable defined in an interactive session with the python interpreter inside a function imported from a module. For instance, imagine that my module (call it defs.py, for instance) consists of: #coding=utf-8 def f(x): return a*x In an interactive session, I import my module: >>> from defs import f and I define a global variable a: >>> a=3 Now I call my module function, expecting to get the triple of the argument I feed it with, but, instead, I get an error: >>> f(2) Traceback (most recent call last): File "", line 1, in File "defs.py", line 3, in f return a*x NameError: global name 'a' is not defined >>> I tried using the global command in the module, both before the function definition and inside the function definition, but none worked as I expected. Of course I could redefine my module function, including the parameter a in the list of arguments, but I'd rather not. So, my question: is there any way of telling the interpreter to use the value of parameters defined in the interactive session when computing the value of a module function? Thanks ljma From kent37 at tds.net Wed Oct 14 14:01:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Oct 2009 08:01:17 -0400 Subject: [Tutor] namespaces and global In-Reply-To: <200910141226.22567.ljmamoreira@gmail.com> References: <200910141226.22567.ljmamoreira@gmail.com> Message-ID: <1c2a2c590910140501k1630c381yd4b8b7af8cec66ce@mail.gmail.com> On Wed, Oct 14, 2009 at 7:26 AM, Jose Amoreira wrote: > I want to use a variable defined in an interactive session with the python > interpreter inside a function imported from a module. > > For instance, imagine that my module (call it defs.py, for instance) consists > of: > #coding=utf-8 > def f(x): > ? ?return a*x > > In an interactive session, I import my module: >>>> from defs import f > and I define a global variable a: >>>> a=3 > Now I call my module function, expecting to get the triple of the argument I > feed it with, but, instead, I get an error: >>>> f(2) > Traceback (most recent call last): > ?File "", line 1, in > ?File "defs.py", line 3, in f > ? ?return a*x > NameError: global name 'a' is not defined >>>> > > I tried using the global command in the module, both before the function > definition and inside the function definition, but none worked as I expected. > Of course I could redefine my module function, including the parameter a in > the list of arguments, but I'd rather not. Python 'global' variables are not really global (everywhere accessible), they have module scope. So your function f() looks for the name 'a' first in its local scope, then in the scope of its containing module defs. It will not look in the namespace of the caller unless it is also in defs. > So, my question: is there any way of telling the interpreter to use the value > of parameters defined in the interactive session when computing the value of a > module function? Why do you want to do this? One option is to pass locals() in to the function. You can also access the caller's context through a stack frame. But both of these are unusual. Kent From greg at thewhittiers.com Wed Oct 14 15:55:37 2009 From: greg at thewhittiers.com (greg whittier) Date: Wed, 14 Oct 2009 09:55:37 -0400 Subject: [Tutor] Help or Advice on MySQL, Python and test data storage In-Reply-To: <4f5a5a4b0910080129o54ea70een628028011fc5b57d@mail.gmail.com> References: <4f5a5a4b0910080129o54ea70een628028011fc5b57d@mail.gmail.com> Message-ID: On Thu, Oct 8, 2009 at 4:29 AM, David Jamieson wrote: > Hi All, > looking for some advice on using Python with MySQL for test data > storage. > While not a relational database, you might also look at http://www.pytables.org. It provides a python interface for writing to and reading from hdf5 files (http://www.hdfgroup.org/HDF5/). -------------- next part -------------- An HTML attachment was scrubbed... URL: From digitalman66 at gmail.com Wed Oct 14 16:08:58 2009 From: digitalman66 at gmail.com (Glen Zangirolami) Date: Wed, 14 Oct 2009 09:08:58 -0500 Subject: [Tutor] Finding and Inserting missing dates in a date range. In-Reply-To: References: <24a9d1f30910091216q7173ee87y415571f42ca4c471@mail.gmail.com> <1c2a2c590910091343l549d05an2fad4033f3707f58@mail.gmail.com> <1255126288.8112.1339240893@webmail.messagingengine.com> <24a9d1f30910091515n429141e5l418dac1f06259d20@mail.gmail.com> Message-ID: <24a9d1f30910140708w3eb1120y68a19c37d448b591@mail.gmail.com> I went ahead and used a date range generator: http://dpaste.com/107140/ to iterate over the range.I then compared the original list with the generated one and inserted the missing dates. I was comparing the generated dates to dates in a list list of tuples: [(date, count), (date, count) ..... (date, count)] Here is the code: http://dpaste.com/107148/ Worked perfectly. Thanks for pointing me in the correct direction. -------------- next part -------------- An HTML attachment was scrubbed... URL: From yam at nerd.cx Wed Oct 14 16:48:09 2009 From: yam at nerd.cx (William Witteman) Date: Wed, 14 Oct 2009 10:48:09 -0400 Subject: [Tutor] Recursive user input collection problem In-Reply-To: References: <20091013202215.GA15650@yam.witteman.ca> Message-ID: <20091014144809.GA2657@yam.witteman.ca> Thanks to all who responded. There were several good points about the code itself, all of which both helped and work. I will likely use Alan's example because I find it the most lucid, but the other suggestions are good signposts to other ways to do the same thing (but right, as opposed to how I was doing it). Lie's suggestion that I didn't understand the calling structure of Python was right on the money, and his included link helps with that, too. Thanks again. -- yours, William From nrhird at gmail.com Wed Oct 14 17:38:28 2009 From: nrhird at gmail.com (Nick Hird) Date: Wed, 14 Oct 2009 11:38:28 -0400 Subject: [Tutor] Not storing the PATH in ZipFile? Message-ID: I was reading another thread and decided to work on a little project to backup some files on a regular basis. Since this will mostly be on windows i am using zipfile and i can create my zip file just fine and all the files are there, it works great! My question is however, is there a way to NOT store the path in the zip file? When i decompress the files, i would like them to not be associated with a particular folder or path, just the files. I looked through the docs but didn't see anything to disable the path. Thanks, -Nick From kent37 at tds.net Wed Oct 14 18:16:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Oct 2009 12:16:04 -0400 Subject: [Tutor] Not storing the PATH in ZipFile? In-Reply-To: References: Message-ID: <1c2a2c590910140916m96143aejf7e98e5f91efa9b0@mail.gmail.com> On Wed, Oct 14, 2009 at 11:38 AM, Nick Hird wrote: > I was reading another thread and decided to work on a little project > to backup some files on a regular basis. Since this will mostly be on > windows i am using zipfile and i can create my zip file just fine and > all the files are there, it works great! My question is however, is > there a way to NOT store the path in the zip file? When i decompress > the files, i would like them to not be associated with a particular > folder or path, just the files ZipFile.write() takes an optional arcname parameter, this is the name the file wll have in the archive. If you pass the plain file name (no path components) as arcname I think it will do what you want. Kent From nrhird at gmail.com Wed Oct 14 18:37:17 2009 From: nrhird at gmail.com (Nick Hird) Date: Wed, 14 Oct 2009 12:37:17 -0400 Subject: [Tutor] Not storing the PATH in ZipFile? In-Reply-To: <1c2a2c590910140916m96143aejf7e98e5f91efa9b0@mail.gmail.com> References: <1c2a2c590910140916m96143aejf7e98e5f91efa9b0@mail.gmail.com> Message-ID: That was it. Thanks so much! I was looking at the docs and didn't think that applied to the path that was stored. Thanks Again! -Nick On Wed, Oct 14, 2009 at 12:16 PM, Kent Johnson wrote: > On Wed, Oct 14, 2009 at 11:38 AM, Nick Hird wrote: >> I was reading another thread and decided to work on a little project >> to backup some files on a regular basis. Since this will mostly be on >> windows i am using zipfile and i can create my zip file just fine and >> all the files are there, it works great! My question is however, is >> there a way to NOT store the path in the zip file? When i decompress >> the files, i would like them to not be associated with a particular >> folder or path, just the files > > ZipFile.write() takes an optional arcname parameter, this is the name > the file wll have in the archive. If you pass the plain file name (no > path components) as arcname I think it will do what you want. > > Kent > -- --Nick From the_only_katala at verizon.net Wed Oct 14 18:38:00 2009 From: the_only_katala at verizon.net (Katt) Date: Wed, 14 Oct 2009 09:38:00 -0700 Subject: [Tutor] PyWin32 - Library of functions to interact with windows? References: Message-ID: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> Hello all, I am currently using WinXP and python 2.6.2 I just installed PyWin32 v214 for python 2.6 from the following link: http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/pywin32-214.win32-py2.6.exe/download Installation seemed to go good as it walked me through while locating my python directory and checking my path. I tried to first to download/save and then run it, but encountered an error and it would not install. When I went back to the link and then clicked "run" instead of save the installation worked. Now I find myself scratching my head and saying to myself: "now what?" Your probably thinking - Dive into the documentation, Search the web, Ask questions. I have looked a bit at the documentation. It definitely seems to believe that I am already a seasoned programmer. Searching the web I have found a lot of general information or overly specific with no way to narrow my search to what I am looking for. I am not sure, but it seems very difficult just to search for a way to change the color of my text. Don't get me wrong. I don't want someone to hand me some code snippet of what I need. I am just looking for an interpreter to translate from computer scientist to beginner. Thus I am hopeful that Asking questions will yield information that I can understand. I am not saying that there is anything wrong with what I have found. I am only saying that my comprehension is not there yet to that level. Looking at the included compiled documentation I think I found what I am looking for. Please let me know if I am incorrect. Searching under "change the color" revealed several topics. I singled out win32gui.SetTextColor. This brought me to the topic "win32api.RGB" and shows the next line as "int = RGB(red,green,blue). Question 1: Did I locate the correct function that I need to use in order to change the color of text within a print ""? Question 2: In order to use this would I just import it? (ie - from win32api import RGB) Question 3: If the above 2 are correct is it just a matter of doing the following: print "The remaining number of apples is: "RGB(red),number_apples The above print statement would yield just the number_apples variable in red text. Thanks in advance, Katt From alan.gauld at btinternet.com Wed Oct 14 19:18:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Oct 2009 18:18:28 +0100 Subject: [Tutor] namespaces and global References: <200910141226.22567.ljmamoreira@gmail.com> Message-ID: "Jose Amoreira" wrote > Of course I could redefine my module function, including the parameter a > in > the list of arguments, but I'd rather not. Why not? That would be good computer science practice and the most reliable way to do it. Why do you not want to go down that route? Is there a specific reason to use a global variable when use of globals is normally considered bad practice? I'm curious? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Oct 14 19:38:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Oct 2009 18:38:31 +0100 Subject: [Tutor] PyWin32 - Library of functions to interact with windows? References: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> Message-ID: "Katt" wrote > I am currently using WinXP and python 2.6.2 > I just installed PyWin32 v214 for python 2.6 from the following link: Well done! :-) > Now I find myself scratching my head and saying to myself: "now what?" Good question. Why did you download and install it? Did you have a specific need or did it just seem like a good idea at the time? If the latter then the best thing to do is just ignore it unttil you have a need. Except for the Pythonwin editor which is far superior to IDLE IMHO. Definitely have a play with that. > I have looked a bit at the documentation. It definitely seems to believe > that I am already a seasoned programmer. Yes, pywin is a set of modules to let you access the Win32 API - the raw Operating System calls that are used by C programmers writing things like MS Word and IE etc. The typical Windows Python user rarely needs access to that stuff. The exceptions are if you are writing sys admin type tasks on Windows. > Searching the web I have found a lot of general information or overly > specific with no way to narrow my search to what I am looking for. I am > not sure, but it seems very difficult just to search for a way to change > the color of my text. That would normally be done using the GUI tookit you are using - Tkinter, wxPython etc - you don't need the Win32 API for that the toolkit does that for you. > code snippet of what I need. I am just looking for an interpreter to > translate from computer scientist to beginner. The best bet is to find a book on basic Windows programming. Pwetzold's "Programming Windows" used to be the Bible for this but I suspect it has now been superceded. There are probably online tutorials to writing MFC applications that you could translate fairly directly. The other area that you can and should use pyWin32 is in interacting with Windows apps via COM. Mark Hammond's book "Python Programming on Win32" is the best source for that, but the docs that come with pyWin32 also cover it. BUt again they expect a certain amount of preknowledge. > I am not saying that there is anything wrong with what I have found. I > am only saying that my comprehension is not there yet to that level. pyWin32 is a powerful tool but it is not an easy one to use. > Looking at the included compiled documentation I think I found what I am > looking for. Please let me know if I am incorrect. > > Searching under "change the color" revealed several topics. I singled > out win32gui.SetTextColor. This brought me to the topic "win32api.RGB" > and > shows the next line as "int = RGB(red,green,blue). > > Question 1: Did I locate the correct function that I need to use in > order to change the color of text within a print ""? Probably not. print goes to stdout which on Windows is usually in a CMD shell window. the Win32API does not directl;y control that output. What you found is the way tochange the colour of a font inside a window - such as a data entry field in a form that you created. > Question 2: In order to use this would I just import it? (ie - from > win32api import RGB) No. You need to import the function as well as the values. Normally you impotrt the module and access the rest via that: import win32gui win32gui.SetTextColor(hdc, win32gui.RGB) or similar. Note that the first parameter is hdc which stahnds for Hamndle to a DeviceContext. A DeviceContext is the window you want to change the color of. So you first need to find a way of obtaining the hdc value. In your own app thats fairtly easy since you assign it to a variable when you create the window/widget. But trying to find the hdc for a cmd shell is very tricky, especially programatically at run time! > Question 3: If the above 2 are correct is it just a matter of doing the > following: > print "The remaining number of apples is: "RGB(red),number_apples No, thats no good, sorry. If you want to change the colour of text in a command window I think you are best investigating wconio or some of the other modules mentioned earlier. But it may not be possible for cmd.exe. The next step is to write a very simple GUI program with a single Text widget on which you write your output. Then you can colour it any way you like. Learning how to build GUIs wioll take a bit of effort but a lot less than trying to use the Win32API to modify a cmd window! Take a look at the Event driven oprogramming topic in my tutorial for an example of just that kind of GUI... You can use EasyGUI to capture user input. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sirgnip at gmail.com Wed Oct 14 20:26:00 2009 From: sirgnip at gmail.com (Scott Nelson) Date: Wed, 14 Oct 2009 13:26:00 -0500 Subject: [Tutor] PyWin32 - Library of functions to interact with windows? In-Reply-To: References: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> Message-ID: <2682ac9b0910141126l92789ft20314ad2d73d9013@mail.gmail.com> If I may chime in... As Alan said, pywin is basically a thin wrapper around the Win32 API. The Win32 API is very complex. Thus pywin is, by necessity, also very complex. There is documentation for pywin, but it is very minimal as you've probably noticed. If you are a *very* bold beginner with lots of patience, the best documentation for pywin is actually the documentation for the Win32 API itself found on Microsoft's "MSDN Library" website [1]. Navigating and using this documentation requires a knowledge of the Windows architecture and C programming. Once you find what you want in the MSDN documentation, you can usually find the same function in pywin. Again, this is not going to be easy if you are a beginner (it is difficult even for more experienced programmers), but I wanted to let you know the info is out there. If you want to dive into Win32 programming and learn the basics, the books Alan mentioned are good. But again, Win32 programming is pretty low-level and complex. There is usually an easier way to do most things you need to do. Especially if you want to create GUI's in Python, don't start with pywin and Win32. Use EasyGUI, Tkinter, or wxPython (in order of easiest to most powerful) Now, back to your specific task. To clarify, I'm assuming you want to color the text that shows up in Window's console when you do "print" from Python, correct? It *is* possible to color console text with Python and pywin. But, it is tricky and not obvious. I've been wondering how to do this myself and I recently found some C code on the web [2] that does this and I translated that into to Python and pywin. It can be done in about 4 lines of Python. To get you started, here is the link [3] to the MSDN documentation that tells you what you need to know about coloring text in a Windows console window (what Python's print command uses). Then, it is up to you to translate this into Python and pywin. The link [2] could also help. If you are up for a challenge, give it a shot. If you get stuck or it takes too long, write back and I/we can nudge you in the right direction with a code snippet. (While writing this email, I also discovered that you can control the cursor position in a win32 console with pywin! Fun!) Best of luck, and feel free to ask for more help! -Scott [1] - http://msdn.microsoft.com/en-us/library/default.aspx [2] - http://www.dreamincode.net/forums/showtopic23272.htm [3] - http://msdn.microsoft.com/en-us/library/ms682088(VS.85).aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Oct 14 20:50:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Oct 2009 14:50:48 -0400 Subject: [Tutor] PyWin32 - Library of functions to interact with windows? In-Reply-To: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> References: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> Message-ID: <1c2a2c590910141150t37019593m23655d672fdeca38@mail.gmail.com> On Wed, Oct 14, 2009 at 12:38 PM, Katt wrote: > Searching the web I have found a lot of general information or overly > specific with no way to narrow my search to what I am looking for. ?I am not > sure, but it seems very difficult just to search for a way to change the > color of my text. Did you look at the console and wconio links Tim Golden provided? They both include methods to set the console text color. Looking at the source for wconio, I see it calls SecConsoleTextAttribute() to set the color. That function is documented here: http://msdn.microsoft.com/en-us/library/ms686047%28VS.85%29.aspx I can't help you figure out how to use this from Python using win32 though... Kent From srilyk at gmail.com Wed Oct 14 23:09:36 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 14 Oct 2009 16:09:36 -0500 Subject: [Tutor] Masking operation Message-ID: <333efb450910141409n17dd9f9cm675226b2229e20a2@mail.gmail.com> I've searched "Python masking" and various other terms in Google and the python docs and came up with nothing useful. This is just a bit of a hobby project that was inspired by some assembly homework that one of my friends is now doing and I did last semester. The assignment was to create a program that took two strings and XOR'ed the one by the other. For example: mask: secret data: This is a secret message! and you would have: s XOR T e XOR h e XOR i t XOR s s XOR ' ' So I basically want a mask the same length as my data (in this case, 25), so I would have: mask = 'secretsecretsecretsecrets' The way I'm currently doing it is: mask = mask * (len(message)/len(mask)) for l, m in zip(message, mask): word += chr(ord(l) ^ ord(m)) but I'm wondering if there are any easier/more pythonic ways. Thanks, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From ljmamoreira at gmail.com Thu Oct 15 00:24:22 2009 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Wed, 14 Oct 2009 23:24:22 +0100 Subject: [Tutor] namespaces and global In-Reply-To: References: <200910141226.22567.ljmamoreira@gmail.com> Message-ID: <200910142324.22839.ljmamoreira@gmail.com> Alan, Kent, hello! Thanks for your help. As for your "curiosity", I'm teaching elementary physics to undergraduates in computer engineering. Trying to speak my students' language, I wanted to show them simple applications that compute numerical values for the kinematics formulas of uniformly accelerated motion (the weaker students call these formulas Chinese gibberish). What I had in mind was to have a module define vectors and vector algebra operations using a simple class definition, and another with kinematics formulas, like (for uniformly accelerated motion) def pos(t): return r0+v0*t+0.5*a*t**2 Here r0 (initial position) v0 (initial velocity) and a (acceleration) are global vector parameters which I'd define in an interactive session with the students, but I'd rather not include them in the formal parameter list of function pos, just because they aren't usually displayed as such in physical formulae. I'd like to keep the look and feel of those formulas in the interactive python session, without having to type the function definitions in that session, but rather import them from a pre-prepared module file. Anyway, thanks again! Best Regards, Jose On Wednesday 14 October 2009 06:18:28 pm Alan Gauld wrote: > "Jose Amoreira" wrote > > > Of course I could redefine my module function, including the parameter a > > in > > the list of arguments, but I'd rather not. > > Why not? That would be good computer science practice and the > most reliable way to do it. Why do you not want to go down that > route? Is there a specific reason to use a global variable when > use of globals is normally considered bad practice? > > I'm curious? From roadierich at googlemail.com Thu Oct 15 01:31:17 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 15 Oct 2009 00:31:17 +0100 Subject: [Tutor] Masking operation In-Reply-To: <333efb450910141409n17dd9f9cm675226b2229e20a2@mail.gmail.com> References: <333efb450910141409n17dd9f9cm675226b2229e20a2@mail.gmail.com> Message-ID: 2009/10/14 Wayne : > I've searched "Python masking" and various other terms in Google and the > python docs and came up with nothing useful. > This is just a bit of a hobby project that was inspired by some assembly > homework that one of my friends is now doing and I did last semester. The > assignment was to create a program that took two strings and XOR'ed the one > by the other. > For example: > mask: secret > data: This is a secret message! > and you would have: > s XOR T > e XOR h > > e XOR i > t XOR s > > s XOR ' ' > So I basically want a mask the same length as my data (in this case, 25), so > I would have: > mask = 'secretsecretsecretsecrets' > The way I'm currently doing it is: > mask = mask * (len(message)/len(mask)) > for l, m in zip(message, mask): > ?? ?word += chr(ord(l) ^ ord(m)) > but I'm wondering if there are any easier/more pythonic ways. > Thanks, > Wayne > -- > To be considered stupid and to be told so is more painful than being called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn?t. - Primo Levi > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Look up the itertools module: http://docs.python.org/library/itertools.html Specifically, cycle and izip. itertools.cycle is the trick here, izip is a more efficient (in this case) version of zip. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From alan.gauld at btinternet.com Thu Oct 15 01:56:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Oct 2009 00:56:42 +0100 Subject: [Tutor] PyWin32 - Library of functions to interact with windows? References: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> <2682ac9b0910141126l92789ft20314ad2d73d9013@mail.gmail.com> Message-ID: "Scott Nelson" wrote > myself and I recently found some C code on the web [2] that does this and > I > translated that into to Python and pywin. It can be done in about 4 > lines > of Python. Yes, its much easier than I expected. I had never seen the SetConsoleTextAttribute API call before nor the GetStdHandle for accessing stdout. Thanks for the link. > (While writing this email, I also discovered that you can control the > cursor > position in a win32 console with pywin! Fun!) I'd still go for wconio for that kind of stuff - including changing colors... http://newcenturycomputers.net/projects/wconio.html Alan G From alan.gauld at btinternet.com Thu Oct 15 02:00:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Oct 2009 01:00:42 +0100 Subject: [Tutor] Masking operation References: <333efb450910141409n17dd9f9cm675226b2229e20a2@mail.gmail.com> Message-ID: "Wayne" wrote > I've searched "Python masking" and various other terms in Google and the > python docs and came up with nothing useful. Try the Using the OS topic in my tutorial. There is a sidebar in there about using the bitwise operators to do masking about half way down. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Thu Oct 15 04:48:38 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 14 Oct 2009 21:48:38 -0500 Subject: [Tutor] Masking operation In-Reply-To: References: <333efb450910141409n17dd9f9cm675226b2229e20a2@mail.gmail.com> Message-ID: <333efb450910141948i128eb9d2kab5165640fe664a@mail.gmail.com> On Wed, Oct 14, 2009 at 6:31 PM, Rich Lovely wrote: > > Specifically, cycle and izip. itertools.cycle is the trick here, izip > is a more efficient (in this case) version of zip. Ahah! Cycle is exactly what I wanted - I thought there was something like this but I forgot where I found it. Using zip is redundant for me, this is what my function looks like now: def crypt(msg, mask): m = itertools.cycle(mask) word = '' for l in msg: word += chr(ord(l) ^ ord(m.next())) return word and works quite perfectly. Alan - I wish I had known this a few days ago when I was trying to use masks to set debug levels. Oh well - having experimented with what I've learned in my discrete structures class about and, or, xor, I've learned what I need to know, and reviewing your tutorial really helps put some of the pieces together that I wasn't able to come up with on my own. Thanks all! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From the_only_katala at verizon.net Thu Oct 15 06:46:47 2009 From: the_only_katala at verizon.net (Katt) Date: Wed, 14 Oct 2009 21:46:47 -0700 Subject: [Tutor] Changing the color of text in the windows shell (WinXP/python 2.6.2) References: Message-ID: Hello All, > Message: 4 > Date: Wed, 14 Oct 2009 18:38:31 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] PyWin32 - Library of functions to interact with > windows? > > "Katt" wrote > >> Now I find myself scratching my head and saying to myself: "now what?" > > Good question. Why did you download and install it? > Did you have a specific need or did it just seem like a good idea at the > time? I installed the pywin32 as to use the color changing capacity. > Except for the Pythonwin editor which is far superior to IDLE IMHO. > Definitely have a play with that. Actually I am using "Programmer's Notepad" to create my python scripts. > > HTH, > Thanks both to Alan G. and Scott N. and Kent J. for your responses. I think that I will eventually learn all aspects of python programming (if I am lucky). So I will pursue all three types of changing color. First I will try WConio, next to be followed by EasyGUI, and last as Scott has pointed out the more difficult pywin32. Below please find my first basic attempt at using the WConio: --------code-------- from WConio import textcolor apples_left = 5 print "There are",(textcolor(4)),apples_left,(textcolor(7)),"left in the basket." --------------------- The output works, but there is one snag. I think that I am leaving something out because it has the word "None" on both sides of the variable. There are None 5 None left in the basket. I tried both textcolor(4 | 0) and textcolor (4,0). The first has no change and the second has an error: --------------- Traceback (most recent call last) File "changecolor.py", line 6, in print "There are",(textcolor(4,0)),apples_left,(textcolor(7,0)),"left in the basket." SyntaxError: invalid syntax --------------- Could someone let me know what I am missing? Thanks in advance, Katt From alan.gauld at btinternet.com Thu Oct 15 09:11:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Oct 2009 08:11:11 +0100 Subject: [Tutor] Changing the color of text in the windows shell (WinXP/python 2.6.2) References: Message-ID: "Katt" wrote > lucky). So I will pursue all three types of changing color. > > First I will try WConio, next to be followed by EasyGUI, EasyGUI won;t help change colour, it is just a way of making a command line script act like a GUI - by popping up dialog boxes to capture input and dsplay messages. It replaces raw_input and print with dialogs. > --------code-------- > from WConio import textcolor > > apples_left = 5 > > print "There are",(textcolor(4)),apples_left,(textcolor(7)),"left in the > basket." > --------------------- > > The output works, but there is one snag. I think that I am leaving > something out because it has the word "None" on both sides of the > variable. The textcolor() function returns None. so you need to keep it out of your print statement:. This means you need to split your print into multiple separate statements. (This will also be true for the pywin32 version) print "There are", textcolor(4) print apples_left, textcolor(7) print "left in the basket." The way I'd handle thus is to create a function which takes a list of tuples as input, with each tuple containing the string and its colour: def colorPrint(strings): for string in strings: textcolor(string[1]) print string[0], colorPrint([("There are", 0),(str(apples_left),4),("left in the basket.",7),("\n",0) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Thu Oct 15 10:35:30 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 15 Oct 2009 09:35:30 +0100 Subject: [Tutor] PyWin32 - Library of functions to interact with windows? In-Reply-To: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> References: <5C9D64AAA86343A697750478F3B9E095@COMPUTER01> Message-ID: <4AD6DED2.5040002@timgolden.me.uk> Katt wrote: > Hello all, > > I am currently using WinXP and python 2.6.2 > I just installed PyWin32 v214 for python 2.6 from the following link: [... snip lots of advice from other people ...] Hi, Katt. Thanks for posting back over here. I must admit, I hadn't realised you were posting to the tutor list when I answered your question originally. (I subscribe to several Python lists and they come into the same mailbox). I rather assumed you were an experienced programmer who just wanted this snippet of win32 info. I'd have been a bit more explanatory if I'd realised. It looks like you've got some useful advice from other people which will hopefully take you somewhere, but some more general advice: it's always a good idea to explain what you're trying to achieve ("I'm trying to write a hangman game which will run in a console window" or "I want to use a GUI to display the text from a web page" or whatever) rather than how you think you want to do it ("How to I position characters at locations on a Console?" or "How do convert HTML colour codes to Windows colour codes") It makes it easier for people trying to help to give the right context to their answers. Good luck and keep posting back here with questions if you have them TJG From timothy.hall at uqconnect.edu.au Thu Oct 15 11:28:32 2009 From: timothy.hall at uqconnect.edu.au (Mr Timothy Hall) Date: Thu, 15 Oct 2009 09:28:32 +0000 Subject: [Tutor] numerical problem Message-ID: hi, i am writing a program for a runge-cutter method of solving ODE's and im having a problem with one part. whenever i run this part of the program, no matter what values i put in for vto, k1t etc... it always equals zero. im slightly aware of floating point numbers but im not sure why this will not give me a real answer. when i do it on my calculator the answer is 0.897 for the correct values of k3t etc. so its not like the result is extremely small. any help would be great. def runge_tang(vto,k1t,k3t,k4t,k5t,k6t): vn = vto+(16/135)*k1t+(6656/12825)*k3t+(28561/56430)*k4t-(9/50)*k5t+(2/55)*k6t return vn -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Oct 15 12:54:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Oct 2009 06:54:57 -0400 Subject: [Tutor] Masking operation In-Reply-To: <333efb450910141948i128eb9d2kab5165640fe664a@mail.gmail.com> References: <333efb450910141409n17dd9f9cm675226b2229e20a2@mail.gmail.com> <333efb450910141948i128eb9d2kab5165640fe664a@mail.gmail.com> Message-ID: <1c2a2c590910150354p3920d978q915df1119165d830@mail.gmail.com> On Wed, Oct 14, 2009 at 10:48 PM, Wayne wrote: > Using zip is redundant for me, this is what my function looks like now: > def crypt(msg, mask): > ?? ?m = itertools.cycle(mask) > ?? ?word = '' > ?? ?for l in msg: > ?? ? ? ?word += chr(ord(l) ^ ord(m.next())) > ?? ?return word With zip() and a generator expression you can write it as def crypt(msg, mask): mask = itertools.cycle(mask) chars = zip(msg, mask) return ''.join(chr(ord(l) ^ ord(m)) for l, m in chars) which could be reduced to a one-liner if you like. Kent From andreengels at gmail.com Thu Oct 15 12:59:57 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Oct 2009 12:59:57 +0200 Subject: [Tutor] numerical problem In-Reply-To: References: Message-ID: <6faf39c90910150359s33adf2f6t88256b28d9707daf@mail.gmail.com> On Thu, Oct 15, 2009 at 11:28 AM, Mr Timothy Hall wrote: > ?hi, > i am writing a program for a runge-cutter method of solving ODE's and im > having a problem with one part. > > whenever i run this part of the program, no matter what values i put in for > vto, k1t etc... it always equals zero. > im slightly aware of floating point numbers but im not sure why this will > not give me a real answer. > when i do it on my calculator the answer is 0.897 for the correct values of > k3t etc. so its not like the result > is extremely small. > any help would be great. > > def runge_tang(vto,k1t,k3t,k4t,k5t,k6t): > ??? vn = vto+(16/135)*k1t+(6656/12825)*k3t+(28561/56430)*k4t-(9/50)*k5t+(2/55)*k6t > ??? return vn The problem is that Python 2 (it has changed in Python 3) uses integer division when making the quotient of integers. 16/135 is thus evaluated to zero, 6656/12825 as well, etcetera. There are 2 ways to solve this: 1. At the top of your file, add the line "from __future__ import division" - this makes the division behave as in Python 3, which uses floating point division when dividing integers as well. 2. Change something to float before doing the division, for example through: vn = vto+(float(16)/135)*k1t+(float(6656)/12825)*k3t+(float(28561)/56430)*k4t-(float(9)/50)*k5t+(float(2)/55)*k6t or vn = vto+(16.0/135)*k1t+(6656.0/12825)*k3t+(28561.0/56430)*k4t-(9.0/50)*k5t+(2.0/55)*k6t -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Thu Oct 15 13:03:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Oct 2009 07:03:41 -0400 Subject: [Tutor] numerical problem In-Reply-To: References: Message-ID: <1c2a2c590910150403o6e3dddd7t94f5b4be81ef223c@mail.gmail.com> On Thu, Oct 15, 2009 at 5:28 AM, Mr Timothy Hall wrote: > whenever i run this part of the program, no matter what values i put in for > vto, k1t etc... it always equals zero. > im slightly aware of floating point numbers but im not sure why this will > not give me a real answer. > when i do it on my calculator the answer is 0.897 for the correct values of > k3t etc. so its not like the result > is extremely small. > any help would be great. > > def runge_tang(vto,k1t,k3t,k4t,k5t,k6t): > ??? vn = > vto+(16/135)*k1t+(6656/12825)*k3t+(28561/56430)*k4t-(9/50)*k5t+(2/55)*k6t > ??? return vn By default, division of integers in Python (and many other languages) produces another integer, for example: In [28]: 16/235 Out[28]: 0 So all your constants are 0! There are two ways around this: Use floats: In [29]: 16.0 /235.0 Out[29]: 0.068085106382978725 Use future division: In [30]: from __future__ import division In [31]: 16/235 Out[31]: 0.068085106382978725 Kent From davea at ieee.org Thu Oct 15 13:48:06 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 15 Oct 2009 07:48:06 -0400 Subject: [Tutor] namespaces and global In-Reply-To: <200910142324.22839.ljmamoreira@gmail.com> References: <200910141226.22567.ljmamoreira@gmail.com> <200910142324.22839.ljmamoreira@gmail.com> Message-ID: <4AD70BF6.6020705@ieee.org> Jose Amoreira wrote: > Alan, Kent, hello! > Thanks for your help. As for your "curiosity", I'm teaching elementary physics > to undergraduates in computer engineering. Trying to speak my students' > language, I wanted to show them simple applications that compute numerical > values for the kinematics formulas of uniformly accelerated motion (the weaker > students call these formulas Chinese gibberish). > What I had in mind was to have a module define vectors and vector algebra > operations using a simple class definition, and another with kinematics > formulas, like (for uniformly accelerated motion) > > def pos(t): > return r0+v0*t+0.5*a*t**2 > > Here r0 (initial position) v0 (initial velocity) and a (acceleration) are > global vector parameters which I'd define in an interactive session with the > students, but I'd rather not include them in the formal parameter list of > function pos, just because they aren't usually displayed as such in physical > formulae. I'd like to keep the look and feel of those formulas in the > interactive python session, without having to type the function definitions in > that session, but rather import them from a pre-prepared module file. > > Anyway, thanks again! > Best Regards, > Jose > > > On Wednesday 14 October 2009 06:18:28 pm Alan Gauld wrote: > >> "Jose Amoreira" wrote >> >> >>> Of course I could redefine my module function, including the parameter a >>> in >>> the list of arguments, but I'd rather not. >>> >> Why not? That would be good computer science practice and the >> most reliable way to do it. Why do you not want to go down that >> route? Is there a specific reason to use a global variable when >> use of globals is normally considered bad practice? >> >> I'm curious? >> > > I see nothing "wrong" with using different modularity rules in interactive sessions than you would in a formally written program. So I'm going to show you the direct approach first, then a "preferable" one. Add some comments to your module to define what you're up to. And preferably list in those comments all the "global" values that your module assumes are going to be set. Then in the interactive session, instead of using from defs import f Use import defs Followed by either f = defs.f or from defs import f Now, when defining the global, you have to put it in the right place, which is in the defs module. Simply use defs.a = 3 and your function will work as you expect. The "preferable" method might be to make these functions methods of a class. It's perfectly reasonable to have method attributes for all these values you're calling globals. And it's perfectly reasonble for a class method to access those attributes as needed, in addition to its own arguments. In terms of typing in the interpreter, it comes out pretty similar. Instead of defs.a, you use obj.a. Only catch is that you call the function as obj.f(). And even that could be finessed if you wanted. If you had lots of functions, and the "globals" varied among them, I'd probably do the class approach. But if they're all similar enough that a single set of globals makes sense for all of them, then you've got your answer. Use the defs module namespace. (Incidentally, there are lots of variations on these two approaches; please don't think this is definitive. And though I tested this quickly, the names were all so different I may have some typos above.) DaveA From davea at ieee.org Thu Oct 15 13:54:23 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 15 Oct 2009 07:54:23 -0400 Subject: [Tutor] Recursive user input collection problem In-Reply-To: <20091014144809.GA2657@yam.witteman.ca> References: <20091013202215.GA15650@yam.witteman.ca> <20091014144809.GA2657@yam.witteman.ca> Message-ID: <4AD70D6F.3000905@ieee.org> William Witteman wrote: > Thanks to all who responded. There were several good points about the > code itself, all of which both helped and work. > > I will likely use Alan's example because I find it the most lucid, but > the other suggestions are good signposts to other ways to do the same > thing (but right, as opposed to how I was doing it). > > Lie's suggestion that I didn't understand the calling structure of > Python was right on the money, and his included link helps with that, > too. Thanks again. > The problem with that approach is that you're still making unnecessary recursive calls. The problem isn't a recursive one, so why take the risks that artificial recursion imposes. You need a loop, and putting a while True: around the whole thing solves it nicely. Don't *call* the function again, just loop back and do the operation again. That's what loops are for. Incidentally, learning about recursion is a very good thing, and useful. I just don't think it's the right answer here. DaveA From yam at nerd.cx Thu Oct 15 15:07:14 2009 From: yam at nerd.cx (William Witteman) Date: Thu, 15 Oct 2009 09:07:14 -0400 Subject: [Tutor] Recursive user input collection problem In-Reply-To: <4AD70D6F.3000905@ieee.org> References: <20091013202215.GA15650@yam.witteman.ca> <20091014144809.GA2657@yam.witteman.ca> <4AD70D6F.3000905@ieee.org> Message-ID: <20091015130714.GA1893@yam.witteman.ca> On Thu, Oct 15, 2009 at 07:54:23AM -0400, Dave Angel wrote: >William Witteman wrote: >>Thanks to all who responded. There were several good points about the >>code itself, all of which both helped and work. >> >>I will likely use Alan's example because I find it the most lucid, but >>the other suggestions are good signposts to other ways to do the same >>thing (but right, as opposed to how I was doing it). >> >>Lie's suggestion that I didn't understand the calling structure of >>Python was right on the money, and his included link helps with that, >>too. Thanks again. >You need a loop, and putting a while True: around the whole thing >solves it nicely. Don't *call* the function again, just loop back >and do the operation again. That's what loops are for. True, that's why my code currently looks like this: def getinput(prompt): """ Get the input by prompting the user and collecting the response - if it is a non-integer, try again. """ while True: try: return int(raw_input(prompt)) except ValueError: print("We need an integer (number) here.") >Incidentally, learning about recursion is a very good thing, and >useful. I just don't think it's the right answer here. I wasn't learning about recursion - I have to use it fairly often, but you are right that it isn't the right approach here. -- yours, William From skylarstruble at gmail.com Thu Oct 15 16:18:19 2009 From: skylarstruble at gmail.com (Skylar Struble) Date: Thu, 15 Oct 2009 10:18:19 -0400 Subject: [Tutor] ok i need some help with a for loop Message-ID: <664a3e4c0910150718k1246c656ocba748c51a3f7ac2@mail.gmail.com> ok so im working on a text based rpg game and am trying to get this code to work, items = ['crate', 'grave'] lookwords = ['look', 'examine', 'investigate','open') input1 = raw_input('What do you want to do:') for word in items: for word2 in lookwords: if word and word2 in input1: print 'you look in the crate and find a map!' else: print 'sorry you used a word i didnt understand' it prints out all of the print things 2 times when i want it to print 1 or the other because what im trying to do is see if the input1 has both an item from items and lookwords in the string and if so print you look in the map or if it finds 1 or none to print sorry you used a word i didnt understand thanks for takeing the time to read this and gl. From motoom at xs4all.nl Thu Oct 15 16:35:35 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Thu, 15 Oct 2009 16:35:35 +0200 Subject: [Tutor] ok i need some help with a for loop In-Reply-To: <664a3e4c0910150718k1246c656ocba748c51a3f7ac2@mail.gmail.com> References: <664a3e4c0910150718k1246c656ocba748c51a3f7ac2@mail.gmail.com> Message-ID: <4AD73337.6070506@xs4all.nl> Skylar Struble wrote: > lookwords = ['look', 'examine', 'investigate','open') The ')' probably has to be a ']'. > if word and word2 in input1: Try this: if (word in input1) and (word2 in input1): > it prints out all of the print things 2 times when i want it to print > 1 or the other because what im trying to do is see if the input1 has > both an item from items and lookwords in the string and if so print > you look in the map or if it finds 1 or none to print sorry you used a > word i didnt understand Some interpunction would make this text easier to understand. -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From waynejwerner at gmail.com Thu Oct 15 16:36:47 2009 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 15 Oct 2009 09:36:47 -0500 Subject: [Tutor] Most pythonic input validation Message-ID: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> Hi, I'm writing a text based menu and want to validate the user input. I'm giving the options as integers, and I want to make sure the user enters a proper value. Here's what I've got so far: http://pastebin.com/m1fdd5863 I'm most interested in this segment: while True: choice = raw_input(prompt) if valid_choice(choice, 0, len(options)-1): break return choice Is that the most pythonic way of validating? Is there a better way? As an aside, in the valid_choice function I know I could do: if not choice in range(min, max) but I figured a comparison would probably be the better choice, correct? Thanks, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Oct 15 16:47:07 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 15 Oct 2009 16:47:07 +0200 Subject: [Tutor] ok i need some help with a for loop In-Reply-To: <664a3e4c0910150718k1246c656ocba748c51a3f7ac2@mail.gmail.com> References: <664a3e4c0910150718k1246c656ocba748c51a3f7ac2@mail.gmail.com> Message-ID: <4AD735EB.3000706@compuscan.co.za> Skylar Struble wrote: > ok so im working on a text based rpg game and am trying to get this > code to work, > > items = ['crate', 'grave'] > lookwords = ['look', 'examine', 'investigate','open') > input1 = raw_input('What do you want to do:') > for word in items: > for word2 in lookwords: > if word and word2 in input1: > print 'you look in the crate and find a map!' > else: > print 'sorry you used a word i didnt understand' > > it prints out all of the print things 2 times when i want it to print > 1 or the other because what im trying to do is see if the input1 has > both an item from items and lookwords in the string and if so print > you look in the map or if it finds 1 or none to print sorry you used a > word i didnt understand > > > thanks for takeing the time to read this and gl. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > What you could do is transform it a little to something like the following: items = ['crate', 'grave'] lookwords = ['look', 'examine', 'investigate','open') input1 = raw_input('What do you want to do:') success = False for lw in lookwords: if lw in input1: for iw in items: if iw in input1: print 'You %s and found a map.' % input1 success = True if success: break if success: break if not success: print 'You used a word I did not understand' That will first check to see if any of your `lookwords` are contained in the input (if they're not there why bother continuing as they haven't chosen a valid action) and if their input does contain the action then carry on and check to see if a valid item was selected. If a valid item was selected then the variable `success` will be made True and before the next iteration it will break out of the loop (useful for speed if you have large lists of objects / actions to get through). If it loops through everything and doesn't find any matches it will print out 'You used a word I did not understand' because the success variable is still False. This is just a rather basic idea, but it will get the job done. -- Kind Regards, Christian Witts From dperlman at wisc.edu Thu Oct 15 17:14:51 2009 From: dperlman at wisc.edu (David Perlman) Date: Thu, 15 Oct 2009 10:14:51 -0500 Subject: [Tutor] Methods that return instances of their own class? Message-ID: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> I'm trying to figure out how to define a class so that its instances have a method that return a different object of the same class. In particular, I'm trying to run a simple prisoner's dilemma game, and I want to make a "game" object that has a method which returns the "game" object with the payoffs reversed; that is, the payoff matrix from the other player's point of view. Basically a kind of transpose which is specific to this application. class Payoffs(list): def __init__(self, value=None): list.__init__(self) if value==None: # use a default prisoner's dilemma value=[[(3,3),(0,5)], [(5,0),(1,1)]] self.extend(value) def __repr__(self): l1="Your Choice: Cooperate Defect\n" l2="My choice: -------------------------\n" l3="Cooperate | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0] [0][0], self[0][0][1], self[0][1][0], self[0][1][1]) l4=" ----------------------- \n" l5="Defect | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1] [0][0], self[1][0][1], self[1][1][0], self[1][1][1]) l6=" -------------------------\n" return l1+l2+l3+l4+l5+l6 def transpose(self): And that's where I'm at. How can I have the transpose method return another Payoffs object? Here's the beginning of it: def transpose(self): trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1] [0][0])], [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1] [1][0])]] But now "trans" is type list, not type Payoffs. I don't know how to get it into a Payoffs object so that the transpose will have my other new methods. Thanks very much. I searched for answers but I'm not sure what this would be called, which made it hard to find. -- -dave---------------------------------------------------------------- Unfortunately, as soon as they graduate, our people return to a world driven by a tool that is the antithesis of thinking: PowerPoint. Make no mistake, PowerPoint is not a neutral tool ? it is actively hostile to thoughtful decision-making. It has fundamentally changed our culture by altering the expectations of who makes decisions, what decisions they make and how they make them. -Colonel T. X. Hammes, USMC From andreengels at gmail.com Thu Oct 15 17:31:36 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Oct 2009 17:31:36 +0200 Subject: [Tutor] Methods that return instances of their own class? In-Reply-To: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> References: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> Message-ID: <6faf39c90910150831n78d4ebf3x800ca36dd1d215f4@mail.gmail.com> On Thu, Oct 15, 2009 at 5:14 PM, David Perlman wrote: > I'm trying to figure out how to define a class so that its instances have a > method that return a different object of the same class. > > In particular, I'm trying to run a simple prisoner's dilemma game, and I > want to make a "game" object that has a method which returns the "game" > object with the payoffs reversed; that is, the payoff matrix from the other > player's point of view. ?Basically a kind of transpose which is specific to > this application. > > class Payoffs(list): > ? ?def __init__(self, value=None): > ? ? ? ?list.__init__(self) > ? ? ? ?if value==None: # use a default prisoner's dilemma > ? ? ? ? ? ?value=[[(3,3),(0,5)], > ? ? ? ? ? ? ? ? ? [(5,0),(1,1)]] > ? ? ? ?self.extend(value) > > ? ?def __repr__(self): > ? ? ? ?l1="Your Choice: ? Cooperate ? ?Defect\n" > ? ? ? ?l2="My choice: ? -------------------------\n" > ? ? ? ?l3="Cooperate ? ?| (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0][0][0], > self[0][0][1], self[0][1][0], self[0][1][1]) > ? ? ? ?l4=" ? ? ? ? ? ? ?----------------------- \n" > ? ? ? ?l5="Defect ? ? ? | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1][0][0], > self[1][0][1], self[1][1][0], self[1][1][1]) > ? ? ? ?l6=" ? ? ? ? ? ? -------------------------\n" > ? ? ? ?return l1+l2+l3+l4+l5+l6 > > ? ?def transpose(self): > > And that's where I'm at. ?How can I have the transpose method return another > Payoffs object? ?Here's the beginning of it: > > ? ?def transpose(self): > ? ? ? ?trans=[[(self[0][0][1],self[0][0][0]), > (self[1][0][1],self[1][0][0])], > ? ? ? ? ? ? ? [(self[0][1][1],self[0][1][0]), > (self[1][1][1],self[1][1][0])]] > > But now "trans" is type list, not type Payoffs. ?I don't know how to get it > into a Payoffs object so that the transpose will have my other new methods. > > > Thanks very much. ?I searched for answers but I'm not sure what this would > be called, which made it hard to find. I may be thinking too simple, but isn't this just: def transpose(self): trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1][0][0])], [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1][1][0])]] return Payoffs(trans) -- Andr? Engels, andreengels at gmail.com From dperlman at wisc.edu Thu Oct 15 17:45:31 2009 From: dperlman at wisc.edu (David Perlman) Date: Thu, 15 Oct 2009 10:45:31 -0500 Subject: [Tutor] Methods that return instances of their own class? In-Reply-To: <6faf39c90910150831n78d4ebf3x800ca36dd1d215f4@mail.gmail.com> References: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> <6faf39c90910150831n78d4ebf3x800ca36dd1d215f4@mail.gmail.com> Message-ID: <5761D4E0-37E2-4DEC-A293-78989358A2A5@wisc.edu> Oh my goodness, it really is that easy! I guess I assumed that was too simple to work. Silly me. Thanks Andre! On Oct 15, 2009, at 10:31 AM, Andre Engels wrote: > On Thu, Oct 15, 2009 at 5:14 PM, David Perlman > wrote: >> I'm trying to figure out how to define a class so that its >> instances have a >> method that return a different object of the same class. >> >> In particular, I'm trying to run a simple prisoner's dilemma game, >> and I >> want to make a "game" object that has a method which returns the >> "game" >> object with the payoffs reversed; that is, the payoff matrix from >> the other >> player's point of view. Basically a kind of transpose which is >> specific to >> this application. >> >> class Payoffs(list): >> def __init__(self, value=None): >> list.__init__(self) >> if value==None: # use a default prisoner's dilemma >> value=[[(3,3),(0,5)], >> [(5,0),(1,1)]] >> self.extend(value) >> >> def __repr__(self): >> l1="Your Choice: Cooperate Defect\n" >> l2="My choice: -------------------------\n" >> l3="Cooperate | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0] >> [0][0], >> self[0][0][1], self[0][1][0], self[0][1][1]) >> l4=" ----------------------- \n" >> l5="Defect | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1] >> [0][0], >> self[1][0][1], self[1][1][0], self[1][1][1]) >> l6=" -------------------------\n" >> return l1+l2+l3+l4+l5+l6 >> >> def transpose(self): >> >> And that's where I'm at. How can I have the transpose method >> return another >> Payoffs object? Here's the beginning of it: >> >> def transpose(self): >> trans=[[(self[0][0][1],self[0][0][0]), >> (self[1][0][1],self[1][0][0])], >> [(self[0][1][1],self[0][1][0]), >> (self[1][1][1],self[1][1][0])]] >> >> But now "trans" is type list, not type Payoffs. I don't know how >> to get it >> into a Payoffs object so that the transpose will have my other new >> methods. >> >> >> Thanks very much. I searched for answers but I'm not sure what >> this would >> be called, which made it hard to find. > > I may be thinking too simple, but isn't this just: > > def transpose(self): > trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1][0] > [0])], > [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1] > [1][0])]] > return Payoffs(trans) > > > -- > Andr? Engels, andreengels at gmail.com -- -dave---------------------------------------------------------------- Unfortunately, as soon as they graduate, our people return to a world driven by a tool that is the antithesis of thinking: PowerPoint. Make no mistake, PowerPoint is not a neutral tool ? it is actively hostile to thoughtful decision-making. It has fundamentally changed our culture by altering the expectations of who makes decisions, what decisions they make and how they make them. -Colonel T. X. Hammes, USMC From roadierich at googlemail.com Thu Oct 15 17:50:57 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 15 Oct 2009 16:50:57 +0100 Subject: [Tutor] Most pythonic input validation In-Reply-To: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> Message-ID: 2009/10/15 Wayne Werner : > Hi, > I'm writing a text based menu and want to validate the user input. I'm > giving the options as integers, and I want to make sure the user enters a > proper value. > Here's what I've got so far:?http://pastebin.com/m1fdd5863 > I'm most interested in this segment: > ?? ?while True: > ?? ? ? ?choice = raw_input(prompt) > ?? ? ? ?if valid_choice(choice, 0, len(options)-1): > ?? ? ? ? ? ?break > ?? ?return choice > Is that the most pythonic way of validating? Is there a better way? > As an aside, in the valid_choice function I know I could do: > if not choice in range(min, max) > but I figured a comparison would probably be the better choice, correct? > Thanks, > Wayne > -- > To be considered stupid and to be told so is more painful than being called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn?t. - Primo Levi > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > The most pythonic way would be to use a try except block: while True: choice = raw_input(prompt) try: options[int(choice)] except (KeyError, IndexError, TypeError): print "Invalid input, try again." continue return choice Also, did you want to convert choice to an int at some point? You appear to be comparing it to a number in valid_choice(), but it will be passed out of the method as a str. Hence I've added a conversion to int, and I'm catching KeyError (for dicts), IndexError (for lists), and TypeError, for when int(choice) fails. This is a principle called "It's Easier to Ask Forgiveness than Permission" (EAFP), which is one of the pythonic principles. Hope that helps. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From roadierich at googlemail.com Thu Oct 15 17:58:34 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 15 Oct 2009 16:58:34 +0100 Subject: [Tutor] Masking operation In-Reply-To: <1c2a2c590910150354p3920d978q915df1119165d830@mail.gmail.com> References: <333efb450910141409n17dd9f9cm675226b2229e20a2@mail.gmail.com> <333efb450910141948i128eb9d2kab5165640fe664a@mail.gmail.com> <1c2a2c590910150354p3920d978q915df1119165d830@mail.gmail.com> Message-ID: 2009/10/15 Kent Johnson : > On Wed, Oct 14, 2009 at 10:48 PM, Wayne wrote: > >> Using zip is redundant for me, this is what my function looks like now: >> def crypt(msg, mask): >> ?? ?m = itertools.cycle(mask) >> ?? ?word = '' >> ?? ?for l in msg: >> ?? ? ? ?word += chr(ord(l) ^ ord(m.next())) >> ?? ?return word > > With zip() and a generator expression you can write it as > def crypt(msg, mask): > ?mask = itertools.cycle(mask) > ?chars = zip(msg, mask) > ?return ''.join(chr(ord(l) ^ ord(m)) for l, m in chars) > > which could be reduced to a one-liner if you like. > > Kent > And that's why itertools is probably my favourite module. For extra jollies, you can define it as a lambda: crypt = lambda msg, mask: "".join(chr(ord(l)^ord(m)) for l,m in zip(msg, itertools.cycle(mask))) But that's maybe going a little over the top, unless we're entering an obfuscated code contest. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From waynejwerner at gmail.com Thu Oct 15 18:14:09 2009 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 15 Oct 2009 11:14:09 -0500 Subject: [Tutor] Most pythonic input validation In-Reply-To: References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> Message-ID: <333efb450910150914y71b36208se197e604db7cb98d@mail.gmail.com> On Thu, Oct 15, 2009 at 10:50 AM, Rich Lovely wrote: > 2009/10/15 Wayne Werner : > > Hi, > > I'm writing a text based menu and want to validate the user input. I'm > > giving the options as integers, and I want to make sure the user enters a > > proper value. > > Here's what I've got so far: http://pastebin.com/m1fdd5863 > > I'm most interested in this segment: > > while True: > > choice = raw_input(prompt) > > if valid_choice(choice, 0, len(options)-1): > > break > > return choice > > Is that the most pythonic way of validating? Is there a better way? > > As an aside, in the valid_choice function I know I could do: > > if not choice in range(min, max) > > but I figured a comparison would probably be the better choice, correct? > > Thanks, > > Wayne > > -- > > To be considered stupid and to be told so is more painful than being > called > > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every > weakness, > > every vice, has found its defenders, its rhetoric, its ennoblement and > > exaltation, but stupidity hasn?t. - Primo Levi > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > The most pythonic way would be to use a try except block: > > while True: > choice = raw_input(prompt) > try: > options[int(choice)] > except (KeyError, IndexError, TypeError): > print "Invalid input, try again." > continue > return choice > Ah, that's much cleaner, I like it :) yeah, I noticed right after I had sent my email that I forgot to convert it to an int. Though I do believe (and checking confirms) it's ValueError on an int() fail: ValueError: invalid literal for int() with base 10: 'asdf' Now I can eliminate a function, so that's helpful :) Thanks, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Thu Oct 15 18:17:16 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 15 Oct 2009 17:17:16 +0100 Subject: [Tutor] Most pythonic input validation In-Reply-To: <333efb450910150914y71b36208se197e604db7cb98d@mail.gmail.com> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> <333efb450910150914y71b36208se197e604db7cb98d@mail.gmail.com> Message-ID: 2009/10/15 Wayne Werner : > > > On Thu, Oct 15, 2009 at 10:50 AM, Rich Lovely > wrote: >> >> 2009/10/15 Wayne Werner : >> > Hi, >> > I'm writing a text based menu and want to validate the user input. I'm >> > giving the options as integers, and I want to make sure the user enters >> > a >> > proper value. >> > Here's what I've got so far:?http://pastebin.com/m1fdd5863 >> > I'm most interested in this segment: >> > ?? ?while True: >> > ?? ? ? ?choice = raw_input(prompt) >> > ?? ? ? ?if valid_choice(choice, 0, len(options)-1): >> > ?? ? ? ? ? ?break >> > ?? ?return choice >> > Is that the most pythonic way of validating? Is there a better way? >> > As an aside, in the valid_choice function I know I could do: >> > if not choice in range(min, max) >> > but I figured a comparison would probably be the better choice, correct? >> > Thanks, >> > Wayne >> > -- >> > To be considered stupid and to be told so is more painful than being >> > called >> > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every >> > weakness, >> > every vice, has found its defenders, its rhetoric, its ennoblement and >> > exaltation, but stupidity hasn?t. - Primo Levi >> > >> > _______________________________________________ >> > Tutor maillist ?- ?Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> >> The most pythonic way would be to use a try except block: >> >> ? ?while True: >> ? ? ? ?choice = raw_input(prompt) >> ? ? ? ?try: >> ? ? ? ? ? ?options[int(choice)] >> ? ? ? ?except (KeyError, IndexError, TypeError): >> ? ? ? ? ? ?print "Invalid input, try again." >> ? ? ? ? ? ?continue >> ? ? ? ?return choice > > Ah, that's much cleaner, I like it :) > ?yeah, I noticed right after I had sent my email that I forgot to convert it > to an int. Though I do believe (and checking confirms) it's ValueError on an > int() fail: > ValueError: invalid literal for int() with base 10: 'asdf' > Now I can eliminate a function, so that's helpful :) > Thanks, > Wayne Ah yes, should probably have checked that myself... I added that before the conversion to int, and trying to index a list with a string raises TypeError... -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From pine508 at hotmail.com Thu Oct 15 19:33:51 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 15 Oct 2009 13:33:51 -0400 Subject: [Tutor] Methods that return instances of their own class? In-Reply-To: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> References: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> Message-ID: > In particular, I'm trying to run a simple prisoner's dilemma game, and > I want to make a "game" object that has a method which returns the > "game" object with the payoffs reversed; that is, the payoff matrix > from the other player's point of view. Basically a kind of transpose > which is specific to this application. Since this is the tutor list, I'd like to ask some questions about structures used here that I haven't encountered before. I hope you'll excuse me asking instead of Googling them, but words like list and value are tough to get the relevant sense of them for these cases... > class Payoffs(list): > def __init__(self, value=None): > list.__init__(self) This class is a list that has methods? That seems sort of unusual to me. Am I interpreting that right? How is this class called? With a list AND a value? What does it mean to initialize a list (the third line?). > if value==None: # use a default prisoner's dilemma > value=[[(3,3),(0,5)], > [(5,0),(1,1)]] > self.extend(value) This means that the list that is the instantiation of this class is being extended by the hardcoded values given here. But if value == None, was there any list to extend, or was it an empty list, []? Why not just pass a list and to a class directly, and if not use a default list without having to use .extend()? There is no case here in which a passed-in list would be extended with a hardcoded list, correct? > def __repr__(self): > l1="Your Choice: Cooperate Defect\n" > l2="My choice: -------------------------\n" > l3="Cooperate | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0] > [0][0], self[0][0][1], self[0][1][0], self[0][1][1]) > l4=" ----------------------- \n" > l5="Defect | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1] > [0][0], self[1][0][1], self[1][1][0], self[1][1][1]) > l6=" -------------------------\n" > return l1+l2+l3+l4+l5+l6 What is the reason for using __repr__() here and also this |1 style? I have not seen this before. > def transpose(self): > > And that's where I'm at. How can I have the transpose method return > another Payoffs object? Here's the beginning of it: > > def transpose(self): > trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1] > [0][0])], > [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1] > [1][0])]] Did this have to be hardcoded like this, or is there a more Pythonic way to transpose the payoff list? Maybe it needs to look like this, but this does not strike me as very readable. Thanks for any future insight, Che _________________________________________________________________ Your E-mail and More On-the-Go. Get Windows Live Hotmail Free. http://clk.atdmt.com/GBL/go/171222985/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Oct 15 19:46:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Oct 2009 18:46:43 +0100 Subject: [Tutor] Recursive user input collection problem References: <20091013202215.GA15650@yam.witteman.ca><20091014144809.GA2657@yam.witteman.ca> <4AD70D6F.3000905@ieee.org> <20091015130714.GA1893@yam.witteman.ca> Message-ID: "William Witteman" wrote >>You need a loop, and putting a while True: around the whole thing >>solves it nicely. Don't *call* the function again, just loop back >>and do the operation again. That's what loops are for. > > True, that's why my code currently looks like this: Personally I don't think recursion is a problem in this context. You would need a pretty dumb user to get it wrong 1000 times (Pythons default recursion limit). So although a loop is the more pythonic idiom a recursive solution here is fine in my personal view. But that may just be because I'm (yet again) playing with Lisp and therefore thinking recursively about problems rather than thinking loops. :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Oct 15 20:04:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Oct 2009 19:04:08 +0100 Subject: [Tutor] Methods that return instances of their own class? References: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> Message-ID: "Che M" wrote > Since this is the tutor list, I'd like to ask some questions about > structures used here that I haven't encountered before. I hope > you'll excuse me asking Thats OK. > class Payoffs(list): > def __init__(self, value=None): > list.__init__(self) > This class is a list that has methods? That seems sort > of unusual to me. Am I interpreting that right? Its right and normal. Standard Python lists have methids try dir(list) > How is this class called? With a list AND a value? No, just a value, like any other class. All that is happening is normal class definition where the superclass is a built in type. > does it mean to initialize a list (the third line?). Its initialising the underlying list - the superclass - the python list object. Although it may not work as expected, I suspect the OP may need to do this via creating a __new__ method. > here. But if value == None, was there any list to extend, It means no value was provided so we are creating a default one > Why not just pass a list and to a class directly, and if > not use a default list without having to use .extend()? I'm not sure why extend is being used - I didn't look that closely, but essentially the OP is doing what you suggest. > def __repr__(self): > What is the reason for using __repr__() here and also > this |1 style? I have not seen this before. Its the OPs prefered style of representing his list. You can always override repr to present the object in a more readable style - where readable is subjective. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From m.kossner at tu-bs.de Thu Oct 15 20:04:15 2009 From: m.kossner at tu-bs.de (markus kossner) Date: Thu, 15 Oct 2009 20:04:15 +0200 Subject: [Tutor] multiprocessing with more than two arguments Message-ID: <1255629855.9883.7.camel@akb-6> Hi, let's simply start with an example: #!/usr/bin/python2.6 import numpy as n def calculate(a,b=3,c=4): print b return n.sqrt(n.exp(a*b+c)/n.exp(c)**2) from multiprocessing import Pool p = Pool(processes=2) a_list=range(100000) result=p.map(calculate,a_list) This code works qite fine, as long as i yust want to map the calculate function onto a list of values of a (the first argument of the function). But what if I want to change the value of b in the compute function to some other value, than the default one? I tested things like result=p.map(calculate,a_list,b=5) or result=p.map(calculate,args=(a_list,b=5)) but nothing works? Thanks in advance for any help! Cheers Markus From steve at alchemy.com Thu Oct 15 20:14:29 2009 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 15 Oct 2009 11:14:29 -0700 Subject: [Tutor] Methods that return instances of their own class? In-Reply-To: References: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> Message-ID: <20091015181429.GA34048@dragon.alchemy.com> On Thu, Oct 15, 2009 at 01:33:51PM -0400, Che M wrote: > > > > > In particular, I'm trying to run a simple prisoner's dilemma game, and > > I want to make a "game" object that has a method which returns the > > "game" object with the payoffs reversed; that is, the payoff matrix > > from the other player's point of view. Basically a kind of transpose > > which is specific to this application. > > Since this is the tutor list, I'd like to ask some questions about > structures used here that I haven't encountered before. I hope > you'll excuse me asking instead of Googling them, but words like > list and value are tough to get the relevant sense of them for > these cases... > > > class Payoffs(list): > > def __init__(self, value=None): > > list.__init__(self) > > This class is a list that has methods? That seems sort > of unusual to me. Am I interpreting that right? Lists have methods, like any other class of objects. For example, list.append(). What you have here is a new type of data collection called Payoffs, which is a sub-class of list. IOW, it's a specialized kind of list which has all the normal behavior of lists, plus some special stuff added. > How is this class called? With a list AND a value? What > does it mean to initialize a list (the third line?). Payoffs, unlike regular lists, interpret the values in them so an initialization makes some sense. And regular lists are (or can be) initialized with a value parameter too: a = list([1,2,3,4]) Not that you'd normally write that exactly like that, of course, but you might do that to create, say, a list from a tuple of values: a = list(some_tuple) So really this is just an extension of that idea. > > > if value==None: # use a default prisoner's dilemma > > value=[[(3,3),(0,5)], > > [(5,0),(1,1)]] > > self.extend(value) So just saying a = Payoffs() gets you a default arrangement, but you could specify something different if you wanted. > This means that the list that is the instantiation of this > class is being extended by the hardcoded values given > here. But if value == None, was there any list to extend, This starts out as a regular list object (note the call to list.__init__() at the start of Payoff's __init__), so it'll be [] by default. > or was it an empty list, []? Why not just pass a list and > to a class directly, and if not use a default list without > having to use .extend()? There is no case here in which > a passed-in list would be extended with a hardcoded list, > correct? This could have been a stand-alone class which contained a list attribute, yes. When designing a class you have to consider whether you get a better design by extending a class (particularly like here when it only really has a single value which is already very similar to another type), or by starting a new class which contains other objects as attributes. > > def __repr__(self): > > > l1="Your Choice: Cooperate Defect\n" > > l2="My choice: -------------------------\n" > > l3="Cooperate | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[0] > > [0][0], self[0][0][1], self[0][1][0], self[0][1][1]) > > l4=" ----------------------- \n" > > l5="Defect | (% 3d,% 3d) | (% 3d,% 3d) |\n" % (self[1] > > [0][0], self[1][0][1], self[1][1][0], self[1][1][1]) > > l6=" -------------------------\n" > > return l1+l2+l3+l4+l5+l6 > > What is the reason for using __repr__() here and also > this |1 style? I have not seen this before. It's usual for a class to define __str__ and/or __repr__ so that you get a useful string representation of an instance of that class. Here the object explains what it represents more clearly than just saying "it's a bunch of numbers in a list." -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From dperlman at wisc.edu Thu Oct 15 20:16:35 2009 From: dperlman at wisc.edu (David Perlman) Date: Thu, 15 Oct 2009 13:16:35 -0500 Subject: [Tutor] Methods that return instances of their own class? In-Reply-To: References: <78EE175A-6E8C-42F1-BB1E-1E31B3610328@wisc.edu> Message-ID: <69CBDD90-DC40-4720-8A11-6CBF4D35636F@wisc.edu> Maybe there's a prettier way to do this, but I did it explicitly like this because the "transpose" I needed was specific to the structure of the game payoff matrix; it isn't a normal mathematical transpose. I agree that it's hard to read but I'm not sure the specific needs of this application allow a cleaner solution. I'd love to hear it if there was one though! On Oct 15, 2009, at 12:33 PM, Che M wrote: > > def transpose(self): > > > > And that's where I'm at. How can I have the transpose method return > > another Payoffs object? Here's the beginning of it: > > > > def transpose(self): > > trans=[[(self[0][0][1],self[0][0][0]), (self[1][0][1],self[1] > > [0][0])], > > [(self[0][1][1],self[0][1][0]), (self[1][1][1],self[1] > > [1][0])]] > > Did this have to be hardcoded like this, or is there a more > Pythonic way to transpose the payoff list? Maybe it needs > to look like this, but this does not strike me as very readable. -- -dave---------------------------------------------------------------- Unfortunately, as soon as they graduate, our people return to a world driven by a tool that is the antithesis of thinking: PowerPoint. Make no mistake, PowerPoint is not a neutral tool ? it is actively hostile to thoughtful decision-making. It has fundamentally changed our culture by altering the expectations of who makes decisions, what decisions they make and how they make them. -Colonel T. X. Hammes, USMC From kent37 at tds.net Thu Oct 15 21:44:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Oct 2009 15:44:18 -0400 Subject: [Tutor] multiprocessing with more than two arguments In-Reply-To: <1255629855.9883.7.camel@akb-6> References: <1255629855.9883.7.camel@akb-6> Message-ID: <1c2a2c590910151244t3aabba00qed3184e6c4ce9b34@mail.gmail.com> On Thu, Oct 15, 2009 at 2:04 PM, markus kossner wrote: > Hi, > let's simply start with an example: > > #!/usr/bin/python2.6 > import numpy as n > > def calculate(a,b=3,c=4): > ? ? ? ?print b > ? ? ? ?return n.sqrt(n.exp(a*b+c)/n.exp(c)**2) > > from multiprocessing import Pool > p = Pool(processes=2) > a_list=range(100000) > > result=p.map(calculate,a_list) > > This code works qite fine, as long as i yust want to map the > calculate function onto a list of values of a (the first argument of the > function). But what if I want to change the value of b in the compute > function to some other value, than the default one? Pool.map() seems to only support a single parameter. I think you will have to redefine calculate() to take for example a dict parameter containing the actual arcuments. Kent From emile at fenx.com Thu Oct 15 21:45:17 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 15 Oct 2009 12:45:17 -0700 Subject: [Tutor] Most pythonic input validation In-Reply-To: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> Message-ID: On 10/15/2009 7:36 AM Wayne Werner said... > Is that the most pythonic way of validating? Is there a better way? Pythonic in part having been addressed, I've some further comments to your valid_choice code... -- Emile def valid_choice(choice, min, max): # don't use min and max -- they shadow built in functions # try least/most minimum/maximum minval/maxval etc... try: choice = int(choice) min = int(min) max = int(max) except ValueError: r = False # the next line is indeterminant if the above fails # as your min/max/choice variables may not be ints # IIRC, the comparisons may even fail and raise errors # in some versions of python if max < choice or min > choice: r = False else: r = True if not r: print "Choice is not valid, please try again" return r From goodpotatoes at yahoo.com Fri Oct 16 00:04:14 2009 From: goodpotatoes at yahoo.com (GoodPotatoes) Date: Thu, 15 Oct 2009 15:04:14 -0700 (PDT) Subject: [Tutor] Putting a variable into a statement Message-ID: <942041.13002.qm@web51809.mail.re2.yahoo.com> I am using the module active_directory and have an ad object called myuser. I would like to run a series of statements like: myuser.attribute where attribute is a string variable, but python says that this is not the correct syntax. error: for x in myuser.properties: # "myuser.properties" returns a tuple of properties associated with the myuser AD object print myuser.x Traceback (most recent call last): File "", line 2, in print myuser.x File "build\bdist.win32\egg\active_directory.py", line 421, in __getattr__ raise AttributeError AttributeError example: >>> myuser.properties[0] #first value in user tuple u'cn' >>> myuser.cn u'Joe Sixpack' How can I iterate through all of the values of the properties tuple and get each value? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Oct 16 00:16:55 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 15 Oct 2009 18:16:55 -0400 Subject: [Tutor] Putting a variable into a statement In-Reply-To: <942041.13002.qm@web51809.mail.re2.yahoo.com> References: <942041.13002.qm@web51809.mail.re2.yahoo.com> Message-ID: <4AD79F57.2060205@gmail.com> GoodPotatoes wrote: > I am using the module active_directory and have an ad object called > myuser. > > I would like to run a series of statements like: > > myuser.attribute > > where attribute is a string variable, but python says that this is not > the correct syntax. > > error: > for x in myuser.properties: # "myuser.properties" returns a tuple > of properties associated with the myuser AD object > print myuser.x > > Traceback (most recent call last): > File "", line 2, in > print myuser.x > File "build\bdist.win32\egg\active_directory.py", line 421, in > __getattr__ > raise AttributeError > AttributeError > print getattr(myuser ,x) > > example: > >>> myuser.properties[0] #first value in user tuple > u'cn' > >>> myuser.cn > u'Joe Sixpack' > > How can I iterate through all of the values of the properties tuple > and get each value? > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Fri Oct 16 00:19:15 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 15 Oct 2009 18:19:15 -0400 Subject: [Tutor] Putting a variable into a statement In-Reply-To: <942041.13002.qm@web51809.mail.re2.yahoo.com> References: <942041.13002.qm@web51809.mail.re2.yahoo.com> Message-ID: <4AD79FE3.508@gmail.com> GoodPotatoes wrote: > I am using the module active_directory and have an ad object called > myuser. > > I would like to run a series of statements like: > > myuser.attribute > > where attribute is a string variable, but python says that this is not > the correct syntax. > > error: > for x in myuser.properties: # "myuser.properties" returns a tuple > of properties associated with the myuser AD object > print myuser.x > > Traceback (most recent call last): > File "", line 2, in > print myuser.x > File "build\bdist.win32\egg\active_directory.py", line 421, in > __getattr__ > raise AttributeError > AttributeError My previous suggestion was assuming that elements of myuser.properties were strings (names of the properties). If instead they are the properties then you'd print x -- Bob Gailer Chapel Hill NC 919-636-4239 From Lbrannma at yahoo.com Fri Oct 16 06:23:36 2009 From: Lbrannma at yahoo.com (LL) Date: Fri, 16 Oct 2009 06:23:36 +0200 Subject: [Tutor] cannot convert eps to png using PIL Message-ID: Hi.. I also asked this question on the imaging group but thought people here might have insights as well.. all of the following code executes interactively except the last line. Converting a .jpg file to .png works fine. I'm using the PIL version for Python 2.6. Any suggestions will be greatly appreciated. Thanks, Lance ------------------------------------ PythonWin 2.6.3 (r263:75183, Oct 5 2009, 14:41:55) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> import os >>> import zlib >>> import Image >>> os.chdir("c:\\foo") >>> img = Image.open("foo1.eps") >>> img.save("foo1.png") Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\PIL\Image.py", line 1372, in save self.load() File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 283, in load self.im = Ghostscript(self.tile, self.size, self.fp) File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 72, in Ghostscript gs.write(s) IOError: [Errno 32] Broken pipe -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Fri Oct 16 07:17:53 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 16 Oct 2009 00:17:53 -0500 Subject: [Tutor] cannot convert eps to png using PIL In-Reply-To: References: Message-ID: <200910160017.54169.cfuller084@thinkingplanet.net> It's trying to launch GhostScript, and failing. The broken pipe is a clue that its trying to communicate with external software. Most likely, you don't have ghostscript installed. Google Ghostscript and you should find instructions for installing on windows (I'm fairly sure there is a port). As for getting it to work with PIL, I'd just try getting it on your path (os.environ['PATH'] should work, too). But you want to talk to the GhostScript folks; this isn't a Python problem, and there isn't an alternate solution that is more Pythonic. Cheers On Thursday 15 October 2009 23:23, LL wrote: > Hi.. I also asked this question on the imaging group but thought people > here might have insights as well.. > > all of the following code executes interactively except the last line. > Converting a .jpg file to .png works fine. I'm using the PIL version for > Python 2.6. Any suggestions will be greatly appreciated. Thanks, Lance > ------------------------------------ > PythonWin 2.6.3 (r263:75183, Oct 5 2009, 14:41:55) [MSC v.1500 32 bit > (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see > 'Help/About PythonWin' for further copyright information. > > >>> import os > >>> import zlib > >>> import Image > >>> os.chdir("c:\\foo") > >>> img = Image.open("foo1.eps") > >>> img.save("foo1.png") > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python26\lib\site-packages\PIL\Image.py", line 1372, in save > self.load() > File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 283, in > load self.im = Ghostscript(self.tile, self.size, self.fp) > File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 72, in > Ghostscript gs.write(s) > IOError: [Errno 32] Broken pipe From the_only_katala at verizon.net Fri Oct 16 09:36:24 2009 From: the_only_katala at verizon.net (Katt) Date: Fri, 16 Oct 2009 00:36:24 -0700 Subject: [Tutor] Changing the text color in the WinXP dos shell (WinXP/py2.6.2) References: Message-ID: <18D5EBED75084A269F7198E7EEA217C8@COMPUTER01> > Date: Thu, 15 Oct 2009 08:11:11 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Changing the color of text in the windows shell > (WinXP/python 2.6.2) > Message-ID: > > "Katt" wrote > >> lucky). So I will pursue all three types of changing color. >> >> First I will try WConio, next to be followed by EasyGUI, > > EasyGUI won;t help change colour, it is just a way of making > a command line script act like a GUI - by popping up dialog > boxes to capture input and dsplay messages. It replaces > raw_input and print with dialogs. Got that. I remeber in the old world of BBS's creating ANSI screens for the WWIV software. This shouldn't be any different just in a different language. > >> --------code-------- >> from WConio import textcolor >> >> apples_left = 5 >> >> print "There are",(textcolor(4)),apples_left,(textcolor(7)),"left in the >> basket." >> --------------------- >> >> The output works, but there is one snag. I think that I am leaving >> something out because it has the word "None" on both sides of the >> variable. > > The textcolor() function returns None. so you need to keep it > out of your print statement:. This means you need to split your > print into multiple separate statements. (This will also be true > for the pywin32 version) > > print "There are", > textcolor(4) > print apples_left, > textcolor(7) > print "left in the basket." > > The way I'd handle thus is to create a function which takes a > list of tuples as input, with each tuple containing the string > and its colour: > > def colorPrint(strings): > for string in strings: > textcolor(string[1]) > print string[0], > > colorPrint([("There are", 0),(str(apples_left),4),("left in the > basket.",7),("\n",0) > Thank you for the code snippet. At first when I tried this code it was printing correctly and following up with an error. It was just because the end of the statement was missing the extra ]) at the end. Then after that I was wondering why the phrase "There are" was invisible. Realized that was because the color number was 0. That was very helpful. Thanks again, Katt From the_only_katala at verizon.net Fri Oct 16 09:57:45 2009 From: the_only_katala at verizon.net (Katt) Date: Fri, 16 Oct 2009 00:57:45 -0700 Subject: [Tutor] PyWin32 - Library of functions to interact with windows References: Message-ID: <91033731D792444D86377B15C2CB863E@COMPUTER01> > Message: 4 > Date: Thu, 15 Oct 2009 09:35:30 +0100 > From: Tim Golden > Cc: tutor at python.org > Subject: Re: [Tutor] PyWin32 - Library of functions to interact with > windows? > Message-ID: <4AD6DED2.5040002 at timgolden.me.uk> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Katt wrote: >> Hello all, >> >> I am currently using WinXP and python 2.6.2 >> I just installed PyWin32 v214 for python 2.6 from the following link: > > [... snip lots of advice from other people ...] > > Hi, Katt. Thanks for posting back over here. I must admit, > I hadn't realised you were posting to the tutor list when > I answered your question originally. (I subscribe to several > Python lists and they come into the same mailbox). I rather > assumed you were an experienced programmer who just wanted > this snippet of win32 info. I'd have been a bit more explanatory > if I'd realised. No harm done. No I can't imagine just asking for the code. I mean how would I learn anything. I would rather struggle, then post the code that I was trying and get nudged in the right direction. You learn more from your failures than your successes. > > It looks like you've got some useful advice from other people > which will hopefully take you somewhere, but some more general > advice: it's always a good idea to explain what you're trying to Yes, I got some great advice. I also like the fact that everyone tries to point you in the right direction versus just giving you code. That helps me as a beginner in providing me with new exercises which you don't find to much of in the tutorials. Thanks for the advice. I will try to be more verbose in the future in what I am trying to do so I don't come off as an experienced programmer trying to snag some free code. Btw, I am just learning on my own not through any classes. So far I have learned alot from two of the five tutorials that I have read so far(Josh Cogliati's: Non-Programmer's Tutorial for Python and Alan Gauld's: Tutor - May 27, 2007). > > Good luck and keep posting back here with questions if you > have them > You bet. When I finish the date reminder program that I am working on I will be asking about working with the EasyGUI and the pywin32. Thanks again, Katt From the_only_katala at verizon.net Fri Oct 16 10:37:25 2009 From: the_only_katala at verizon.net (Katt) Date: Fri, 16 Oct 2009 01:37:25 -0700 Subject: [Tutor] Most pythonic input validation References: Message-ID: > Message: 3 > Date: Thu, 15 Oct 2009 16:50:57 +0100 > From: Rich Lovely > To: Wayne Werner > Cc: "tutor at python.org" > Subject: Re: [Tutor] Most pythonic input validation > Message-ID: > > Content-Type: text/plain; charset=windows-1252 > > 2009/10/15 Wayne Werner : >> Hi, >> I'm writing a text based menu and want to validate the user input. I'm >> giving the options as integers, and I want to make sure the user enters a >> proper value. >> Here's what I've got so far:?http://pastebin.com/m1fdd5863 >> I'm most interested in this segment: >> ?? ?while True: >> ?? ? ? ?choice = raw_input(prompt) >> ?? ? ? ?if valid_choice(choice, 0, len(options)-1): >> ?? ? ? ? ? ?break >> ?? ?return choice >> Is that the most pythonic way of validating? Is there a better way? >> As an aside, in the valid_choice function I know I could do: >> if not choice in range(min, max) >> but I figured a comparison would probably be the better choice, correct? >> Thanks, >> Wayne >> -- >> To be considered stupid and to be told so is more painful than being >> called >> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every >> weakness, >> every vice, has found its defenders, its rhetoric, its ennoblement and >> exaltation, but stupidity hasn?t. - Primo Levi >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > The most pythonic way would be to use a try except block: > > while True: > choice = raw_input(prompt) > try: > options[int(choice)] > except (KeyError, IndexError, TypeError): > print "Invalid input, try again." > continue > return choice > > > Also, did you want to convert choice to an int at some point? You > appear to be comparing it to a number in valid_choice(), but it will > be passed out of the method as a str. > > Hence I've added a conversion to int, and I'm catching KeyError (for > dicts), IndexError (for lists), and TypeError, for when int(choice) > fails. > > This is a principle called "It's Easier to Ask Forgiveness than > Permission" (EAFP), which is one of the pythonic principles. > > > Hope that helps. > -- > Rich "Roadie Rich" Lovely As I am a new programmer I am specifically trying to pay attention to when you guys discuss making thing more python like. I am a bit confused though on a couple things in this code. Probably since I have not dealt with it as of yet. The first is the while statement. I have made a successful menu selection but my while statement is: while prompt != 0: 0 of course meaning exit. Does "while True:" mean the same? Second is the input statement. Could you not just put choice = int(raw_input(prompt)) instead of using two different statements? Or is it that my example will return as string? The third is the "try" statement. How is this different from the "for" loop or "if" loop? The fourth is except (KeyError, IndexError, TypeError): why do you check for three different types of errors? Thanks in advance, Katt From the_only_katala at verizon.net Fri Oct 16 11:03:40 2009 From: the_only_katala at verizon.net (Katt) Date: Fri, 16 Oct 2009 02:03:40 -0700 Subject: [Tutor] Understanding what the code does behind the scenes References: Message-ID: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> > Message: 3 > Date: Thu, 15 Oct 2009 08:11:11 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Changing the color of text in the windows shell > (WinXP/python 2.6.2) > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > The textcolor() function returns None. so you need to keep it > out of your print statement:. This means you need to split your > print into multiple separate statements. (This will also be true > for the pywin32 version) > > print "There are", > textcolor(4) > print apples_left, > textcolor(7) > print "left in the basket." The above code is very easy to understand when looking at it, but from what I see of other programmers this would not be as pythonic. > > The way I'd handle thus is to create a function which takes a > list of tuples as input, with each tuple containing the string > and its colour: > > def colorPrint(strings): > for string in strings: > textcolor(string[1]) > print string[0], > In the above function please let me know if I am correct in my interpretation. The first line of course would be the defining of the function and puting something in the parenthesis indicates that you will be passing a value to this function. The second line says that for each string in the colorPrint statement check to see what the color code is. The third line says that if it detects a ",#" to change it to a color based on the textcolor function in the WConio module. The fourth line puzzles me though. I think it says that when the textcolor returns the zero that it doesn't print the None? I am not sure though. Could you let me know if I have the right idea? Thanks in advance, Katt From cwitts at compuscan.co.za Fri Oct 16 12:20:51 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 16 Oct 2009 12:20:51 +0200 Subject: [Tutor] Most pythonic input validation In-Reply-To: References: Message-ID: <4AD84903.4070308@compuscan.co.za> Katt wrote: > >> Message: 3 >> Date: Thu, 15 Oct 2009 16:50:57 +0100 >> From: Rich Lovely >> To: Wayne Werner >> Cc: "tutor at python.org" >> Subject: Re: [Tutor] Most pythonic input validation >> Message-ID: >> >> Content-Type: text/plain; charset=windows-1252 >> >> 2009/10/15 Wayne Werner : >>> Hi, >>> I'm writing a text based menu and want to validate the user input. I'm >>> giving the options as integers, and I want to make sure the user >>> enters a >>> proper value. >>> Here's what I've got so far:?http://pastebin.com/m1fdd5863 >>> I'm most interested in this segment: >>> ?? ?while True: >>> ?? ? ? ?choice = raw_input(prompt) >>> ?? ? ? ?if valid_choice(choice, 0, len(options)-1): >>> ?? ? ? ? ? ?break >>> ?? ?return choice >>> Is that the most pythonic way of validating? Is there a better way? >>> As an aside, in the valid_choice function I know I could do: >>> if not choice in range(min, max) >>> but I figured a comparison would probably be the better choice, >>> correct? >>> Thanks, >>> Wayne >>> -- >>> To be considered stupid and to be told so is more painful than being >>> called >>> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every >>> weakness, >>> every vice, has found its defenders, its rhetoric, its ennoblement and >>> exaltation, but stupidity hasn?t. - Primo Levi >>> >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> The most pythonic way would be to use a try except block: >> >> while True: >> choice = raw_input(prompt) >> try: >> options[int(choice)] >> except (KeyError, IndexError, TypeError): >> print "Invalid input, try again." >> continue >> return choice >> >> >> Also, did you want to convert choice to an int at some point? You >> appear to be comparing it to a number in valid_choice(), but it will >> be passed out of the method as a str. >> >> Hence I've added a conversion to int, and I'm catching KeyError (for >> dicts), IndexError (for lists), and TypeError, for when int(choice) >> fails. >> >> This is a principle called "It's Easier to Ask Forgiveness than >> Permission" (EAFP), which is one of the pythonic principles. >> >> >> Hope that helps. >> -- >> Rich "Roadie Rich" Lovely > > As I am a new programmer I am specifically trying to pay attention to > when you guys discuss making thing more python like. > > I am a bit confused though on a couple things in this code. Probably > since I have not dealt with it as of yet. > > The first is the while statement. I have made a successful menu > selection but my while statement is: > while prompt != 0: > 0 of course meaning exit. Does "while True:" mean the same? > > Second is the input statement. Could you not just put choice = > int(raw_input(prompt)) instead of using two different statements? Or > is it that my example will return as string? > > The third is the "try" statement. How is this different from the > "for" loop or "if" loop? > > The fourth is except (KeyError, IndexError, TypeError): why do you > check for three different types of errors? > > Thanks in advance, > > Katt > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > 1) `while True` will result in an infinite loop unless you test for your prompt condition inside the loop and if it's true then use a break statement to exit the loop, eg. while True: if prompt == 0: break 2) If you were to put the `choice = int(raw_input(prompt))` into one line, remember to put it in a try/except block as you could be casting an alphanumeric into an integer. The reasoning behind putting it on two lines is to increase readability and so that you have a variable `choice` which contains the actual input in case you wanted to use it for something if it causes an exception, eg. choice = raw_input(prompt) try: options[int(choice)] except (KeyError, IndexError, TypeError): print '%s is not a valid choice' % choice 3) If you start a `try` block it is because you want to handle any errors occurring from the statements / expressions in the block itself. It is not a loop, it just runs through once completely or until it receives the first exception and in that case then moves onto the `except` section 4) The three exceptions lists are for various errors that might have occurred. The KeyError is if `options` is a dictionary and the key (contained in choice) is not in your dictionary, although for a dictionary I would rather write `if int(choice) in options:`. The IndexError is if `options` is a list and your choice was supposed to be the index that you want to seek to, eg. options = ['Exit', 'Start New Game', 'High Scores'] choice = raw_input(prompt) # lets say you use the number 3 here try options[int(choice)] except IndexError: print 'Selection out of range, please use a number between 0 and %s' % (len(options)-1) Counting starts from zero so there are 0, 1, 2 as valid choices in this example. The TypeError, should be a ValueError, is for catching conversion errors. If you supply a choice of 'a' and try and convert that to an integer it will throw a ValueError letting you know that what you are trying to convert is not an integer. TypeError will catch a NoneType conversion which you won't be able to type in on the console. Hope that helps. -- Kind Regards, Christian Witts From davea at ieee.org Fri Oct 16 12:44:18 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 16 Oct 2009 06:44:18 -0400 Subject: [Tutor] Putting a variable into a statement In-Reply-To: <4AD79F57.2060205@gmail.com> References: <942041.13002.qm@web51809.mail.re2.yahoo.com> <4AD79F57.2060205@gmail.com> Message-ID: <4AD84E82.3030705@ieee.org> bob gailer wrote: > GoodPotatoes wrote: >> : >> for x in myuser.properties: # "myuser.properties" returns a tuple >> of properties associated with the myuser AD object >> print myuser.x >> >> Traceback (most recent call last): >> File "", line 2, in >> print myuser.x >> File "build\bdist.win32\egg\active_directory.py", line 421, in >> __getattr__ >> raise AttributeError >> AttributeError >> > > print getattr(myuser ,x) > >> >> example: >> >>> myuser.properties[0] #first value in user tuple >> u'cn' >> >>> myuser.cn >> u'Joe Sixpack' >> >> How can I iterate through all of the values of the properties tuple >> and get each value? >> > I haven 't downloaded your module active_directory, ( http://timgolden.me.uk/python/active_directory.html ) so I'll just post something that works for me (python 2.6.2), and you can check if it works for you as well. class MyClass(object): pass obj = MyClass() obj.xyzzy = 44 obj.label = "text" #This displays attributes and values for a lot more than what you want here. But it can be useful. for att in dir(obj): print att, "---", getattr(obj, att) print "-----------" #This is probably what you're asking about. Use __dict__ to get the attribute names, and then getattr() to get their values. for att in obj.__dict__: print att, "---", getattr(obj, att) #or even for att, value in obj.__dict__.items(): print att, "---", value HTH DaveA From davea at ieee.org Fri Oct 16 13:21:42 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 16 Oct 2009 07:21:42 -0400 Subject: [Tutor] Understanding what the code does behind the scenes In-Reply-To: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> References: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> Message-ID: <4AD85746.9090300@ieee.org> Katt wrote: >> >> The textcolor() function returns None. so you need to keep it >> out of your print statement:. This means you need to split your >> print into multiple separate statements. (This will also be true >> for the pywin32 version) >> >> print "There are", >> textcolor(4) >> print apples_left, >> textcolor(7) >> print "left in the basket." > > The above code is very easy to understand when looking at it, but from > what I see of other programmers this would not be as pythonic. > Nothing wrong with that code. It's readable, and everything is in one place. But if you had a dozen items insstead of three, you'd get pretty tired of typing, and even more important, the next maintainer of the code will get tired of reading. Having lots of similar code with a repeating pattern is a good clue that factoring might be called for.. >> >> The way I'd handle thus is to create a function which takes a >> list of tuples as input, with each tuple containing the string >> and its colour: >> >> def colorPrint(strings): >> for string in strings: >> textcolor(string[1]) >> print string[0], >> > > In the above function please let me know if I am correct in my > interpretation. > The first line of course would be the defining of the function and > puting something in the parenthesis indicates that you will be passing > a value to this function. > The second line says that for each string in the colorPrint statement > check to see what the color code is. > The third line says that if it detects a ",#" to change it to a color > based on the textcolor function in the WConio module. > The fourth line puzzles me though. I think it says that when the > textcolor returns the zero that it doesn't print the None? I am not > sure though. > > Could you let me know if I have the right idea? > > Thanks in advance, > > Katt > I'm in a good position to critique this function, since I recently posted a similarly confusing function. Your questions tell me the function needs to be reworked, for readability. My attempt at readability (untested): def colorPrint(color_items): #1 """Call this function to print one or more strings, each with a color number specified, to the console. The argument is a list of items, where each item is a tuple consisting of a string and an integer color number, with the color number determining what color the string will be displayed in. This function will not work with redirection, as the color logic only works with the Win32 console.""" #2 for text, color in color_items: #3 textcolor(color) #4 print text #5 I added line-number comments, just so we can comment on the lines without any confusion as to which ones we're talking about. #1 - This is the function declaration line; the function takes a single parameter, a list of color items. #2 - This is a docstring, used to explain what the function is for, and briefly how to use it. There are utilities to deal with docstrings, so it's better than just putting comments inline. #3 - This is a loop construct, that iterates over the list that was passed as an argument to the function. Notice the "text, color" syntax. That automatically unpacks the tuple that each item of the list is supposed to be. #4 - This is the win32 call that tells the console to change color. There's no ",#" logic or anything else. It's simply taking a number and passing it to the console system. #5 - This is an ordinary print, that goes to sys.stdout. Notice that if it's redirected, the colors will still go to the console, so the redirected file will not have any color information in it. It would be possible (and maybe even desirable) to write a different function to just take a single string, and parse it for some escape sequence to cause the color changes. But that's not what this one does. HTH DaveA From eike.welk at gmx.net Fri Oct 16 13:53:43 2009 From: eike.welk at gmx.net (Eike Welk) Date: Fri, 16 Oct 2009 13:53:43 +0200 Subject: [Tutor] Understanding what the code does behind the scenes In-Reply-To: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> References: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> Message-ID: <200910161353.43784.eike.welk@gmx.net> On Friday 16 October 2009, Katt wrote: > > print "There are", > > textcolor(4) > > print apples_left, > > textcolor(7) > > print "left in the basket." > > The above code is very easy to understand when looking at it, but > from what I see of other programmers this would not be as pythonic. I think it's perfectly Pythonic, because it is easy to understand. I always try to make my programs look so simple that an 8 year old child could understand them. But I'm not always successful. One problem with a simple structure is, that a function might become long. And then it is difficult to understand because of its length. This is one reason why programming is an art. (Offcourse you can disagree and enjoy cleverly written Programs, that only the most smart people can understand. Programs, that are like the intricate gears of expensive Swiss wristwatches. But you should rather learn C++ in this case. :-)) I have an other idea for a color function. It cam be embedded in the print statement because it returns an empty string: def color(color_num): '''Change text color and return empty string.''' textcolor(color_num) return '' print "There are", color(4), apples_left, \ color(7), "left in the basket." #or print "There are " + color(4) + str(apples_left) \ + color(7) + " left in the basket." Kind regards, Eike. From robert.johansson at math.umu.se Fri Oct 16 13:25:08 2009 From: robert.johansson at math.umu.se (Robert Johansson) Date: Fri, 16 Oct 2009 13:25:08 +0200 Subject: [Tutor] Most pythonic input validation In-Reply-To: References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> Message-ID: <000c01ca4e53$51597630$f40c6290$@johansson@math.umu.se> > Hi, > I'm writing a text based menu and want to validate the user input. I'm > giving the options as integers, and I want to make sure the user enters a > proper value. > Here's what I've got so far:?http://pastebin.com/m1fdd5863 > I'm most interested in this segment: > ?? ?while True: > ?? ? ? ?choice = raw_input(prompt) > ?? ? ? ?if valid_choice(choice, 0, len(options)-1): > ?? ? ? ? ? ?break > ?? ?return choice > Is that the most pythonic way of validating? Is there a better way? > As an aside, in the valid_choice function I know I could do: > if not choice in range(min, max) > but I figured a comparison would probably be the better choice, correct? > Thanks, > Wayne > -- > To be considered stupid and to be told so is more painful than being called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn?t. - Primo Levi > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > The most pythonic way would be to use a try except block: while True: choice = raw_input(prompt) try: options[int(choice)] except (KeyError, IndexError, TypeError): print "Invalid input, try again." continue return choice Also, did you want to convert choice to an int at some point? You appear to be comparing it to a number in valid_choice(), but it will be passed out of the method as a str. Hence I've added a conversion to int, and I'm catching KeyError (for dicts), IndexError (for lists), and TypeError, for when int(choice) fails. This is a principle called "It's Easier to Ask Forgiveness than Permission" (EAFP), which is one of the pythonic principles. Hope that helps. -- Rich "Roadie Rich" Lovely What if a valid user input has to be an integer between 10 and 20? I mean, it could be that you are doing something that only makes sense for that input. Would it be pythonic to add a test like: If prompt in range(10,21): ... else: ... raise an error If I understand the error handling correctly you can add your own user defined error, but is that really what you should do in that case? /Robert From kent37 at tds.net Fri Oct 16 14:12:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Oct 2009 08:12:50 -0400 Subject: [Tutor] Most pythonic input validation In-Reply-To: <921847067735067219@unknownmsgid> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> <921847067735067219@unknownmsgid> Message-ID: <1c2a2c590910160512s301e7fd5jba2bd3af93b5623@mail.gmail.com> On Fri, Oct 16, 2009 at 7:25 AM, Robert Johansson wrote: > What if a valid user input has to be an integer between 10 and 20? I mean, > it could be that you are doing something that only makes sense for that > input. Would it be pythonic to add a test like: > > If prompt in range(10,21): Better to write if 10 <= prompt <= 20: > ?... > else: > ?... raise an error > > If I understand the error handling correctly you can add your own user > defined error, but is that really what you should do in that case? It depend on the context. You could raise ValueError (it's OK to raise built-in exception types if they apply) or your own exception type or just handle the error. Kent From cwitts at compuscan.co.za Fri Oct 16 14:15:53 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 16 Oct 2009 14:15:53 +0200 Subject: [Tutor] Most pythonic input validation In-Reply-To: <000c01ca4e53$51597630$f40c6290$@johansson@math.umu.se> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> <000c01ca4e53$51597630$f40c6290$@johansson@math.umu.se> Message-ID: <4AD863F9.8040803@compuscan.co.za> Robert Johansson wrote: >> Hi, >> I'm writing a text based menu and want to validate the user input. I'm >> giving the options as integers, and I want to make sure the user enters a >> proper value. >> Here's what I've got so far: http://pastebin.com/m1fdd5863 >> I'm most interested in this segment: >> while True: >> choice = raw_input(prompt) >> if valid_choice(choice, 0, len(options)-1): >> break >> return choice >> Is that the most pythonic way of validating? Is there a better way? >> As an aside, in the valid_choice function I know I could do: >> if not choice in range(min, max) >> but I figured a comparison would probably be the better choice, correct? >> Thanks, >> Wayne >> -- >> To be considered stupid and to be told so is more painful than being >> > called > >> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every >> > weakness, > >> every vice, has found its defenders, its rhetoric, its ennoblement and >> exaltation, but stupidity hasn?t. - Primo Levi >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > The most pythonic way would be to use a try except block: > > while True: > choice = raw_input(prompt) > try: > options[int(choice)] > except (KeyError, IndexError, TypeError): > print "Invalid input, try again." > continue > return choice > > > Also, did you want to convert choice to an int at some point? You > appear to be comparing it to a number in valid_choice(), but it will > be passed out of the method as a str. > > Hence I've added a conversion to int, and I'm catching KeyError (for > dicts), IndexError (for lists), and TypeError, for when int(choice) > fails. > > This is a principle called "It's Easier to Ask Forgiveness than > Permission" (EAFP), which is one of the pythonic principles. > > > Hope that helps. > >>> What if a valid user input has to be an integer between 10 and 20? I mean, it >>> could be that you are doing something that only makes sense for that input. >>> Would it be pythonic to add a test like: >>> If prompt in range(10,21): >>> ... >>> else: >>> ... raise an error >>> >>> If I understand the error handling correctly you can add your own user >>> defined error, but is that really what you should do in that case? >>> >>> /Robert `if prompt in range(start, stop)` would require building the list every single time you try to make a choice rendering it slower than `if start <= choice <= stop`, although on a small choice set the speed difference would hardly be noticeable. -- Kind Regards, Christian Witts From kent37 at tds.net Fri Oct 16 14:16:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Oct 2009 08:16:11 -0400 Subject: [Tutor] Understanding what the code does behind the scenes In-Reply-To: <200910161353.43784.eike.welk@gmx.net> References: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> <200910161353.43784.eike.welk@gmx.net> Message-ID: <1c2a2c590910160516l46ee8164yba6eae513f435067@mail.gmail.com> On Fri, Oct 16, 2009 at 7:53 AM, Eike Welk wrote: > I have an other idea for a color function. It cam be embedded in the > print statement because it returns an empty string: > > > def color(color_num): > ? ?'''Change text color and return empty string.''' > ? ?textcolor(color_num) > ? ?return '' > > print "There are", color(4), apples_left, \ > ? ? ?color(7), "left in the basket." This will put double spaces between the actual strings. Kent From kent37 at tds.net Fri Oct 16 14:21:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Oct 2009 08:21:06 -0400 Subject: [Tutor] Understanding what the code does behind the scenes In-Reply-To: <4AD85746.9090300@ieee.org> References: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> <4AD85746.9090300@ieee.org> Message-ID: <1c2a2c590910160521kad9faa3nf91365fb66e41a75@mail.gmail.com> On Fri, Oct 16, 2009 at 7:21 AM, Dave Angel wrote: > My attempt at readability ?(untested): > > def colorPrint(color_items): ? ? ? #1 > ? """Call this function to print one or more strings, each with > ? ? ? a color number specified, to the console. ?The argument > ? ? ? is a list of items, where each item is > ? ? ? a tuple consisting of a string and an integer color number, > ? ? ? with the color number determining what color the string > ? ? ? will be displayed in. ?This function will not work with > ? ? ? redirection, as the color logic only works with the Win32 console.""" > ? #2 > ? for text, color in color_items: ? ? ?#3 > ? ? ? textcolor(color) ? ? ? ? ?#4 > ? ? ? print text ? ? ? ? ? ? ? ? ? ?#5 I would make the signature def colorPrint(*color_items): This was the caller doesn't need to enclose the arguments in a list, it would be called like colorPrint(('text', 0), ('more text', 1)) Another way to do this would be to make an object to hold the color value and a print function that special cases it. A sketch: class Style(object): def __init__(self, style): self.style = style def set_style(self): # Set the text color according to self.style def colorPrint(*items): for item in items: if isinstance(item, Style): item.set_style() else: print item, Now you can say colorPrint(Style(0), 'some text', Style(1), 'some text in a different color') Kent From eike.welk at gmx.net Fri Oct 16 14:29:42 2009 From: eike.welk at gmx.net (Eike Welk) Date: Fri, 16 Oct 2009 14:29:42 +0200 Subject: [Tutor] Oh no! Wrong advice! In-Reply-To: <200910161353.43784.eike.welk@gmx.net> References: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> <200910161353.43784.eike.welk@gmx.net> Message-ID: <200910161429.42701.eike.welk@gmx.net> Well, my ideas weren't so good: On Friday 16 October 2009, Eike Welk wrote: > I have an other idea for a color function. It cam be embedded in > the print statement because it returns an empty string: > > > def color(color_num): > '''Change text color and return empty string.''' > textcolor(color_num) > return '' > > print "There are", color(4), apples_left, \ > color(7), "left in the basket." This one is a bit inelegant; look at Kent's mail. > > #or > > print "There are " + color(4) + str(apples_left) \ > + color(7) + " left in the basket." And this statement unfortunately doesn't work. The color change commands are both executed when the string is assembled; before the string is printed. So the whole text is printed in color 7. Sorry for wasting your time, Eike. From alan.gauld at btinternet.com Fri Oct 16 14:41:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Oct 2009 13:41:38 +0100 Subject: [Tutor] Most pythonic input validation References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> <37439.8431661122$1255694206@news.gmane.org> Message-ID: "Robert Johansson" wrote > What if a valid user input has to be an integer between 10 and 20? > Would it be pythonic to add a test like: > > If prompt in range(10,21): > ... > else: > ... raise an error Yes and it could be a ValueError in this case. You could also test using conditions which, for a wide range, would be more efficient if minVal < choice < maxVal: ... else: raise ValueError("Choice (%d) should be between %d and %d" % (choice, minVal, maxVal) ) > If I understand the error handling correctly you can add your own user > defined error, but is that really what you should do in that case? In this case I'd just use ValueError although I would add a string message to state the valid range, as shown above. But it is a trivial task to create a custom Exception class: class RangeError(Exception): pass and then raise RangeError("Choice (%d) should be between %d and %d" % (choice, minVal, maxVal) ) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Oct 16 14:54:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Oct 2009 13:54:37 +0100 Subject: [Tutor] PyWin32 - Library of functions to interact with windows References: <91033731D792444D86377B15C2CB863E@COMPUTER01> Message-ID: "Katt" wrote > and Alan Gauld's: Tutor - > May 27, 2007). Oops, thats the old Freenet version. The most recent one(with a few bug fixes etc) is as per my .sig... (The 3 yucky Geocities images at the top will be disappearing soon as I finally move the files to the new server and turn off the redirect (hopefully this weekend!) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Oct 16 15:04:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Oct 2009 14:04:47 +0100 Subject: [Tutor] Understanding what the code does behind the scenes References: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> Message-ID: "Katt" wrote >> def colorPrint(strings): >> for string in strings: >> textcolor(string[1]) >> print string[0], >> > > In the above function please let me know if I am correct in my > interpretation. > The first line of course would be the defining of the function and puting > something in the parenthesis indicates that you will be passing a value > to this function. Correct > The second line says that for each string in the colorPrint statement > check to see what the color code is. no, it assigns each item in the input value strings to a local variable string > The third line says that if it detects a ",#" to change it to a color > based on the textcolor function in the WConio module. no, it pulls out the second value from the string tuple passed in and applies it via the wconio function textcolor(). > The fourth line puzzles me though. I think it says that when the > textcolor returns the zero that it doesn't print the None? I am not sure > though. No it selects the first item from the string tuple and prints it. So for colorPrint(("here is a ",15), ("warning", 5)) the loop first of all sets string to the tuple ("here is a ",15) it then extracts the color, 15, by using string[1] and applies it via textcolor() it then extracts the first tuple element "here is a " and prints it. the loop then sets string to the second tuple ("warning", 5) it then extracts the color, 5, by using string[1] and applies it via textcolor() it then extracts the first tuple element "warning" and prints it. So for this example we could replace the function call with textcolor(15) print "here is a ", textcolor(5) print "warning", > Could you let me know if I have the right idea? Not quite, you need to revise on tuples and how to index their contents and for loops. In my tutorial you will find the tuple info in the Raw Materials topic and the for loops in the Loops topic. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Oct 16 15:07:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Oct 2009 14:07:20 +0100 Subject: [Tutor] Understanding what the code does behind the scenes References: <9896CEB564244C29ADA29A94A7533CEB@COMPUTER01> <4AD85746.9090300@ieee.org> Message-ID: "Dave Angel" wrote > for text, color in color_items: #3 > textcolor(color) #4 > print text #5 Ah! Good call, I never thought of unpacking the tuple in the loop. Big improvement. > It would be possible (and maybe even desirable) to write a different > function to just take a single string, and parse it for some escape > sequence to cause the color changes. But that's not what this one does. I considered doing that but figured the OP would get even more confused if I tried that! :-) Alan G. From robert.johansson at math.umu.se Fri Oct 16 15:44:46 2009 From: robert.johansson at math.umu.se (Robert Johansson) Date: Fri, 16 Oct 2009 15:44:46 +0200 Subject: [Tutor] Most pythonic input validation In-Reply-To: <1c2a2c590910160512s301e7fd5jba2bd3af93b5623@mail.gmail.com> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> <921847067735067219@unknownmsgid> <1c2a2c590910160512s301e7fd5jba2bd3af93b5623@mail.gmail.com> Message-ID: <004c01ca4e66$d344c290$79ce47b0$@johansson@math.umu.se> > What if a valid user input has to be an integer between 10 and 20? I mean, > it could be that you are doing something that only makes sense for that > input. Would it be pythonic to add a test like: > > If prompt in range(10,21): Better to write if 10 <= prompt <= 20: > ?... > else: > ?... raise an error > > If I understand the error handling correctly you can add your own user > defined error, but is that really what you should do in that case? It depend on the context. You could raise ValueError (it's OK to raise built-in exception types if they apply) or your own exception type or just handle the error. Kent Thanks Kent, If I wanted prompt to be an integer, is my check with range still bad? Is this the way to define my own error and to use it: class MyValueError(Exception): define initialization and printing try: if test ok: ... else: raise MyValueError except MyValueError: ... From zstumgoren at gmail.com Fri Oct 16 15:53:09 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 16 Oct 2009 09:53:09 -0400 Subject: [Tutor] way to see code execution in real-time? Message-ID: Hello everybody, I was wondering -- is there a way to "watch" a program execute by piping a report of its actions to standard output or to a file? Basically, I'd like to see the order that functions/methods are executing as they happen, along with how long each one takes. Is this something cProfile would do, or is there another tool built for that purpose? Thanks! Serdar From lowelltackett at yahoo.com Fri Oct 16 17:52:26 2009 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Fri, 16 Oct 2009 08:52:26 -0700 (PDT) Subject: [Tutor] way to see code execution in real-time? In-Reply-To: Message-ID: <885067.10384.qm@web110114.mail.gq1.yahoo.com> Try the "pdb" module--the python debugger. >From the virtual desk of Lowell Tackett? --- On Fri, 10/16/09, Serdar Tumgoren wrote: From: Serdar Tumgoren Subject: [Tutor] way to see code execution in real-time? To: "Python Tutor" Date: Friday, October 16, 2009, 9:53 AM Hello everybody, I was wondering -- is there a way to "watch" a program execute by piping a report of its actions to standard output or to a file? Basically, I'd like to see the order that functions/methods are executing as they happen, along with how long each one takes. Is this something cProfile would do, or is there another tool built for that purpose? Thanks! Serdar _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Oct 16 17:54:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Oct 2009 11:54:29 -0400 Subject: [Tutor] Most pythonic input validation In-Reply-To: <-4884959348189443883@unknownmsgid> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> <921847067735067219@unknownmsgid> <1c2a2c590910160512s301e7fd5jba2bd3af93b5623@mail.gmail.com> <-4884959348189443883@unknownmsgid> Message-ID: <1c2a2c590910160854w2526f0e1qd69ff09995b7cf4c@mail.gmail.com> On Fri, Oct 16, 2009 at 9:44 AM, Robert Johansson wrote: > If I wanted prompt to be an integer, is my check with range still bad? If the prompt is coming from raw_input() then you have already guaranteed it is an integer when you convert it in a try/except block. > Is this the way to define my own error and to use it: > > class MyValueError(Exception): > ?define initialization and printing You usually don't need to define anything extra, the Exception methods are fine. > try: > ?if test ok: > ? ? ... > ?else: > ? ? raise MyValueError raise MyValueError() # with parentheses to create an instance > except MyValueError: Kent From kent37 at tds.net Fri Oct 16 18:00:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Oct 2009 12:00:00 -0400 Subject: [Tutor] way to see code execution in real-time? In-Reply-To: References: Message-ID: <1c2a2c590910160900vef96a6bi4f0c58d1d953064d@mail.gmail.com> On Fri, Oct 16, 2009 at 9:53 AM, Serdar Tumgoren wrote: > Hello everybody, > > I was wondering -- is there a way to "watch" a program execute by > piping a report of its actions to standard output or to a file? > Basically, I'd like to see the order that functions/methods are > executing as they happen, along with how long each one takes. > > Is this something cProfile would do, or is there another tool built > for that purpose? The profiler will show you which functions are called and how long they take but it does not show you the order in which they are called. I think CodeInvestigator tracks the order of execution but I have never tried it: http://codeinvestigator.googlepages.com/main And of course a debugger (pdb or WinDbg for example) will let you follow along as functions execute, but I don't think they will show you times. Kent From alan.gauld at btinternet.com Fri Oct 16 19:29:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Oct 2009 18:29:03 +0100 Subject: [Tutor] way to see code execution in real-time? References: Message-ID: "Serdar Tumgoren" wrote > I was wondering -- is there a way to "watch" a program execute by > piping a report of its actions to standard output or to a file? There are tools for doing that - Look! - is one I know that works for C++ and Java but I don;t know iof any freware ones or that work for Python. > Basically, I'd like to see the order that functions/methods are > executing as they happen, along with how long each one takes. You can run it in any debugger and use the step into/step over buttons to walk through the code. But it is extremely tiresome! One of my colleagues once spent nearly two weeks stepping though some undocumented code we had been given to find out how it works. He was not a happy man. If you do go that way I strongly recommend using a graphical front end like IDLE/Pythonwin/Eclipse(PyDev) etc. > Is this something cProfile would do, or is there another tool built > for that purpose? Never come across cProfile but profiling tools generally just give you a report at the ed of what has been executed. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zstumgoren at gmail.com Fri Oct 16 19:43:22 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 16 Oct 2009 13:43:22 -0400 Subject: [Tutor] way to see code execution in real-time? In-Reply-To: References: Message-ID: Hey everybody, Thanks for the recommendations -- I usually do use pdb to step through chunks of code, but always by setting a breakpoint. And then I have to "manually" print out the variables to see what's going on in the code. Is there a way to wrestle pdb into spitting out the code being executed, as it executes (without having to manually do so myself)? Perhaps a profiler will get me most of the way to where. The time element isn't as necessary for me as understanding what gets fired, how many times, etc. It would be great to see the order of execution, so I'll try CodeInvestigator to see if that will do the trick. Meantime, thanks as always! Serdar On Fri, Oct 16, 2009 at 1:29 PM, Alan Gauld wrote: > > "Serdar Tumgoren" wrote > >> I was wondering -- is there a way to "watch" a program execute by >> piping a report of its actions to standard output or to a file? > > There are tools for doing that - Look! - is one I know that works for C++ > and Java but I don;t know iof any freware ones or that work for Python. > >> Basically, I'd like to see the order that functions/methods are >> executing as they happen, along with how long each one takes. > > You can run it in any debugger and use the step into/step over buttons to > walk through the code. But it is extremely tiresome! > One of my colleagues once spent nearly two weeks stepping though some > undocumented code we had been given to find out how it works. He was not a > happy man. > > If you do go that way I strongly recommend using a graphical front end like > IDLE/Pythonwin/Eclipse(PyDev) etc. > >> Is this something cProfile would do, or is there another tool built >> for that purpose? > > Never come across cProfile but profiling tools ?generally just give you a > report at the ed of what has been executed. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Oct 16 20:24:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Oct 2009 14:24:56 -0400 Subject: [Tutor] way to see code execution in real-time? In-Reply-To: References: Message-ID: <1c2a2c590910161124u46f06c03s741ccdd5f29814f8@mail.gmail.com> On Fri, Oct 16, 2009 at 1:43 PM, Serdar Tumgoren wrote: > Hey everybody, > > Thanks for the recommendations -- I usually do use pdb to step through > chunks of code, but always by setting a breakpoint. And then I have to > "manually" print out the variables to see what's going on in the code. WinPdb (sorry, not WinDbg) or other graphical debuggers will show you the variables. http://winpdb.org/docs/ > > Is there a way to wrestle pdb into spitting out the code being > executed, as it executes (without having to manually do so myself)? You can do this with the settrace() function. Here is an example: http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html Kent From nathan.farrar at gmail.com Fri Oct 16 21:45:29 2009 From: nathan.farrar at gmail.com (Nathan Farrar) Date: Fri, 16 Oct 2009 13:45:29 -0600 Subject: [Tutor] Help with pexpect Message-ID: <348a45770910161245v3dddf02cge158eec0e8547c40@mail.gmail.com> I'm trying to automate the collection of data to remote devices over ssh via pexpect. I had originally attempted (with limited success) to use paramiko, however due to cisco's ssh implimentation I cannot send mulitple commands over the same connection, which is absolutely essential. Therefore, I'm now attempting to use pexpect, but am having trouble getting started. I have a simple script, such as: session = pexpect.spawn('ssh user at host') session.expect([pexpect.TIMETOUT, 'password:']) session.send('password') print session.read() # shouldn't this display the logon banner & command prompt? session.close() This code results in no output & a hanging window. What am I doing incorrect? Additionally, I will need to add conditional pexpect statements, such that when I execute a command I want to gather the output, however if '--More--' is encountered (and it this can happen multiple times), I want to send a newline character to the session and continue gathering the output. Thanks for the help! Nathan -- "The presence of those seeking the truth is infinitely to be preferred to the presence of those who think they've found it." ?Terry Pratchett From vinces1979 at gmail.com Fri Oct 16 22:33:36 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 16 Oct 2009 14:33:36 -0600 Subject: [Tutor] Help with pexpect In-Reply-To: <348a45770910161245v3dddf02cge158eec0e8547c40@mail.gmail.com> References: <348a45770910161245v3dddf02cge158eec0e8547c40@mail.gmail.com> Message-ID: <1e53c510910161333x72c327c3n4dca0ff94f08608d@mail.gmail.com> On Fri, Oct 16, 2009 at 1:45 PM, Nathan Farrar wrote: > I'm trying to automate the collection of data to remote devices over > ssh via pexpect. I had originally attempted (with limited success) to > use paramiko, however due to cisco's ssh implimentation I cannot send > mulitple commands over the same connection, which is absolutely > essential. Therefore, I'm now attempting to use pexpect, but am > having trouble getting started. I have a simple script, such as: > > session = pexpect.spawn('ssh user at host') > session.expect([pexpect.TIMETOUT, 'password:']) > session.send('password') > print session.read() # shouldn't this display the logon banner & command > prompt? > session.close() > > This code results in no output & a hanging window. What am I doing > incorrect? > > Additionally, I will need to add conditional pexpect statements, such > that when I execute a command I want to gather the output, however if > '--More--' is encountered (and it this can happen multiple times), I > want to send a newline character to the session and continue gathering > the output. > > Thanks for the help! > Nathan > > -- > "The presence of those seeking the truth is infinitely to be preferred > to the presence of those who think they've found it." > > ?Terry Pratchett > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > when using pexpect for ssh you can run into some issues, I have used to script some elaborate green screen apps, but not without some unforeseen bugs when connecting to a new machine, most ssh client will ask you verify the fingerprint something like: > are you sure you want to continue (yes/no)? also session.send < doesn't send eol "\n" but sendline does So this should fix your connection ### session = pexpect.spawn('ssh user at host') i = session.expect([pexpect.TIMETOUT, 'password:', "yes/no"]) if i == 2: session.sendline("yes") session.expect([pexpect.TIMETOUT, 'password:']) if i == 1: session.sendline('password') print session.read() # shouldn't this display the logon banner & command prompt? session.close() ### the other your question, pexpects sendline(''), will just send a newline not perfect but should work ### license = "" while True: i = session.expect(["--more--", "yes/no"]) if i == 1: break license += session.before session.sendline('') ### Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From mzanfardino at gmail.com Fri Oct 16 22:43:35 2009 From: mzanfardino at gmail.com (Mark K. Zanfardino) Date: Fri, 16 Oct 2009 13:43:35 -0700 Subject: [Tutor] Help with pexpect In-Reply-To: <348a45770910161245v3dddf02cge158eec0e8547c40@mail.gmail.com> References: <348a45770910161245v3dddf02cge158eec0e8547c40@mail.gmail.com> Message-ID: <1255725815.4935.112.camel@mycroft64.Hormann> Nathan, Depending upon how much control you have over the calling machine you can eliminate the pesky password prompt from ssh altogether by creating a private/public key pair for the client machine and copy the public key to the host machine. This way when you ssh to the host you will be authenticated based on the key pair. Check out ssh-copy-id. Mark On Fri, 2009-10-16 at 13:45 -0600, Nathan Farrar wrote: > I'm trying to automate the collection of data to remote devices over > ssh via pexpect. I had originally attempted (with limited success) to > use paramiko, however due to cisco's ssh implimentation I cannot send > mulitple commands over the same connection, which is absolutely > essential. Therefore, I'm now attempting to use pexpect, but am > having trouble getting started. I have a simple script, such as: > > session = pexpect.spawn('ssh user at host') > session.expect([pexpect.TIMETOUT, 'password:']) > session.send('password') > print session.read() # shouldn't this display the logon banner & command prompt? > session.close() > > This code results in no output & a hanging window. What am I doing incorrect? > > Additionally, I will need to add conditional pexpect statements, such > that when I execute a command I want to gather the output, however if > '--More--' is encountered (and it this can happen multiple times), I > want to send a newline character to the session and continue gathering > the output. > > Thanks for the help! > Nathan > From the_only_katala at verizon.net Fri Oct 16 23:49:54 2009 From: the_only_katala at verizon.net (Katt) Date: Fri, 16 Oct 2009 14:49:54 -0700 Subject: [Tutor] Tutorials and How important is pseudocode References: Message-ID: <04F087709314401BB9A85A4066AAB886@COMPUTER01> > Message: 7 > Date: Fri, 16 Oct 2009 13:54:37 +0100 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] PyWin32 - Library of functions to interact with > windows > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > > "Katt" wrote > >> and Alan Gauld's: Tutor - > May 27, 2007). > > Oops, thats the old Freenet version. > > The most recent one(with a few bug fixes etc) is as per my .sig... > Thanks Alan G. I got the new version now. I will go back to the beginning and step through it again. Also, out of curiousity what does everyone think of using pseudocode? Once when I was in a programming class the teacher had us first write the program in pseudocode (writing the code in english) before we actually used real code to create the program. Thanks again, Katt From alan.gauld at btinternet.com Sat Oct 17 01:34:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Oct 2009 00:34:28 +0100 Subject: [Tutor] Tutorials and How important is pseudocode References: <04F087709314401BB9A85A4066AAB886@COMPUTER01> Message-ID: "Katt" wrote >> The most recent one(with a few bug fixes etc) is as per my .sig... >> > Thanks Alan G. I got the new version now. I will go back to the > beginning and step through it again. No, you don;t need to do that, its mainly typos and stuff thats fixed. There is no radical changes. I am currently reworking the tutor to v3 of Python and that does have some major rewrites but the v2 version is only typo chages and a few bug fixes > Also, out of curiousity what does everyone think of using pseudocode? I love pseudocode and use it all the time. > when I was in a programming class the teacher had us first write the > program in pseudocode (writing the code in english) before we actually > used real code to create the program. When I was actually writing production quality code the normal practice was to do the design down to pseudocode level then use the pseudocode as comments from which we wrote the real code. That was in C which is much lower level than Python so I don;t know if I'd use that approach writing Python. Python has been called "executable pseudo code" and whjile I don't go that far, it is far better than C. But if you are trying to explain an algorithm (or even figure one out) pseudo code saves you worrying about all the syntactical niceties For example remembering the colon after an if statement or even that you should close a file etc. You can also miss out all the try/except and other error handling, you only focus on what you need to make it work. Add the other stuff once that has been cracked. Or hide it in a blanket statemenmt like try do stuff here and more pseudocode stiff etc etc... except handle all errors The bit between try/except is true pseudocode the rest is just a reminder that you do need to do some error handling somewhere... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Sat Oct 17 04:41:45 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 16 Oct 2009 22:41:45 -0400 Subject: [Tutor] Most pythonic input validation In-Reply-To: <1c2a2c590910160854w2526f0e1qd69ff09995b7cf4c@mail.gmail.com> References: <333efb450910150736y7fc25861x9e3922a2065b88c0@mail.gmail.com> <921847067735067219@unknownmsgid> <1c2a2c590910160512s301e7fd5jba2bd3af93b5623@mail.gmail.com> <-4884959348189443883@unknownmsgid> <1c2a2c590910160854w2526f0e1qd69ff09995b7cf4c@mail.gmail.com> Message-ID: <4AD92EE9.2090901@ieee.org> Kent Johnson wrote: > > > >> Is this the way to define my own error and to use it: >> >> class MyValueError(Exception): >> define initialization and printing >> > > You usually don't need to define anything extra, the Exception methods are fine. > > > I think there could be confusion over what you meant was unnecessary. It's a "good thing" to define MyValueError(Exception), but it's usually unnecessary to give it a body, because the methods it inherits from Exception are usually just fine. DaveA From Lbrannma at yahoo.com Sat Oct 17 07:51:49 2009 From: Lbrannma at yahoo.com (LL) Date: Sat, 17 Oct 2009 07:51:49 +0200 Subject: [Tutor] cannot convert eps to png using PIL (LL) Message-ID: > It's trying to launch GhostScript, and failing. Not sure this is the problem. Ghostscript is installed on my machine. Also, I am able to convert .jpg to .png. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Sat Oct 17 11:29:46 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 17 Oct 2009 04:29:46 -0500 Subject: [Tutor] cannot convert eps to png using PIL (LL) In-Reply-To: References: Message-ID: <200910170429.46964.cfuller084@thinkingplanet.net> Like I said, you need to find out what's going wrong with GhostScript. Also, converting image formats is something PIL does internally, without requiring a (large) external package like GhostScript, which is an interpreter for a different language (PostScript), which your eps files are coded in. Cheers On Saturday 17 October 2009 00:51, LL wrote: > > It's trying to launch GhostScript, and failing. > > Not sure this is the problem. Ghostscript is installed on my machine. Also, > I am able to convert .jpg to .png. From kent37 at tds.net Sat Oct 17 15:18:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Oct 2009 09:18:02 -0400 Subject: [Tutor] cannot convert eps to png using PIL In-Reply-To: References: Message-ID: <1c2a2c590910170618t38b37622uc98af42a74ddc84f@mail.gmail.com> On Fri, Oct 16, 2009 at 12:23 AM, LL wrote: > Hi.. I also asked this question on the imaging group but thought people here > might have insights as well.. > > all of the following code executes interactively except the last line. > Converting a .jpg file to .png works fine. I'm using the PIL version for > Python 2.6. Any suggestions will be greatly appreciated. Thanks, Lance > ------------------------------------ > PythonWin 2.6.3 (r263:75183, Oct? 5 2009, 14:41:55) [MSC v.1500 32 bit > (Intel)] on win32. > Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for > further copyright information. >>>> import os >>>> import zlib >>>> import Image >>>> os.chdir("c:\\foo") >>>> img = Image.open("foo1.eps") >>>> img.save("foo1.png") > Traceback (most recent call last): > ? File "", line 1, in > ? File "C:\Python26\lib\site-packages\PIL\Image.py", line 1372, in save > ??? self.load() > ? File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 283, in > load > ??? self.im = Ghostscript(self.tile, self.size, self.fp) > ? File "C:\Python26\lib\site-packages\PIL\EpsImagePlugin.py", line 72, in > Ghostscript > ??? gs.write(s) > IOError: [Errno 32] Broken pipe Looking at the source for the Ghostscript() function in EpsImagePlugin.py', it says "Unix only". Perhaps you could make it work on Windows by changing the command line created there. Kent From nitinchandra1 at gmail.com Sun Oct 18 22:28:04 2009 From: nitinchandra1 at gmail.com (nitin chandra) Date: Mon, 19 Oct 2009 01:58:04 +0530 Subject: [Tutor] Any one got any idea Message-ID: <965122bf0910181328q1429bdcgfea3359479e15c8d@mail.gmail.com> Hello Everyone, i am compiling Python 2.6.2 from source and have successfully been able to cross .... at least that is what i am thinking ..... ./configure and make .... but i am facing a peculiar problem in installing it this time. (This is the second time i am installing on the same system with as much as similar structure like before .... this was required as i had to install Tcl / Tk 8.5 + Tix 8.4.3 --with-threads... on FC10 ... which does not have Tcl/Tk 8.5 with threads enabled in the default install.) Compiling /opt/python262/lib/python2.6/xmllib.py ... Compiling /opt/python262/lib/python2.6/xmlrpclib.py ... Compiling /opt/python262/lib/python2.6/zipfile.py ... [17894 refs] make: *** [libinstall] Error 1 [root at mi Python-2.6.2]# This is enabled in Modules/Setup # Andrew Kuchling's zlib module. # This require zlib 1.1.3 (or later). # See http://www.gzip.org/zlib/ zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz 'zipfile.py' also exist in in the source dir .../Python-2.6.2/Lib/ Thanks Nitin From zstumgoren at gmail.com Sun Oct 18 23:43:22 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Sun, 18 Oct 2009 17:43:22 -0400 Subject: [Tutor] introspecting an object for method's name? Message-ID: Hi everyone, I'm trying to create a generic logging function, and I'm able to get at the name of the module and class using the built-in attributes __module__, __class__, and __name__. But I wasn't sure how to also grab the name of the function or method, so that when an error occurs, I can log the name of the failing method as well. I'd like to do something like: class Dummy(object): get_name(self): print "%s, %s, %s" % (self.__module__, self.__class__.__name__, METHOD_NAME) Is there a way to dynamically grab the name of the method? E.g., "get_name" in the above class. Feels like I'm overlooking something obvious.... Serdar From nitinchandra1 at gmail.com Mon Oct 19 00:08:03 2009 From: nitinchandra1 at gmail.com (nitin chandra) Date: Mon, 19 Oct 2009 03:38:03 +0530 Subject: [Tutor] Any one got any idea In-Reply-To: <965122bf0910181328q1429bdcgfea3359479e15c8d@mail.gmail.com> References: <965122bf0910181328q1429bdcgfea3359479e15c8d@mail.gmail.com> Message-ID: <965122bf0910181508x18891755s8f2a147595d40a70@mail.gmail.com> On Mon, Oct 19, 2009 at 1:58 AM, nitin chandra wrote: > Hello Everyone, > > i am compiling Python 2.6.2 from source and have successfully been > able to cross .... at least that is what i am thinking ..... > ./configure and make .... but i am facing a peculiar problem in > installing it this time. (This is the second time i am installing on > the same system with as much as similar structure like before .... > this was required as i had to install Tcl / Tk 8.5 + Tix 8.4.3 > --with-threads... on FC10 ... which does not have Tcl/Tk 8.5 with > threads enabled in the default install.) > On running 'make install' i am getting the following error :- > > Compiling /opt/python262/lib/python2.6/xmllib.py ... > Compiling /opt/python262/lib/python2.6/xmlrpclib.py ... > Compiling /opt/python262/lib/python2.6/zipfile.py ... > [17894 refs] > make: *** [libinstall] Error 1 > [root at mi Python-2.6.2]# > > This is enabled in Modules/Setup > > # Andrew Kuchling's zlib module. > # This require zlib 1.1.3 (or later). > # See http://www.gzip.org/zlib/ > zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz > > > 'zipfile.py' also exist in in the source dir .../Python-2.6.2/Lib/ > > > Thanks > > Nitin > From alan.gauld at btinternet.com Mon Oct 19 01:35:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 00:35:47 +0100 Subject: [Tutor] introspecting an object for method's name? References: Message-ID: "Serdar Tumgoren" wrote > Is there a way to dynamically grab the name of the method? E.g., > "get_name" in the above class. > There may be more direct or easier ways but the traceback moduile lets you inspect the call stack to see what the current method or function is. Thats how Python produces its error message traceback... Alan G. From david at pythontoo.com Mon Oct 19 01:36:54 2009 From: david at pythontoo.com (David) Date: Sun, 18 Oct 2009 19:36:54 -0400 Subject: [Tutor] Any one got any idea In-Reply-To: <965122bf0910181508x18891755s8f2a147595d40a70@mail.gmail.com> References: <965122bf0910181328q1429bdcgfea3359479e15c8d@mail.gmail.com> <965122bf0910181508x18891755s8f2a147595d40a70@mail.gmail.com> Message-ID: <4ADBA696.2070008@pythontoo.com> nitin chandra wrote: > On Mon, Oct 19, 2009 at 1:58 AM, nitin chandra wrote: >> Hello Everyone, >> >> i am compiling Python 2.6.2 from source and have successfully been >> able to cross .... at least that is what i am thinking ..... >> ./configure and make .... but i am facing a peculiar problem in >> installing it this time. (This is the second time i am installing on >> the same system with as much as similar structure like before .... >> this was required as i had to install Tcl / Tk 8.5 + Tix 8.4.3 >> --with-threads... on FC10 ... which does not have Tcl/Tk 8.5 with >> threads enabled in the default install.) >> On running 'make install' i am getting the following error :- You are on the wrong list, try the Fedora mail list [1] or irc [2] [1] https://www.redhat.com/mailman/listinfo/fedora-list [2] http://fedoraproject.org/wiki/Communicate#IRC -- David Abbott (dabbott) From ghashsnaga at gmail.com Mon Oct 19 02:36:26 2009 From: ghashsnaga at gmail.com (Ara Kooser) Date: Sun, 18 Oct 2009 18:36:26 -0600 Subject: [Tutor] CSV question for getting data from a text file Message-ID: <2107481c0910181736l67fb96d8xbd2b16d7023ae52b@mail.gmail.com> Hello all, I fell off the python programming wagon for awhile and I am quite rusty. I a text file that looks like this *a bunch of stuff above* O(-2)/O(0) 12.5731 0.7181 ----------------------------Distribution of species---------------------------- Log Log Log Species Molality Activity Molality Activity Gamma OH- 4.121e-06 3.489e-06 -5.385 -5.457 -0.072 H+ 1.437e-09 1.259e-09 -8.843 -8.900 -0.057 H2O 5.551e+01 9.994e-01 1.744 -0.000 0.000 C(4) 5.334e-03 HCO3- 4.517e-03 3.877e-03 -2.345 -2.411 -0.066 *stuff below* I wrote this program: import string import csv, sys import matplotlib.pyplot as plt import numpy as np filein = raw_input("What is the name of your file?") testreader = csv.reader(open(filein)) for row in testreader: print(row) The output looks like this: [] ['----------------------------Distribution of species----------------------------'] [] ['\t Log Log Log '] ['\tSpecies Molality Activity Molality Activity Gamma'] [] ['\tOH- 4.121e-06 3.489e-06 -5.385 -5.457 -0.072'] ['\tH+ 1.437e-09 1.259e-09 -8.843 -8.900 -0.057'] ['\tH2O 5.551e+01 9.994e-01 1.744 -0.000 0.000'] What I am interested in is the species column and the activity column. The eventual goal is do do a bunch of calculations on the activties and plot it up using matplotlib. How do ignore everything before and after the Distribution of species and then pull out the species and activties so I can perform calculations on them? Is csv the best for that or am I better off using split and dumping into a dictionary? I think I need to specify white space as the delimiter, is that correct? Thank you very much. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 19 03:15:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 02:15:04 +0100 Subject: [Tutor] CSV question for getting data from a text file References: <2107481c0910181736l67fb96d8xbd2b16d7023ae52b@mail.gmail.com> Message-ID: "Ara Kooser" wrote > testreader = csv.reader(open(filein)) > for row in testreader: > print(row) > > The output looks like this: > [] > ['----------------------------Distribution of > species----------------------------'] > [] > ['\t Log Log Log > '] > ['\tSpecies Molality Activity Molality Activity > Gamma'] > [] > ['\tOH- 4.121e-06 > .489e-06 -5.385 -5.457 -0.072'] > > How do ignore everything before and after the Distribution of species You don't tell us how the "after species" is defined but the before bit can be done with a flag that gets set when you hit the required line: active = False for row in testreader: if not actve and "Distribution" in row: active = True elif : active = False else: process species stuff here > then pull out the species and activties so I can perform calculations on > them? Is csv the best for that or am I better off using split and dumping > into a dictionary? I think I need to specify white space as the > delimiter, > is that correct? You would need to specify whitespace. But in that case I suspect split will work just as well. Whether you feed into a dictionary or just index the list produced by split() depends on exactly what processing you need to do to the results. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Mon Oct 19 03:29:53 2009 From: srilyk at gmail.com (Wayne) Date: Sun, 18 Oct 2009 20:29:53 -0500 Subject: [Tutor] Testing for empty list Message-ID: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> Hi, I think I recall seeing this here, but I wanted to make sure I'm correct. Is the best way to test for an empty list just test for the truth value? I.e. mylist = [1,2,3] while mylist: print mylist.pop() Thanks, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Mon Oct 19 03:41:18 2009 From: vinces1979 at gmail.com (vince spicer) Date: Sun, 18 Oct 2009 19:41:18 -0600 Subject: [Tutor] Testing for empty list In-Reply-To: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> Message-ID: <1e53c510910181841o6f2de7f0q32dbc06577654b5a@mail.gmail.com> On Sun, Oct 18, 2009 at 7:29 PM, Wayne wrote: > Hi, I think I recall seeing this here, but I wanted to make sure I'm > correct. > Is the best way to test for an empty list just test for the truth value? > I.e. > > mylist = [1,2,3] > > while mylist: > print mylist.pop() > > Thanks, > Wayne > > -- > To be considered stupid and to be told so is more painful than being called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn?t. - Primo Levi > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I believe it is better to check the list length, I think some changes are coming on evaling list mylist = [1,2,3] while len(mylist) > 0: print mylist.pop() Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Mon Oct 19 08:28:35 2009 From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Mon, 19 Oct 2009 11:58:35 +0530 Subject: [Tutor] Testing for empty list In-Reply-To: <1e53c510910181841o6f2de7f0q32dbc06577654b5a@mail.gmail.com> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> <1e53c510910181841o6f2de7f0q32dbc06577654b5a@mail.gmail.com> Message-ID: <6478D7E0-14C6-4B57-8DFF-91EAA58B6DDE@gmail.com> On 19-Oct-09, at 7:11 AM, vince spicer wrote: > > > On Sun, Oct 18, 2009 at 7:29 PM, Wayne wrote: > Hi, I think I recall seeing this here, but I wanted to make sure I'm > correct. > > Is the best way to test for an empty list just test for the truth > value? I.e. > > mylist = [1,2,3] > > while mylist: > print mylist.pop() > > Thanks, > Wayne > > > I believe it is better to check the list length, I think some > changes are coming on evaling list > > > mylist = [1,2,3] > > while len(mylist) > 0: > print mylist.pop() or while mylist != []: print mylist.pop() or for reverse iteration without popping the values in the list. for x in reversed(mylist): print x regards, shantanoo From tmatsumoto at gmx.net Mon Oct 19 09:26:16 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Mon, 19 Oct 2009 09:26:16 +0200 Subject: [Tutor] Testing for empty list In-Reply-To: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> Message-ID: <20091019072616.215150@gmx.net> The while loop will print each index of the list. In a way it checks that if the list is empty by printing the items. As far as I know there isn't any 'True' or 'False' output from a list. If you want to do something if mylist is empty you can check it like this: if not mylist: ... do something ... T -------- Original-Nachricht -------- > Datum: Sun, 18 Oct 2009 20:29:53 -0500 > Von: Wayne > An: "tutor at python.org" > Betreff: [Tutor] Testing for empty list > Hi, I think I recall seeing this here, but I wanted to make sure I'm > correct. > Is the best way to test for an empty list just test for the truth value? > I.e. > > mylist = [1,2,3] > > while mylist: > print mylist.pop() > > Thanks, > Wayne > > -- > To be considered stupid and to be told so is more painful than being > called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every > weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn?t. - Primo Levi -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From andreengels at gmail.com Mon Oct 19 09:36:17 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 19 Oct 2009 09:36:17 +0200 Subject: [Tutor] Testing for empty list In-Reply-To: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> Message-ID: <6faf39c90910190036y2bd95278q74bb85cc2ad8d8ed@mail.gmail.com> On Mon, Oct 19, 2009 at 3:29 AM, Wayne wrote: > Hi, I think I recall seeing this here, but I wanted to make sure I'm > correct. > Is the best way to test for an empty list just test for the truth value? > I.e. > mylist = [1,2,3] > while mylist: > ?? print mylist.pop() Whether it is the 'best' way depends on what you mean by 'best', but I do think it's the most idiomatically pythonic one. -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Mon Oct 19 09:37:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 08:37:37 +0100 Subject: [Tutor] Testing for empty list References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> <20091019072616.215150@gmx.net> Message-ID: "Todd Matsumoto" wrote > The while loop will print each index of the list. No, the while does nothing with list indexes, that is entirely down to the programmer. The while loop simply repeats for as long as its test expression evaluates to True. > As far as I know there isn't any 'True' or 'False' output from a list. Lists are considered True if they are non empty, in the same way as strings. So the OPs test is perfectly valid while myList: do something to reduce mylist (or use break but then you should use while True) > If you want to do something if mylist is empty you can check it like > this: > > if not mylist: > ... do something ... Which is the logical inverse of what the OP was testing in his while loop. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Mon Oct 19 09:38:55 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 19 Oct 2009 02:38:55 -0500 Subject: [Tutor] Testing for empty list In-Reply-To: <20091019072616.215150@gmx.net> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> <20091019072616.215150@gmx.net> Message-ID: On Mon, Oct 19, 2009 at 2:26 AM, Todd Matsumoto wrote: > The while loop will print each index of the list. No it's printing each element of the list, not the index. > In a way it checks that if the list is empty by printing the items. As far > as I know there isn't any 'True' or 'False' output from a list. > I'm not sure what you mean here because... > > If you want to do something if mylist is empty you can check it like this: > > if not mylist: > An "if" statement checks a boolean state so the list must be evaluating to a boolean somehow. (It does, it's False if it's empty and True otherwise). -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Oct 19 10:52:40 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 19 Oct 2009 04:52:40 -0400 Subject: [Tutor] Testing for empty list In-Reply-To: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> Message-ID: <4ADC28D8.1050308@ieee.org> Wayne wrote: > Hi, I think I recall seeing this here, but I wanted to make sure I'm > correct. > Is the best way to test for an empty list just test for the truth value? > I.e. > > mylist = [1,2,3] > > while mylist: > print mylist.pop() > > Thanks, > Wayne > > My take is simple: Use the above form if you *know* that mylist is in fact a list. If you don't know its type for sure (the name is a clue, but not conclusive ;-) ) then use a more specific test. In your case, you know it's a list, or least something that supports pop(). So your form should be great. DaveA From tmatsumoto at gmx.net Mon Oct 19 11:24:48 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Mon, 19 Oct 2009 11:24:48 +0200 Subject: [Tutor] Testing for empty list In-Reply-To: <4ADC28D8.1050308@ieee.org> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> <4ADC28D8.1050308@ieee.org> Message-ID: <20091019092448.215160@gmx.net> I don't understand how the while loop efficiently tests if the list is empty. Why would going through the entire list be a good test to simply see find out if the list is empty or not. Wouldn't you want to test the list itself, rather than the contents of it? Cheers, T -------- Original-Nachricht -------- > Datum: Mon, 19 Oct 2009 04:52:40 -0400 > Von: Dave Angel > An: Wayne > CC: "tutor at python.org" > Betreff: Re: [Tutor] Testing for empty list > > > Wayne wrote: > > Hi, I think I recall seeing this here, but I wanted to make sure I'm > > correct. > > Is the best way to test for an empty list just test for the truth value? > > I.e. > > > > mylist = [1,2,3] > > > > while mylist: > > print mylist.pop() > > > > Thanks, > > Wayne > > > > > My take is simple: Use the above form if you *know* that mylist is in > fact a list. If you don't know its type for sure (the name is a clue, > but not conclusive ;-) ) then use a more specific test. > > In your case, you know it's a list, or least something that supports > pop(). So your form should be great. > > DaveA > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From stefan_ml at behnel.de Mon Oct 19 11:57:29 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 19 Oct 2009 11:57:29 +0200 Subject: [Tutor] Testing for empty list In-Reply-To: <20091019092448.215160@gmx.net> References: <333efb450910181829k185a6989ke61f2950443bdef9@mail.gmail.com> <4ADC28D8.1050308@ieee.org> <20091019092448.215160@gmx.net> Message-ID: Hi, please don't top-post. Todd Matsumoto wrote: > I don't understand how the while loop efficiently tests if the list is > empty. It doesn't. It only tests a condition. And the result of the condition is determined by the list itself, which knows if it's empty or not. Stefan From kent37 at tds.net Mon Oct 19 14:31:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Oct 2009 08:31:05 -0400 Subject: [Tutor] introspecting an object for method's name? In-Reply-To: References: Message-ID: <1c2a2c590910190531s5cc62d62p51b9baed178a2c39@mail.gmail.com> On Sunday, October 18, 2009, Serdar Tumgoren wrote: > Hi everyone, > I'm trying to create a generic logging function, and I'm able to get > at the name of the module and class using the built-in attributes > __module__, __class__, and __name__. > > But I wasn't sure how to also grab the name of the function or method, > so that when an error occurs, I can log the name of the failing method > as well. Using sys._getframe() you can get the name of the current function or the name of the calling function. Getting the name of the caller means you can wrap your logger into a function. See this recipe: http://code.activestate.com/recipes/66062/ Kent From mail at timgolden.me.uk Mon Oct 19 14:40:12 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 19 Oct 2009 13:40:12 +0100 Subject: [Tutor] introspecting an object for method's name? In-Reply-To: <1c2a2c590910190531s5cc62d62p51b9baed178a2c39@mail.gmail.com> References: <1c2a2c590910190531s5cc62d62p51b9baed178a2c39@mail.gmail.com> Message-ID: <4ADC5E2C.5000803@timgolden.me.uk> Kent Johnson wrote: > On Sunday, October 18, 2009, Serdar Tumgoren wrote: >> Hi everyone, >> I'm trying to create a generic logging function, and I'm able to get >> at the name of the module and class using the built-in attributes >> __module__, __class__, and __name__. >> >> But I wasn't sure how to also grab the name of the function or method, >> so that when an error occurs, I can log the name of the failing method >> as well. > > Using sys._getframe() you can get the name of the current function or > the name of the calling function. Getting the name of the caller means > you can wrap your logger into a function. See this recipe: > http://code.activestate.com/recipes/66062/ Or just use the built-in logging module which lets you specify the containing function name as one of its formatting keywords: http://docs.python.org/library/logging.html#formatter-objects TJG From zstumgoren at gmail.com Mon Oct 19 15:03:53 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 19 Oct 2009 09:03:53 -0400 Subject: [Tutor] introspecting an object for method's name? In-Reply-To: <4ADC5E2C.5000803@timgolden.me.uk> References: <1c2a2c590910190531s5cc62d62p51b9baed178a2c39@mail.gmail.com> <4ADC5E2C.5000803@timgolden.me.uk> Message-ID: > Or just use the built-in logging module which lets you specify > the containing function name as one of its formatting keywords: > > http://docs.python.org/library/logging.html#formatter-objects > Aha! I had skimmed the logging docs, but hadn't gone far enough down to notice the %(funcName)s formatting option. Thanks to one and all for the suggestions! Serdar From kent37 at tds.net Mon Oct 19 15:17:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Oct 2009 09:17:13 -0400 Subject: [Tutor] introspecting an object for method's name? In-Reply-To: <4ADC5E2C.5000803@timgolden.me.uk> References: <1c2a2c590910190531s5cc62d62p51b9baed178a2c39@mail.gmail.com> <4ADC5E2C.5000803@timgolden.me.uk> Message-ID: <1c2a2c590910190617j4715fd89r1b92fbd2ca06ec77@mail.gmail.com> On Mon, Oct 19, 2009 at 8:40 AM, Tim Golden wrote: > Or just use the built-in logging module which lets you specify > the containing function name as one of its formatting keywords: > > http://docs.python.org/library/logging.html#formatter-objects Sweet! And much better than rolling your own logger. Kent From the_only_katala at verizon.net Mon Oct 19 16:44:36 2009 From: the_only_katala at verizon.net (Katt) Date: Mon, 19 Oct 2009 07:44:36 -0700 Subject: [Tutor] Testing for empty list References: Message-ID: <5EE6B864CEEF4FA196E2F2CE7EB23F13@COMPUTER01> > Wayne wrote: >> Hi, I think I recall seeing this here, but I wanted to make sure I'm >> correct. >> Is the best way to test for an empty list just test for the truth value? >> I.e. >> >> mylist = [1,2,3] >> >> while mylist: >> print mylist.pop() >> >> Thanks, >> Wayne >> >> > My take is simple: Use the above form if you *know* that mylist is in > fact a list. If you don't know its type for sure (the name is a clue, > but not conclusive ;-) ) then use a more specific test. > > In your case, you know it's a list, or least something that supports > pop(). So your form should be great. > > DaveA > Hello all, Just a newbie question, but when would you test for an empty list? Is it part of a code error detection or an error check to make sure that there is user input? Couldn't you just use something like: while len(mylist) > 0: continue program else: print "mylist is empty or is my lack of python knowledge preventing me from seeing the meaning of the question? Thanks in advance, Katt From mike at fozzil.net Mon Oct 19 17:24:32 2009 From: mike at fozzil.net (Mike Sweany) Date: Mon, 19 Oct 2009 11:24:32 -0400 Subject: [Tutor] Python List Help Message-ID: <016001ca50d0$43c230a0$cb4691e0$@net> Hi all, I am a PHP developer that just started learning Python for a specific application and the transition has been pretty easily assisted by google, but I just don?t see the issue with this one? I?ve got a list that created and populate in a loop that shows the correct info when I print it, but if I try to print array[0], it says the list index is out of range. Here is the code snippet. Basically, I have a link here that I am pulling the href info from and splitting it up, only keeping the 5th value, which I am then adding to the playerid array. playerid = [] for i in range(0, players): player = playerlink[i]['href'] breakup = player.split('/') playerid.append(breakup[4]) stats = test.findAll(text=True) print len(playerid) ? this shows the expected result print playerid[0] ?this kills the script 33 print len(playerid) 34 print playerid[0] 35 playerid = [] : list index out of range args = ('list index out of range',) message = 'list index out of range' If I change the print playerid[0] to print playerid[1], same error, but if I change it to print playerid[2] or higher, it will show the same error, but the playerid= [] will show the actual list values in the debug. Any help would be appreciated, thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Mon Oct 19 17:32:54 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 19 Oct 2009 16:32:54 +0100 Subject: [Tutor] Testing for empty list In-Reply-To: <5EE6B864CEEF4FA196E2F2CE7EB23F13@COMPUTER01> References: <5EE6B864CEEF4FA196E2F2CE7EB23F13@COMPUTER01> Message-ID: 2009/10/19 Katt > > Hello all, > > Just a newbie question, but when would you test for an empty list? ?Is it part of a code error detection or an error check to make sure that there is user input? > > Couldn't you just use something like: > > while len(mylist) > 0: > ? continue program > else: > ? print "mylist is empty > > or is my lack of python knowledge preventing me from seeing the meaning of the question? > > Thanks in advance, > > Katt > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor There's various situations, consider this simple implementation of a queue of tasks that need completing: from abc import abstractmethod class QueueableItem(object): """abstract base class to allow tasks to be queued""" def queue(self): """Add the task to the queue""" queue.append(self) def completed(self): """Mark the task as completed, and remove it from the queue""" queue.remove(self) @abstractmethod def run(self, *args): """complete the queued task, should call self.completed() after running.""" class PrintTask(QueueableItem): def __init__(self, data): self.data = data def run(self, *args): print self.data self.completed() def processQueue(): while queue: queue[0].run() print "Queue Processed\n" if __name__ == "__main__": queue = [] PrintTask("Hello").queue() PrintTask("World").queue() processQueue() In this situtation, the while loop could be substituted for a for loop, but consider the following task: class TaskThePrecedent(QueueableItem): def run(self, *args): if precedentCompleted(): #do stuff self.completed() else: queue.insert(0, PrecedentTask()) Yes, the precedentTask code could be pasted into the else block, but what if more than one class used that precedent, or the precedent had precedents itself, which in turn were used by multiple classes? OK, That was pretty contrieved, and I'm sure other tutors can come up with better examples, but I think it gives an idea of one of the many situtations in which you might need to test for a lists contents. I also put far too much work into it. "Simple", my foot. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From eduardo.susan at gmail.com Mon Oct 19 18:39:51 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 19 Oct 2009 10:39:51 -0600 Subject: [Tutor] "if clause" in list comprehensions. Message-ID: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Hello, The other day I was making a script and decided to use a list compreehension and I found out that this code: mylist = ['John', 'Canada', 25, 32, 'right'] a = [item.upper() for item in mylist if type(item) == type('good')] returned this: ['JOHN', 'CANADA', 'RIGHT'] I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] So, actually the "if" acted like a filter. In order to use a list comprehension I created this function instead. def upperfy(item) try: item = item.upper() except AttributeError: pass return item a = [upperfy(item) for item in mylist] My question is? Am I solving the problem in the right way? Am I missing something? Thanks for all the help I've been getting as a newcomer. Eduardo From msh at blisses.org Mon Oct 19 18:10:08 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 19 Oct 2009 12:10:08 -0400 Subject: [Tutor] updating Unix config file Message-ID: <20091019161008.GB15752@chicago.blisses.org> Hi All. The below script seems to work well enough to use but I'm wondering if I'm doing the file edit stuff in a "kosher" manner. I was just reading the Lutz O'Reilly "Learning" book and remembered that strings are immutable. So how was I able to change the strings for my dotted quad? I did not explicitly open a separate file in /tmp and then overwrite the ipf.conf file which seemed like the safer way. Yet somehow the below syntax works. Also I need to figure out how to update the LASTKNOWN variable after my IP changes. Thanks for any advice. import socket # import fileinput import subprocess import string import re SENDMAIL = "/usr/sbin/sendmail" CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] LASTKNOWN = '173.48.204.168' if CURRENT == LASTKNOWN: print 'Nevermind.' subprocess.sys.exit() else: cf = open("/etc/ipf.conf", "r") lns = cf.readlines() lns = "".join(lns) # close it so that we can open for writing later lns = re.sub(LASTKNOWN, CURRENT, lns) cf = open("/etc/ipf.conf", "w") cf.write(lns) cf.close() subprocess.call('/sbin/ipf -Fa -f /etc/ipf.conf', shell=True) subprocess.call('/sbin/ipnat -CF -f /etc/ipnat.conf', shell=True) ptchew = subprocess.Popen("%s -t" % SENDMAIL, "w") ptchew.write("To: msh at blisses.org\n") ptchew.write("Subject: YOUR IP ADDRESS HAS CHANGED\n") ptchew.write("\n") # blank line separating headers from body ptchew.write("Your IP address has changed to: ") ptchew.write(CURRENT) ptchew.write(time.asctime()) ptchew = p.close() -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald From sander.sweers at gmail.com Mon Oct 19 19:13:18 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 19 Oct 2009 19:13:18 +0200 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: 2009/10/19 Eduardo Vieira : > mylist = ['John', 'Canada', 25, 32, 'right'] > a = [item.upper() for item in mylist if type(item) == type('good')] Usually it is recommended to use hasattr() instead of type() hasattr(s, 'upper') > returned this: ['JOHN', 'CANADA', 'RIGHT'] > I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] > So, actually the "if" acted like a filter. > In order to use a list comprehension I created this function instead. > def upperfy(item) > ? ?try: > ? ? ? ?item = item.upper() > ? ?except AttributeError: > ? ? ? ?pass > ? ?return item I would move return item under the except and remove the pass, other might disagree on this. > a = [upperfy(item) for item in mylist] You can use this which gives the added benefit that you can document why you are using this within the function. But you can include else in list comprehension. a = [item.upper() if hasattr(item, 'upper') else item for item in mylist] Your case it might be "overkill" to use the function. Greets Sander From srilyk at gmail.com Mon Oct 19 19:25:55 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 19 Oct 2009 12:25:55 -0500 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: <333efb450910191025x40870474u4521c7dbf37c3b84@mail.gmail.com> On Mon, Oct 19, 2009 at 11:39 AM, Eduardo Vieira wrote: > Hello, > The other day I was making a script and decided to use a list > compreehension and I found out that this code: > mylist = ['John', 'Canada', 25, 32, 'right'] > a = [item.upper() for item in mylist if type(item) == type('good')] > returned this: ['JOHN', 'CANADA', 'RIGHT'] > I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] > What type is 'good' ? What type is 25? Also, perhaps you misunderstand what a list comprehension does: a = [item for item in mylist if type(item) == type('good')] will look at the first item - is it of type string? if so then it's added to the list, otherwise it's ignored. So, actually the "if" acted like a filter. > In order to use a list comprehension I created this function instead. > def upperfy(item) > try: > item = item.upper() > except AttributeError: > pass > return item > > a = [upperfy(item) for item in mylist] > > My question is? Am I solving the problem in the right way? Am I > missing something? > Thanks for all the help I've been getting as a newcomer. I don't know if it's the "right" way, but it looks fine to me. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Oct 19 19:35:21 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 19 Oct 2009 13:35:21 -0400 Subject: [Tutor] Python List Help In-Reply-To: <016001ca50d0$43c230a0$cb4691e0$@net> References: <016001ca50d0$43c230a0$cb4691e0$@net> Message-ID: <4ADCA359.2040801@ieee.org> Mike Sweany wrote: > Hi all, > > > > I am a PHP developer that just started learning Python for a specific > application and the transition has been pretty easily assisted by google, > but I just don?t see the issue with this one? > > > > I?ve got a list that created and populate in a loop that shows the correct > info when I print it, but if I try to print array[0], it says the list index > is out of range. > > > > Here is the code snippet. Basically, I have a link here that I am pulling > the href info from and splitting it up, only keeping the 5th value, which I > am then adding to the playerid array. > > > > playerid = [] > > for i in range(0, players): > > player = playerlink[i]['href'] > > breakup = player.split('/') > > playerid.append(breakup[4]) > > > > stats = test.findAll(text=True) > > print len(playerid) ? this shows the expected result > > print playerid[0] ?this kills the script > > > > > > > 33 print len(playerid) > > > 34 print playerid[0] > > > 35 > > > > playerid = [] > > : list index out of range > args = ('list index out of range',) > message = 'list index out of range' > > If I change the print playerid[0] to print playerid[1], same error, but if I > change it to print playerid[2] or higher, it will show the same error, but > the playerid= [] will show the actual list values in the debug. > > Any help would be appreciated, thank you! > > > > I'm very confused about your formatting. You seem to be using tabs with a large column setting (prefer 4 columns, and tabs should become spaces in the editor). But there's no context. So this stuff is indented, but it's not inside a function?? And the numbers 33, 34, and 35, what are they from? What debugger are you running, that somehow displays list values when you assign an empty list to playerid? That makes no sense. If it's an exotic debugger, then perhaps you should be doing this straight from the python interpreter. I suggest that until you're comfortable enough with python to know what to include, that you post exactly what happened, without trying so hard to customize it. Show the file, in its entirety (if it's too big, then you would need a smaller example). And put markers at begin and end so we can see what part is the file. Then if you're running from the interpreter prompt, show the whole session, from import xxxx to the traceback error. Note that if you want to print variables from the imported program, you'd use >>> print mymodule.playerid The following is not intended to be good programming, it's intended to encapsulate what you already had, with some initialization to avoid needing other stuff that's presumably irrelevant here. ***file stuff2.py **** #!/usr/bin/env python #-*- coding: utf-8 -*- link0 = {"href":"this /is /a /test/of the stuff/before here"} link1 = {"href":"this /is /a /test/different stuff/before here"} link2 = {"href":"this /is /a /test/other stuff/before here"} playerlink = [link0, link1, link2] players = len(playerlink) def doit(): global playerid playerid = [] for i in range(0, players): player = playerlink[i]['href'] breakup = player.split('/') playerid.append(breakup[4]) print len(playerid) # this shows the expected result print playerid[0] #this gets an exception if __name__ == "__main__": doit() *** end file ***** And now the interpreter session: M:\Programming\Python\sources\dummy>python26 ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import stuff2 >>> stuff2.doit() 3 of the stuff >>> print len(stuff2.playerid) 3 >>> print stuff2.playerid[0] of the stuff >>> Of course, I didn't get any error. But if you do, your transcript should be enough information for people to better tell why. One more thing: copy/paste, don't retype. Otherwise you may obscure the problem or introduce others. DaveA From alan.gauld at btinternet.com Mon Oct 19 21:01:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 20:01:58 +0100 Subject: [Tutor] Testing for empty list References: <5EE6B864CEEF4FA196E2F2CE7EB23F13@COMPUTER01> Message-ID: "Katt" wrote > Just a newbie question, but when would you test for an empty list? When you are processing a list such that you are deleting items as you go. When the list is empty stop processing! And Python helps you do that by treating an empty list as a False boolean value so you can do while myList: process items from myList This will keep on processing myList until all the items have been deleted. Note, this could be more times than the number of items in the list...for example: counter = 0 myList = [12,24] nines = [] while myList: counter += 1 print "iteration number", counter index = 0 while index < len(myList): # copes with disappearing members if myList[index] % 9 == 0: # is it divisible by 9? nines.append(myList[index]) del(myList[index]) # remove from list else: myList[index] -= 1 index += 1 print nines > while len(mylist) > 0: > continue program > else: > print "mylist is empty That is the same as while mylist: continue program else: print 'mylist is empty' HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Oct 19 21:07:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 20:07:47 +0100 Subject: [Tutor] updating Unix config file References: <20091019161008.GB15752@chicago.blisses.org> Message-ID: "Matt Herzog" wrote > remembered that strings are immutable. > So how was I able to change the strings for my dotted quad? You didn't. > LASTKNOWN = '173.48.204.168' > lns = cf.readlines() > lns = "".join(lns) > lns = re.sub(LASTKNOWN, CURRENT, lns) I assume this is the line in question? sub() returns a new string containing the substitutions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Oct 19 21:20:17 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 20:20:17 +0100 Subject: [Tutor] "if clause" in list comprehensions. References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: "Sander Sweers" wrote >> mylist = ['John', 'Canada', 25, 32, 'right'] >> a = [item.upper() for item in mylist if type(item) == type('good')] > > Usually it is recommended to use hasattr() instead of type() > hasattr(s, 'upper') Nope, they do completely different things I think you might be thinking of isinstance() which can be used instead of type(). I see you use hasattr as a means of testing for a method but that is still different from testing type - the method names might be the same but the functions be completely different in effect! >> returned this: ['JOHN', 'CANADA', 'RIGHT'] >> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] >> So, actually the "if" acted like a filter. It is intended to be used as a filter. >> In order to use a list comprehension I created this function instead. >> def upperfy(item) >> try: >> item = item.upper() >> except AttributeError: >> pass >> return item > I would move return item under the except and remove the pass, other > might disagree on this. I would :-) Doing that would result in None being returned for each successful conversion. The OPs code is correct (even if unnecessary) >> a = [upperfy(item) for item in mylist] a = [item.upper() if type(item) == str else item for item in mylist] should do it I think. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sander.sweers at gmail.com Mon Oct 19 21:57:08 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 19 Oct 2009 21:57:08 +0200 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: 2009/10/19 Alan Gauld : >> Usually it is recommended to use hasattr() instead of type() >> ? hasattr(s, 'upper') > > Nope, they do ?completely different things > I think you might be thinking of isinstance() which can be used instead of > type(). I see you use hasattr as a means of testing for a method but that is > still different from testing type - the method names might be the same but > the functions be completely different in effect! Indeed, I was and stand corrected. >>> In order to use a list comprehension I created this function instead. >>> def upperfy(item) >>> ? try: >>> ? ? ? item = item.upper() >>> ? except AttributeError: >>> ? ? ? pass >>> ? return item > >> I would move return item under the except and remove the pass, other >> might disagree on this. > > I would :-) > Doing that would result in None being returned for each successful > conversion. The OPs code is correct (even if unnecessary) I missed that the try: did not return anything. I was thinking more of something like this. def upperfy(item): try: item.upper() return item except AttributeError: return item Thanks for correcting me! Greets Sander PS: Note to self, never reply in a hurry :-( From emile at fenx.com Mon Oct 19 21:58:47 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 19 Oct 2009 12:58:47 -0700 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: On 10/19/2009 12:20 PM Alan Gauld said... > > "Sander Sweers" wrote > >>> mylist = ['John', 'Canada', 25, 32, 'right'] >>> a = [item.upper() for item in mylist if type(item) == type('good')] >> >> Usually it is recommended to use hasattr() instead of type() >> hasattr(s, 'upper') > > Nope, they do completely different things > I think you might be thinking of isinstance() which can be used instead > of type(). I see you use hasattr as a means of testing for a method but > that is still different from testing type - the method names might be > the same but the functions be completely different in effect! > >>> returned this: ['JOHN', 'CANADA', 'RIGHT'] >>> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] >>> So, actually the "if" acted like a filter. > > It is intended to be used as a filter. > >>> In order to use a list comprehension I created this function instead. >>> def upperfy(item) >>> try: >>> item = item.upper() >>> except AttributeError: >>> pass >>> return item > >> I would move return item under the except and remove the pass, other >> might disagree on this. > > I would :-) > Doing that would result in None being returned for each successful > conversion. The OPs code is correct (even if unnecessary) > >>> a = [upperfy(item) for item in mylist] > > a = [item.upper() if type(item) == str else item for item in mylist] > > should do it I think. or even a = [ str(item).upper() for item in mylist ] Emile > > HTH, > > From vinces1979 at gmail.com Mon Oct 19 22:14:55 2009 From: vinces1979 at gmail.com (vince spicer) Date: Mon, 19 Oct 2009 14:14:55 -0600 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: <1e53c510910191314u56c33da2hfd5cff289a3f87dd@mail.gmail.com> On Mon, Oct 19, 2009 at 1:58 PM, Emile van Sebille wrote: > On 10/19/2009 12:20 PM Alan Gauld said... > > >> "Sander Sweers" wrote >> >> mylist = ['John', 'Canada', 25, 32, 'right'] >>>> a = [item.upper() for item in mylist if type(item) == type('good')] >>>> >>> >>> Usually it is recommended to use hasattr() instead of type() >>> hasattr(s, 'upper') >>> >> >> Nope, they do completely different things >> I think you might be thinking of isinstance() which can be used instead of >> type(). I see you use hasattr as a means of testing for a method but that is >> still different from testing type - the method names might be the same but >> the functions be completely different in effect! >> >> returned this: ['JOHN', 'CANADA', 'RIGHT'] >>>> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] >>>> So, actually the "if" acted like a filter. >>>> >>> >> It is intended to be used as a filter. >> >> In order to use a list comprehension I created this function instead. >>>> def upperfy(item) >>>> try: >>>> item = item.upper() >>>> except AttributeError: >>>> pass >>>> return item >>>> >>> >> I would move return item under the except and remove the pass, other >>> might disagree on this. >>> >> >> I would :-) >> Doing that would result in None being returned for each successful >> conversion. The OPs code is correct (even if unnecessary) >> >> a = [upperfy(item) for item in mylist] >>>> >>> >> a = [item.upper() if type(item) == str else item for item in mylist] >> >> should do it I think. >> > > or even > > a = [ str(item).upper() for item in mylist ] > > Emile > > > >> HTH, >> >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Lambda can save the day to keep everything on one line, and leave variable type the same: mylist = ['John', 'Canada', 25, 32, 'right'] new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in x] >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Mon Oct 19 22:16:10 2009 From: vinces1979 at gmail.com (vince spicer) Date: Mon, 19 Oct 2009 14:16:10 -0600 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: <1e53c510910191314u56c33da2hfd5cff289a3f87dd@mail.gmail.com> References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> <1e53c510910191314u56c33da2hfd5cff289a3f87dd@mail.gmail.com> Message-ID: <1e53c510910191316w75fbf929if410079e5e3feff@mail.gmail.com> On Mon, Oct 19, 2009 at 2:14 PM, vince spicer wrote: > > > On Mon, Oct 19, 2009 at 1:58 PM, Emile van Sebille wrote: > >> On 10/19/2009 12:20 PM Alan Gauld said... >> >> >>> "Sander Sweers" wrote >>> >>> mylist = ['John', 'Canada', 25, 32, 'right'] >>>>> a = [item.upper() for item in mylist if type(item) == type('good')] >>>>> >>>> >>>> Usually it is recommended to use hasattr() instead of type() >>>> hasattr(s, 'upper') >>>> >>> >>> Nope, they do completely different things >>> I think you might be thinking of isinstance() which can be used instead >>> of type(). I see you use hasattr as a means of testing for a method but that >>> is still different from testing type - the method names might be the same >>> but the functions be completely different in effect! >>> >>> returned this: ['JOHN', 'CANADA', 'RIGHT'] >>>>> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] >>>>> So, actually the "if" acted like a filter. >>>>> >>>> >>> It is intended to be used as a filter. >>> >>> In order to use a list comprehension I created this function instead. >>>>> def upperfy(item) >>>>> try: >>>>> item = item.upper() >>>>> except AttributeError: >>>>> pass >>>>> return item >>>>> >>>> >>> I would move return item under the except and remove the pass, other >>>> might disagree on this. >>>> >>> >>> I would :-) >>> Doing that would result in None being returned for each successful >>> conversion. The OPs code is correct (even if unnecessary) >>> >>> a = [upperfy(item) for item in mylist] >>>>> >>>> >>> a = [item.upper() if type(item) == str else item for item in mylist] >>> >>> should do it I think. >>> >> >> or even >> >> a = [ str(item).upper() for item in mylist ] >> >> Emile >> >> >> >>> HTH, >>> >>> >>> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > Lambda can save the day to keep everything on one line, and leave variable > type the same: > > mylist = ['John', 'Canada', 25, 32, 'right'] > new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in > mylist ] > > >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] > > Vince > wrong var name "x", fixed -------------- next part -------------- An HTML attachment was scrubbed... URL: From emmanuel.ruellan at laposte.net Mon Oct 19 22:36:05 2009 From: emmanuel.ruellan at laposte.net (Emmanuel Ruellan) Date: Mon, 19 Oct 2009 22:36:05 +0200 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: <7296745c0910191336i12330320kce6f199f2e64371c@mail.gmail.com> On Mon, Oct 19, 2009 at 9:20 PM, Alan Gauld wrote: > > > "Sander Sweers" wrote > > mylist = ['John', 'Canada', 25, 32, 'right'] >>> a = [item.upper() for item in mylist if type(item) == type('good')] >>> >> >> Usually it is recommended to use hasattr() instead of type() >> hasattr(s, 'upper') >> > > Nope, they do completely different things > I think you might be thinking of isinstance() which can be used instead of > type(). I see you use hasattr as a means of testing for a method but that is > still different from testing type - the method names might be the same but > the functions be completely different in effect! When I read Sander's advice, I thought it would be the sensible thing to do when working with strings that could be either vanilla 8-bit strings or Unicode strings. For example: >>> my_list = ['a string', u'another string', 42] >>> print [item.upper() for item in my_list if hasattr(item, 'upper')] ['A STRING', u'ANOTHER STRING'] >>> print [item.upper() for item in my_list if type(item) == type('good')] ['A STRING'] Thinking of it, the same result could be achieved with 'if isinstance(item, basestring)'. Is there any compelling reason to write: [item.upper() for item in my_list if isinstance(item, basestring)] rather than the following? [item.upper() for item in my_list if hasattr(item, 'upper')] Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From dgou at mac.com Mon Oct 19 22:10:50 2009 From: dgou at mac.com (Douglas Philips) Date: Mon, 19 Oct 2009 16:10:50 -0400 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: <8E18EDDB-DC4F-4BFD-8D0B-8776CF3B9C34@mac.com> On or about 2009 Oct 19, at 3:57 PM, Sander Sweers indited: > I missed that the try: did not return anything. I was thinking more of > something like this. > > def upperfy(item): > try: > item.upper() > return item > except AttributeError: > return item > > Thanks for correcting me! Depending on what 'item' is, item.upper() might return an new thing, but the code looks as if you're expecting .upper() to modify item itself. If item is a string, item.upper() will return a new string and leave item alone (since strings are immutable in Python). -Doug From eduardo.susan at gmail.com Mon Oct 19 23:58:27 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 19 Oct 2009 15:58:27 -0600 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: <9356b9f30910191458m1522fadat667e2747377f77c8@mail.gmail.com> On Mon, Oct 19, 2009 at 1:20 PM, Alan Gauld wrote: > > "Sander Sweers" wrote > >>> mylist = ['John', 'Canada', 25, 32, 'right'] >>> a = [item.upper() for item in mylist if type(item) == type('good')] >> >> Usually it is recommended to use hasattr() instead of type() >> ? hasattr(s, 'upper') > > Nope, they do ?completely different things > I think you might be thinking of isinstance() which can be used instead of > type(). I see you use hasattr as a means of testing for a method but that is > still different from testing type - the method names might be the same but > the functions be completely different in effect! > >>> returned this: ['JOHN', 'CANADA', 'RIGHT'] >>> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] >>> So, actually the "if" acted like a filter. > > It is intended to be used as a filter. > >>> In order to use a list comprehension I created this function instead. >>> def upperfy(item) >>> ? try: >>> ? ? ? item = item.upper() >>> ? except AttributeError: >>> ? ? ? pass >>> ? return item > >> I would move return item under the except and remove the pass, other >> might disagree on this. > > I would :-) > Doing that would result in None being returned for each successful > conversion. The OPs code is correct (even if unnecessary) > >>> a = [upperfy(item) for item in mylist] > > a = [item.upper() if type(item) == str else item for item in mylist] > > should do it I think. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for all the guidance. I'm glad I learned I could use "else" in the list comp. after all. I thought I could, but when I tried it, I got it wrong and forgot how I did it. Yeah, I had an impression that a function was unnecessary in this case, but didn't know how to get around it. To: Emmanuel: Thanks for your remark in the case of unicode. In my code that wasn't a problem, but it's something to consider. Regards, Eduardo From alan.gauld at btinternet.com Tue Oct 20 00:00:53 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 19 Oct 2009 22:00:53 +0000 (GMT) Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: <7296745c0910191336i12330320kce6f199f2e64371c@mail.gmail.com> References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> <7296745c0910191336i12330320kce6f199f2e64371c@mail.gmail.com> Message-ID: <491054.93042.qm@web86706.mail.ird.yahoo.com> Is there any compelling reason to write: > >[item.upper() for item in my_list if isinstance(item, basestring)] > >rather than the following? > >[item.upper() for item in my_list if hasattr(item, 'upper')]What happens if you have an object in your list that has an 'upper' merthod that, say, reboots your PC into an upper level of admin access? Or that sets the bank account credit limit to the upper limit? Your list comprehension will happily run and apply upper to the object but the result may not be what you expected. If you check isinstance you know that you are working with some kind of string at least. (A programmer could still override upper do do some wacky thing but then that programmer is abusing upper, whereas, in the bank account case it's a perfectly valid application of upper() ) Even more to the point the 'upper' that hasattr() finds may not be callable, it could be the upper value of a range for example. Then when you try to use it in the comprehension you will get an error. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Oct 20 00:22:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 23:22:26 +0100 Subject: [Tutor] "if clause" in list comprehensions. References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> Message-ID: "Emile van Sebille" wrote >> a = [item.upper() if type(item) == str else item for item in mylist] >> >> should do it I think. > > or even > > a = [ str(item).upper() for item in mylist ] That was my first attempt but the OP wanted his integers preserved as integers whereas this would convert them to strings. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 20 00:25:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 23:25:37 +0100 Subject: [Tutor] "if clause" in list comprehensions. References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> <1e53c510910191314u56c33da2hfd5cff289a3f87dd@mail.gmail.com> <1e53c510910191316w75fbf929if410079e5e3feff@mail.gmail.com> Message-ID: "vince spicer" wrote >> Lambda can save the day to keep everything on one line, and leave >> variable >> type the same: >> >> mylist = ['John', 'Canada', 25, 32, 'right'] >> new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a >> in >> mylist ] >> >> >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] >> >> Vince >> > > wrong var name "x", fixed > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Oct 20 00:29:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Oct 2009 23:29:40 +0100 Subject: [Tutor] "if clause" in list comprehensions. References: <9356b9f30910190939r424b0181i1d9ecf9cf14f3ec3@mail.gmail.com> <1e53c510910191314u56c33da2hfd5cff289a3f87dd@mail.gmail.com> <1e53c510910191316w75fbf929if410079e5e3feff@mail.gmail.com> Message-ID: Ooops, hit send by mistake... "vince spicer" wrote >> Lambda can save the day to keep everything on one line, and leave >> variable >> type the same: >> >> mylist = ['John', 'Canada', 25, 32, 'right'] >> new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a >> in >> mylist ] >> >> >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] In what way does lambda help? new_list = [y.upper() if hasattr(y, 'upper') else y for y in mylist] does exactly the same and is shorter. lambda helps if you want to pass a function object around but defining it and immediately calling it means it can be replaced directly by the expression within the lambda. But using hasattr() still has the problem of failing if upper is not a callable attribute (or does something radical like exiting) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From msh at blisses.org Tue Oct 20 01:51:06 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 19 Oct 2009 19:51:06 -0400 Subject: [Tutor] updating Unix config file In-Reply-To: References: <20091019161008.GB15752@chicago.blisses.org> Message-ID: <20091019235106.GD19454@chicago.blisses.org> On Mon, Oct 19, 2009 at 08:07:47PM +0100, Alan Gauld wrote: > > "Matt Herzog" wrote > > >remembered that strings are immutable. > >So how was I able to change the strings for my dotted quad? > > You didn't. > > >LASTKNOWN = '173.48.204.168' > > lns = cf.readlines() > > lns = "".join(lns) > > lns = re.sub(LASTKNOWN, CURRENT, lns) > > I assume this is the line in question? > sub() returns a new string containing the substitutions. > > HTH, Yes! It sure does help. I just discovered that my script does not exit if the CURRENT IP is the same as the LASTKNOWN IP. ------------------------------ snip -------------------------------------- CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] ------------------------------ snip -------------------------------------- Turns out the above is an unreliable way to get the IP of the interface since the machine the above is running on does not have a proper hostname and is a dhcp client on a broadband network. Anyway, I'd like a hint as to how I could convert this: ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() x = string.split(ifcfg_lines[3])[1] to the subprocess module. The os module is going away, right? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald From msh at blisses.org Tue Oct 20 01:59:04 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 19 Oct 2009 19:59:04 -0400 Subject: [Tutor] updating Unix config file In-Reply-To: <20091019235106.GD19454@chicago.blisses.org> References: <20091019161008.GB15752@chicago.blisses.org> <20091019235106.GD19454@chicago.blisses.org> Message-ID: <20091019235904.GE19454@chicago.blisses.org> On Mon, Oct 19, 2009 at 07:51:06PM -0400, Matt Herzog wrote: > On Mon, Oct 19, 2009 at 08:07:47PM +0100, Alan Gauld wrote: > > > > "Matt Herzog" wrote > > > > >remembered that strings are immutable. > > >So how was I able to change the strings for my dotted quad? > > > > You didn't. > > > > >LASTKNOWN = '173.48.204.168' > > > lns = cf.readlines() > > > lns = "".join(lns) > > > lns = re.sub(LASTKNOWN, CURRENT, lns) > > > > I assume this is the line in question? > > sub() returns a new string containing the substitutions. > > > > HTH, > > Yes! It sure does help. I just discovered that my script does not exit if the CURRENT IP is the same as the LASTKNOWN IP. Please ignore the above. > ------------------------------ snip -------------------------------------- > CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] > ------------------------------ snip -------------------------------------- > Turns out the above is an unreliable way to get the IP of the interface since the machine the above is running on does not have a proper hostname and is a dhcp client on a broadband network. It's unreliable because it uses DNS, I believe. I'm not faulting the author. > > Anyway, I'd like a hint as to how I could convert this: > > ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() > x = string.split(ifcfg_lines[3])[1] > > to the subprocess module. The os module is going away, right? > > > > > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > -- > The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. > > -- F. Scott Fitzgerald > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald From kb1pkl at aim.com Tue Oct 20 03:53:51 2009 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 19 Oct 2009 21:53:51 -0400 Subject: [Tutor] Running Python on a Calculator Message-ID: <4ADD182F.8050104@aim.com> Hey tutors. I have a TI-84 plus, and I am making some math tools, and I don't know the native language of the Ti-84, and was wondering, has anyone worked with a version of Python that can run on that small of a processor? Thanks in advance, ~Corey From mike at fozzil.net Tue Oct 20 04:46:53 2009 From: mike at fozzil.net (Mike Sweany) Date: Mon, 19 Oct 2009 22:46:53 -0400 Subject: [Tutor] Python List Help In-Reply-To: <4ADCA359.2040801@ieee.org> References: <016001ca50d0$43c230a0$cb4691e0$@net> <4ADCA359.2040801@ieee.org> Message-ID: <018601ca512f$96f6cd30$c4e46790$@net> Thanks for the reply and Tips Dave... I think the formatting came out weird because I didn?t specify plain text when I created the email. I'm using Google App Engine and it's internal debugger shows what I posted earlier when the code breaks, I agree that what I am seeing from the debugger makes no sense... Thanks for the tips, I will look at what you have and see if I can make it work... >From top to bottom, I am using BeautifulSoup to parse an html document and what you are seeing is a part of the processing that just didn?t jive with practices that I had already carried over and had working with the rest of the code. I don?t have it set up to do the import with an interpreter session like you laid out below, basically I am printing the stuff as it goes, it's in a loop and this code is processed multiple times. Honestly, I need to do some reading on how python works as I was plugging along on this script with just a couple of hours into python for this scraping project, but what you have shown me here will help and I will come back to the list after I have a better understanding of what I am doing. Thanks, Mike -----Original Message----- From: Dave Angel [mailto:davea at ieee.org] Sent: Monday, October 19, 2009 1:35 PM To: Mike Sweany Cc: tutor at python.org Subject: Re: [Tutor] Python List Help Mike Sweany wrote: > Hi all, > > > > I am a PHP developer that just started learning Python for a specific > application and the transition has been pretty easily assisted by google, > but I just don?t see the issue with this one? > > > > I?ve got a list that created and populate in a loop that shows the correct > info when I print it, but if I try to print array[0], it says the list index > is out of range. > > > > Here is the code snippet. Basically, I have a link here that I am pulling > the href info from and splitting it up, only keeping the 5th value, which I > am then adding to the playerid array. > > > > playerid = [] > > for i in range(0, players): > > player = playerlink[i]['href'] > > breakup = player.split('/') > > playerid.append(breakup[4]) > > > > stats = test.findAll(text=True) > > print len(playerid) ? this shows the expected result > > print playerid[0] ?this kills the script > > > > > > > 33 print len(playerid) > > > 34 print playerid[0] > > > 35 > > > > playerid = [] > > : list index out of range > args = ('list index out of range',) > message = 'list index out of range' > > If I change the print playerid[0] to print playerid[1], same error, but if I > change it to print playerid[2] or higher, it will show the same error, but > the playerid= [] will show the actual list values in the debug. > > Any help would be appreciated, thank you! > > > > I'm very confused about your formatting. You seem to be using tabs with a large column setting (prefer 4 columns, and tabs should become spaces in the editor). But there's no context. So this stuff is indented, but it's not inside a function?? And the numbers 33, 34, and 35, what are they from? What debugger are you running, that somehow displays list values when you assign an empty list to playerid? That makes no sense. If it's an exotic debugger, then perhaps you should be doing this straight from the python interpreter. I suggest that until you're comfortable enough with python to know what to include, that you post exactly what happened, without trying so hard to customize it. Show the file, in its entirety (if it's too big, then you would need a smaller example). And put markers at begin and end so we can see what part is the file. Then if you're running from the interpreter prompt, show the whole session, from import xxxx to the traceback error. Note that if you want to print variables from the imported program, you'd use >>> print mymodule.playerid The following is not intended to be good programming, it's intended to encapsulate what you already had, with some initialization to avoid needing other stuff that's presumably irrelevant here. ***file stuff2.py **** #!/usr/bin/env python #-*- coding: utf-8 -*- link0 = {"href":"this /is /a /test/of the stuff/before here"} link1 = {"href":"this /is /a /test/different stuff/before here"} link2 = {"href":"this /is /a /test/other stuff/before here"} playerlink = [link0, link1, link2] players = len(playerlink) def doit(): global playerid playerid = [] for i in range(0, players): player = playerlink[i]['href'] breakup = player.split('/') playerid.append(breakup[4]) print len(playerid) # this shows the expected result print playerid[0] #this gets an exception if __name__ == "__main__": doit() *** end file ***** And now the interpreter session: M:\Programming\Python\sources\dummy>python26 ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import stuff2 >>> stuff2.doit() 3 of the stuff >>> print len(stuff2.playerid) 3 >>> print stuff2.playerid[0] of the stuff >>> Of course, I didn't get any error. But if you do, your transcript should be enough information for people to better tell why. One more thing: copy/paste, don't retype. Otherwise you may obscure the problem or introduce others. DaveA From alan.gauld at btinternet.com Tue Oct 20 09:29:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 Oct 2009 08:29:59 +0100 Subject: [Tutor] updating Unix config file References: <20091019161008.GB15752@chicago.blisses.org> <20091019235106.GD19454@chicago.blisses.org> Message-ID: "Matt Herzog" wrote > Anyway, I'd like a hint as to how I could convert this: > > ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() > x = string.split(ifcfg_lines[3])[1] > > to the subprocess module. The os module is going away, right? The os module is not going away although the popen function might some day. However subprocess is currently the recommended way to do subprocess control and is more powerful and flexible than popen. Did you see the subprocess documentation page that shows how to do the equivalent of popen etc? Look down to section 18.1.3.5 http://docs.python.org/library/subprocess.html#module-subprocess HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 20 09:33:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 Oct 2009 08:33:56 +0100 Subject: [Tutor] Running Python on a Calculator References: <4ADD182F.8050104@aim.com> Message-ID: "Corey Richardson" wrote > Hey tutors. I have a TI-84 plus, and I am making some math tools, and I > don't know the native language of the Ti-84, and was wondering, has > anyone worked with a version of Python that can run on that small of a > processor? Never say never but.... The smallest thing I've seen Python run on was an early Palm Pilot and that was way more powerful than a calculator. So I doubt if you will find anything. I don't even know how you would begin, there is no OS as such and no available compilers with which to build Python on the TI84. The only folks who could even contemplate doing it would be the peple who built the calculator in the first place I suspect. Alan G From lie.1296 at gmail.com Tue Oct 20 10:23:04 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Oct 2009 19:23:04 +1100 Subject: [Tutor] Running Python on a Calculator In-Reply-To: <4ADD182F.8050104@aim.com> References: <4ADD182F.8050104@aim.com> Message-ID: Corey Richardson wrote: > Hey tutors. I have a TI-84 plus, and I am making some math tools, and I > don't know the native language of the Ti-84, and was wondering, has > anyone worked with a version of Python that can run on that small of a > processor? Thanks in advance, A quote from Wikipedia says: """ ... BBC Basic has already been ported to the TI 83&84 series and other on-board languages and programming tools discussed by many include Fortran, awk, Pascal, Rexx, perl, Common Lisp, Python, tcl, and various Unix shells. """ So, I guess it's a no, but the platform can handle it if someone spent enough time to port the interpreter. From paul.leinan at ntnu.no Tue Oct 20 10:30:35 2009 From: paul.leinan at ntnu.no (Paul Roger Leinan) Date: Tue, 20 Oct 2009 10:30:35 +0200 Subject: [Tutor] Python and Abaqus Message-ID: <4ADD752B.1010402@ntnu.no> Hi! Referring to http://mail.python.org/pipermail/tutor/2008-November/065270.html Would you be able to send me these python examples to? Regards Paul Leinan -- Paul Roger Leinan PhD Student Department of Structural Engineering - Biomechanics - Norwegian University of Science and Technology (NTNU) Web: www.ntnu.no/biomechanics Email: paul.leinan at ntnu.no Phone: (+47) 481 81 457 From jfabiani at yolo.com Tue Oct 20 16:27:19 2009 From: jfabiani at yolo.com (John) Date: Tue, 20 Oct 2009 07:27:19 -0700 Subject: [Tutor] cross platform authenticating Message-ID: <200910200727.20035.jfabiani@yolo.com> Hi, Is there a general discussion (somewhere on the web) on how to 1. determine what authentication the platform requires 2. can #1 be determine dynamically 3. If I know #1 will it be cross platform? Googling reveals that there are many authenticating modules, LDAP, PAS, RADIUS, Active Directory, PAM, and something called pluggable authentication. But I don't see anything that tells me how to determine what the platform requires. And what if there is no authentication required - like on a single computer. Also if I am able to determine the authentication requirements will the modules then be cross platform - working on Linux, Mac, and Windows? As you guys can see I'm just starting out in the authentication world. Thanks in advance for any help, Johnf From msh at blisses.org Tue Oct 20 16:44:16 2009 From: msh at blisses.org (Matt Herzog) Date: Tue, 20 Oct 2009 10:44:16 -0400 Subject: [Tutor] updating Unix config file In-Reply-To: References: <20091019235106.GD19454@chicago.blisses.org> Message-ID: <20091020144416.GI19454@chicago.blisses.org> On Tue, Oct 20, 2009 at 08:29:59AM +0100, Alan Gauld wrote: > "Matt Herzog" wrote > > >Anyway, I'd like a hint as to how I could convert this: > > > >ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() > >x = string.split(ifcfg_lines[3])[1] > > > >to the subprocess module. The os module is going away, right? > > The os module is not going away although the popen > function might some day. > > However subprocess is currently the recommended way > to do subprocess control and is more powerful and flexible > than popen. > > Did you see the subprocess documentation page that > shows how to do the equivalent of popen etc? > Look down to section 18.1.3.5 Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. > > http://docs.python.org/library/subprocess.html#module-subprocess > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald From tiagosaboga at gmail.com Tue Oct 20 16:49:53 2009 From: tiagosaboga at gmail.com (Tiago Saboga) Date: Tue, 20 Oct 2009 14:49:53 +0000 Subject: [Tutor] updating Unix config file In-Reply-To: <20091020144416.GI19454@chicago.blisses.org> References: <20091019235106.GD19454@chicago.blisses.org> <20091020144416.GI19454@chicago.blisses.org> Message-ID: <3351535a0910200749j7f696c17q8c42a94e84a70d00@mail.gmail.com> On Tue, Oct 20, 2009 at 2:44 PM, Matt Herzog wrote: > Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! > > Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. It is really like any other module. If you just import subprocess, you can access all its methods and attributes by spelling it out: import subprocess handler = subprocess.Popen(['cat'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) Or you can import just the names you will use in the global namespace: from subprocess import Popen, PIPE handler = Popen(['cat'], stdout=PIPE, stdin=PIPE) HTH, Tiago Saboga. From steve at alchemy.com Tue Oct 20 16:53:17 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 20 Oct 2009 07:53:17 -0700 Subject: [Tutor] updating Unix config file In-Reply-To: <20091020144416.GI19454@chicago.blisses.org> References: <20091019235106.GD19454@chicago.blisses.org> <20091020144416.GI19454@chicago.blisses.org> Message-ID: <20091020145317.GA10767@dragon.alchemy.com> On Tue, Oct 20, 2009 at 10:44:16AM -0400, Matt Herzog wrote: > Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! > > Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. It's always been like that. Otherwise we'd have lots of collisions between module global names that namespaces are designed to avoid in the first place. So you either name them explicitly, or import them explicitly: import subprocess # now you can reference subprocess.PIPE --or-- from subprocess import Popen, PIPE # now you can reference PIPE without the namespace identifier --or-- from subprocess import * # but I don't recommend this one (caution! danger!) From kent37 at tds.net Tue Oct 20 16:55:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Oct 2009 10:55:54 -0400 Subject: [Tutor] updating Unix config file In-Reply-To: <20091020144416.GI19454@chicago.blisses.org> References: <20091019235106.GD19454@chicago.blisses.org> <20091020144416.GI19454@chicago.blisses.org> Message-ID: <1c2a2c590910200755k5fd59b8tfc0b62debf4fbbde@mail.gmail.com> On Tue, Oct 20, 2009 at 10:44 AM, Matt Herzog wrote: > Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! > > Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. That is standard behaviour of import. If you import subprocess then you access its members as subprocess.Popen, subprocess.PIPE etc. There is nothing special to subprocess or PIPE here. You can use from subprocess import Popen, PIPE if you want to be able to use unqualified names. Kent From msh at blisses.org Tue Oct 20 18:58:27 2009 From: msh at blisses.org (Matt Herzog) Date: Tue, 20 Oct 2009 12:58:27 -0400 Subject: [Tutor] updating Unix config file In-Reply-To: <3351535a0910200749j7f696c17q8c42a94e84a70d00@mail.gmail.com> References: <20091019235106.GD19454@chicago.blisses.org> <20091020144416.GI19454@chicago.blisses.org> <3351535a0910200749j7f696c17q8c42a94e84a70d00@mail.gmail.com> Message-ID: <20091020165827.GJ19454@chicago.blisses.org> On Tue, Oct 20, 2009 at 02:49:53PM +0000, Tiago Saboga wrote: > On Tue, Oct 20, 2009 at 2:44 PM, Matt Herzog wrote: > > Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! > > > > Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. > > It is really like any other module. If you just import subprocess, you > can access all its methods and attributes by spelling it out: > > import subprocess > handler = subprocess.Popen(['cat'], stdout=subprocess.PIPE, > stdin=subprocess.PIPE) > > Or you can import just the names you will use in the global namespace: > > from subprocess import Popen, PIPE > handler = Popen(['cat'], stdout=PIPE, stdin=PIPE) > > HTH, It does help. I never knew this. I don't remember seeing this quirk before. Thanks. > > Tiago Saboga. -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald From msh at blisses.org Tue Oct 20 19:00:06 2009 From: msh at blisses.org (Matt Herzog) Date: Tue, 20 Oct 2009 13:00:06 -0400 Subject: [Tutor] updating Unix config file In-Reply-To: <20091020145317.GA10767@dragon.alchemy.com> References: <20091019235106.GD19454@chicago.blisses.org> <20091020144416.GI19454@chicago.blisses.org> <20091020145317.GA10767@dragon.alchemy.com> Message-ID: <20091020170006.GK19454@chicago.blisses.org> On Tue, Oct 20, 2009 at 07:53:17AM -0700, Steve Willoughby wrote: > On Tue, Oct 20, 2009 at 10:44:16AM -0400, Matt Herzog wrote: > > Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! > > > > Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. > I have been reading python books and trying to learn python for about a year now and this has never met my attention before. Thanks. > It's always been like that. Otherwise we'd have lots of collisions between module global > names that namespaces are designed to avoid in the first place. So you either name them > explicitly, or import them explicitly: > > import subprocess > # now you can reference subprocess.PIPE > > --or-- > > from subprocess import Popen, PIPE > # now you can reference PIPE without the namespace identifier > > --or-- > > from subprocess import * > # but I don't recommend this one (caution! danger!) > -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald From nathan.farrar at gmail.com Tue Oct 20 19:11:06 2009 From: nathan.farrar at gmail.com (Nathan Farrar) Date: Tue, 20 Oct 2009 11:11:06 -0600 Subject: [Tutor] Pexpect maxread & searchwindowsize, timeout Message-ID: <348a45770910201011l42aa57f3k81eb8273b46379b@mail.gmail.com> I haven't been able to find any real examples of pexpect usage, nor documentation. Just little bits here and there, so I'm kind of struggling through. I've got the follow bit of code I'm working with: def main(): try: print 'attempting to spawn connection ... ' session = pexpect.spawn('ssh username at x.x.x.x') except: print 'couldn\'t spawn connection ... ' print 'waiting for password prompt ... ' session.expect('password:') print 'received password prompt ... ' try: print 'attempting to send password ... ' session.sendline(password) except: print 'error sending password ... ' print 'waiting for command prompt ... ' session.expect(command_prompt) print 'received command prompt ... ' try: print 'attempting to issue \'show version\' command ... ' session.sendline([expect.TIMEOUT=1, 'show version']) except: print 'error issuing \'show version\' command ... ' print 'waiting for command prompt ... ' session.expect(command_prompt) print 'received command prompt ... ' print 'attempting to print command results ... ' print session.before print 'closing session ... ' session.close() if __name__=='__main__': main() When I run this against a cisco device, it times out waiting for the command prompt after issuing the show version command. However, if I change 'show version' to something like 'blah blah' it doesn't time out, and I get the results of the command (an error message that is much shorter in length). I believe that the results of the show version command are simply too large. I think I may need to increase the size of maxread & searchwindowsize & set the timeout to something lower than the default, but I haven't been able to figure out how to do this correctly yet. Any help would be greatly appreciated. I'm pulling my hair out. Thank you. -- "The presence of those seeking the truth is infinitely to be preferred to the presence of those who think they've found it." ?Terry Pratchett From vinces1979 at gmail.com Tue Oct 20 19:26:14 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 20 Oct 2009 11:26:14 -0600 Subject: [Tutor] Pexpect maxread & searchwindowsize, timeout In-Reply-To: <348a45770910201011l42aa57f3k81eb8273b46379b@mail.gmail.com> References: <348a45770910201011l42aa57f3k81eb8273b46379b@mail.gmail.com> Message-ID: <1e53c510910201026v13c2e5d4l770c82c85619bf33@mail.gmail.com> On Tue, Oct 20, 2009 at 11:11 AM, Nathan Farrar wrote: > I haven't been able to find any real examples of pexpect usage, nor > documentation. Just little bits here and there, so I'm kind of > struggling through. > > I've got the follow bit of code I'm working with: > > def main(): > try: > print 'attempting to spawn connection ... ' > session = pexpect.spawn('ssh username at x.x.x.x') > except: > print 'couldn\'t spawn connection ... ' > > print 'waiting for password prompt ... ' > session.expect('password:') > print 'received password prompt ... ' > > try: > print 'attempting to send password ... ' > session.sendline(password) > except: > print 'error sending password ... ' > > print 'waiting for command prompt ... ' > session.expect(command_prompt) > print 'received command prompt ... ' > > try: > print 'attempting to issue \'show version\' command ... ' > session.sendline([expect.TIMEOUT=1, 'show version']) > except: > print 'error issuing \'show version\' command ... ' > > print 'waiting for command prompt ... ' > session.expect(command_prompt) > print 'received command prompt ... ' > > print 'attempting to print command results ... ' > print session.before > > print 'closing session ... ' > session.close() > > if __name__=='__main__': > main() > > When I run this against a cisco device, it times out waiting for the > command prompt after issuing the show version command. However, if I > change 'show version' to something like 'blah blah' it doesn't time > out, and I get the results of the command (an error message that is > much shorter in length). > > I believe that the results of the show version command are simply too > large. I think I may need to increase the size of maxread & > searchwindowsize & set the timeout to something lower than the > default, but I haven't been able to figure out how to do this > correctly yet. > > Any help would be greatly appreciated. I'm pulling my hair out. Thank > you. > > -- > "The presence of those seeking the truth is infinitely to be preferred > to the presence of those who think they've found it." > > ?Terry Pratchett > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Looks like you are trying to end multiple commands to the sendline and not expect you can specify the timeout on the expect line try this code: #================================================ def main(): try: print 'attempting to spawn connection ... ' session = pexpect.spawn('ssh username at x.x.x.x') except: print 'couldn\'t spawn connection ... ' print 'waiting for password prompt ... ' session.expect('password:') print 'received password prompt ... ' try: print 'attempting to send password ... ' session.sendline(password) except: print 'error sending password ... ' print 'waiting for command prompt ... ' session.expect(command_prompt) print 'received command prompt ... ' try: print 'attempting to issue \'show version\' command ... ' session.sendline('show version') #: send only command except: print 'error issuing \'show version\' command ... ' print 'waiting for command prompt ... ' session.expect(command_prompt, timeout=1) #: set the timeout here print 'received command prompt ... ' print 'attempting to print command results ... ' print session.before print 'closing session ... ' session.close() if __name__=='__main__': main() #============================== Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From nathan.farrar at gmail.com Tue Oct 20 21:02:07 2009 From: nathan.farrar at gmail.com (Nathan Farrar) Date: Tue, 20 Oct 2009 13:02:07 -0600 Subject: [Tutor] Pexpect maxread & searchwindowsize, timeout In-Reply-To: <1e53c510910201026v13c2e5d4l770c82c85619bf33@mail.gmail.com> References: <348a45770910201011l42aa57f3k81eb8273b46379b@mail.gmail.com> <1e53c510910201026v13c2e5d4l770c82c85619bf33@mail.gmail.com> Message-ID: <348a45770910201202p662008d2s2c2f89e1808d1423@mail.gmail.com> Thanks! That solves my question about configuring the timeout value. However - I still have the problem (I believe) that by default, I can handle all the output. When I issue the "show version" it fails, but if I issue a command with less data returned it succeeds. In the documentation I can see that pexpect uses a maxread and a searchwindowsize value, but I'm not sure how to use them. Any tips? Thanks again. On Tue, Oct 20, 2009 at 11:26 AM, vince spicer wrote: > > > On Tue, Oct 20, 2009 at 11:11 AM, Nathan Farrar > wrote: >> >> I haven't been able to find any real examples of pexpect usage, nor >> documentation. ?Just little bits here and there, so I'm kind of >> struggling through. >> >> I've got the follow bit of code I'm working with: >> >> def main(): >> ? ?try: >> ? ? ? ?print 'attempting to spawn connection ... ' >> ? ? ? ?session = pexpect.spawn('ssh username at x.x.x.x') >> ? ?except: >> ? ? ? ?print 'couldn\'t spawn connection ... ' >> >> ? ?print 'waiting for password prompt ... ' >> ? ?session.expect('password:') >> ? ?print 'received password prompt ... ' >> >> ? ?try: >> ? ? ? ?print 'attempting to send password ... ' >> ? ? ? ?session.sendline(password) >> ? ?except: >> ? ? ? ?print 'error sending password ... ' >> >> ? ?print 'waiting for command prompt ... ' >> ? ?session.expect(command_prompt) >> ? ?print 'received command prompt ... ' >> >> ? ?try: >> ? ? ? ?print 'attempting to issue \'show version\' command ... ' >> ? ? ? ?session.sendline([expect.TIMEOUT=1, 'show version']) >> ? ?except: >> ? ? ? ?print 'error issuing \'show version\' command ... ' >> >> ? ?print 'waiting for command prompt ... ' >> ? ?session.expect(command_prompt) >> ? ?print 'received command prompt ... ' >> >> ? ?print 'attempting to print command results ... ' >> ? ?print session.before >> >> ? ?print 'closing session ... ' >> ? ?session.close() >> >> if __name__=='__main__': >> ? ?main() >> >> When I run this against a cisco device, it times out waiting for the >> command prompt after issuing the show version command. ?However, if I >> change 'show version' to something like 'blah blah' it doesn't time >> out, and I get the results of the command (an error message that is >> much shorter in length). >> >> I believe that the results of the show version command are simply too >> large. ?I think I may need to increase the size of maxread & >> searchwindowsize & set the timeout to something lower than the >> default, but I haven't been able to figure out how to do this >> correctly yet. >> >> Any help would be greatly appreciated. ?I'm pulling my hair out. ?Thank >> you. >> >> -- >> "The presence of those seeking the truth is infinitely to be preferred >> to the presence of those who think they've found it." >> >> ?Terry Pratchett >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Looks like you are trying to end multiple commands to the sendline and not > expect > you can specify the timeout on the expect line > > try this code: > > #================================================ > > def main(): > ? ?try: > ? ? ? ?print 'attempting to spawn connection ... ' > ? ? ? ?session = pexpect.spawn('ssh username at x.x.x.x') > ? ?except: > ? ? ? ?print 'couldn\'t spawn connection ... ' > > ? ?print 'waiting for password prompt ... ' > ? ?session.expect('password:') > ? ?print 'received password prompt ... ' > > ? ?try: > ? ? ? ?print 'attempting to send password ... ' > ? ? ? ?session.sendline(password) > ? ?except: > ? ? ? ?print 'error sending password ... ' > > ? ?print 'waiting for command prompt ... ' > ? ?session.expect(command_prompt) > ? ?print 'received command prompt ... ' > > ? ?try: > ? ? ? ?print 'attempting to issue \'show version\' command ... ' > ? ? ? ?session.sendline('show version') #: send only command > ?? except: > ? ? ? ?print 'error issuing \'show version\' command ... ' > > ? ?print 'waiting for command prompt ... ' > ? ?session.expect(command_prompt, timeout=1) #: set the timeout here > ? ?print 'received command prompt ... ' > > ? ?print 'attempting to print command results ... ' > ? ?print session.before > > ? ?print 'closing session ... ' > ? ?session.close() > > if __name__=='__main__': > ? ?main() > #============================== > > Vince > > > -- "The presence of those seeking the truth is infinitely to be preferred to the presence of those who think they've found it." ?Terry Pratchett From alan.gauld at btinternet.com Tue Oct 20 21:41:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 Oct 2009 20:41:28 +0100 Subject: [Tutor] cross platform authenticating References: <200910200727.20035.jfabiani@yolo.com> Message-ID: "John" wrote > As you guys can see I'm just starting out in the authentication world. This is a list for beginners in Python not authentication. You would probably be better off posting on a security or authentication forum/list But you never know, lots of clever people here so you may get an answer. Alan G From davea at ieee.org Wed Oct 21 01:16:49 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 20 Oct 2009 19:16:49 -0400 Subject: [Tutor] updating Unix config file In-Reply-To: <20091020165827.GJ19454@chicago.blisses.org> References: <20091019235106.GD19454@chicago.blisses.org> <20091020144416.GI19454@chicago.blisses.org> <3351535a0910200749j7f696c17q8c42a94e84a70d00@mail.gmail.com> <20091020165827.GJ19454@chicago.blisses.org> Message-ID: <4ADE44E1.8070106@ieee.org> Matt Herzog wrote: > On Tue, Oct 20, 2009 at 02:49:53PM +0000, Tiago Saboga wrote: > >> On Tue, Oct 20, 2009 at 2:44 PM, Matt Herzog wrote: >> >>> Yes, thanks. What failed was the invocation of PIPE. Apparently I had to explicitly import PIPE from subprocess or python had no clue as to what PIPE was! >>> >>> Dare I say, "wtf?" since when fo I have to specify such? Shouldn't importing the subprocess module make all its methods available? I can't remember having to do this before. >>> >> It is really like any other module. If you just import subprocess, you >> can access all its methods and attributes by spelling it out: >> >> import subprocess >> handler = subprocess.Popen(['cat'], stdout=subprocess.PIPE, >> stdin=subprocess.PIPE) >> >> Or you can import just the names you will use in the global namespace: >> >> from subprocess import Popen, PIPE >> handler = Popen(['cat'], stdout=PIPE, stdin=PIPE) >> >> HTH, >> > > It does help. I never knew this. I don't remember seeing this quirk before. > > Thanks. > > I don't know how much you've used Python, but you were already using os.popen(). It's the same thing. In order to reference a symbol defined in another module, you either have to qualify that symbol with the module name (like the "os." prefix), or use the fancier from xx import yy statement. How about if I elaborate a bit: When you do import mymodule you've added exactly one symbol to your "global" namespace, the symbol mymodule. If you do from mymodule import symbol1, symbol2, symbol3 you do the equivalent of three assignment statements, adding three symbols to your global namespace. symbol1 = mymodule.symbol1 symbol2 = mymodule.symbol2 symbol3 = mymodule.symbol3 HTH DaveA From jfabiani at yolo.com Wed Oct 21 02:43:01 2009 From: jfabiani at yolo.com (John) Date: Tue, 20 Oct 2009 17:43:01 -0700 Subject: [Tutor] cross platform authenticating In-Reply-To: References: <200910200727.20035.jfabiani@yolo.com> Message-ID: <200910201743.01374.jfabiani@yolo.com> On Tuesday 20 October 2009 12:41:28 pm Alan Gauld wrote: > "John" wrote > > > As you guys can see I'm just starting out in the authentication world. > > This is a list for beginners in Python not authentication. > You would probably be better off posting on a security > or authentication forum/list > > But you never know, lots of clever people here so you may get an answer. > > Alan G From a python beginner thanks. Johnf From lfseeney at comcast.net Tue Oct 20 23:55:28 2009 From: lfseeney at comcast.net (lfseeney at comcast.net) Date: Tue, 20 Oct 2009 21:55:28 +0000 (UTC) Subject: [Tutor] New to Python Message-ID: <1233932837.6180841256075728226.JavaMail.root@sz0056a.emeryville.ca.mail.comcast.net> Hello all, Just started looking at Python, I have not programmed in a good 8-10 years now, and find myself woefully behind. I was wondering if there was a Preset Menu and file system module for Python so I would not have to look at setting it all up? Trying to start again, Car wreck took me out for the last 10 years, and my memoery is lacking so I forget how things worked and now relearning things. Was never a true programmer mostly a trouble shooter for HW and SW development so I can scan and read code fair enough but was not the one writing code. So basically (pardon the pun), is there a good reference online for using the libariers to give me a simple Interface with pull downs and such, file system and so? Last time I did any real coding had to write that myself, of course that was before many on the list was born I would guess. So I need a site that can handhold be a bit til whats left in the little gray cells can start working. The Issue that brings this up is I want to put together a program to help Miniature Wargame Players run mid to long campaign games, with all the wargames out there one would think there would be more than a few of these about, but there are very few and the better one still works like a DOS program. I am trying to put together a simple, expandable system that will folks to track and write reports for each turn of the game. Thanks for the help, once I have some idea what I am doing hopefully I can ask questions that do not seem so dumb. Lee -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Wed Oct 21 09:30:40 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 21 Oct 2009 00:30:40 -0700 (PDT) Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: Message-ID: <773809.37684.qm@web110711.mail.gq1.yahoo.com> Is the if-else (esp. 'else') in a list comprehension specific for Python 3.x? Or did I miss something? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before you criticize someone, walk a mile in their shoes, that way when you do criticize them, you're a mile away and you have their shoes! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Tue, 10/20/09, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] "if clause" in list comprehensions. > To: tutor at python.org > Date: Tuesday, October 20, 2009, 12:29 AM > Ooops, hit send by mistake... > > "vince spicer" > wrote > > >> Lambda can save the day to keep everything on one > line, and leave variable > >> type the same: > >> > >> mylist = ['John', 'Canada', 25, 32, 'right'] > >> new_list = [(lambda y: y.upper() if hasattr(y, > 'upper') else y)(a) for a in > >> mylist ] > >> > >> >>? ['JACK', 'CANADA', 25, 32, > 'RIGHT'] > > In what way does lambda help? > > new_list = [y.upper() if hasattr(y, 'upper') else y for y > in mylist] > > does exactly the same and is shorter. > > lambda helps if you want to pass a function object around > but > defining it and immediately calling it means it can be > replaced > directly by the expression within the lambda. > > But using hasattr() still has the problem of failing if > upper is not a > callable attribute (or does something radical like > exiting) > > > -- Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From cwitts at compuscan.co.za Wed Oct 21 10:21:40 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 21 Oct 2009 10:21:40 +0200 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: <773809.37684.qm@web110711.mail.gq1.yahoo.com> References: <773809.37684.qm@web110711.mail.gq1.yahoo.com> Message-ID: <4ADEC494.1050703@compuscan.co.za> Albert-Jan Roskam wrote: > Is the if-else (esp. 'else') in a list comprehension specific for Python 3.x? Or did I miss something? > > Cheers!! > Albert-Jan > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Before you criticize someone, walk a mile in their shoes, that way > when you do criticize them, you're a mile away and you have their shoes! > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > --- On Tue, 10/20/09, Alan Gauld wrote: > > >> From: Alan Gauld >> Subject: Re: [Tutor] "if clause" in list comprehensions. >> To: tutor at python.org >> Date: Tuesday, October 20, 2009, 12:29 AM >> Ooops, hit send by mistake... >> >> "vince spicer" >> wrote >> >> >>>> Lambda can save the day to keep everything on one >>>> >> line, and leave variable >> >>>> type the same: >>>> >>>> mylist = ['John', 'Canada', 25, 32, 'right'] >>>> new_list = [(lambda y: y.upper() if hasattr(y, >>>> >> 'upper') else y)(a) for a in >> >>>> mylist ] >>>> >>>> >>>>>> ['JACK', 'CANADA', 25, 32, >>>>>> >> 'RIGHT'] >> >> In what way does lambda help? >> >> new_list = [y.upper() if hasattr(y, 'upper') else y for y >> in mylist] >> >> does exactly the same and is shorter. >> >> lambda helps if you want to pass a function object around >> but >> defining it and immediately calling it means it can be >> replaced >> directly by the expression within the lambda. >> >> But using hasattr() still has the problem of failing if >> upper is not a >> callable attribute (or does something radical like >> exiting) >> >> >> -- Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Python 2.5+ if memory serves me correctly. I know 2.4 running on one of our servers does not support the else section. -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Wed Oct 21 11:57:23 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 21 Oct 2009 09:57:23 +0000 (GMT) Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: <773809.37684.qm@web110711.mail.gq1.yahoo.com> References: <773809.37684.qm@web110711.mail.gq1.yahoo.com> Message-ID: <299463.39064.qm@web86705.mail.ird.yahoo.com> > Is the if-else (esp. 'else') in a list comprehension specific for Python 3.x? Or > did I miss something? Its not part of list comprehensions per se, you can use it in any *expression*. It was introduced in Python 2.5 as a response to C's ternary operator: C: x = foo?bar:baz Python x = bar if foo else baz So in the list comprehension case we are simply using that standard expression syntax as the value part of the LC. HTH, Alan G. From alan.gauld at btinternet.com Wed Oct 21 12:09:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Oct 2009 11:09:25 +0100 Subject: [Tutor] New to Python References: <1233932837.6180841256075728226.JavaMail.root@sz0056a.emeryville.ca.mail.comcast.net> Message-ID: wrote > Just started looking at Python Welcome to the list. > I was wondering if there was a Preset Menu and file system module Not really sure what you are expecting here? Can you give examples of what you would expect these to do? There are operations for acting on files, if thats what you mean. > So basically (pardon the pun), is there a good reference online > for using the libariers to give me a simple Interface with > pull downs and such, file system and so? If you mean a GUI then there are GUI toolkits for building user interfaces. If you mean an IDE then there is IDLE which comes as standard (and a whole bunch of others you can download). I'm still not quite sure what you are expecting based on your description. > Last time I did any real coding had to write that myself, > of course that was before many on the list was born I would guess. You still need to write your own GUI for your apps although you should find the tookits now are easier to use. Also there are a few graphical tools to help build GUIs although my own experience is that none of the Python ones are great. > So I need a site that can handhold be a bit til whats left in the > little gray cells can start working. There are lots of tutorials around both for basic Python programming and for GUI building (depending on the toolkit - there are several) If you just want a flavour you could look at the GUI topic in my tutorial. > The Issue that brings this up is I want to put together a program > to help Miniature Wargame Players run mid to long campaign games, > with all the wargames out there one would think there would be > more than a few of these about, but there are very few and > the better one still works like a DOS program. Batch oriented programs are often best driven by a command line so that may be the reason but I have no experience in that area so can't really comment. > I am trying to put together a simple, expandable system that > will folks to track and write reports for each turn of the game. Sounds like a good project, just take it step by step. A GUI is probably the last step! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Wed Oct 21 12:22:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Oct 2009 06:22:19 -0400 Subject: [Tutor] "if clause" in list comprehensions. In-Reply-To: <773809.37684.qm@web110711.mail.gq1.yahoo.com> References: <773809.37684.qm@web110711.mail.gq1.yahoo.com> Message-ID: <1c2a2c590910210322r5d1e9590u35810013388e9a0a@mail.gmail.com> On Wed, Oct 21, 2009 at 3:30 AM, Albert-Jan Roskam wrote: > Is the if-else (esp. 'else') in a list comprehension specific for Python 3.x? Or did I miss something? List comps have always allowed a condition since they were introduced: [ for in if ] This is the form of the original question. Conditional expressions of the form if else are relatively new. The answers to the original question use this as part of the term of the list comp. So they are not using any new list comp syntax, they are using new expression syntax. Kent From srilyk at gmail.com Wed Oct 21 12:36:17 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 21 Oct 2009 05:36:17 -0500 Subject: [Tutor] New to Python In-Reply-To: <1233932837.6180841256075728226.JavaMail.root@sz0056a.emeryville.ca.mail.comcast.net> References: <1233932837.6180841256075728226.JavaMail.root@sz0056a.emeryville.ca.mail.comcast.net> Message-ID: <333efb450910210336x3b789f2cy3cd7adbe542aa6de@mail.gmail.com> On Tue, Oct 20, 2009 at 4:55 PM, wrote: > Hello all, > Just started looking at Python, I have not programmed in a good 8-10 years > now, and find myself woefully behind. > Luckily it shouldn't take you too much time with python - it's a lot easier to learn/relearn than a lot of other languages! > I was wondering if there was a Preset Menu and file system module for > Python so I would not have to look at setting it all up? > The short answer: yes But that leaves out a lot of details :) > Trying to start again, Car wreck took me out for the last 10 years, and my > memoery is lacking so I forget how things worked and now relearning things. > Well if you get stuck, we're glad to help around here :) Especially if you follow the "asking good questions" guidelines you get in response to your first email. > Was never a true programmer mostly a trouble shooter for HW and SW > development so I can scan and read code fair enough but was not the one > writing code. > Honestly you probably got a decent amount of experience that way - I think it may be more difficult reading someone else's code than reading your own! > So basically (pardon the pun), is there a good reference online for using > the libariers to give me a simple Interface with pull downs and such, file > system and so? > There are *lots* of good online python references - including some written by the folks around here. > Last time I did any real coding had to write that myself, of course that > was before many on the list was born I would guess. > > So I need a site that can handhold be a bit til whats left in the little > gray cells can start working. > > The Issue that brings this up is I want to put together a program to help > Miniature Wargame Players run mid to long campaign games, with all the > wargames out there one would think there would be more than a few of these > about, but there are very few and the better one still works like a DOS > program. > > I am trying to put together a simple, expandable system that will folks to > track and write reports for each turn of the game. > At first I was a little confused by what you wanted to do, but after reading this it seems like you want a GUI? If so, Tkinter is probably the right choice - I find it a lot simpler than most GUI libraries, but powerful enough to handle what you need/want it to. Tkinter (indeed most python scripts/GUIs) has the added benefit of being cross platform. If you write something that works in windows, it probably works under another platform (mac, *nix), as long as python is installed. My personal recommendation would be to check out some of the regular programming tutorials available - several written by some of the top contributers here (in terms of activity, experience, and intelligence). After you're refreshed as to some general programming concepts and syntax, then it's a bit easier to pick up some of the GUIs. In reality, most people have their favourite GUI, whether it be Tkinter, PyGTK+ (mine, but mainly because I've found it has a bit more advanced drawing methods - I always wanted to write up a sketchbook type program. Then I found mypaint, written in PyGTK+ with a little bit of C that turns out to be perfect for my desires), Qt, or any one of a number of others. Most of those who are pretty familiar with their GUI of choice could probably toss up a few features of the kind of thing you seem to be describing (menus, forms) with very little trouble. Python has lots of built-in file system operations/modules. You can easily read/write a file from within python with no imports, although with what you seem to want to do you might look at the pickle library (enables writing then reading objects directly from a file, as opposed to just attributes), configparser (which does pretty much what it sounds like - parses config formatted files), or what might be the best option if you're planning to support lots of campaign info - sqlite. Of course there are probably a few people with other ideas and suggestions. Anyway, HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Wed Oct 21 13:23:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 21 Oct 2009 22:23:28 +1100 Subject: [Tutor] Python List Help In-Reply-To: <016001ca50d0$43c230a0$cb4691e0$@net> References: <016001ca50d0$43c230a0$cb4691e0$@net> Message-ID: Mike Sweany wrote: > 33 print len(playerid) > > 34 print playerid[0] > > 35 > > *playerid* = [] > > **: list index out of range > args = ('list index out of range',) > message = 'list index out of range' > > If I change the print playerid[0] to print playerid[1], same error, but > if I change it to print playerid[2] or higher, it will show the same > error, but the playerid= [] will show the actual list values in the debug. As far as I can see, playerid[0] can only fail with IndexError if playerid is an empty list. Have you made sure that playerid will always have something in it? From lead.expression at gmail.com Wed Oct 21 15:42:46 2009 From: lead.expression at gmail.com (Nicola De Quattro) Date: Wed, 21 Oct 2009 15:42:46 +0200 Subject: [Tutor] PyGTK: is there a library for both Linux and Windows Message-ID: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> Hi I'm starting to design some windows for my little tool. I've two questions for you: 1) In this page http://www.pygtk.org/downloads.html there are two different library for Windows and GNU/Linux, but I want my application to be executed identically under Windows and under GNU/Linux. Is PyGTK a good choice? There are some difference between PyGTK library under Windows and under GNU/Linux, that is have I to develop two different versions of my tool? 2) Do you suggest to use Glade to design windows? Note: I'm totally new both to python and to GUI design (I've always worked on signal processing, never develop a MMI) so I'm searching something that can be as much as possible both "educational" and friendly. Thank you for your help -- Nicola De Quattro Mobile: (+39)3292964937 Web: http://nikde4.altervista.org Skype: lead_expression MSNetwork: lead_expression at hotmail.com From srilyk at gmail.com Wed Oct 21 16:38:17 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 21 Oct 2009 09:38:17 -0500 Subject: [Tutor] PyGTK: is there a library for both Linux and Windows In-Reply-To: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> References: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> Message-ID: <333efb450910210738l45c1b9e1oe160771d97d860a6@mail.gmail.com> On Wed, Oct 21, 2009 at 8:42 AM, Nicola De Quattro < lead.expression at gmail.com> wrote: > Hi > I'm starting to design some windows for my little tool. > I've two questions for you: > 1) In this page http://www.pygtk.org/downloads.html there are two > different library for Windows and GNU/Linux, but I want my application > to be executed identically under Windows and under GNU/Linux. Is PyGTK > a good choice? There are some difference between PyGTK library under > Windows and under GNU/Linux, that is have I to develop two different > versions of my tool? > There shouldn't be. There might be some decorative differences, but that's due to the different window managers. But yes, PyGTK is a good choice. > 2) Do you suggest to use Glade to design windows? Note: I'm totally > new both to python and to GUI design (I've always worked on signal > processing, never develop a MMI) so I'm searching something that can > be as much as possible both "educational" and friendly. Glade is pretty useful for most people. I don't personally use it because I find that, personally, I spend more time looking up how to adjust something in Glade than just write the code myself. I guess if I were trying to write some large project or had a great desire to learn Glade, I'd find it useful. I know some people prefer it - I guess it should come down to this line of questioning: If you make a webpage do you prefer Arachnophilia/Dreamweaver/WYSIWYG or vi/emacs/notepad? When you regularly program do you prefer IDLE/Codeblocks/Etc. or vi/emacs/notepad? If you lean towards the former, I would recommend Glade. If you lean towards the latter, I would recommend you try out Glade, but you may likely find simply coding in your favourite editor works better for you. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Wed Oct 21 16:29:39 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 21 Oct 2009 09:29:39 -0500 Subject: [Tutor] PyGTK: is there a library for both Linux and Windows In-Reply-To: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> References: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> Message-ID: <200910210929.40137.cfuller084@thinkingplanet.net> The version of GTK for windows I like to use is at http://gladewin32.sourceforge.net/, but it is rather out of date. It's main advantage is everything is bundled up in a nice installer. You can also get it from the main site at ftp://ftp.gtk.org/pub/gtk, but you have to grab several files and install manually. I've never tried to figure out which ones, but I expect it wouldn't be hard. You could check the dependencies of the PyGTK shared objects, i.e. with http://www.dependencywalker.com/ You could also just get a more current, but still bundled up runtime from Pidgin (http://www.pidgin.im/), and install glade separately, as its only a single file. Note that you'll need to get PyGTK from the gnome site http://ftp.gnome.org/pub/gnome/binaries/win32/. Get PyGTK, PyObject, and PyCairo. Yes, glade is awesome. You'll need to learn how to hook the signals into your code. There are a lot of tutorials out there, but the ones I used are at the Linux Journal site: http://www.linuxjournal.com/article/6586 http://www.linuxjournal.com/article/7421 http://www.linuxjournal.com/article/4702 There's a bit of a caveat. You will find in most cases that the system Python and GTK (or numpy, PIL, etc) that your distribution provides is lagging somewhat behind what you can easily install on a Windows box, since there's aren't so many interdependencies. I'm just now starting to playing around with ArchLinux to see if I can get aruond this. Cheers On Wednesday 21 October 2009 08:42, Nicola De Quattro wrote: > Hi > I'm starting to design some windows for my little tool. > I've two questions for you: > 1) In this page http://www.pygtk.org/downloads.html there are two > different library for Windows and GNU/Linux, but I want my application > to be executed identically under Windows and under GNU/Linux. Is PyGTK > a good choice? There are some difference between PyGTK library under > Windows and under GNU/Linux, that is have I to develop two different > versions of my tool? > 2) Do you suggest to use Glade to design windows? Note: I'm totally > new both to python and to GUI design (I've always worked on signal > processing, never develop a MMI) so I'm searching something that can > be as much as possible both "educational" and friendly. > > Thank you for your help From cfuller084 at thinkingplanet.net Wed Oct 21 16:43:26 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 21 Oct 2009 09:43:26 -0500 Subject: [Tutor] PyGTK: is there a library for both Linux and Windows In-Reply-To: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> References: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> Message-ID: <200910210943.26413.cfuller084@thinkingplanet.net> on differences: The downloads include binaries, so there have to be distinct files for Linux and Windoze. If you download the same versions, there shouldn't be any noticeable differences, with one big exception: multithreading and PyGTK don't mix well on Windows. Your application might run perfectly (and look correct) on Linux, but in Windoze it's a mess. You can find workarounds, but I haven't come across one that looked reliable. If you have Python 2.6 or higher, you can use the multiprocessing module (also available separately for earlier versions) to emulate threads with processes, which will relieve the problem, but make it a little harder for your threads (processes) to communicate with each other. Cheers From ksterling at mindspring.com Wed Oct 21 17:19:57 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Wed, 21 Oct 2009 11:19:57 -0400 (EDT) Subject: [Tutor] PyGTK: is there a library for both Linux and Windows Message-ID: <6665982.1256138397786.JavaMail.root@elwamui-muscovy.atl.sa.earthlink.net> -----Original Message----- >From: Chris Fuller >Sent: Oct 21, 2009 10:43 AM >To: tutor at python.org >Subject: Re: [Tutor] PyGTK: is there a library for both Linux and Windows > > >on differences: > >The downloads include binaries, so there have to be distinct files for Linux >and Windoze. If you download the same versions, there shouldn't be any >noticeable differences, with one big exception: multithreading and PyGTK >don't mix well on Windows. Your application might run perfectly (and look >correct) on Linux, but in Windoze it's a mess. You can find workarounds, but >I haven't come across one that looked reliable. If you have Python 2.6 or >higher, you can use the multiprocessing module (also available separately for >earlier versions) to emulate threads with processes, which will relieve the >problem, but make it a little harder for your threads (processes) to >communicate with each other. > >Cheers In a forum like this why do some presumably intelligent people insist on using insulting and derogatory terminology as above? Flame wars are ugly. . From kent37 at tds.net Wed Oct 21 17:38:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Oct 2009 11:38:17 -0400 Subject: [Tutor] PyGTK: is there a library for both Linux and Windows In-Reply-To: <200910210943.26413.cfuller084@thinkingplanet.net> References: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> <200910210943.26413.cfuller084@thinkingplanet.net> Message-ID: <1c2a2c590910210838l46ddb4c7ubd3140164088da4@mail.gmail.com> On Wed, Oct 21, 2009 at 10:43 AM, Chris Fuller wrote: > > on differences: > > The downloads include binaries, so there have to be distinct files for Linux > and Windoze. ?If you download the same versions, there shouldn't be any > noticeable differences, with one big exception: ?multithreading and PyGTK > don't mix well on Windows. ?Your application might run perfectly (and look > correct) on Linux, but in Windoze it's a mess. Wow. You can't make a multithreaded Windows GUI app using PyGTK? That is a huge limitation - in my experience most large GUI programs do use threads to allow the GUI to be responsive during long-running tasks. Kent From yanglizhi at gmail.com Wed Oct 21 20:09:00 2009 From: yanglizhi at gmail.com (Lizhi Yang) Date: Wed, 21 Oct 2009 14:09:00 -0400 Subject: [Tutor] Detect duplicate object names Message-ID: <3da557ee0910211109q50d8ba81iba7efa09e98256c4@mail.gmail.com> Hi, When I define functions in a Module, how to avoid override the name of existing functions? For example: define func1(): define func2(): define func1(): Is there anyway to pop up the warnings? From kent37 at tds.net Wed Oct 21 20:16:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Oct 2009 14:16:26 -0400 Subject: [Tutor] PyGTK: is there a library for both Linux and Windows In-Reply-To: <200910211221.19829.cfuller084@thinkingplanet.net> References: <83afd1db0910210642p5fd4653dy1522a25cbe921007@mail.gmail.com> <200910210943.26413.cfuller084@thinkingplanet.net> <1c2a2c590910210838l46ddb4c7ubd3140164088da4@mail.gmail.com> <200910211221.19829.cfuller084@thinkingplanet.net> Message-ID: <1c2a2c590910211116o252db5f1nebe919280447f443@mail.gmail.com> Forwarding to the list with my reply... On Wed, Oct 21, 2009 at 1:21 PM, Chris Fuller wrote: > > There are workarounds. ?The point is that they aren't necessary in Linux, and > usually involve something fishy, like sleeping a (more or less) arbitrary > period to get the synchronization right, which might work some of the time, > but not under unusual circumstances (but who cares if its just a GUI update?) > > Possibly, the Linux environment is more forgiving, but I don't have similar > problems in Tkinter, and special treatment isn't necessary if you only access > the GUI via the main thread. > > http://faq.pygtk.org/index.py?file=faq20.006.htp&req=show Oh, OK. Accessing the GUI only from the GUI thread is (in my experience) a pretty common requirement. I'm currently using WinForms which requires that GUI elements be accessed from the thread that created them, and IIRC Java Swing has the same limitation. Kent > It may be that the last time I tangled with the issue, I was missing some key > docs. ?In any case, its a potential pitfall to watch out for. > > Cheers > > On Wednesday 21 October 2009 10:38, you wrote: >> On Wed, Oct 21, 2009 at 10:43 AM, Chris Fuller >> >> wrote: >> > on differences: >> > >> > The downloads include binaries, so there have to be distinct files for >> > Linux and Windoze. ?If you download the same versions, there shouldn't be >> > any noticeable differences, with one big exception: ?multithreading and >> > PyGTK don't mix well on Windows. ?Your application might run perfectly >> > (and look correct) on Linux, but in Windoze it's a mess. >> >> Wow. You can't make a multithreaded Windows GUI app using PyGTK? That >> is a huge limitation - in my experience most large GUI programs do use >> threads to allow the GUI to be responsive during long-running tasks. >> >> Kent > From chaoticslacker at gmail.com Wed Oct 21 20:21:23 2009 From: chaoticslacker at gmail.com (Jason Willis) Date: Wed, 21 Oct 2009 14:21:23 -0400 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work Message-ID: hi everyone, sorry for the rather boring question but i'm having serious issues getting my programs to run from the command line without having to type "python" in-front of them. I've tried a lot of different variations on the #!/usr/bin/ etc. line and have come up with the following every time: *[root at localhost moonshinerat]# mycode.py bash: mycode.py: command not found [root at localhost moonshinerat]# mycode bash: mycode: command not found [root at localhost moonshinerat]# I've chmod'ed the program and everything but i still get command not found from the shell. The only thing that does work is ./mycode.py but from what i understand that's been built into linux itself to work that way... please someone let me know what i'm doing wrong here and possibly help?? thanks! * -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Oct 21 20:31:04 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 21 Oct 2009 12:31:04 -0600 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: Message-ID: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis wrote: > hi everyone, > > sorry for the rather boring question but i'm having serious issues getting > my programs to run from the command line without having to type "python" > in-front of them. I've tried a lot of different variations on the > #!/usr/bin/ etc. line and have come up with the following every time: > > *[root at localhost moonshinerat]# mycode.py > bash: mycode.py: command not found > [root at localhost moonshinerat]# mycode > bash: mycode: command not found > [root at localhost moonshinerat]# > > I've chmod'ed the program and everything but i still get command not found > from the shell. The only thing that does work is ./mycode.py but from what i > understand that's been built into linux itself to work that way... > > please someone let me know what i'm doing wrong here and possibly help?? > > thanks! > > * > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > try: ./mycode.py since i'm guess your current path isn't in the system path Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From amosanderson at gmail.com Wed Oct 21 20:31:37 2009 From: amosanderson at gmail.com (Amos Anderson) Date: Wed, 21 Oct 2009 13:31:37 -0500 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: Message-ID: Are you by chance editing the file in Windows? Have you verified that python is in /usr/bin? In some cases it could be in a different location. On Wed, Oct 21, 2009 at 1:21 PM, Jason Willis wrote: > hi everyone, > > sorry for the rather boring question but i'm having serious issues getting > my programs to run from the command line without having to type "python" > in-front of them. I've tried a lot of different variations on the > #!/usr/bin/ etc. line and have come up with the following every time: > > *[root at localhost moonshinerat]# mycode.py > bash: mycode.py: command not found > [root at localhost moonshinerat]# mycode > bash: mycode: command not found > [root at localhost moonshinerat]# > > I've chmod'ed the program and everything but i still get command not found > from the shell. The only thing that does work is ./mycode.py but from what i > understand that's been built into linux itself to work that way... > > please someone let me know what i'm doing wrong here and possibly help?? > > thanks! > > * > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Oct 21 20:33:39 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 21 Oct 2009 12:33:39 -0600 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: <1e53c510910211133x3e5afd64h195c95700f39d3d6@mail.gmail.com> On Wed, Oct 21, 2009 at 12:31 PM, vince spicer wrote: > > > On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis wrote: > >> hi everyone, >> >> sorry for the rather boring question but i'm having serious issues getting >> my programs to run from the command line without having to type "python" >> in-front of them. I've tried a lot of different variations on the >> #!/usr/bin/ etc. line and have come up with the following every time: >> >> *[root at localhost moonshinerat]# mycode.py >> bash: mycode.py: command not found >> [root at localhost moonshinerat]# mycode >> bash: mycode: command not found >> [root at localhost moonshinerat]# >> >> I've chmod'ed the program and everything but i still get command not found >> from the shell. The only thing that does work is ./mycode.py but from what i >> understand that's been built into linux itself to work that way... >> >> please someone let me know what i'm doing wrong here and possibly help?? >> >> thanks! >> >> * >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > try: > > ./mycode.py > > since i'm guess your current path isn't in the system path > > Vince > > Sorry didn't read full post, you would have add your program directory to the system path in order to call the program by name you can add this to you bashrc export PATH=~/my/program/dir:"${PATH}" Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From ericlhoward at gmail.com Wed Oct 21 20:34:26 2009 From: ericlhoward at gmail.com (Eric L. Howard) Date: Wed, 21 Oct 2009 14:34:26 -0400 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: Message-ID: The directory you are sitting in doesn't appear to be in your path... [ehoward at preacher ~/bin]$ ls macosver macosver* [ehoward at preacher ~/bin]$ macosver 10.5.8 [ehoward at preacher ~/bin]$ echo $PATH /bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:~/bin:/opt/local/bin:/opt/local/sbin ~elh On Wed, Oct 21, 2009 at 2:21 PM, Jason Willis wrote: > hi everyone, > > sorry for the rather boring question but i'm having serious issues getting > my programs to run from the command line without having to type "python" > in-front of them. I've tried a lot of different variations on the > #!/usr/bin/ etc. line and have come up with the following every time: > > [root at localhost moonshinerat]# mycode.py > bash: mycode.py: command not found > [root at localhost moonshinerat]# mycode > bash: mycode: command not found > [root at localhost moonshinerat]# > > I've chmod'ed the program and everything but i still get command not found > from the shell. The only thing that does work is ./mycode.py but from what i > understand that's been built into linux itself to work that way... > > please someone let me know what i'm doing wrong here and possibly help?? > > thanks! > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Iron sharpens iron, so one man sharpens another. -Proverbs 27:17 NASB From steve at alchemy.com Wed Oct 21 20:36:08 2009 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 21 Oct 2009 11:36:08 -0700 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: Message-ID: <20091021183608.GA71982@dragon.alchemy.com> On Wed, Oct 21, 2009 at 02:21:23PM -0400, Jason Willis wrote: > hi everyone, > > sorry for the rather boring question but i'm having serious issues getting > my programs to run from the command line without having to type "python" > in-front of them. I've tried a lot of different variations on the > #!/usr/bin/ etc. line and have come up with the following every time: If ./mycode.py works, then the #! line is fine. It just means that the directory containing mycode.py is not in your PATH. If you set up a directory like /usr/local/bin and put mycode.py in it (or rename it to mycode), and have /usr/local/bin in your path, then you can just type: $ mycode and it will work as expected. Having to type a full (absolute or relative) path to it (and ./mycode *is* a relative pathname explicitly saying you want the "mycode" in the current directory) Generally speaking, while Linux/Unix won't STOP you from putting "." in your path, it's not a good idea, *especially* for the root account. Being in a directory which just happens to contain the names of common commands can be a pain if the system is set to run whatever out of the current directory. If the #! line isn't being recognized at all, do the following: Make sure your file is formatted as a Unix text file (lines ending with \n, not \r\n). Also make sure you know the full path to Python, for example: # which python /usr/local/bin/python "Aha! Looks like python is in /usr/local/bin!" Put that location in your shebang line: #!/usr/local/bin/python -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From vinces1979 at gmail.com Wed Oct 21 20:36:22 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 21 Oct 2009 12:36:22 -0600 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: <1e53c510910211133x3e5afd64h195c95700f39d3d6@mail.gmail.com> References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> <1e53c510910211133x3e5afd64h195c95700f39d3d6@mail.gmail.com> Message-ID: <1e53c510910211136v942d3rd7905738b49c96af@mail.gmail.com> On Wed, Oct 21, 2009 at 12:33 PM, vince spicer wrote: > > > On Wed, Oct 21, 2009 at 12:31 PM, vince spicer wrote: > >> >> >> On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis wrote: >> >>> hi everyone, >>> >>> sorry for the rather boring question but i'm having serious issues >>> getting my programs to run from the command line without having to type >>> "python" in-front of them. I've tried a lot of different variations on the >>> #!/usr/bin/ etc. line and have come up with the following every time: >>> >>> *[root at localhost moonshinerat]# mycode.py >>> bash: mycode.py: command not found >>> [root at localhost moonshinerat]# mycode >>> bash: mycode: command not found >>> [root at localhost moonshinerat]# >>> >>> I've chmod'ed the program and everything but i still get command not >>> found from the shell. The only thing that does work is ./mycode.py but from >>> what i understand that's been built into linux itself to work that way... >>> >>> please someone let me know what i'm doing wrong here and possibly help?? >>> >>> thanks! >>> >>> * >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> try: >> >> ./mycode.py >> >> since i'm guess your current path isn't in the system path >> >> Vince >> >> > Sorry didn't read full post, > > you would have add your program directory to the system path in order to > call the program by name > > you can add this to you bashrc > > export PATH=~/my/program/dir:"${PATH}" > > > Vince > A better description of linux PATH: http://www.linuxheadquarters.com/howto/basic/path.shtml http://www.linfo.org/path_env_var.html Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Oct 21 21:06:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Oct 2009 15:06:45 -0400 Subject: [Tutor] Detect duplicate object names In-Reply-To: <3da557ee0910211109q50d8ba81iba7efa09e98256c4@mail.gmail.com> References: <3da557ee0910211109q50d8ba81iba7efa09e98256c4@mail.gmail.com> Message-ID: <1c2a2c590910211206r21bf4c51o1da2f825528b16fc@mail.gmail.com> On Wed, Oct 21, 2009 at 2:09 PM, Lizhi Yang wrote: > Hi, > > When I define functions in a Module, how to avoid override the name of > existing functions? > For example: > > define func1(): > define func2(): > define func1(): > > Is there anyway to pop up the warnings? Take a look at PyFlakes and PyChecker, they should be able to detect this sort of error. Kent From yanglizhi at gmail.com Wed Oct 21 21:26:49 2009 From: yanglizhi at gmail.com (Lizhi Yang) Date: Wed, 21 Oct 2009 15:26:49 -0400 Subject: [Tutor] ifdef in python Message-ID: <3da557ee0910211226i1d406776q96039916d51a9c65@mail.gmail.com> Is there anything similar to ifdef statement in C or C++ in python? From kent37 at tds.net Wed Oct 21 21:36:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Oct 2009 15:36:50 -0400 Subject: [Tutor] ifdef in python In-Reply-To: <3da557ee0910211226i1d406776q96039916d51a9c65@mail.gmail.com> References: <3da557ee0910211226i1d406776q96039916d51a9c65@mail.gmail.com> Message-ID: <1c2a2c590910211236j728abe4of5aad34a0682802a@mail.gmail.com> On Wed, Oct 21, 2009 at 3:26 PM, Lizhi Yang wrote: > Is there anything similar to ifdef statement in C or C++ in python? No, Python doesn't have a preprocessor. Can you say why you want it? You may be able to do what you want using an ordinary if statement, for example you can conditionally import or define objects. Kent From lie.1296 at gmail.com Wed Oct 21 22:24:57 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 22 Oct 2009 07:24:57 +1100 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: Message-ID: Jason Willis wrote: > hi everyone, > > sorry for the rather boring question but i'm having serious issues > getting my programs to run from the command line without having to type > "python" in-front of them. I've tried a lot of different variations on > the #!/usr/bin/ etc. line and have come up with the following every time: > > *[root at localhost moonshinerat]# mycode.py > bash: mycode.py: command not found > [root at localhost moonshinerat]# mycode > bash: mycode: command not found > [root at localhost moonshinerat]# > > I've chmod'ed the program and everything but i still get command not > found from the shell. The only thing that does work is ./mycode.py but > from what i understand that's been built into linux itself to work that > way... > > please someone let me know what i'm doing wrong here and possibly help?? > No, you're not doing anything wrong. It is just the way the hashbang line and PATH environment variable works. The line $ ./script.py will find an executable file named script.py in the *current working directory* (i.e. "."); and pass it the the interpreter defined in the hashbang line. The line $ script.py will find an executable file named script.py in the PATH environment variable and pass it to the interpreter defined in the hashbang line. In both cases, the hashbang line is used to find the interpreter. As others have said, it is possible to add "." to PATH to make Linux works like Windows (or rather bash to work like cmd), but this is not a good idea for security since it makes it trivial for hacker to trick users (esp. root) to run a script named similar to a system executable. From lie.1296 at gmail.com Wed Oct 21 22:29:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 22 Oct 2009 07:29:37 +1100 Subject: [Tutor] ifdef in python In-Reply-To: <3da557ee0910211226i1d406776q96039916d51a9c65@mail.gmail.com> References: <3da557ee0910211226i1d406776q96039916d51a9c65@mail.gmail.com> Message-ID: Lizhi Yang wrote: > Is there anything similar to ifdef statement in C or C++ in python? Not really, but python's regular if can be used for a similar purpose: DEBUG = True if DEBUG: import logging def foo(): # debug version else: def foo(): # normal version def main(): foo() if __name__ == '__main__': main() or something like that. From srilyk at gmail.com Wed Oct 21 23:37:35 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 21 Oct 2009 16:37:35 -0500 Subject: [Tutor] ifdef in python In-Reply-To: References: <3da557ee0910211226i1d406776q96039916d51a9c65@mail.gmail.com> Message-ID: <333efb450910211437o6cf2f34j3e49f6a4a0a152f8@mail.gmail.com> On Wed, Oct 21, 2009 at 3:29 PM, Lie Ryan wrote: > Lizhi Yang wrote: > >> Is there anything similar to ifdef statement in C or C++ in python? >> > > Not really, but python's regular if can be used for a similar purpose: > > DEBUG = True > > if DEBUG: > import logging > def foo(): > # debug version > else: > def foo(): > # normal version > > def main(): > foo() > > if __name__ == '__main__': > main() > > or something like that. Really a try/except block would actually work def spam1(): pass try: spam2 except NameError: def spam2(): pass Because if DEBUG isn't declared you'll throw a NameError -------------- next part -------------- An HTML attachment was scrubbed... URL: From chaoticslacker at gmail.com Wed Oct 21 23:56:39 2009 From: chaoticslacker at gmail.com (Jason Willis) Date: Wed, 21 Oct 2009 17:56:39 -0400 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: so i changed the .bashrc and added at the end : PATH="/home/compy/pythons:$PATH" ###which is the actual path to my python proggies### and i still get compy at compy-laptop:~/pythons$ herosinventory.py herosinventory.py: command not found compy at compy-laptop:~/pythons$ herosinventory.py herosinventory.py: command not found compy at compy-laptop:~/pythons$ herosinventory herosinventory: command not found compy at compy-laptop:~/pythons$ I must be retarded. I'm sorry , what am I doing wrong here? On Wed, Oct 21, 2009 at 2:31 PM, vince spicer wrote: > > > On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis wrote: > >> hi everyone, >> >> sorry for the rather boring question but i'm having serious issues getting >> my programs to run from the command line without having to type "python" >> in-front of them. I've tried a lot of different variations on the >> #!/usr/bin/ etc. line and have come up with the following every time: >> >> *[root at localhost moonshinerat]# mycode.py >> bash: mycode.py: command not found >> [root at localhost moonshinerat]# mycode >> bash: mycode: command not found >> [root at localhost moonshinerat]# >> >> I've chmod'ed the program and everything but i still get command not found >> from the shell. The only thing that does work is ./mycode.py but from what i >> understand that's been built into linux itself to work that way... >> >> please someone let me know what i'm doing wrong here and possibly help?? >> >> thanks! >> >> * >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > try: > > ./mycode.py > > since i'm guess your current path isn't in the system path > > Vince > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Oct 22 00:12:47 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 21 Oct 2009 17:12:47 -0500 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: On Wed, Oct 21, 2009 at 4:56 PM, Jason Willis wrote: > so i changed the .bashrc and added at the end : > PATH="/home/compy/pythons:$PATH" ###which is the actual path to my python > proggies### No, you have to set the environment variable from within the path, not modifying .bashrc. $PATH refers to your current path. If you're in, say /temp/mystuff , and you set the environment variable from there, then it will set PATH="/home/compy/pythons;/temp/mystuff" but if you edit the file directly it can't retrieve the value of $PATH (an envrionment varaible) so it actually adds the value "$PATH" to your path, which probably doesn't exist unless you mkdir $PATH and put your files in it and run it that way. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Oct 22 00:15:58 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 21 Oct 2009 17:15:58 -0500 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: On Wed, Oct 21, 2009 at 5:12 PM, Luke Paireepinart wrote: > > > On Wed, Oct 21, 2009 at 4:56 PM, Jason Willis wrote: > >> so i changed the .bashrc and added at the end : >> PATH="/home/compy/pythons:$PATH" ###which is the actual path to my python >> proggies### > > No, you have to set the environment variable from within the path, not > modifying .bashrc. $PATH refers to your current path. If you're in, say > /temp/mystuff , and you set the environment variable from there, then it > will set PATH="/home/compy/pythons;/temp/mystuff" but if you edit the file > directly it can't retrieve the value of $PATH (an envrionment varaible) so > it actually adds the value "$PATH" to your path, which probably doesn't > exist unless you mkdir $PATH and put your files in it and run it that way. > So what you really want to do is export PATH=$PATH:/home/compy/pythons from the command line. Unless I don't understand what .bashrc is for which is definitely possible, I'm a Windoze programmer. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jsseabold at gmail.com Thu Oct 22 00:28:16 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Wed, 21 Oct 2009 18:28:16 -0400 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: On Wed, Oct 21, 2009 at 5:56 PM, Jason Willis wrote: > so i changed the .bashrc and added at the end : > PATH="/home/compy/pythons:$PATH"? ###which is the actual path to my python > proggies### > > and i still get > compy at compy-laptop:~/pythons$ herosinventory.py > herosinventory.py: command not found > compy at compy-laptop:~/pythons$ herosinventory.py > herosinventory.py: command not found > compy at compy-laptop:~/pythons$ herosinventory > herosinventory: command not found > compy at compy-laptop:~/pythons$ > > > I must be retarded. I'm sorry , what am I doing wrong here? > You might need to restart X (or just the terminal, can't remember) or type "source ~/.bashrc" (no quotes) at the command line, if you added the correct line to your bash profile. From vinces1979 at gmail.com Thu Oct 22 00:51:13 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 21 Oct 2009 16:51:13 -0600 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: <1e53c510910211551k745a625bl776cd8afefd549c7@mail.gmail.com> On Wed, Oct 21, 2009 at 3:56 PM, Jason Willis wrote: > so i changed the .bashrc and added at the end : > PATH="/home/compy/pythons:$PATH" ###which is the actual path to my python > proggies### > > and i still get > compy at compy-laptop:~/pythons$ herosinventory.py > herosinventory.py: command not found > compy at compy-laptop:~/pythons$ herosinventory.py > herosinventory.py: command not found > compy at compy-laptop:~/pythons$ herosinventory > herosinventory: command not found > compy at compy-laptop:~/pythons$ > > > I must be retarded. I'm sorry , what am I doing wrong here? > > > On Wed, Oct 21, 2009 at 2:31 PM, vince spicer wrote: > >> >> >> On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis wrote: >> >>> hi everyone, >>> >>> sorry for the rather boring question but i'm having serious issues >>> getting my programs to run from the command line without having to type >>> "python" in-front of them. I've tried a lot of different variations on the >>> #!/usr/bin/ etc. line and have come up with the following every time: >>> >>> *[root at localhost moonshinerat]# mycode.py >>> bash: mycode.py: command not found >>> [root at localhost moonshinerat]# mycode >>> bash: mycode: command not found >>> [root at localhost moonshinerat]# >>> >>> I've chmod'ed the program and everything but i still get command not >>> found from the shell. The only thing that does work is ./mycode.py but from >>> what i understand that's been built into linux itself to work that way... >>> >>> please someone let me know what i'm doing wrong here and possibly help?? >>> >>> thanks! >>> >>> * >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> try: >> >> ./mycode.py >> >> since i'm guess your current path isn't in the system path >> >> Vince >> >> > you need export: export PATH="/home/compy/pythons:$PATH Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Oct 22 09:34:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Oct 2009 08:34:00 +0100 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python"or "#!/usr/bin/python" to work References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: "Luke Paireepinart" wrote > So what you really want to do is > export PATH=$PATH:/home/compy/pythons > > from the command line. > Unless I don't understand what .bashrc is for which is definitely > possible, > I'm a Windoze programmer. bashrc is the equivalent of the old DOS autoexec.bat. It gets run every time bash starts. So putting the PATH setting in there is perfectly sensible. Alan G. From alan.gauld at btinternet.com Thu Oct 22 09:42:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Oct 2009 08:42:41 +0100 Subject: [Tutor] Detect duplicate object names References: <3da557ee0910211109q50d8ba81iba7efa09e98256c4@mail.gmail.com> Message-ID: "Lizhi Yang" wrote > When I define functions in a Module, how to avoid override the name of > existing functions? Do you mean other functions within the same module or do you mean functions in other modules? For the first case, keep the number of functions to a reasonable number so you can remember what's in there, and use classes top group related functions together. If you have too many functions in a single module it gets difficult for the module user to remember them too so its a good idea to split big modules up when they get too busy. For the second case you don;t need to woory because thats why we use modules - to separate out the namespaces. So if you have two functions f() inn two modules A and B you just import A and B and access A.f() and B.f() > For example: > > define func1(): > define func2(): > define func1(): > > Is there anyway to pop up the warnings? Kent mentioned support tools already. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ericlhoward at gmail.com Thu Oct 22 19:31:11 2009 From: ericlhoward at gmail.com (Eric L. Howard) Date: Thu, 22 Oct 2009 13:31:11 -0400 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: If you're using bash for your shell - it looks like you need to re-source your .bashrc. You can do this from the command line source ~/.bashrc or log out and log back in. ~elh On Wed, Oct 21, 2009 at 5:56 PM, Jason Willis wrote: > so i changed the .bashrc and added at the end : > PATH="/home/compy/pythons:$PATH"? ###which is the actual path to my python > proggies### > > and i still get > compy at compy-laptop:~/pythons$ herosinventory.py > herosinventory.py: command not found > compy at compy-laptop:~/pythons$ herosinventory.py > herosinventory.py: command not found > compy at compy-laptop:~/pythons$ herosinventory > herosinventory: command not found > compy at compy-laptop:~/pythons$ > > > I must be retarded. I'm sorry , what am I doing wrong here? > > > On Wed, Oct 21, 2009 at 2:31 PM, vince spicer wrote: >> >> >> On Wed, Oct 21, 2009 at 12:21 PM, Jason Willis >> wrote: >>> >>> hi everyone, >>> >>> sorry for the rather boring question but i'm having serious issues >>> getting my programs to run from the command line without having to type >>> "python" in-front of them. I've tried a lot of different variations on the >>> #!/usr/bin/ etc. line and have come up with the following every time: >>> >>> [root at localhost moonshinerat]# mycode.py >>> bash: mycode.py: command not found >>> [root at localhost moonshinerat]# mycode >>> bash: mycode: command not found >>> [root at localhost moonshinerat]# >>> >>> I've chmod'ed the program and everything but i still get command not >>> found from the shell. The only thing that does work is ./mycode.py but from >>> what i understand that's been built into linux itself to work that way... >>> >>> please someone let me know what i'm doing wrong here and possibly help?? >>> >>> thanks! >>> >>> >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> try: >> >> ./mycode.py >> >> since i'm guess your current path isn't in the system path >> >> Vince >> > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Iron sharpens iron, so one man sharpens another. -Proverbs 27:17 NASB From nitinchandra1 at gmail.com Thu Oct 22 19:36:59 2009 From: nitinchandra1 at gmail.com (nitin chandra) Date: Thu, 22 Oct 2009 23:06:59 +0530 Subject: [Tutor] PyWX Message-ID: <965122bf0910221036p4f12a7cew3e213093fb6084aa@mail.gmail.com> Hi I was wondering if there is any one on the list who has experience in installing PyWX with AOLserver on Linux. I am facing some issues. any support will be welcome ... either on list or off list. Thanks Nitin nitinchandra1 at gmail.com From malaclypse2 at gmail.com Thu Oct 22 22:06:57 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 22 Oct 2009 16:06:57 -0400 Subject: [Tutor] Curses - What does it do and why is it called this? In-Reply-To: <658BAD57AED04708975EE68925F05848@COMPUTER01> References: <658BAD57AED04708975EE68925F05848@COMPUTER01> Message-ID: <16651e80910221306o553690b3n7d99137d3277fa55@mail.gmail.com> On Tue, Oct 13, 2009 at 3:11 AM, Katt wrote: > Now I understand. ?Makes sense. ?If "Curses" is for UNIX what would I use on > a Windows XP system using Python 2.6.2? I like the Console package: http://effbot.org/zone/console-index.htm -- Jerry From littlemog at gmail.com Fri Oct 23 05:59:29 2009 From: littlemog at gmail.com (Kenny Shen) Date: Fri, 23 Oct 2009 11:59:29 +0800 Subject: [Tutor] Help with my program In-Reply-To: References: Message-ID: Hi tanner, I suppose the following is possible: class A: def __init__(self): self.height = 1 self.weight = 7 self.name = "tanner" self.grade = "A" def getinfo(self): info = [] info.append(self.name) info.append(self.weight) info.append(self.height) info.append(self.grade) return info class B: def __init__(self, a): self.info = a.getinfo() print self.info a = A() b = B(a) Thanks, Kenny On Fri, Oct 23, 2009 at 9:59 AM, tanner barnes wrote: > Ok so im in need of some help! I have a program with 2 classes and in one > 4 variables are created (their name, height, weight, and grade). What im > trying to make happen is to get the variables from the first class and use > them in the second class. > > ------------------------------ > Windows 7: It helps you do more. Explore Windows 7. > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- - "A mental model is good. I change mine all the time." -------------- next part -------------- An HTML attachment was scrubbed... URL: From stuart at sjsears.com Fri Oct 23 10:32:22 2009 From: stuart at sjsears.com (Stuart Sears) Date: Fri, 23 Oct 2009 09:32:22 +0100 Subject: [Tutor] i can't for the life of me get "#! /usr/bin/env python" or "#!/usr/bin/python" to work In-Reply-To: References: <1e53c510910211131k2578cf21hdf56435ab5acf7a1@mail.gmail.com> Message-ID: <4AE16A16.8080700@sjsears.com> On 21/10/09 23:12, Luke Paireepinart wrote: > On Wed, Oct 21, 2009 at 4:56 PM, Jason Willis > wrote: > >> so i changed the .bashrc and added at the end : >> PATH="/home/compy/pythons:$PATH" ###which is the actual path to my >> python proggies### That should work, but you'll have to tell the shell to re-read the file. try this: source ~/.bashrc technically you should put this stuff in ~/.bash_profile, log out and log in again. Otherwise you rick repeatedly redefining PATH and adding the same directory to it over and over again. Which is relatively harmless but can be annoying. you should also export the PATH variable so that it is passed to subshells (many shell commands run in a subshell) the 'correct' command in your bash startup files would be export PATH=$PATH:/home/compy/pythons the new dir should really go on the end of the path in case you inadvertently create a script with the same name as a system command. > No, you have to set the environment variable from within the path, > not modifying .bashrc. $PATH refers to your current path. no, it doesn't. I think you misunderstand. $PATH is the search path used by the shell when looking for executable commands. it is not your current working directory. That's $PWD > If you're in, say /temp/mystuff , and you set the environment > variable from there, then it will set > PATH="/home/compy/pythons;/temp/mystuff" but if you edit the file > directly it can't retrieve the value of $PATH (an envrionment > varaible) so it actually adds the value "$PATH" to your path, which > probably doesn't exist unless you mkdir $PATH and put your files in > it and run it that way. no. it will resolve $PATH first and then run the command. you can see what PATH currently contains by typing echo $PATH so, if for example echo $PATH prints /bin:/usr/bin:/usr/local/bin then export PATH=$PATH:/home/compy/pythons is interpreted as export PATH=/bin:/usr/bin:/usr/local/bin:/home/compy/pythons Regards, Stuart -- Stuart Sears RHCA etc. "It's today!" said Piglet. "My favourite day," said Pooh. From tanner989 at hotmail.com Fri Oct 23 03:59:43 2009 From: tanner989 at hotmail.com (tanner barnes) Date: Thu, 22 Oct 2009 20:59:43 -0500 Subject: [Tutor] Help with my program Message-ID: Ok so im in need of some help! I have a program with 2 classes and in one 4 variables are created (their name, height, weight, and grade). What im trying to make happen is to get the variables from the first class and use them in the second class. _________________________________________________________________ Windows 7: It helps you do more. Explore Windows 7. http://www.microsoft.com/Windows/windows-7/default.aspx?ocid=PID24727::T:WLMTAGL:ON:WL:en-US:WWL_WIN_evergreen3:102009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Oct 23 15:08:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Oct 2009 09:08:20 -0400 Subject: [Tutor] Help with my program In-Reply-To: References: Message-ID: <1c2a2c590910230608j533c7259q4d42f6371985bf58@mail.gmail.com> On Thu, Oct 22, 2009 at 11:59 PM, Kenny Shen wrote: > Hi tanner, > > I suppose the following is possible: > > class A: > ? def __init__(self): > ????? self.height = 1 > ????? self.weight = 7 > ????? self.name = "tanner" > ????? self.grade = "A" > ? def getinfo(self): > ????? info = [] > ????? info.append(self.name) > ????? info.append(self.weight) > ????? info.append(self.height) > ????? info.append(self.grade) > ????? return info > > class B: > ? def __init__(self, a): > ????? self.info = a.getinfo() > ????? print self.info You don't need A.getinfo(). Just have B.__init__() keep a reference to its 'a' in an attribute: class B: def __init__(self, a): self.a = a Then in any methods of B you can refer to self.a.height, etc. Kent From jfabiani at yolo.com Fri Oct 23 17:05:29 2009 From: jfabiani at yolo.com (John) Date: Fri, 23 Oct 2009 08:05:29 -0700 Subject: [Tutor] replacing a long list of if,elif Message-ID: <200910230805.29791.jfabiani@yolo.com> I'm using python 2.5 I have a long list of if, elif, else. I always thought it was very NOT pythonic. It's easy to read but not pretty. for fldType in fieldList: if "int" in fldType: fld = "I" elif "char" in fldType : fld = "C" elif "bool" in fldType : fld = "B" ..... else: fld = '?' I have considered: mydict = {'int': 'I', 'char':'C', 'bool':'B'....} for fldType in fieldList: try: fld = mydict[fldType] except: fld = '?' I also considered some sort of lambda function as x = lambda fld: mydict[fldType] But could not determine how to account for the key exception. So I tried x = lambda fldType: mydict[fldType] if fldType in mydict: x(fldType) else: fld = '?' Any suggestions would be helpful and would help me learn. Johnf From vinces1979 at gmail.com Fri Oct 23 17:18:09 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 23 Oct 2009 09:18:09 -0600 Subject: [Tutor] replacing a long list of if,elif In-Reply-To: <200910230805.29791.jfabiani@yolo.com> References: <200910230805.29791.jfabiani@yolo.com> Message-ID: <1e53c510910230818o2f101388k6f2c0b298f610c32@mail.gmail.com> On Fri, Oct 23, 2009 at 9:05 AM, John wrote: > I'm using python 2.5 > > I have a long list of if, elif, else. I always thought it was very NOT > pythonic. It's easy to read but not pretty. > > for fldType in fieldList: > if "int" in fldType: > fld = "I" > elif "char" in fldType : > fld = "C" > elif "bool" in fldType : > fld = "B" ..... > else: > fld = '?' > > > I have considered: > > mydict = {'int': 'I', 'char':'C', 'bool':'B'....} > for fldType in fieldList: > try: > fld = mydict[fldType] > except: > fld = '?' > > I also considered some sort of lambda function as > > x = lambda fld: mydict[fldType] > > But could not determine how to account for the key exception. So I tried > > x = lambda fldType: mydict[fldType] > if fldType in mydict: > x(fldType) > else: > fld = '?' > > > Any suggestions would be helpful and would help me learn. > > Johnf > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > John, Using a Dictionary is the best method to use here and you can use dict.get in order to bypass the KeyError EX: myDict.get(fldType, None) this will output the value from myDict if the key exists, if not it will return None Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Fri Oct 23 17:58:43 2009 From: jfabiani at yolo.com (John) Date: Fri, 23 Oct 2009 08:58:43 -0700 Subject: [Tutor] replacing a long list of if,elif In-Reply-To: <200910230805.29791.jfabiani@yolo.com> References: <200910230805.29791.jfabiani@yolo.com> Message-ID: <200910230858.43392.jfabiani@yolo.com> On Friday 23 October 2009 08:05:29 am John wrote: > I'm using python 2.5 > > I have a long list of if, elif, else. I always thought it was very NOT > pythonic. It's easy to read but not pretty. > > for fldType in fieldList: > if "int" in fldType: > fld = "I" > elif "char" in fldType : > fld = "C" > elif "bool" in fldType : > fld = "B" ..... > else: > fld = '?' > > > I have considered: > > mydict = {'int': 'I', 'char':'C', 'bool':'B'....} > for fldType in fieldList: > try: > fld = mydict[fldType] > except: > fld = '?' > > I also considered some sort of lambda function as > > x = lambda fld: mydict[fldType] > > But could not determine how to account for the key exception. So I tried > > x = lambda fldType: mydict[fldType] > if fldType in mydict: > x(fldType) > else: > fld = '?' > > > Any suggestions would be helpful and would help me learn. > > Johnf >John, >Using a Dictionary is the best method to use here and you can use dict.get >in order to bypass the KeyError >EX: >myDict.get(fldType, None) >this will output the value from myDict if the key exists, if not it will > >return None Thanks this looks perfect - did not know dict.get() Johnf Vince From emile at fenx.com Fri Oct 23 18:25:41 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 23 Oct 2009 09:25:41 -0700 Subject: [Tutor] replacing a long list of if,elif In-Reply-To: <200910230858.43392.jfabiani@yolo.com> References: <200910230805.29791.jfabiani@yolo.com> <200910230858.43392.jfabiani@yolo.com> Message-ID: >> myDict.get(fldType, None) > >> this will output the value from myDict if the key exists, if not it will >> >> return None > > Thanks this looks perfect - did not know dict.get() You may also want to consider {}.setdefault -- that would collect the fldType entries not defined. >>> a = {'a':1,'b':2} >>> a.setdefault('a','?') 1 >>> a.setdefault('c','?') '?' >>> a {'a': 1, 'c': '?', 'b': 2} Emile From kent37 at tds.net Fri Oct 23 19:51:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Oct 2009 13:51:22 -0400 Subject: [Tutor] replacing a long list of if,elif In-Reply-To: <200910230805.29791.jfabiani@yolo.com> References: <200910230805.29791.jfabiani@yolo.com> Message-ID: <1c2a2c590910231051l1318e5dare118f191577e1b85@mail.gmail.com> On Fri, Oct 23, 2009 at 11:05 AM, John wrote: > ?mydict = {'int': 'I', 'char':'C', 'bool':'B'....} > ?for fldType in fieldList: > ? ?try: > ? ? ? ?fld = mydict[fldType] > ? ?except: > ? ? ? ?fld = '?' Use fld = mydict.get(fldType, '?') > I also considered some sort of ?lambda function as > > x = lambda fld: mydict[fldType] You don't have to use a lambda, you can use the dict methods, e.g. x = mydict.__getitem__ or x = mydict.get > But could not determine how to account for the key exception. So I tried > > x = lambda fldType: mydict[fldType] > if fldType in mydict: > ? x(fldType) This is really no different than just using mydict[fldType] directly. > else: > ? ?fld = '?' Kent From xchimeras at gmail.com Sat Oct 24 16:14:22 2009 From: xchimeras at gmail.com (Tom Green) Date: Sat, 24 Oct 2009 10:14:22 -0400 Subject: [Tutor] Pack as HEX question Message-ID: Hello everyone, First, I wanted to thank everyone in advance for your help and any feedback is appreciated. Here is what I am trying to accomplish: I have this encrypted data that was sent across the network. The decryption is a simple XOR with a 16 byte key. I started writing a basic Python script that would decrypt the traffic by XORing each byte with the XOR key. I was wondering if there was someway in Python to indicate that the string is a string of HEX values similar to Perl's pack. For example: Encrypted string in hex "313B372C2E2C63362E2128" Four byte key XOR key "41424344" Is there any way to tell Python that the encrypted string and XOR key is HEX? This way I can XOR each byte without having to either place a \x between every two characters. I realize I need to convert everything to an integer first. I have done this numerous times, but I wanted to throw it out there as I know there must be a easier way. I am using Python 2.5.2 Thank you, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Oct 24 16:24:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Oct 2009 15:24:46 +0100 Subject: [Tutor] Pack as HEX question References: Message-ID: "Tom Green" wrote > wondering if there was someway in Python to indicate that the string is a > string of HEX values similar to Perl's pack. You need to be very careful in your terminology here. Is it "a string of hex values" ie a string representation of a hex value or is it a string of bytes which can be represented in hex as you showed? The two and their processing are entirely different! > Encrypted string in hex > "313B372C2E2C63362E2128" > > Four byte key > XOR key "41424344" Assuming the data really is binary data represented by the hex value you display above then you can use the struct module to unpack the values into integers directly. If it is a string of characters representing hex values then you can use the int() function to convert them by providing a base argument of 16.. > I have done this numerous times, but I wanted to throw it out there as I > know there must be a easier way. I am using Python 2.5.2 There is almost certainly an easier way but which way we that is cannot tell for sure from the information given. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From xchimeras at gmail.com Sat Oct 24 17:05:25 2009 From: xchimeras at gmail.com (Tom Green) Date: Sat, 24 Oct 2009 11:05:25 -0400 Subject: [Tutor] Pack as HEX question In-Reply-To: References: Message-ID: Alan, Thanks for your response and hopefully I can clear things up. I apologize for not being more clear. I obtain the HEX encoded data from Winhex i.e. copy Hex values. The HEX encode data is very large and I simply paste it into my Python script along with the XOR key. The data is a string of bytes represented in HEX, as I showed. Here is the problem I ran into. Take the 4 byte XOR key. If I convert them to int with Base 16 it takes the 4 and converts it to 0x34 when I in turn I actually need 0x41. Thanks for your feedback. Mike On Sat, Oct 24, 2009 at 10:24 AM, Alan Gauld wrote: > > "Tom Green" wrote > > > wondering if there was someway in Python to indicate that the string is a >> string of HEX values similar to Perl's pack. >> > > You need to be very careful in your terminology here. > > Is it "a string of hex values" ie a string representation of a hex > value or is it a string of bytes which can be represented in hex > as you showed? The two and their processing are entirely different! > > > Encrypted string in hex >> "313B372C2E2C63362E2128" >> >> Four byte key >> XOR key "41424344" >> > > > Assuming the data really is binary data represented by the hex > value you display above then you can use the struct module to > unpack the values into integers directly. > > If it is a string of characters representing hex values then you can use > the int() function to convert them by providing a base argument of 16.. > > > I have done this numerous times, but I wanted to throw it out there as I >> know there must be a easier way. I am using Python 2.5.2 >> > > There is almost certainly an easier way but which way we > that is cannot tell for sure from the information given. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkid at insightbb.com Sat Oct 24 19:57:24 2009 From: beachkid at insightbb.com (Ken G.) Date: Sat, 24 Oct 2009 13:57:24 -0400 Subject: [Tutor] Using IDLE v2.6 Message-ID: <4AE34004.4080008@insightbb.com> I just reinstalled Python v2.6.2 due to a computer crash. I reinstalled IDLE v2.6 but I was wondering if there is something better than IDLE. I am using Ubuntu 9.04 so they do have some limited choices available. Thanks for your input. Ken From alan.gauld at btinternet.com Sat Oct 24 20:41:28 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 24 Oct 2009 18:41:28 +0000 (GMT) Subject: [Tutor] Pack as HEX question In-Reply-To: References: Message-ID: <411414.37807.qm@web86710.mail.ird.yahoo.com> > Take the 4 byte XOR key. If I convert them to int with Base 16 > it takes the 4 and converts it to 0x34 when I in turn I actually need 0x41. OK, thats because int is for converting strings. You need to use struct.unpack to convert the 4 bytes into an int. You also need to figure out how many ints you have in your data and construct a format string with that many ints to struct unpack the data. Them apply the xor to each int using the key something like key = struct.unpack("d", keydata) num_ints = len(raw_data)/len(int) data = struct.unpack("%dd" % num_ints, raw_data) result = [n^key for n in data] (untested pseudo code!) HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Oct 24 20:51:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Oct 2009 19:51:24 +0100 Subject: [Tutor] Using IDLE v2.6 References: <4AE34004.4080008@insightbb.com> Message-ID: "Ken G." wrote > IDLE v2.6 but I was wondering if there is something better than IDLE. There is a wealth of options and a Google search on Python IDEs will throw many up. Some common recommendations: PyDev on Eclipse (good if you already use Eclipse for say Java or C++) Eric SPE Scipe/Notepad++ (but these may be windows only?) Komodo (from activestate) Of these I was most impressed with PyDev and SPE (which includes a GUI builder) And there are several others. Personally on Linux I, and several others, prefer to use the OS as our IDE and stick with a 3 window approach: 1) running vim/emacs as editor 2) a python interpreter running in an xterm for experimenting/testing 3) a blank xterm for running the saved script There is also a python mode for emacs if you are a heavy user of emacs. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From xchimeras at gmail.com Sat Oct 24 21:36:43 2009 From: xchimeras at gmail.com (Tom Green) Date: Sat, 24 Oct 2009 15:36:43 -0400 Subject: [Tutor] Pack as HEX question In-Reply-To: <411414.37807.qm@web86710.mail.ird.yahoo.com> References: <411414.37807.qm@web86710.mail.ird.yahoo.com> Message-ID: This is what I have so far, import struct EncryptString="313B372C2E2C63362E2128" XorKey="41424344" key = struct.unpack("d", XorKey) num_ints = len(EncryptString)/11 data = struct.unpack("%dd"% num_ints,EncryptString) The above code generates an error the my string must be a string length of 16 When you say I need to determine the number of ints in my data i.e. EncryptString that value would be 11 right? I appreciate your help. Mike. On Sat, Oct 24, 2009 at 2:41 PM, ALAN GAULD wrote: > > Take the 4 byte XOR key. If I convert them to int with Base 16 > > it takes the 4 and converts it to 0x34 when I in turn I actually need > 0x41. > > OK, thats because int is for converting strings. You need to use > struct.unpack > to convert the 4 bytes into an int. > > You also need to figure out how many ints you have in your data and > construct a format string with that many ints to struct unpack the data. > > Them apply the xor to each int using the key > > something like > > key = struct.unpack("d", keydata) > num_ints = len(raw_data)/len(int) > data = struct.unpack("%dd" % num_ints, raw_data) > > result = [n^key for n in data] > > (untested pseudo code!) > > HTH, > > Alan G. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sat Oct 24 21:49:13 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 24 Oct 2009 12:49:13 -0700 (PDT) Subject: [Tutor] ifdef in python In-Reply-To: <333efb450910211437o6cf2f34j3e49f6a4a0a152f8@mail.gmail.com> Message-ID: <489964.51308.qm@web110713.mail.gq1.yahoo.com> Isn't it better to use if __debug__: I thought such an if statement always evaluated to False when the python program was run in OPTIMIZED (-o) mode? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before you criticize someone, walk a mile in their shoes, that way when you do criticize them, you're a mile away and you have their shoes! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Wed, 10/21/09, Wayne wrote: > From: Wayne > Subject: Re: [Tutor] ifdef in python > To: "Lie Ryan" > Cc: tutor at python.org > Date: Wednesday, October 21, 2009, 11:37 PM > > > On Wed, Oct 21, 2009 at 3:29 PM, > Lie Ryan > wrote: > > > Lizhi Yang wrote: > > > Is there anything similar to ifdef statement in C or C++ in > python? > > > > > Not really, but python's regular if can be used for a > similar purpose: > > > > DEBUG = True > > > > if DEBUG: > > ? ?import logging > > ? ?def foo(): > > ? ? ? ?# debug version > > else: > > ? ?def foo(): > > ? ? ? ?# normal version > > > > def main(): > > ? ?foo() > > > > if __name__ == '__main__': > > ? ?main() > > > > or something like that. > Really a try/except block would actually > work > def spam1():?? ?pass > try:?? spam2except > NameError: > > ?? def spam2():?? ? ? > pass > Because if DEBUG isn't declared you'll > throw a NameError > > -----Inline Attachment Follows----- > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From davea at ieee.org Sat Oct 24 22:43:28 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 24 Oct 2009 16:43:28 -0400 Subject: [Tutor] Pack as HEX question In-Reply-To: References: Message-ID: <4AE366F0.7070902@ieee.org> Tom Green wrote: > Alan, > > Thanks for your response and hopefully I can clear things up. I apologize > for not being more clear. > > I obtain the HEX encoded data from Winhex i.e. copy Hex values. The HEX > encode data is very large and I simply paste it into my Python script along > with the XOR key. The data is a string of bytes represented in HEX, as I > showed. > > Here is the problem I ran into. > > Take the 4 byte XOR key. If I convert them to int with Base 16 it takes the > 4 and converts it to 0x34 when I in turn I actually need 0x41. > > Thanks for your feedback. > > Mike > > On Sat, Oct 24, 2009 at 10:24 AM, Alan Gauld wrote: > > >> >> Encrypted string in hex >> >>> "313B372C2E2C63362E2128" >>> >>> Four byte key >>> XOR key "41424344" >>> >>> >> If by Winhex, you mean the hex editor, then you're undoubtedly going about it the long way. There's no need to convert the file to printable hex, you should be able to work on it directly. Just open the file, read it into a string (in python2.x), then loop through it, one byte at a time. Store your key in a binary string as well. Now just loop through the two in pairs (use zip, and cycle) doing a chr of xor of ords. And when you respond, give us your python version, and show us the code you've got (almost) working. DaveA From xchimeras at gmail.com Sat Oct 24 22:52:45 2009 From: xchimeras at gmail.com (Tom Green) Date: Sat, 24 Oct 2009 16:52:45 -0400 Subject: [Tutor] Pack as HEX question In-Reply-To: <4AE366F0.7070902@ieee.org> References: <4AE366F0.7070902@ieee.org> Message-ID: Thanks for your reply Dave. I am capturing the data off the network (wireshark) and saving it in WinHex for testing. I am actually building a socket to decrypt the data, so prior to implementing my logic in the socket, I figured I would write the algorithm in a quick script. Here is what I have so far and it works. import struct,binascii decrypt=[] data_count=0 key_pos=0 #packed data consists of HEX values packed_data = binascii.unhexlify('313B372C2E2C63362E2128') #XorKey data consists of HEX values packed_XorKey=binascii.unhexlify('41424344') while data_count < len(packed_data): if key_pos >len(packed_XorKey)-1: key_pos=0 decrypt.append(chr(ord(packed_data[data_count])^ord(packed_XorKey[key_pos]))) key_pos+=1 data_count+=1 print "".join(decrypt) This decrypts to Python rock This logic seems to work, but I am certain there is a better way. Mike On Sat, Oct 24, 2009 at 4:43 PM, Dave Angel wrote: > Tom Green wrote: > >> Alan, >> >> Thanks for your response and hopefully I can clear things up. I apologize >> for not being more clear. >> >> I obtain the HEX encoded data from Winhex i.e. copy Hex values. The HEX >> encode data is very large and I simply paste it into my Python script >> along >> with the XOR key. The data is a string of bytes represented in HEX, as I >> showed. >> >> Here is the problem I ran into. >> >> Take the 4 byte XOR key. If I convert them to int with Base 16 it takes >> the >> 4 and converts it to 0x34 when I in turn I actually need 0x41. >> >> Thanks for your feedback. >> >> Mike >> >> On Sat, Oct 24, 2009 at 10:24 AM, Alan Gauld > >wrote: >> >> >> >>> >>> Encrypted string in hex >>> >>> >>>> "313B372C2E2C63362E2128" >>>> >>>> Four byte key >>>> XOR key "41424344" >>>> >>>> >>>> >>> >>> >> If by Winhex, you mean the hex editor, then you're undoubtedly going about > it the long way. There's no need to convert the file to printable hex, you > should be able to work on it directly. Just open the file, read it into a > string (in python2.x), then loop through it, one byte at a time. Store your > key in a binary string as well. Now just loop through the two in pairs (use > zip, and cycle) doing a chr of xor of ords. > > > And when you respond, give us your python version, and show us the code > you've got (almost) working. > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kurt at tool.net Sun Oct 25 01:18:05 2009 From: kurt at tool.net (Kurt Bendl) Date: Sat, 24 Oct 2009 19:18:05 -0400 Subject: [Tutor] Using IDLE v2.6 In-Reply-To: References: <4AE34004.4080008@insightbb.com> Message-ID: <4AE38B2D.6010200@tool.net> > "Ken G." wrote >> IDLE v2.6 but I was wondering if there is something better than IDLE. I've been happy with WingIDE on Linux, fwiw. I'm still a TextMate fanboy (if you use a Mac). -kb From davea at ieee.org Sun Oct 25 01:40:01 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 24 Oct 2009 19:40:01 -0400 Subject: [Tutor] Pack as HEX question In-Reply-To: References: <4AE366F0.7070902@ieee.org> Message-ID: <4AE39051.1090302@ieee.org> Tom Green wrote: > Thanks for your reply Dave. I am capturing the data off the network > (wireshark) and saving it in WinHex for testing. I am actually building a > socket to decrypt the data, so prior to implementing my logic in the socket, > I figured I would write the algorithm in a quick script. Here is what I > have so far and it works. > > import struct,binascii > decrypt=[] > data_count=0 > key_pos=0 > #packed data consists of HEX values > packed_data = binascii.unhexlify('313B372C2E2C63362E2128') > #XorKey data consists of HEX values > packed_XorKey=binascii.unhexlify('41424344') > while data_count < len(packed_data): > if key_pos >len(packed_XorKey)-1: > key_pos=0 > > decrypt.append(chr(ord(packed_data[data_count])^ord(packed_XorKey[key_pos]))) > key_pos+=1 > data_count+=1 > print "".join(decrypt) > > This decrypts to Python rock > > This logic seems to work, but I am certain there is a better way. > > Mike > > > On Sat, Oct 24, 2009 at 4:43 PM, Dave Angel wrote: > > >> Tom Green wrote: >> >> >>> Alan, >>> >>> Thanks for your response and hopefully I can clear things up. I apologize >>> for not being more clear. >>> >>> I obtain the HEX encoded data from Winhex i.e. copy Hex values. The HEX >>> encode data is very large and I simply paste it into my Python script >>> along >>> with the XOR key. The data is a string of bytes represented in HEX, as I >>> showed. >>> >>> Here is the problem I ran into. >>> >>> Take the 4 byte XOR key. If I convert them to int with Base 16 it takes >>> the >>> 4 and converts it to 0x34 when I in turn I actually need 0x41. >>> >>> Thanks for your feedback. >>> >>> Mike >>> >>> On Sat, Oct 24, 2009 at 10:24 AM, Alan Gauld >> >>>> wrote: >>>> >>> >>> >>> >>>> Encrypted string in hex >>>> >>>> >>>> >>>>> "313B372C2E2C63362E2128" >>>>> >>>>> Four byte key >>>>> XOR key "41424344" >>>>> >>>>> >>>>> >>>>> >>>> >>>> >>>> >>> If by Winhex, you mean the hex editor, then you're undoubtedly going about >>> >> it the long way. There's no need to convert the file to printable hex, you >> should be able to work on it directly. Just open the file, read it into a >> string (in python2.x), then loop through it, one byte at a time. Store your >> key in a binary string as well. Now just loop through the two in pairs (use >> zip, and cycle) doing a chr of xor of ords. >> >> >> And when you respond, give us your python version, and show us the code >> you've got (almost) working. >> >> DaveA >> >> > > (You top-posted, so your message is out of order) Replace your while -- loop with the following simpler version. for byte0, byte1 in itertools.izip(packed_data, itertools.cycle(packed_XorKey)): decrypt.append(chr(ord(byte0) ^ ord(byte1))) (You'll need an import itertools, at beginning, of course.) itertools.cycle() repeats the pattern of the keys. itertools.izip() combines two iterables into one. Then you just loop through that one in the usual way, where byte0 comes from the packed_data, and byte1 comes from the XorKey. DaveA From xchimeras at gmail.com Sun Oct 25 01:41:59 2009 From: xchimeras at gmail.com (Tom Green) Date: Sat, 24 Oct 2009 19:41:59 -0400 Subject: [Tutor] Pack as HEX question In-Reply-To: <4AE39051.1090302@ieee.org> References: <4AE366F0.7070902@ieee.org> <4AE39051.1090302@ieee.org> Message-ID: Sweet nice tip I love this list. Thank you. Mike On Sat, Oct 24, 2009 at 7:40 PM, Dave Angel wrote: > Tom Green wrote: > >> Thanks for your reply Dave. I am capturing the data off the network >> (wireshark) and saving it in WinHex for testing. I am actually building a >> socket to decrypt the data, so prior to implementing my logic in the >> socket, >> I figured I would write the algorithm in a quick script. Here is what I >> have so far and it works. >> >> import struct,binascii >> decrypt=[] >> data_count=0 >> key_pos=0 >> #packed data consists of HEX values >> packed_data = binascii.unhexlify('313B372C2E2C63362E2128') >> #XorKey data consists of HEX values >> packed_XorKey=binascii.unhexlify('41424344') >> while data_count < len(packed_data): >> if key_pos >len(packed_XorKey)-1: >> key_pos=0 >> >> >> decrypt.append(chr(ord(packed_data[data_count])^ord(packed_XorKey[key_pos]))) >> key_pos+=1 >> data_count+=1 >> print "".join(decrypt) >> >> This decrypts to Python rock >> >> This logic seems to work, but I am certain there is a better way. >> >> Mike >> >> >> On Sat, Oct 24, 2009 at 4:43 PM, Dave Angel wrote: >> >> >> >>> Tom Green wrote: >>> >>> >>> >>>> Alan, >>>> >>>> Thanks for your response and hopefully I can clear things up. I >>>> apologize >>>> for not being more clear. >>>> >>>> I obtain the HEX encoded data from Winhex i.e. copy Hex values. The HEX >>>> encode data is very large and I simply paste it into my Python script >>>> along >>>> with the XOR key. The data is a string of bytes represented in HEX, as >>>> I >>>> showed. >>>> >>>> Here is the problem I ran into. >>>> >>>> Take the 4 byte XOR key. If I convert them to int with Base 16 it takes >>>> the >>>> 4 and converts it to 0x34 when I in turn I actually need 0x41. >>>> >>>> Thanks for your feedback. >>>> >>>> Mike >>>> >>>> On Sat, Oct 24, 2009 at 10:24 AM, Alan Gauld >>> >>>> >>>>> wrote: >>>>> >>>>> >>>> >>>> >>>> >>>> >>>>> Encrypted string in hex >>>>> >>>>> >>>>> >>>>> >>>>>> "313B372C2E2C63362E2128" >>>>>> >>>>>> Four byte key >>>>>> XOR key "41424344" >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>> >>>>> >>>>> >>>>> >>>> If by Winhex, you mean the hex editor, then you're undoubtedly going >>>> about >>>> >>>> >>> it the long way. There's no need to convert the file to printable hex, >>> you >>> should be able to work on it directly. Just open the file, read it into >>> a >>> string (in python2.x), then loop through it, one byte at a time. Store >>> your >>> key in a binary string as well. Now just loop through the two in pairs >>> (use >>> zip, and cycle) doing a chr of xor of ords. >>> >>> >>> And when you respond, give us your python version, and show us the code >>> you've got (almost) working. >>> >>> DaveA >>> >>> >>> >> >> >> > (You top-posted, so your message is out of order) > > Replace your while -- loop with the following simpler version. > > > for byte0, byte1 in itertools.izip(packed_data, > itertools.cycle(packed_XorKey)): > decrypt.append(chr(ord(byte0) ^ ord(byte1))) > > (You'll need an import itertools, at beginning, of course.) > > itertools.cycle() repeats the pattern of the keys. itertools.izip() > combines two iterables into one. Then you just loop through that one in the > usual way, where byte0 comes from the packed_data, and byte1 comes from the > XorKey. > > DaveA > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Sat Oct 24 23:14:55 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sat, 24 Oct 2009 17:14:55 -0400 Subject: [Tutor] Using IDLE v2.6 In-Reply-To: <4AE34004.4080008@insightbb.com> References: <4AE34004.4080008@insightbb.com> Message-ID: <1256418895.6872.49.camel@bermanrl-desktop> Ken, Two recommendations. 1) Komodo Edit 5. Free edition available from Activestate. www.activestate,com 2) Wing IDE 101 Free Edition from www.wingware.com my favorite of the freely available IDE's. Good luck, Robert On Sat, 2009-10-24 at 13:57 -0400, Ken G. wrote: > I just reinstalled Python v2.6.2 due to a computer crash. I reinstalled > IDLE v2.6 but I was wondering if there is something better than IDLE. > > I am using Ubuntu 9.04 so they do have some limited choices available. > > Thanks for your input. > > Ken > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Oct 25 02:20:27 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 25 Oct 2009 01:20:27 +0000 (GMT) Subject: [Tutor] Pack as HEX question In-Reply-To: References: <411414.37807.qm@web86710.mail.ird.yahoo.com> Message-ID: <743720.74487.qm@web86711.mail.ird.yahoo.com> EncryptString="313B372C2E2C63362E2128" > > >This is different to what I expected, it is a string of ascii bytes representing hex values. >Is that the real format of your data? If so we need to split it into pairs and use >int() to convert it. Or is your real data a string of bytes that happen to have >those 11 hex values? > >XorKey="41424344" >key = struct.unpack("d", XorKey) > >You have here 8 bytes(chars) not 4 bytes. This is what I was talking about in my first message you need to be clear about exactly what form your data takes. Is it a string representing hex values or is it a sequence of bytes? For example the 4 hex bytes 41,42,43,44 are represented by the string "ABCD" which is very different to "41424344" which is a string of 8 bytes and we can see those values with: for c in XorKey: print hex(ord(c)) num_ints = len(EncryptString)/11I said divide the data by the length of an int. An int is usually 4 bytes (you can find that by using the calcsize() function in the struct module) so you want to divide EncryptString by 4. But only if the data is not in this format. If it is in this string format you need to split the string into 2 character pairs and feed them to int() data = struct.unpack("%dd"% num_ints,EncryptString) > >> The above code generates an error the my string must be a string length of 16Always post full error messages do not summarize them. Its not clear exactl;y which string the error is complaining about nor why. I suspect you have a value of 2 for num_ints so your unpack is looking for 8 bytes but you are giving it 22. So where the 16 is coming from I'm not sure. > When you say I need to determine the number of ints in my data >> i.e. EncryptString that value would be 11 right?Your string is 22 characters (i.e. bytes) long. It represents 11 bytes in hex which is 3 ints plus 3 bytes left over. You need to really stop and check what kind of data you are dealing with. In this case its strings, but in your real world case it may be real bytes in which case your test code is invalid. Understanding the data is critical in this kind of scenario. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Oct 25 02:57:57 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 24 Oct 2009 21:57:57 -0400 Subject: [Tutor] Pack as HEX question In-Reply-To: <4AE39051.1090302@ieee.org> References: <4AE366F0.7070902@ieee.org> <4AE39051.1090302@ieee.org> Message-ID: <4AE3B0A5.8050900@gmail.com> Dave Angel wrote: > > > for byte0, byte1 in itertools.izip(packed_data, > itertools.cycle(packed_XorKey)): > decrypt.append(chr(ord(byte0) ^ ord(byte1))) > And of course that leads to: decrypt = [chr(ord(byte0) ^ ord(byte1)) for byte0, byte1 in itertools.izip(packed_data, itertools.cycle(packed_XorKey))] -- Bob Gailer Chapel Hill NC 919-636-4239 From ptmkenny at gmail.com Sun Oct 25 05:38:37 2009 From: ptmkenny at gmail.com (Patrick Kenny) Date: Sun, 25 Oct 2009 13:38:37 +0900 Subject: [Tutor] Moving a Shelf Between Linux and Mac OS X Message-ID: <1256445517.26849.1341771209@webmail.messagingengine.com> Greetings, I recently started learning Python and I have written a script that uses a shelf on Mac OS X using Python 2.6. I recently attempted to move the directory over to my Linux system, which also has Python 2.6 installed, and run the script there. The script works fine, but the shelf does not load. Instead, it appears that a new shelf is created. On the Mac, the shelf file is saved as class-shelve.db, but after running the script on Linux, a new file, class-shelve (without a .db suffix) is created. I tried simply deleting class-shelve and renaming class-shelve.db as class-shelve, but when I run the script I get this error: Traceback (most recent call last): File "card.py", line 232, in DisplayInventory(scope) File "card.py", line 65, in DisplayInventory db = shelve.open('class-shelve') File "/usr/lib64/python2.6/shelve.py", line 234, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "/usr/lib64/python2.6/shelve.py", line 218, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback) File "/usr/lib64/python2.6/anydbm.py", line 82, in open mod = __import__(result) ImportError: No module named bsddb185 Are shelves portable between different OSs? I would like to make the data created on the shelf on the Mac also accessible on Linux; is there an easy way to do this? Cheers, Patrick From hyperneato at gmail.com Sun Oct 25 07:49:17 2009 From: hyperneato at gmail.com (Isaac) Date: Sat, 24 Oct 2009 23:49:17 -0700 Subject: [Tutor] request for comments regarding my function Message-ID: <7260654a0910242349x2983ab7cj38940e46d6f0676f@mail.gmail.com> Hello all, I wrote a function to organize a list of sorted objects ( django blog entries ); each object has a Python datetime attribute ( called pub_date ). I am posting a message to the tutor mailing list to get feedback regarding better ways to accomplish the same task. I have a feeling I could use recursion here, instead of looping through the entire _query list 3 times. Here is my code: def create_archive_list(_query): """ given a sorted queryset, return a list in the format: archive_list = [{'2009': [{'December': ['entry1', 'entry2']}, {'January': ['entry3', 'entry4']} ] }, {'2008': [{'January': ['entry5', 'entry6']}, ] } ] """ archive_list = [] tmp_year_list = [] # make a list of Python dictionaries; the keys are the year, as in '2009', and the value # is an empty list. for item in _query: if item.pub_date.year not in tmp_year_list: tmp_year_list.append(item.pub_date.year) tmp_dict = {} tmp_dict[item.pub_date.year] = [] archive_list.append(tmp_dict) else: pass # for every list in the archive_list dictionaries, append a dictionary with the # blog entry's month name as a key, and the value being an empty list for entry in _query: for item in archive_list: _year = entry.pub_date.year if _year in item: _tmp_month = entry.pub_date.strftime("%B") # make a dictionary with the month name as a key and an empty list as a value tmp_dict = {} tmp_dict[_tmp_month] = [] if tmp_dict not in item[_year]: item[_year].append(tmp_dict) # append the blog entry object to the list if the pub_date month and year match # the dictionary keys in the archive_list dictionary/list tree. for entry in _query: # dict in list for item in archive_list: # year of entry _year = entry.pub_date.year if _year in item: _year_list = item[_year] for _dict_month in _year_list: _tmp_month = entry.pub_date.strftime("%B") if _tmp_month in _dict_month: _dict_month[_tmp_month].append(entry) return archive_list From srilyk at gmail.com Sun Oct 25 13:41:28 2009 From: srilyk at gmail.com (Wayne) Date: Sun, 25 Oct 2009 07:41:28 -0500 Subject: [Tutor] Moving a Shelf Between Linux and Mac OS X In-Reply-To: <1256445517.26849.1341771209@webmail.messagingengine.com> References: <1256445517.26849.1341771209@webmail.messagingengine.com> Message-ID: <333efb450910250541g1bb733acp6ef3642daa2ccf02@mail.gmail.com> On Sat, Oct 24, 2009 at 11:38 PM, Patrick Kenny wrote: > Are shelves portable between different OSs? I would like to make the > data created on the shelf on the Mac also accessible on Linux; is there > an easy way to do this? > I confess I know nothing about shelve, but you should be able to use a sqlite database or the configparser module. I don't know how well either would work, or if they're "easy" enough. HTH, -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Sun Oct 25 15:09:04 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 25 Oct 2009 14:09:04 +0000 Subject: [Tutor] request for comments regarding my function In-Reply-To: <7260654a0910242349x2983ab7cj38940e46d6f0676f@mail.gmail.com> References: <7260654a0910242349x2983ab7cj38940e46d6f0676f@mail.gmail.com> Message-ID: 2009/10/25 Isaac : > Hello all, > I wrote a function to organize a list of sorted objects ( django blog > entries ); each object has a Python datetime attribute ( called > pub_date ). I am posting a message to the tutor mailing list to get > feedback regarding better ways to accomplish the same task. I have a > feeling I could use recursion here, instead of looping through the > entire _query list 3 times. Here is my code: > > def create_archive_list(_query): > ? ?""" > ? ?given a sorted queryset, return a list in the format: > > ? ?archive_list = [{'2009': [{'December': ['entry1', 'entry2']}, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{'January': ['entry3', 'entry4']} > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?] > ? ? ? ? ? ? ? ? ? ? }, > > ? ? ? ? ? ? ? ? ? ?{'2008': [{'January': ['entry5', 'entry6']}, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?] > ? ? ? ? ? ? ? ? ? ? } > ? ? ? ? ? ? ? ? ? ?] > ? ?""" > > ? ?archive_list = [] > ? ?tmp_year_list = [] > > ? ?# make a list of Python dictionaries; the keys are the year, as in > '2009', and the value > ? ?# is an empty list. > ? ?for item in _query: > ? ? ? ?if item.pub_date.year not in tmp_year_list: > ? ? ? ? ? ?tmp_year_list.append(item.pub_date.year) > ? ? ? ? ? ?tmp_dict = {} > ? ? ? ? ? ?tmp_dict[item.pub_date.year] = [] > ? ? ? ? ? ?archive_list.append(tmp_dict) > ? ? ? ?else: > ? ? ? ? ? ?pass > > ? ?# for every list in the archive_list dictionaries, append a > dictionary with the > ? ?# blog entry's month name as a key, and the value being an empty list > ? ?for entry in _query: > ? ? ? ?for item in archive_list: > ? ? ? ? ? ?_year = entry.pub_date.year > ? ? ? ? ? ?if _year in item: > ? ? ? ? ? ? ? ?_tmp_month = entry.pub_date.strftime("%B") > ? ? ? ? ? ? ? ?# make a dictionary with the month name as a key and > an empty list as a value > ? ? ? ? ? ? ? ?tmp_dict = {} > ? ? ? ? ? ? ? ?tmp_dict[_tmp_month] = [] > > ? ? ? ? ? ? ? ?if tmp_dict not in item[_year]: > ? ? ? ? ? ? ? ? ? ?item[_year].append(tmp_dict) > > ? ?# append the blog entry object to the list if the pub_date month > and year match > ? ?# the dictionary keys in the archive_list dictionary/list tree. > ? ?for entry in _query: > ? ? ? ?# dict in list > ? ? ? ?for item in archive_list: > ? ? ? ? ? ?# year of entry > ? ? ? ? ? ?_year = entry.pub_date.year > ? ? ? ? ? ?if _year in item: > ? ? ? ? ? ? ? ?_year_list = item[_year] > ? ? ? ? ? ? ? ?for _dict_month in _year_list: > ? ? ? ? ? ? ? ? ? ?_tmp_month = entry.pub_date.strftime("%B") > ? ? ? ? ? ? ? ? ? ?if _tmp_month in _dict_month: > ? ? ? ? ? ? ? ? ? ? ? ?_dict_month[_tmp_month].append(entry) > > ? ?return archive_list > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Instant first comment, after just a glance at your code, Can't you use an int for the year and months, rather than strings? (This is a principle of the MVC (Model, View, Controller) structure: you keep your model (The actual data) as easy to handle as possible, and using ints as keys makes conversion between the query and the output and sorting easier. Conversion from {2009:{12: ...}} to "December 2009: ..." should be handled by the view: either the GUI, or immediatly before it's displayed. (This may be a point of contention, it could be argued that the view should only display it, and all manipulation should be handled by the controller level.) This isn't a case for recursion: recursion is best used when you have one thing containing a container, which contains a container, which contains another, which contains another, etc, to (usually) unknown depths. (Yes, there are numeric uses for recursion, but they are usually best replaced with an iterative approach). It would be more pythonic to format your output as a dict of dicts (of lists), rather than lists of single-item dicts of lists of single-item dicts: archive_list = \ {2009: {12: ['entry1', 'entry2'], 1: ['entry3', 'entry4']} }, '2008': {1: ['entry5', 'entry6']} } You loose the ordering, but that isn't a problem when your keys have implicit ordering. Look up collections.defaultdict. To generate this structure, you can use dict as the factory function with defaultdict: d = collections.defaultdict(dict) or, more usefully, d = collections.defaultdict(functools.partial(collections.defaultdict, list)) This will give a defaultdict of defaultdicts of lists. (The functools.partial just returns a callable, which is what defaultdict needs to create its default value. Then, as you iterate through the report, you simply assign to the dict as follows: for entry in month_record: d[year][month].append(entry) It avoids all the messing around with tmp_year_list and so on. Another way, using only builtins, is to use dict.setdefault(): d = {} d.setdefault(year, {}).setdefault(month, []) This is essentially what the defaultdict does for you. Doing it like this will give you the advantage of being easy to read: I'm struggling to follow what your code does at the moment: you've got far too many levels of nesting and temporary variables. I don't know the structure of your query result, but using pseudo-functions: import collections, functools def create_archive_list(query): d = collections.defaultdict(functools.partial(collections.defaultdict, list)) for entry in query: #iterate over blog posts, rather than years, months etc - therefore using a single pass d[entry.year()][entry.month()].append(entry.data()) return d And finally, a little utility function, which DOES use recursion: def mapToDict(d): """"recursively convert defaultdicts into regular dicts""" d = dict(d) d.update((k, map_to_dict(v)) for k,v in d.items() if isinstance(v, collections.defaultdict)) return d This function is more for personal comfort than regular use (although it does clean up debugging output): it's poor programming if code that works with a regular dict fails if given a defaultdict. If you DO discover any, I highly recommend reporting it as a bug. Like I said, I've not seen your data structure, so I'm making some big guesses here, but this should give you enough to look into towards improving your code. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From roadierich at googlemail.com Sun Oct 25 15:31:03 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 25 Oct 2009 14:31:03 +0000 Subject: [Tutor] Using IDLE v2.6 In-Reply-To: References: <4AE34004.4080008@insightbb.com> Message-ID: 2009/10/24 Alan Gauld : > "Ken G." wrote >> >> IDLE v2.6 but I was wondering if there is something better than IDLE. > > There is a wealth of options and a Google search on Python IDEs will throw > many up. > > Some common recommendations: > > PyDev on Eclipse (good if you already use Eclipse for say Java or C++) > Eric > SPE > Scipe/Notepad++ ?(but these may be windows only?) I've got Notepad++ running nicely under wine on my ubuntu install, and SciTE (which I'm assuming is what you meant) is open source and has versions for most platforms - it's based on the Scintilla editor widget, which is the system behind the excellent (IMHO) PythonWin IDE. I do simiar to this, except I use IDLE for editing (I spend most of my time on OS X or ubuntu) and quick testing and the python interpretter for more complex testing - there are some known bugs in the IDLE interpretter. When I'm on Windows, I use PythonWin. I'll also second Komodo Edit. Although I don't use it for python, it's extremely good at php, and seems well thought out. ActiveState (who make Komodo), also produce the ActivePython distribution, which is the usually recommended python distribution for windows. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From alan.gauld at btinternet.com Sun Oct 25 15:54:07 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 25 Oct 2009 14:54:07 +0000 (GMT) Subject: [Tutor] Using IDLE v2.6 In-Reply-To: References: <4AE34004.4080008@insightbb.com> Message-ID: <982485.1577.qm@web86705.mail.ird.yahoo.com> > > Scipe/Notepad++ (but these may be windows only?) > > I've got Notepad++ running nicely under wine on my ubuntu install, and > SciTE (which I'm assuming is what you meant) is open source and has > versions for most platforms - it's based on the Scintilla editor Yes I meant SciTE, thanks. I thought it was available on Linux but Notepad++ is also based on Scintilla and as I was pretty sure it was Windows only I wondered if SciTE might be too. Thanks for clarifying. > ActiveState (who make Komodo), also produce the ActivePython > distribution, which is the usually recommended python distribution for > windows. Yes and it includes Pythonwin as standard too. Alan G. From highcar at gmail.com Sun Oct 25 04:30:57 2009 From: highcar at gmail.com (elca) Date: Sat, 24 Oct 2009 20:30:57 -0700 (PDT) Subject: [Tutor] how to use lxml and win32com? Message-ID: <26045028.post@talk.nabble.com> hello... i really want to know...i was searched in google lot of time. but can't found clear soultion. and also because of my lack of python knowledge. i want to use IE.navigate function with beautifulsoup or lxml.. if anyone know about this or sample. please help me! thanks in advance .. -- View this message in context: http://www.nabble.com/how-to-use-lxml-and-win32com--tp26045028p26045028.html Sent from the Python - tutor mailing list archive at Nabble.com. From the_only_katala at verizon.net Sun Oct 25 23:53:54 2009 From: the_only_katala at verizon.net (Katt) Date: Sun, 25 Oct 2009 15:53:54 -0700 Subject: [Tutor] Reading information from a text file into a list of lists (WinXP/py2.6.2) References: Message-ID: <802E6BD77E64415C9DAF437EAB4F3AAC@COMPUTER01> Hello all, Currently I am working on a program that reads text from a text file. I would like it to place the information int a list and inside the information would have sublists of information. The text file looks like this: "Old Test","2009_10_20" "Current Test","2009_10_25" "Future Test","2009_11_01" I am trying to get the list of lists to look like the following after the information is read from the text file: important_dates = [["Old Test","2009_10_20"],["Current Test",2009_10_25"],["Future Test","2009_11_01"]] What I currently have is: def read_important_dates(): print "\nReading text file into program: important.txt" text_file = open("important.txt", "r") dates = text_file.readlines() text_file.close() print dates # read_important_dates() When it gets to print dates I see the following: [ ' "Old Test","2009_10_20"\n', ' "Current Test",2009_10_25"\n', ' "Future Test","2009_11_01" ' ] Does it look this way because I am using the "print"? Or do I still need to add the inner [ ] and strip out the \n and '? If I add brackets to the text file I am reading from my output looks like this: ['["Old Test","2009_10_20"]\n', '["Current Test",2009_10_25"]\n', '["Future Test","2009_11_01"]'] The program in which I am reading the information into reads a list of lists in which I am trying to simulate when reading from the text file mentioned above. Which acomplishes the in list's brackets, but still leaves the \n and the ' characters. I have tried line.strip() to remove the \n and ' characters, but get the following error: Reading text file into program: important.txt Traceback (most recent call last): File "fileio.py", line 9, in read_important_dates() File "fileio.py", line 6, in read_important_dates line.strip() NameError: global name 'line' is not defined If I try the following to split dates into another list called important_dates I receive a different error: ---------code---------- def read_important_dates(): print "\nReading text file into program: reminders.txt" text_file = open("important", "r") dates = text_file.readlines() text_file.close() important_dates = dates.split() print dates print important_dates # read_important_dates() ------------------------- --------error----------- Reading text file into program: important.txt Traceback (most recent call last): File "fileio.py", line 10, in read_important_dates() File "fileio.py", line 6, in read_important_dates important_dates = dates.split() NameError: 'list' object has no attribute 'split' -------------------------- All help is appreciated, Thanks in advance, Katt From alan.gauld at btinternet.com Mon Oct 26 02:02:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Oct 2009 01:02:47 -0000 Subject: [Tutor] Reading information from a text file into a list of lists (WinXP/py2.6.2) References: <802E6BD77E64415C9DAF437EAB4F3AAC@COMPUTER01> Message-ID: "Katt" wrote > def read_important_dates(): > print "\nReading text file into program: important.txt" > text_file = open("important.txt", "r") > dates = text_file.readlines() > text_file.close() > print dates > # > read_important_dates() > > When it gets to print dates I see the following: > > [ ' "Old Test","2009_10_20"\n', ' "Current Test",2009_10_25"\n', ' > "Future Test","2009_11_01" ' ] > > Does it look this way because I am using the "print"? Or do I still need > to add the inner [ ] and strip out the \n and '? Its that way because you are just storing the raw strings read from the file (notice the outer single quotes). You need to interpret(ie parse) the strings to extract the data. You should also strip the lines to get rid of the \n characters. > If I add brackets to the text file I am reading from my output looks like If you have control over the text file then add a unique character as a field separator and then uyou can use split() to split the fields easily. Common choices of field separator include unlikely currency symbols or graphics characters. > I have tried line.strip() to remove the \n and ' characters, but get the > following error: > > File "fileio.py", line 6, in read_important_dates > line.strip() > NameError: global name 'line' is not defined And sure enough you have no line variable. You will need to process the lines one by one. A list comp can do this for you > dates = text_file.readlines() becomes dates = [line.strip() for line in text_file] And if you knew the sepsatator char you could do that too dates = [line.strip().split(sep) for line in text_file] > File "fileio.py", line 6, in read_important_dates > important_dates = dates.split() > NameError: 'list' object has no attribute 'split' True ebough. You really need to process the lines one at a time. This is usually best done as you read them from the file rather than after storing them in a list - it saves processing the data twice. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From emailkgnow at gmail.com Mon Oct 26 02:06:00 2009 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Mon, 26 Oct 2009 04:06:00 +0300 Subject: [Tutor] A question about the self and other stuff Message-ID: Hi everybody, So I'm new to python and have questions about the following code: class Robot: '''Represents a Robot with a name. Deletes and makes Robots for testing perpuses''' #a var for counting the number of Robots population = 0 def __init__(self, name): '''initializes the data''' self.name=name print ('initializing {0}'.format(self.name)) Robot.population+=1 def __del__(self): '''I'm dying''' print ('{0} is being destroyed!'.format(self.name)) Robot.population-=1 if Robot.population==0: print ("{0} was the last one".format(self.name)) else: print ("there are still {0:d} Robots working".format(Robot.population)) def Sayhi (self): '''This is just a hi thing. Just to say hi<<< to practice convention of docstrings''' print ('hello, khalid calls me {0}'.format(self.name)) def howMany(): '''prints how many''' print ('we have {0:d} Robots'.format (Robot.population)) howMany= staticmethod(howMany) droid1 = Robot('D23') droid1.Sayhi() Robot.howMany() droid2 = Robot('F0009') droid2.Sayhi() Robot.howMany() print ("\nRobots can do some work here\n") print ("Robots have finished their work. So let's destroy them") del droid1 del droid2 Robot.howMany() 1- In the class definition above, I don't get the "self.name=name". I understand that the self is supposed to refer to the actual object, but since it is an initialization method, there is no way to enter a name in place of the arguments. 2- in the final few lines where I assign an object to the class, I notice that a parameter was entered in the class name, "Robot(D23)", although when defining the class I didn't put any arguments for it. 3- what is the difference between all the underscore, underscore attributes like:__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__ and the rest of the normal methods for a class.? I know, lots of questions, but what can i say... I am new!! so can you guy/gals help? thanks a million. khalid -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 26 02:05:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Oct 2009 01:05:06 -0000 Subject: [Tutor] how to use lxml and win32com? References: <26045028.post@talk.nabble.com> Message-ID: "elca" wrote > i want to use IE.navigate function with beautifulsoup or lxml.. > if anyone know about this or sample. the parsers both effectively replace the browser so you can't really use any functions of IE to modify soup or lxml. Why do you want to use navigate()? What are you trying to do? There is likely to be another way to do it from Python. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Mon Oct 26 03:38:24 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 25 Oct 2009 21:38:24 -0500 Subject: [Tutor] Reading information from a text file into a list of lists (WinXP/py2.6.2) In-Reply-To: <802E6BD77E64415C9DAF437EAB4F3AAC@COMPUTER01> References: <802E6BD77E64415C9DAF437EAB4F3AAC@COMPUTER01> Message-ID: <4AE50BA0.7050702@ieee.org> Katt wrote: >
Hello all, > > Currently I am working on a program that reads text from a text file. > I would like it to place the information int a list and inside the > information would have sublists of information. > > The text file looks like this: > > "Old Test","2009_10_20" > "Current Test","2009_10_25" > "Future Test","2009_11_01" > > I am trying to get the list of lists to look like the following after > the information is read from the text file: > > important_dates = [["Old Test","2009_10_20"],["Current > Test",2009_10_25"],["Future Test","2009_11_01"]] > > What I currently have is: > > def read_important_dates(): > print "\nReading text file into program: important.txt" > text_file = open("important.txt", "r") > dates = text_file.readlines() > text_file.close() > print dates # > read_important_dates() > > When it gets to print dates I see the following: > > [ ' "Old Test","2009_10_20"\n', ' "Current Test",2009_10_25"\n', ' > "Future Test","2009_11_01" ' ] > > Does it look this way because I am using the "print"? Or do I still > need to add the inner [ ] and strip out the \n and '? > If I add brackets to the text file I am reading from my output looks > like this: > > We have to be clear about this. You want an actual list containing sublists. You don't just want something which seems to print out with brackets to mimic that? Probably if you just showed us the whole assignment question, it'd be easier One thing at a time. Please don't try adding brackets to the data file. You're not trying to create brackets, you're trying to create list of list. The brackets are just the way Python shows you what you've got when you print out a list directly. Similarly, the single-quote you see in that print string are just a marker showing that you've got strings. It's what's between the quotes that is the contents of the string. First, you need to get confidence in the relationship between what's really in variables, and what gets printed out when you print in various ways. Then, once you're getting sure of your ability to recognize these, you can actually debug why you're not getting what you want. If you have mystring = "This is a string" print mystring print repr(mystring) what you get is: This is a string 'This is a string' So you can see the string has no quotes within it, but you might see quotes around it when you ask python to display it indirectly. Now let's put a newline into the middle of the string: mystring = "This is line 1\nAnd line 2" print mystring print repr(mystring) The output is: This is line 1 And line 2 'This is line 1\nAnd line 2' So we see there's a control character in the middle of the string, which causes our console to switch to the next line (it's called a newline). But the repr() form shows us the quotes and the slash and the n. There's not really a slash or an n at that point in the string, but repr() uses that form to show us exactly what's happening there. The goal of repr() is to approximate what you might have to do in source code to produce the same data. When we print a list, as a single item, we'll see brackets around the whole thing, and commas between the items. There are no brackets anywhere in the list, that's just python's way of repr() the list. And when an item in the list is a string, it'll have quotes around it, that are not part of the string. And any control characters are represented by the slash-terminology. It's just like with repr() of a single string. It can be useful to loop through the list printing individual items of the list. It can also be useful to use len() on the list to see how many items are in it. for item in mylist: print item print len(mylist) Now let's look at the output you showed: [ ' "Old Test","2009_10_20"\n', ' "Current Test",2009_10_25"\n', ' "Future Test","2009_11_01" ' ] We could also do print len(dates) and see a 3. This is what readlines() produces. It reads the raw data from the file, and produces a list, one string per line. It uses newline to decide where each line ends, and keeps the newlines with the data. It happens you didn't have one at the end of the file, so we only see two of them. readlines() doesn't know how to do anything more with the data in each line. It only understands one level of parsing. So you have to write some form of loop, which visits each item of the list, creating the sublist you said your teacher wanted. The logical way to divide up each line would be to use the split() method of string. If you tell it to split by commas, it would work on the particular file you've got. You have to watch a bit, since somebody may slip in a comma inside one of those quoted items in the data file, and expect you *not* to split based on that one. Again, it'd be good to have a clear problem statement, containing the expectations of the input file, among other things. Now you have the additional problem of getting rid of the newlines and the quotes in the input data. The desired result you showed has no quotes, no commas, and no newlines anywhere in the list of lists. strip() is the usual way of getting rid of leading and trailing delimiters, after readlines, or after split. So write some loops, and try to divvy up the data, and we can guide you as you learn. As always, when you want help with an error, use copy and paste to show us the entire thing. One more question. Are you permitted to use some of the fancier modules of the python library, such as csv? If I were your teacher, I'd explicitly prevent that type of solution, as you need to know how to do things "by hand" before learning some of the more complex tools. DaveA From hyperneato at gmail.com Mon Oct 26 03:56:52 2009 From: hyperneato at gmail.com (Isaac) Date: Sun, 25 Oct 2009 19:56:52 -0700 Subject: [Tutor] request for comments regarding my function In-Reply-To: References: <7260654a0910242349x2983ab7cj38940e46d6f0676f@mail.gmail.com> Message-ID: <7260654a0910251956rd354a36u75d4f2ae6e426c6c@mail.gmail.com> Thank you very much! You certainly gave me plenty to think and read about. I had not known about functools or collections. On Sun, Oct 25, 2009 at 7:09 AM, Rich Lovely wrote: > 2009/10/25 Isaac : >> Hello all, >> I wrote a function to organize a list of sorted objects ( django blog >> entries ); each object has a Python datetime attribute ( called >> pub_date ). I am posting a message to the tutor mailing list to get >> feedback regarding better ways to accomplish the same task. I have a >> feeling I could use recursion here, instead of looping through the >> entire _query list 3 times. Here is my code: >> >> def create_archive_list(_query): >> ? ?""" >> ? ?given a sorted queryset, return a list in the format: >> >> ? ?archive_list = [{'2009': [{'December': ['entry1', 'entry2']}, >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{'January': ['entry3', 'entry4']} >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?] >> ? ? ? ? ? ? ? ? ? ? }, >> >> ? ? ? ? ? ? ? ? ? ?{'2008': [{'January': ['entry5', 'entry6']}, >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?] >> ? ? ? ? ? ? ? ? ? ? } >> ? ? ? ? ? ? ? ? ? ?] >> ? ?""" >> >> ? ?archive_list = [] >> ? ?tmp_year_list = [] >> >> ? ?# make a list of Python dictionaries; the keys are the year, as in >> '2009', and the value >> ? ?# is an empty list. >> ? ?for item in _query: >> ? ? ? ?if item.pub_date.year not in tmp_year_list: >> ? ? ? ? ? ?tmp_year_list.append(item.pub_date.year) >> ? ? ? ? ? ?tmp_dict = {} >> ? ? ? ? ? ?tmp_dict[item.pub_date.year] = [] >> ? ? ? ? ? ?archive_list.append(tmp_dict) >> ? ? ? ?else: >> ? ? ? ? ? ?pass >> >> ? ?# for every list in the archive_list dictionaries, append a >> dictionary with the >> ? ?# blog entry's month name as a key, and the value being an empty list >> ? ?for entry in _query: >> ? ? ? ?for item in archive_list: >> ? ? ? ? ? ?_year = entry.pub_date.year >> ? ? ? ? ? ?if _year in item: >> ? ? ? ? ? ? ? ?_tmp_month = entry.pub_date.strftime("%B") >> ? ? ? ? ? ? ? ?# make a dictionary with the month name as a key and >> an empty list as a value >> ? ? ? ? ? ? ? ?tmp_dict = {} >> ? ? ? ? ? ? ? ?tmp_dict[_tmp_month] = [] >> >> ? ? ? ? ? ? ? ?if tmp_dict not in item[_year]: >> ? ? ? ? ? ? ? ? ? ?item[_year].append(tmp_dict) >> >> ? ?# append the blog entry object to the list if the pub_date month >> and year match >> ? ?# the dictionary keys in the archive_list dictionary/list tree. >> ? ?for entry in _query: >> ? ? ? ?# dict in list >> ? ? ? ?for item in archive_list: >> ? ? ? ? ? ?# year of entry >> ? ? ? ? ? ?_year = entry.pub_date.year >> ? ? ? ? ? ?if _year in item: >> ? ? ? ? ? ? ? ?_year_list = item[_year] >> ? ? ? ? ? ? ? ?for _dict_month in _year_list: >> ? ? ? ? ? ? ? ? ? ?_tmp_month = entry.pub_date.strftime("%B") >> ? ? ? ? ? ? ? ? ? ?if _tmp_month in _dict_month: >> ? ? ? ? ? ? ? ? ? ? ? ?_dict_month[_tmp_month].append(entry) >> >> ? ?return archive_list >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > Instant first comment, after just a glance at your code, Can't you use > an int for the year and months, rather than strings? ?(This is a > principle of the MVC (Model, View, Controller) structure: ?you keep > your model (The actual data) as easy to handle as possible, and using > ints as keys makes conversion between the query and the output and > sorting easier. ?Conversion from {2009:{12: ...}} to "December 2009: > ..." should be handled by the view: either the GUI, or immediatly > before it's displayed. ?(This may be a point of contention, it could > be argued that the view should only display it, and all manipulation > should be handled by the controller level.) > > This isn't a case for recursion: ?recursion is best used when you have > one thing containing a container, which contains a container, which > contains another, which contains another, etc, to (usually) unknown > depths. ?(Yes, there are numeric uses for recursion, but they are > usually best replaced with an iterative approach). > > It would be more pythonic to format your output as a dict of dicts (of > lists), rather than lists of single-item dicts of lists of single-item > dicts: > archive_list = \ > {2009: {12: ['entry1', 'entry2'], > ? ? ? ? ? ? 1: ['entry3', 'entry4']} > ? ? ? ? ? ?}, > '2008': {1: ['entry5', 'entry6']} > } > > You loose the ordering, but that isn't a problem when your keys have > implicit ordering. > > Look up collections.defaultdict. ?To generate this structure, you can > use dict as the factory function with defaultdict: > > d = collections.defaultdict(dict) > > or, more usefully, > d = collections.defaultdict(functools.partial(collections.defaultdict, list)) > This will give a defaultdict of defaultdicts of lists. ?(The > functools.partial just returns a callable, which is what defaultdict > needs to create its default value. > > Then, as you iterate through the report, you simply assign to the dict > as follows: > > for entry in month_record: > ? ?d[year][month].append(entry) > > It avoids all the messing around with tmp_year_list and so on. > > Another way, using only builtins, is to use dict.setdefault(): > > d = {} > d.setdefault(year, {}).setdefault(month, []) > > This is essentially what the defaultdict does for you. > > Doing it like this will give you the advantage of being easy to read: > I'm struggling to follow what your code does at the moment: ?you've > got far too many levels of nesting and temporary variables. > > I don't know the structure of your query result, but using pseudo-functions: > > import collections, functools > > def create_archive_list(query): > ? ?d = collections.defaultdict(functools.partial(collections.defaultdict, > list)) > ? ?for entry in query: #iterate over blog posts, rather than years, > months etc - therefore using a single pass > ? ? ? ?d[entry.year()][entry.month()].append(entry.data()) > ? ?return d > > And finally, a little utility function, which DOES use recursion: > > def mapToDict(d): > ? ?""""recursively convert defaultdicts into regular dicts""" > ? ?d = dict(d) > ? ?d.update((k, map_to_dict(v)) for k,v in d.items() if isinstance(v, > collections.defaultdict)) > ? ?return d > > > This function is more for personal comfort than regular use (although > it does clean up debugging output): ?it's poor programming if code > that works with a regular dict fails if given a defaultdict. ?If you > DO discover any, I highly recommend reporting it as a bug. > > Like I said, I've not seen your data structure, so I'm making some big > guesses here, but this should give you enough to look into towards > improving your code. > > -- > Rich "Roadie Rich" Lovely > > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. > From rabidpoobear at gmail.com Mon Oct 26 04:10:57 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 25 Oct 2009 22:10:57 -0500 Subject: [Tutor] A question about the self and other stuff In-Reply-To: References: Message-ID: On Sun, Oct 25, 2009 at 8:06 PM, Khalid Al-Ghamdi wrote: > Hi everybody, > So I'm new to python and have questions about the following code: > > def __init__(self, name): > '''initializes the data''' > self.name=name > print ('initializing {0}'.format(self.name)) > > droid1 = Robot('D23') > > > 1- In the class definition above, I don't get the "self.name=name". I > understand that the self is supposed to refer to the actual object, but > since it is an initialization method, there is no way to enter a name in > place of the arguments. > Self refers to the object currently being created by the "init" method, so it is always the first parameter to __init__. You can call it 's' or 'foobar' or 'self' or 'cantaloupe', it doesn't matter. It's just always the first argument. "self.name = name" means "take the second argument that is passed to the __init__ method and assign it to the current object under the "name" attribute. Imagine if you were constructing a car. class Car(object): def __init__(self, doors, chassis): self.doors = doors self.chassis = chassis You are passing these parameters to the car so that they can be applied to the specific car. For example, you could then do mychassis = "Dodge Ram" doors1 = "hatchback" doors2 = "4-door" car1 = Car(mychassis, doors1) car2 = Car(mychassis, doors2) Is that a little bit more clear? > 2- in the final few lines where I assign an object to the class, I notice > that a parameter was entered in the class name, "Robot(D23)", although when > defining the class I didn't put any arguments for it. > Yes you did, __init__ takes 2 parameters, "self" and "name". When constructing a new object via Robot(D23) you are implicitly passing "self" and you are explicitly passing 'D23' as "self". > 3- what is the difference between all the underscore, underscore attributes > like:__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', > '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', > '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', > '__setattr__ > They all do different things, I'm not sure what you mean by "what are the differences"? They are functions that are called in certain situations. For example, a + b will call a.__add__(b) and a['blah'] = b will call a.__setitem__(b) etc. (these __ names may be wrong so don't quote me on them.) > > and the rest of the normal methods for a class.? > Depends on the class. There are no "normal methods", the methods that a class has are based upon the type of class it is. You could have a class with no methods and only attributes (but this would be almost completely useless). -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Mon Oct 26 04:12:46 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 25 Oct 2009 22:12:46 -0500 Subject: [Tutor] A question about the self and other stuff In-Reply-To: References: Message-ID: On Sun, Oct 25, 2009 at 10:10 PM, Luke Paireepinart wrote: > > >> 2- in the final few lines where I assign an object to the class, I notice >> that a parameter was entered in the class name, "Robot(D23)", although when >> defining the class I didn't put any arguments for it. >> > Yes you did, > __init__ takes 2 parameters, "self" and "name". When constructing a new > object via Robot(D23) you are implicitly passing "self" and you are > explicitly passing 'D23' as "self". > Correction, When constructing a new object via Robot(*'D23'*) you are implicitly passing "self" and you are explicitly passing 'D23' as "*name*". -------------- next part -------------- An HTML attachment was scrubbed... URL: From smiles at worksmail.net Mon Oct 26 04:08:47 2009 From: smiles at worksmail.net (C or L Smith) Date: Mon, 26 Oct 2009 08:53:47 +0545 Subject: [Tutor] tokenize problem on string literal? Message-ID: <5C88144A4FB4435ABB11311D56334279@kisc.edu.np> Am I misunderstanding a tokenize parse rule or is this an error: ### def tok(s): import tokenize from StringIO import StringIO t = StringIO(s).readline for ti in tokenize.generate_tokens(t): print ti tok("'''quote: \''''") ### produces (3, "'''quote: '''", (1, 0), (1, 13), "'''quote: ''''") (52, "'", (1, 13), (1, 14), "'''quote: ''''") (0, '', (2, 0), (2, 0), '') It's taking the escaped quote to be one of the closing triple quotes and then tokenizing off the last quote. I expected it to give me a single quote only and then the end-of-record: quote: \' /Chris From smiles at worksmail.net Mon Oct 26 05:56:24 2009 From: smiles at worksmail.net (C or L Smith) Date: Mon, 26 Oct 2009 10:41:24 +0545 Subject: [Tutor] tokenize problem on string literal? Message-ID: <27D3F0F68BF64EA781AF0388B4F0B19F@kisc.edu.np> C or L Smith wrote: > Am I misunderstanding a tokenize parse rule or is this an error: > > ### > def tok(s): > import tokenize > from StringIO import StringIO > t = StringIO(s).readline > for ti in tokenize.generate_tokens(t): > print ti > tok("'''quote: \''''") > ### > Note to self: you are misunderstanding what sort of string is being created by the above: since this isn't a raw string, the first \' just becomes a literal quote so it looks like this: '''quote: '''' which is what tokenize is telling you. You have to be careful when using the editor to create examples. When entering the following, the following colors (yellow for string and black for non-string) are noted: foo color for this --------- -------- yellow '''afoo yellow '''a\'''foo black '''a\''''foo If you want to quote that now for testing, make it a raw string: >>> r"'''a\''''foo" "'''a\\''''foo" That *bottom* form is what you should be using to test your quote matcher or tokenize's behavior. sigh :-) /c From bibsmendez at gmail.com Mon Oct 26 08:45:06 2009 From: bibsmendez at gmail.com (bibi midi) Date: Mon, 26 Oct 2009 10:45:06 +0300 Subject: [Tutor] Compute data usage from log Message-ID: Hi all! I have a file with data structure derived from wvdial log: Oct 14 11:03:45 cc000002695 pppd[3092]: Sent 3489538 bytes, received 43317854 bytes. I want to get the 10th field of each line and get the sum for all lines (total my net data usage). In awk u can easily pop it using field variables e..g $10. Since im learning python on my own i thought this is a good way to learn but im stumped how to achieve this goal. I used open() and read line method to store the contents in a list but it is a list of string. I need it to be numbers. Iterating through the string list definitely is unwieldy. Can you guys advise best way how? FWIW im a self learner and just relying from tutorial materials and this medium to learn python. Lead me to the right direction please :-) My IDE is vim and ipython in debian linux. -- Best Regards, bibimidi -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Mon Oct 26 09:20:58 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 26 Oct 2009 10:20:58 +0200 Subject: [Tutor] Compute data usage from log In-Reply-To: References: Message-ID: <4AE55BEA.9010305@compuscan.co.za> bibi midi wrote: > Hi all! > > I have a file with data structure derived from wvdial log: > Oct 14 11:03:45 cc000002695 pppd[3092]: Sent 3489538 bytes, received > 43317854 bytes. > > I want to get the 10th field of each line and get the sum for all > lines (total my net data usage). In awk u can easily pop it using > field variables e..g $10. Since im learning python on my own i thought > this is a good way to learn but im stumped how to achieve this goal. > I used open() and read line method to store the contents in a list but > it is a list of string. I need it to be numbers. Iterating through the > string list definitely is unwieldy. Can you guys advise best way how? > > FWIW im a self learner and just relying from tutorial materials and > this medium to learn python. Lead me to the right direction please :-) > > My IDE is vim and ipython in debian linux. > > > -- > Best Regards, > bibimidi > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > fInput = open('/path/to/log.file', 'rb') total_usage = 0 for line in fInput: total_usage += int(line.split(' ')[9].strip()) print total_usage That would be the simple no frills version. What it does is iterate through the file, on each line it splits it into columns delimited by spaces, takes the 10th element (you count from 0 up and not 1 up), converts it into an integer and adds it to your total_usage counter. Of course this has no error checking and or niceties, but I will leave that up to you. Hope that helps. -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Mon Oct 26 10:00:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Oct 2009 09:00:18 -0000 Subject: [Tutor] A question about the self and other stuff References: Message-ID: "Khalid Al-Ghamdi" wrote > class Robot: > population = 0 > > def __init__(self, name): > self.name=name > print ('initializing {0}'.format(self.name)) > Robot.population+=1 > > def __del__(self): > '''I'm dying''' > print ('{0} is being destroyed!'.format(self.name)) > Robot.population-=1 > droid1 = Robot('D23') > 1- In the class definition above, I don't get the "self.name=name". I > understand that the self is supposed to refer to the actual object, but > since it is an initialization method, there is no way to enter a name in > place of the arguments. When you instantiate a class you create a new object and initialise it. The way you do that in code is object = ClassName(arguments) What then happens is that the ClassName object is created and its __init__ method is called with arguments passed to it. So in your case when you do droid1 = Robot("D23") you are NOT assigning the class to droid1 you are creating a new instance of Robot and passing the argument "D23" to the init method as its name parameter. The __init__ method then assigns the name to self.name, ie to droid1.name The __xxx___ methods are all special methods that Python calls indirectly. __del__ is called when an object is deleted so is the complement of __init__. __eq__ is called when we do an equality test: if drioid1 == droid2 for example will actually call doid1.__eq__(droid2) These methods allow us to change how operatrors work for our classes. You might find it useful to read the OOP topic in my tutorial as an secondary source to the book/course you are currently reading. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Mon Oct 26 12:12:18 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 26 Oct 2009 06:12:18 -0500 Subject: [Tutor] Compute data usage from log In-Reply-To: <4AE55BEA.9010305@compuscan.co.za> References: <4AE55BEA.9010305@compuscan.co.za> Message-ID: On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts wrote: > fInput = open('/path/to/log.file', 'rb') > total_usage = 0 > for line in fInput: > total_usage += int(line.split(' ')[9].strip()) > print total_usage > It's actually bad to assign a variable to the file object in this case (flinput = ....) because Python will automatically close a file after you're done with it if you iterate over it directly, but if you include a reference it will stay open until the python program ends or you explicitly call flinput.close(). It doesn't matter much in this example but in general it is good practice to either 1) call foo.close() immediately after you're done using a file object, or 2) don't alias the file object and just over it directly so Python will auto-close it. Therefore a better (and simpler) way to do the above would be: total_usage = 0 for line in open('/path/to/log.file'): total_usage += int(line.split(' ')[9]) Also note you don't need to strip the input because int() coersion ignores whitespace anyway. And additionally you shouldn't be opening this in binary mode unless you're sure you want to, and I'm guessing the log file is ascii so there's no need for the 'rb'. (reading is default so we don't specify an 'r'.) And since I like list comprehensions a lot, I'd probably do it like this instead: total_usage = sum([int(line.split(' ')[9]) for line in open('/path/to/log.file')]) Which incidentally is even shorter, but may be less readable if you don't use list comprehensions often. Also, the list comprehension version is likely to be more efficient, both because of the use of sum rather than repeated addition (sum is implemented in C) and because list comprehensions in general are a tad faster than explicit iteration, if i recall correctly (don't hold me to that though, I may be wrong.) > > Of course this has no error checking and or niceties, but I will leave that > up to you. The same applies to my modifications. Good luck, and let us know if you need anything else! -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL: From highcar at gmail.com Mon Oct 26 02:17:02 2009 From: highcar at gmail.com (elca) Date: Sun, 25 Oct 2009 18:17:02 -0700 (PDT) Subject: [Tutor] how to use lxml and win32com? In-Reply-To: References: <26045028.post@talk.nabble.com> Message-ID: <26053583.post@talk.nabble.com> Alan Gauld wrote: > > > "elca" wrote > >> i want to use IE.navigate function with beautifulsoup or lxml.. >> if anyone know about this or sample. > > the parsers both effectively replace the browser so you > can't really use any functions of IE to modify soup or lxml. > > Why do you want to use navigate()? What are you trying to do? > There is likely to be another way to do it from Python. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Hello, actually im making web scraper. and scraping is no problem with javascript. after made scraper, i will add some other function and that time i will encounter many javascript, so why i try to use PAMIE or IE http://elca.pastebin.com/m52e7d8e0 i was attached current scraper script source. especially i want to change 'thepage = urllib.urlopen(theurl).read()' to PAMIE method. if possible ,you can check it and correct me? thanks in advance.. -- View this message in context: http://www.nabble.com/how-to-use-lxml-and-win32com--tp26045028p26053583.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Mon Oct 26 13:22:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 Oct 2009 08:22:55 -0400 Subject: [Tutor] Reading information from a text file into a list of lists (WinXP/py2.6.2) In-Reply-To: <802E6BD77E64415C9DAF437EAB4F3AAC@COMPUTER01> References: <802E6BD77E64415C9DAF437EAB4F3AAC@COMPUTER01> Message-ID: <1c2a2c590910260522k27f613a7y2853d335336db685@mail.gmail.com> On Sun, Oct 25, 2009 at 6:53 PM, Katt wrote: > Hello all, > > Currently I am working on a program that reads text from a text file. ?I > would like it to place the information int a list and inside the information > would have sublists of information. > > The text file looks like this: > > "Old Test","2009_10_20" > "Current Test","2009_10_25" > "Future Test","2009_11_01" > > I am trying to get the list of lists to look like the following after the > information is read from the text file: > > important_dates = [["Old Test","2009_10_20"],["Current > Test",2009_10_25"],["Future Test","2009_11_01"]] Take a look at the csv module in the standard lib. You can configure it to use comma as the delimiter and it will handle the quotes for you. Kent From bibsmendez at gmail.com Mon Oct 26 14:25:12 2009 From: bibsmendez at gmail.com (bibi midi) Date: Mon, 26 Oct 2009 16:25:12 +0300 Subject: [Tutor] Compute data usage from log In-Reply-To: References: <4AE55BEA.9010305@compuscan.co.za> Message-ID: On Mon, Oct 26, 2009 at 2:12 PM, Luke Paireepinart wrote: > > > On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts wrote: > >> fInput = open('/path/to/log.file', 'rb') >> total_usage = 0 >> for line in fInput: >> total_usage += int(line.split(' ')[9].strip()) >> print total_usage >> > > It's actually bad to assign a variable to the file object in this case > (flinput = ....) because Python will automatically close a file after you're > done with it if you iterate over it directly, but if you include a reference > it will stay open until the python program ends or you explicitly call > flinput.close(). It doesn't matter much in this example but in general it > is good practice to either > 1) call foo.close() immediately after you're done using a file object, or > 2) don't alias the file object and just over it directly so Python will > auto-close it. > > Therefore a better (and simpler) way to do the above would be: > > total_usage = 0 > for line in open('/path/to/log.file'): > total_usage += int(line.split(' ')[9]) > Hi Luke, Your modification seems cleaner, you called the open function directly in the for loop. > > Also note you don't need to strip the input because int() coersion ignores > whitespace anyway. And additionally you shouldn't be opening this in binary > mode unless you're sure you want to, and I'm guessing the log file is ascii > so there's no need for the 'rb'. (reading is default so we don't specify an > 'r'.) > The file is normal ascii text. Ii open it with no mode set, and that defaults to read-only. > > And since I like list comprehensions a lot, I'd probably do it like this > instead: > > total_usage = sum([int(line.split(' ')[9]) for line in > open('/path/to/log.file')]) > > Which incidentally is even shorter, but may be less readable if you don't > use list comprehensions often. > > Also, the list comprehension version is likely to be more efficient, both > because of the use of sum rather than repeated addition (sum is implemented > in C) and because list comprehensions in general are a tad faster than > explicit iteration, if i recall correctly (don't hold me to that though, I > may be wrong.) > I have read up on list comprehension and I seem to understand it's basics. I will play around with the different solutions on hand. > >> Of course this has no error checking and or niceties, but I will leave >> that up to you. > > The same applies to my modifications. > > Good luck, and let us know if you need anything else! > > -Luke > Thank you as always :-) -- Best Regards, bibimidi Sent from Riyadh, 01, Saudi Arabia -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Oct 26 16:18:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Oct 2009 15:18:11 -0000 Subject: [Tutor] how to use lxml and win32com? References: <26045028.post@talk.nabble.com> <26053583.post@talk.nabble.com> Message-ID: "elca" wrote >>> i want to use IE.navigate function with beautifulsoup or lxml.. >>> if anyone know about this or sample. >> Why do you want to use navigate()? What are you trying to do? >> There is likely to be another way to do it from Python. > so why i try to use PAMIE or IE > http://elca.pastebin.com/m52e7d8e0 > i was attached current scraper script source. OK TherR are several problems in there. First, are you sure you want to define the function getit() inside a while loop? (I'm pretty sure you don't) And are you sure you want the function to recurse infinitely - see the last line (I'm pretty sure you don't) Next, do you really want page_check() to sleep for 13 seconds? (Once per letter in the url) > especially i want to change 'thepage = urllib.urlopen(theurl).read()' to > PAMIE method. And you still don't explain why you don;t want to use urlopen? What advantage does using PAMIE offer? I'd expect it to be slower and more memory hungry (since it uses IE under the covers). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eduardo.susan at gmail.com Mon Oct 26 20:08:10 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 26 Oct 2009 13:08:10 -0600 Subject: [Tutor] Function design Message-ID: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> Hello, I need your help in designing a function. I have created this script to check out if certain column in some csv files has value "0": import csv def zerofound(csvfile, outputfile, lastcolumn ): """Finds columns with zero prices. Column have 0 index""" final = csv.writer(open(outputfile, 'wb'), dialect='excel') reader = csv.reader(open(csvfile, 'rb'), dialect='excel') for row in reader: if '0' in row[:lastcolumn]: final.writerow(row) if __name__ == '__main__': zerofound('pricesfrombv.csv', 'noprices_in_BV.csv', 4) zerofound('excelbv.csv', 'noprices_in_ExcelBV.csv', 6) My question is. Is it OK to create functions with no "returns"? Basically what I did resembles a subroutine, right? How could I redesign this to use "return"? Thanks for your input, Eduardo From rabidpoobear at gmail.com Mon Oct 26 21:08:40 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 26 Oct 2009 15:08:40 -0500 Subject: [Tutor] Function design In-Reply-To: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> References: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> Message-ID: On Mon, Oct 26, 2009 at 2:08 PM, Eduardo Vieira wrote: > Hello, I need your help in designing a function. I have created this > script to check out if certain column in some csv files has value "0": > > import csv > > def zerofound(csvfile, outputfile, lastcolumn ): > """Finds columns with zero prices. Column have 0 index""" > final = csv.writer(open(outputfile, 'wb'), dialect='excel') > > reader = csv.reader(open(csvfile, 'rb'), dialect='excel') > for row in reader: > if '0' in row[:lastcolumn]: > final.writerow(row) > > > if __name__ == '__main__': > zerofound('pricesfrombv.csv', 'noprices_in_BV.csv', 4) > zerofound('excelbv.csv', 'noprices_in_ExcelBV.csv', 6) > > My question is. Is it OK to create functions with no "returns"? > Basically what I did resembles a subroutine, right? How could I > redesign this to use "return"? > Yes, the general "rule of thumb" in Computer Science is that you try to have functions that either have side-effects or return values, but not both. In practice people sometimes have both (eg. try to do some side-effects, if they work return a 0 and if they don't return an error code) but try to avoid it if possible. For example, string.strip() has a return value but no side-effects, because it does not modify the original string, it returns a new copy of the string that is stripped. Whereas list.sort() has no return value (or it returns None, depending on how you look at it) because it modifies the _ORIGINAL LIST_ which is a side-effect. As for your function, try to define the side-effects and change them into a return value. An example of a side-effect is printing to the screen or writing to a file, not just modifying global scoped or input variables. *************SPOILER***************** Your side-effect is that you're writing rows to "final". So you should get rid of all your "final" code and just return the list of rows. I would also suggest renaming the function to find_zeros() and obviously you would pass just the input filename. Then you would have another function write_rows(outfile, rows) and it would output the rows to outfile. I feel that would be a much cleaner design. write_rows probably won't have a return value since you're writing to a function (side-effect!) ***************************************** Hope that helps! -Luke > > Thanks for your input, > > Eduardo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jonesv at cox.net Mon Oct 26 22:47:59 2009 From: jonesv at cox.net (Vincent Jones) Date: Mon, 26 Oct 2009 17:47:59 -0400 Subject: [Tutor] HttpResponse error Message-ID: <000c01ca5685$fc472300$f4d56900$@net> SyntaxError at / ("'return' outside function", ('c:\\Users\\Vincent\\Documents\\django_bookmarks\\..\\django_bookmarks\\boo kmarks\\views.py', 15, None, 'return HttpResponse(output)\n')) As you can tell I am very new to this I am realizing that it is very important that indention and syntax is very important but i don't understand why I am getting this error This is the the original script in the views.py from django.http import HttpResponse def main_page(request) : output = ''' %s

%s

%s

''' % ( 'Django Bookmarks', 'Welcome to Django Bookmarks', 'Where you can store and share bookmarks!' ) return HttpResponse(output) And this (below is the error) Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.1.1 Python Version: 2.6.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites'] Installed Middleware: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware') Traceback: File "C:\Python26\Lib\site-packages\django\core\handlers\base.py" in get_response 83. request.path_info) File "C:\Python26\Lib\site-packages\django\core\urlresolvers.py" in resolve 216. for pattern in self.url_patterns: File "C:\Python26\Lib\site-packages\django\core\urlresolvers.py" in _get_url_patterns 245. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python26\Lib\site-packages\django\core\urlresolvers.py" in _get_urlconf_module 240. self._urlconf_module = import_module(self.urlconf_name) File "C:\Python26\Lib\site-packages\django\utils\importlib.py" in import_module 35. __import__(name) File "C:\Users\Vincent\Documents\django_bookmarks\..\django_bookmarks\urls.py" in 2. from bookmarks.views import * Exception Type: SyntaxError at / Exception Value: ("'return' outside function", ('c:\\Users\\Vincent\\Documents\\django_bookmarks\\..\\django_bookmarks\\boo kmarks\\views.py', 15, None, 'return HttpResponse(output)\n')) -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Mon Oct 26 23:05:27 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 26 Oct 2009 18:05:27 -0400 Subject: [Tutor] HttpResponse error In-Reply-To: <000c01ca5685$fc472300$f4d56900$@net> References: <000c01ca5685$fc472300$f4d56900$@net> Message-ID: > Exception Type: SyntaxError at / > > Exception Value: ("'return' outside function", > ('c:\\Users\\Vincent\\Documents\\django_bookmarks\\..\\django_bookmarks\\bookmarks\\views.py', > 15, None, 'return HttpResponse(output)\n')) > The Error message indicates that you've diagnosed the problem correctly: It appears that the "return" statement is flushed left rather than being indented. Try indenting it so and see if that works. The reason it does not work is explained here: http://docs.python.org/reference/simple_stmts.html#the-return-statement "return may only occur syntactically nested in a function definition, not within a nested class definition." Also, while this is indeed a generic Python syntax issue, the django forums are typically the best place for help with...well...Django. You can check those out at: http://groups-beta.google.com/group/django-users?pli=1 Good luck! Serdar From highcar at gmail.com Mon Oct 26 23:02:56 2009 From: highcar at gmail.com (elca) Date: Mon, 26 Oct 2009 15:02:56 -0700 (PDT) Subject: [Tutor] how to use lxml and win32com? In-Reply-To: References: <26045028.post@talk.nabble.com> <26053583.post@talk.nabble.com> Message-ID: <26068522.post@talk.nabble.com> Alan Gauld wrote: > > > "elca" wrote > >>>> i want to use IE.navigate function with beautifulsoup or lxml.. >>>> if anyone know about this or sample. >>> Why do you want to use navigate()? What are you trying to do? >>> There is likely to be another way to do it from Python. > >> so why i try to use PAMIE or IE >> http://elca.pastebin.com/m52e7d8e0 >> i was attached current scraper script source. > > OK TherR are several problems in there. > First, are you sure you want to define the function getit() inside a > while loop? (I'm pretty sure you don't) And are you sure you want > the function to recurse infinitely - see the last line (I'm pretty sure > you > don't) > Next, do you really want page_check() to sleep for 13 seconds? > (Once per letter in the url) > --> > all your words is correct. i don't need such like getit() and other > function . >> especially i want to change 'thepage = urllib.urlopen(theurl).read()' to >> PAMIE method. > > And you still don't explain why you don;t want to use urlopen? > What advantage does using PAMIE offer? I'd expect it to be slower > and more memory hungry (since it uses IE under the covers). > --> after make scraper i will add some other function that time i need to > handle javascript, > but as you already know urlopen method don't have such can handling > javasript option, > so why i want to use pamie, in addition i was tried other kind of method, > such like Selenium,webdriver > but not so much good for me, thanks for your help > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/how-to-use-lxml-and-win32com--tp26045028p26068522.html Sent from the Python - tutor mailing list archive at Nabble.com. From davea at ieee.org Tue Oct 27 00:09:03 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 26 Oct 2009 18:09:03 -0500 Subject: [Tutor] HttpResponse error In-Reply-To: <000c01ca5685$fc472300$f4d56900$@net> References: <000c01ca5685$fc472300$f4d56900$@net> Message-ID: <4AE62C0F.2080201@ieee.org> Vincent Jones wrote: > SyntaxError at / > > ("'return' outside function", > ('c:\\Users\\Vincent\\Documents\\django_bookmarks\\..\\django_bookmarks\\boo > kmarks\\views.py', 15, None, 'return HttpResponse(output)\n')) > > > > > from django.http import HttpResponse > > def main_page(request) : > > output = ''' > > > > %s > > > >

%s

%s

> > > > > > ''' % ( > > 'Django Bookmarks', > > 'Welcome to Django Bookmarks', > > 'Where you can store and share bookmarks!' > > ) > > return HttpResponse(output) > > The return line needs to be indented the same as the other line(s) in the function definition, which is to say it has to line up with the output= line. There really are only two lines in the body of the function, and they need to start at the same column. (It'd be easier on all of us if the code in your message weren't doublespaced, as well. That might be a email setting. Try using plain text, and see if it works better.) DaveA From davea at ieee.org Tue Oct 27 00:21:45 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 26 Oct 2009 18:21:45 -0500 Subject: [Tutor] Function design In-Reply-To: References: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> Message-ID: <4AE62F09.9090109@ieee.org> Luke Paireepinart wrote: > On Mon, Oct 26, 2009 at 2:08 PM, Eduardo Vieira wrote: > > >> Hello, I need your help in designing a function. I have created this >> script to check out if certain column in some csv files has value "0": >> >> import csv >> >> def zerofound(csvfile, outputfile, lastcolumn ): >> """Finds columns with zero prices. Column have 0 index""" >> final = csv.writer(open(outputfile, 'wb'), dialect='excel') >> >> reader = csv.reader(open(csvfile, 'rb'), dialect='excel') >> for row in reader: >> if '0' in row[:lastcolumn]: >> final.writerow(row) >> >> >> if __name__ == '__main__': >> zerofound('pricesfrombv.csv', 'noprices_in_BV.csv', 4) >> zerofound('excelbv.csv', 'noprices_in_ExcelBV.csv', 6) >> >> My question is. Is it OK to create functions with no "returns"? >> Basically what I did resembles a subroutine, right? How could I >> redesign this to use "return"? >> >> > Yes, the general "rule of thumb" in Computer Science is that you try to have > functions that either have side-effects or return values, but not both. In > practice people sometimes have both (eg. try to do some side-effects, if > they work return a 0 and if they don't return an error code) but try to > avoid it if possible. > > For example, string.strip() has a return value but no side-effects, because > it does not modify the original string, it returns a new copy of the string > that is stripped. Whereas list.sort() has no return value (or it returns > None, depending on how you look at it) because it modifies the _ORIGINAL > LIST_ which is a side-effect. > > As for your function, try to define the side-effects and change them into a > return value. > An example of a side-effect is printing to the screen or writing to a file, > not just modifying global scoped or input variables. > > *************SPOILER***************** > Your side-effect is that you're writing rows to "final". So you should get > rid of all your "final" code and just return the list of rows. I would also > suggest renaming the function to find_zeros() and obviously you would pass > just the input filename. Then you would have another function > write_rows(outfile, rows) and it would output the rows to outfile. I feel > that would be a much cleaner design. write_rows probably won't have a > return value since you're writing to a function (side-effect!) > ***************************************** > > Hope that helps! > -Luke > > > >> Thanks for your input, >> >> Eduardo >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > I agree with Luke's comments. But I'd like to point out an apparent bug (I haven't tried the code, this is just by inspection). You use the test if '0' in row[.....] that's not going to check for a zero value, it's going to check for a zero digit character somewhere in the value. So 504 would also be recognized, as well as 540. Normally, if it's a numeric int field, you want to convert it to int, and check its value, rather than do string manipulations directly, since a value 05 might really be intended to be the same as 5. DaveA From alan.gauld at btinternet.com Tue Oct 27 00:23:45 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Oct 2009 23:23:45 -0000 Subject: [Tutor] Function design References: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> Message-ID: "Eduardo Vieira" wrote > def zerofound(csvfile, outputfile, lastcolumn ): > """Finds columns with zero prices. Column have 0 index""" > final = csv.writer(open(outputfile, 'wb'), dialect='excel') > > reader = csv.reader(open(csvfile, 'rb'), dialect='excel') > for row in reader: > if '0' in row[:lastcolumn]: > final.writerow(row) > My question is. Is it OK to create functions with no "returns"? Yes, its what some other languages call a procedure. But in this case its probably not the best route. > redesign this to use "return"? You could return the number of rows found, that way the user could check for non zero to see if its worthwhile even looking in the output file. Also I think the name of the function could be changed since it actually creates a file of rows with zero. So why not call it write_zero_rows() or somesuch then the row count as a return value would be even more natural. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From transmogribenno at gmail.com Tue Oct 27 12:32:20 2009 From: transmogribenno at gmail.com (Benno Lang) Date: Tue, 27 Oct 2009 20:32:20 +0900 Subject: [Tutor] Function design In-Reply-To: <4AE62F09.9090109@ieee.org> References: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> <4AE62F09.9090109@ieee.org> Message-ID: <9b00d1a90910270432r8fe5b2t5a252a14858684f1@mail.gmail.com> On Tue, Oct 27, 2009 at 8:21 AM, Dave Angel wrote: > I agree with Luke's comments. ?But I'd like to point out an apparent bug (I > haven't tried the code, this is just by inspection). > > You use the test > ? ? if '0' in row[.....] > > that's not going to check for a zero value, it's going to check for a zero > digit character somewhere in the value. ?So 504 would also be recognized, as > well as 540. I thought this sounded rather fishy, along the following lines: row is a list, so slicing it returns a list, so 'in' should compare the list elements (i.e. the strings contained therein) with '0'; this seems perfectly normal. I have checked, and thankfully the world is not upside down. It would only work the way you describe if row was a string, or if 'in' called itself recursively when it found a list. HTH, benno From bibsmendez at gmail.com Tue Oct 27 12:33:14 2009 From: bibsmendez at gmail.com (bibi midi) Date: Tue, 27 Oct 2009 14:33:14 +0300 Subject: [Tutor] Compute data usage from log In-Reply-To: References: <4AE55BEA.9010305@compuscan.co.za> Message-ID: #!/usr/bin/env python # -*- coding: utf-8 -*- ''' Calculate internet data consumption of service provider Code as per help of python tutor mailing list Created: 26-Oct-2009 ''' intro = raw_input('press enter to view your internet data consumption: ') log_file = '/home/bboymen/mobily.data.plan' total_consumed = 0 for line in open(log_file): total_consumed += int(line.split(' ')[9]) total_consumed = total_consumed/1000000.0 print "total data consumed is: %0.3f MB\n" % total_consumed #TODO: #1) show the list comprehension alternative method #2) add exception handling e.g. when log_file cant be found or when key interrupt is pressed # or when index[9] is not a number, etc #3) print latest date of calculated data I'm working on TODO no. 3 e.g. I want to show the latest date when wvdial generated the ppp data. This is normally the date of last line of the ppd: Oct 14 11:03:45 cc000002695 pppd[3092]: Sent 3489538 bytes, received 43317854 bytes. ^^^^^^^^^ For the exception handling i *think* i just use the general exception method e.g. will catch all kinds of error. I really dont know what other errors will show up aside from the ones i listed in the TODO. Advise is appreciated. On Mon, Oct 26, 2009 at 2:12 PM, Luke Paireepinart wrote: > > > On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts wrote: > >> fInput = open('/path/to/log.file', 'rb') >> total_usage = 0 >> for line in fInput: >> total_usage += int(line.split(' ')[9].strip()) >> print total_usage >> > > It's actually bad to assign a variable to the file object in this case > (flinput = ....) because Python will automatically close a file after you're > done with it if you iterate over it directly, but if you include a reference > it will stay open until the python program ends or you explicitly call > flinput.close(). It doesn't matter much in this example but in general it > is good practice to either > 1) call foo.close() immediately after you're done using a file object, or > 2) don't alias the file object and just over it directly so Python will > auto-close it. > > Therefore a better (and simpler) way to do the above would be: > > total_usage = 0 > for line in open('/path/to/log.file'): > total_usage += int(line.split(' ')[9]) > > Also note you don't need to strip the input because int() coersion ignores > whitespace anyway. And additionally you shouldn't be opening this in binary > mode unless you're sure you want to, and I'm guessing the log file is ascii > so there's no need for the 'rb'. (reading is default so we don't specify an > 'r'.) > > > And since I like list comprehensions a lot, I'd probably do it like this > instead: > > total_usage = sum([int(line.split(' ')[9]) for line in > open('/path/to/log.file')]) > > Which incidentally is even shorter, but may be less readable if you don't > use list comprehensions often. > > Also, the list comprehension version is likely to be more efficient, both > because of the use of sum rather than repeated addition (sum is implemented > in C) and because list comprehensions in general are a tad faster than > explicit iteration, if i recall correctly (don't hold me to that though, I > may be wrong.) > >> >> Of course this has no error checking and or niceties, but I will leave >> that up to you. > > The same applies to my modifications. > > Good luck, and let us know if you need anything else! > > -Luke > -- Best Regards, bibimidi -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Oct 27 12:56:57 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 27 Oct 2009 13:56:57 +0200 Subject: [Tutor] Compute data usage from log In-Reply-To: References: <4AE55BEA.9010305@compuscan.co.za> Message-ID: <4AE6E009.6060905@compuscan.co.za> bibi midi wrote: > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > ''' > Calculate internet data consumption > of service provider > Code as per help of python tutor mailing list > Created: 26-Oct-2009 > > ''' > > intro = raw_input('press enter to view your internet data consumption: ') > log_file = '/home/bboymen/mobily.data.plan' > total_consumed = 0 > for line in open(log_file): > total_consumed += int(line.split(' ')[9]) > > > total_consumed = total_consumed/1000000.0 > print "total data consumed is: %0.3f MB\n" % total_consumed > > > #TODO: > #1) show the list comprehension alternative method > #2) add exception handling e.g. when log_file cant be found or when key interrupt is pressed > > # or when index[9] is not a number, etc > #3) print latest date of calculated data > > > I'm working on TODO no. 3 e.g. I want to show the latest date when > wvdial generated the ppp data. This is normally the date of last line > of the ppd: > > Oct 14 11:03:45 cc000002695 pppd[3092]: Sent 3489538 bytes, received > 43317854 bytes. > ^^^^^^^^^ > > For the exception handling i *think* i just use the general exception > method e.g. will catch all kinds of error. I really dont know what > other errors will show up aside from the ones i listed in the TODO. > Advise is appreciated. > > > > > > On Mon, Oct 26, 2009 at 2:12 PM, Luke Paireepinart > > wrote: > > > > On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts > > wrote: > > fInput = open('/path/to/log.file', 'rb') > total_usage = 0 > for line in fInput: > total_usage += int(line.split(' ')[9].strip()) > print total_usage > > > It's actually bad to assign a variable to the file object in this > case (flinput = ....) because Python will automatically close a > file after you're done with it if you iterate over it directly, > but if you include a reference it will stay open until the python > program ends or you explicitly call flinput.close(). It doesn't > matter much in this example but in general it is good practice to > either > 1) call foo.close() immediately after you're done using a file > object, or > 2) don't alias the file object and just over it directly so Python > will auto-close it. > > Therefore a better (and simpler) way to do the above would be: > > total_usage = 0 > for line in open('/path/to/log.file'): > total_usage += int(line.split(' ')[9]) > > Also note you don't need to strip the input because int() coersion > ignores whitespace anyway. And additionally you shouldn't be > opening this in binary mode unless you're sure you want to, and > I'm guessing the log file is ascii so there's no need for the > 'rb'. (reading is default so we don't specify an 'r'.) > > > And since I like list comprehensions a lot, I'd probably do it > like this instead: > > total_usage = sum([int(line.split(' ')[9]) for line in > open('/path/to/log.file')]) > > Which incidentally is even shorter, but may be less readable if > you don't use list comprehensions often. > > Also, the list comprehension version is likely to be more > efficient, both because of the use of sum rather than repeated > addition (sum is implemented in C) and because list comprehensions > in general are a tad faster than explicit iteration, if i recall > correctly (don't hold me to that though, I may be wrong.) > > > Of course this has no error checking and or niceties, but I > will leave that up to you. > > The same applies to my modifications. > > Good luck, and let us know if you need anything else! > > -Luke > > > > > -- > Best Regards, > bibimidi > > Exceptions: * Not finding the log file would be IOError. * Casting an alphanumeric or alpha string to integer would be a ValueError, in this context you won't have a None so you shouldn't need to worry about a TypeError * Selecting the 10th element in your list can raise an IndexError if your line did not contain enough delimiters to create a large enough list. Pedantic: 1MB = 1,024KB = 1,024*1,024B So your total consumed should be div (1024*1024.0) or div 1048576.0 For the date you can look at the time module to get a nice string representation of the date/time. Or as you said you want the last date listed in the log file then you could add something like for line in open(log_file): last_log_date = ' '.join(line.split(' ')[:3] which would take the first 3 elements in your list and combine them again. Of course this is again just a simple representation of what to do. -- Kind Regards, Christian Witts From modulok at gmail.com Tue Oct 27 13:25:14 2009 From: modulok at gmail.com (Modulok) Date: Tue, 27 Oct 2009 06:25:14 -0600 Subject: [Tutor] How to load a dict into a dict subclass? Message-ID: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> List, I'm new to the list, (somewhat new to python too). My code feels hacky. I'd like to know if there is a more eloquent way (more below). If not, a general thumbs up from more experienced programmers would be great! Assume I have a dict, 'foo'. I also have my own class, 'Bar', which subclasses (i.e. is a derived class) of a dict. How do I eloquently get foo into an instace of Bar? Example: ### BEGIN CODE: class Bar(dict): pass # Act like a dict for now. foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return value. myvar = Bar() # The hacky feeling part: for k,v in foo.items(): myvar[k] = v ### END CODE Obviously I can put the dict into an instance variable, but then methods like 'keys()' and such won't work. If that makes any sense... Thanks guys! -Modulok- From bibsmendez at gmail.com Tue Oct 27 13:26:58 2009 From: bibsmendez at gmail.com (bibi midi) Date: Tue, 27 Oct 2009 15:26:58 +0300 Subject: [Tutor] Compute data usage from log In-Reply-To: <4AE6E009.6060905@compuscan.co.za> References: <4AE55BEA.9010305@compuscan.co.za> <4AE6E009.6060905@compuscan.co.za> Message-ID: Hey Christian, There seems to be a missing parenthesis in your join function below. Correct me if I'm wrong. I can live with ppp's time format for now. My script is not world-changing anyway :-). How do i know I'm on the last line of the log file per the code below? Just asking as I'm away from my linux box atm. for line in open(log_file): last_log_date = ' '.join(line.split(' ')[:3]) Thanks. On Tue, Oct 27, 2009 at 2:56 PM, Christian Witts wrote: > bibi midi wrote: > >> #!/usr/bin/env python >> # -*- coding: utf-8 -*- >> >> ''' >> Calculate internet data consumption >> of service provider >> Code as per help of python tutor mailing list >> Created: 26-Oct-2009 >> >> ''' >> >> intro = raw_input('press enter to view your internet data consumption: ') >> log_file = '/home/bboymen/mobily.data.plan' >> total_consumed = 0 >> for line in open(log_file): >> total_consumed += int(line.split(' ')[9]) >> >> >> total_consumed = total_consumed/1000000.0 >> print "total data consumed is: %0.3f MB\n" % total_consumed >> >> >> #TODO: #1) show the list comprehension alternative method >> #2) add exception handling e.g. when log_file cant be found or when key >> interrupt is pressed >> >> # or when index[9] is not a number, etc >> #3) print latest date of calculated data >> >> I'm working on TODO no. 3 e.g. I want to show the latest date when wvdial >> generated the ppp data. This is normally the date of last line of the ppd: >> >> Oct 14 11:03:45 cc000002695 pppd[3092]: Sent 3489538 bytes, received >> 43317854 bytes. >> ^^^^^^^^^ >> >> For the exception handling i *think* i just use the general exception >> method e.g. will catch all kinds of error. I really dont know what other >> errors will show up aside from the ones i listed in the TODO. Advise is >> appreciated. >> >> >> >> >> >> On Mon, Oct 26, 2009 at 2:12 PM, Luke Paireepinart < >> rabidpoobear at gmail.com > wrote: >> >> >> >> On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts >> > wrote: >> >> fInput = open('/path/to/log.file', 'rb') >> total_usage = 0 >> for line in fInput: >> total_usage += int(line.split(' ')[9].strip()) >> print total_usage >> >> >> It's actually bad to assign a variable to the file object in this >> case (flinput = ....) because Python will automatically close a >> file after you're done with it if you iterate over it directly, >> but if you include a reference it will stay open until the python >> program ends or you explicitly call flinput.close(). It doesn't >> matter much in this example but in general it is good practice to >> either >> 1) call foo.close() immediately after you're done using a file >> object, or >> 2) don't alias the file object and just over it directly so Python >> will auto-close it. >> >> Therefore a better (and simpler) way to do the above would be: >> >> total_usage = 0 >> for line in open('/path/to/log.file'): >> total_usage += int(line.split(' ')[9]) >> >> Also note you don't need to strip the input because int() coersion >> ignores whitespace anyway. And additionally you shouldn't be >> opening this in binary mode unless you're sure you want to, and >> I'm guessing the log file is ascii so there's no need for the >> 'rb'. (reading is default so we don't specify an 'r'.) >> >> >> And since I like list comprehensions a lot, I'd probably do it >> like this instead: >> >> total_usage = sum([int(line.split(' ')[9]) for line in >> open('/path/to/log.file')]) >> >> Which incidentally is even shorter, but may be less readable if >> you don't use list comprehensions often. >> >> Also, the list comprehension version is likely to be more >> efficient, both because of the use of sum rather than repeated >> addition (sum is implemented in C) and because list comprehensions >> in general are a tad faster than explicit iteration, if i recall >> correctly (don't hold me to that though, I may be wrong.) >> >> >> Of course this has no error checking and or niceties, but I >> will leave that up to you. >> >> The same applies to my modifications. >> >> Good luck, and let us know if you need anything else! >> >> -Luke >> >> >> >> >> -- >> Best Regards, >> bibimidi >> >> >> > Exceptions: > * Not finding the log file would be IOError. > * Casting an alphanumeric or alpha string to integer would be a ValueError, > in this context you won't have a None so you shouldn't need to worry about a > TypeError > * Selecting the 10th element in your list can raise an IndexError if your > line did not contain enough delimiters to create a large enough list. > > Pedantic: > 1MB = 1,024KB = 1,024*1,024B > So your total consumed should be div (1024*1024.0) or div 1048576.0 > > For the date you can look at the time module to get a nice string > representation of the date/time. Or as you said you want the last date > listed in the log file then you could add something like > > > for line in open(log_file): > last_log_date = ' '.join(line.split(' ')[:3] > > which would take the first 3 elements in your list and combine them again. > Of course this is again just a simple representation of what to do. > > -- > Kind Regards, > Christian Witts > > > -- Best Regards, bibimidi Sent from Riyadh, 01, Saudi Arabia -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Oct 27 13:41:36 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 27 Oct 2009 14:41:36 +0200 Subject: [Tutor] Compute data usage from log In-Reply-To: References: <4AE55BEA.9010305@compuscan.co.za> <4AE6E009.6060905@compuscan.co.za> Message-ID: <4AE6EA80.6000202@compuscan.co.za> bibi midi wrote: > Hey Christian, > > There seems to be a missing parenthesis in your join function below. > Correct me if I'm wrong. > > I can live with ppp's time format for now. My script is not > world-changing anyway :-). How do i know I'm on the last line of the > log file per the code below? Just asking as I'm away from my linux box > atm. > > for line in open(log_file): > last_log_date = ' '.join(line.split(' ')[:3]) > > Thanks. > > > On Tue, Oct 27, 2009 at 2:56 PM, Christian Witts > > wrote: > > bibi midi wrote: > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > ''' > Calculate internet data consumption > of service provider > Code as per help of python tutor mailing list > Created: 26-Oct-2009 > > ''' > > intro = raw_input('press enter to view your internet data > consumption: ') > log_file = '/home/bboymen/mobily.data.plan' > total_consumed = 0 > for line in open(log_file): > total_consumed += int(line.split(' ')[9]) > > > total_consumed = total_consumed/1000000.0 > print "total data consumed is: %0.3f MB\n" % total_consumed > > > #TODO: #1) show the list comprehension alternative method > #2) add exception handling e.g. when log_file cant be found or > when key interrupt is pressed > > # or when index[9] is not a number, etc > #3) print latest date of calculated data > > I'm working on TODO no. 3 e.g. I want to show the latest date > when wvdial generated the ppp data. This is normally the date > of last line of the ppd: > > Oct 14 11:03:45 cc000002695 pppd[3092]: Sent 3489538 bytes, > received 43317854 bytes. > ^^^^^^^^^ > > For the exception handling i *think* i just use the general > exception method e.g. will catch all kinds of error. I really > dont know what other errors will show up aside from the ones i > listed in the TODO. Advise is appreciated. > > > > > > On Mon, Oct 26, 2009 at 2:12 PM, Luke Paireepinart > > >> wrote: > > > > On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts > > >> wrote: > > fInput = open('/path/to/log.file', 'rb') > total_usage = 0 > for line in fInput: > total_usage += int(line.split(' ')[9].strip()) > print total_usage > > > It's actually bad to assign a variable to the file object > in this > case (flinput = ....) because Python will automatically close a > file after you're done with it if you iterate over it directly, > but if you include a reference it will stay open until the > python > program ends or you explicitly call flinput.close(). It > doesn't > matter much in this example but in general it is good > practice to > either > 1) call foo.close() immediately after you're done using a file > object, or > 2) don't alias the file object and just over it directly so > Python > will auto-close it. > > Therefore a better (and simpler) way to do the above would be: > > total_usage = 0 > for line in open('/path/to/log.file'): > total_usage += int(line.split(' ')[9]) > > Also note you don't need to strip the input because int() > coersion > ignores whitespace anyway. And additionally you shouldn't be > opening this in binary mode unless you're sure you want to, and > I'm guessing the log file is ascii so there's no need for the > 'rb'. (reading is default so we don't specify an 'r'.) > > > And since I like list comprehensions a lot, I'd probably do it > like this instead: > > total_usage = sum([int(line.split(' ')[9]) for line in > open('/path/to/log.file')]) > > Which incidentally is even shorter, but may be less readable if > you don't use list comprehensions often. > > Also, the list comprehension version is likely to be more > efficient, both because of the use of sum rather than repeated > addition (sum is implemented in C) and because list > comprehensions > in general are a tad faster than explicit iteration, if i > recall > correctly (don't hold me to that though, I may be wrong.) > > > Of course this has no error checking and or niceties, but I > will leave that up to you. > > The same applies to my modifications. > > Good luck, and let us know if you need anything else! > > -Luke > > > > > -- > Best Regards, > bibimidi > > > > Exceptions: > * Not finding the log file would be IOError. > * Casting an alphanumeric or alpha string to integer would be a > ValueError, in this context you won't have a None so you shouldn't > need to worry about a TypeError > * Selecting the 10th element in your list can raise an IndexError > if your line did not contain enough delimiters to create a large > enough list. > > Pedantic: > 1MB = 1,024KB = 1,024*1,024B > So your total consumed should be div (1024*1024.0) or div 1048576.0 > > For the date you can look at the time module to get a nice string > representation of the date/time. Or as you said you want the last > date listed in the log file then you could add something like > > > for line in open(log_file): > last_log_date = ' '.join(line.split(' ')[:3] > > which would take the first 3 elements in your list and combine > them again. Of course this is again just a simple representation > of what to do. > > -- > Kind Regards, > Christian Witts > > > > > > -- > Best Regards, > bibimidi > > Sent from Riyadh, 01, Saudi Arabia Hi Bibi, Yeah there was a missing parenthesis, I was just typing away. As for knowing if you're on the last line of your log file, basically what will happen is for every line you iterate through it will parse the first 3 elements of your line and use that for the last_log_date. If you know for certain that every line will start with the time stamp then it will work fine, if that is not the case then you will need to build in some checking to ensure you get the correct information. -- Kind Regards, Christian Witts From cwitts at compuscan.co.za Tue Oct 27 13:45:28 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 27 Oct 2009 14:45:28 +0200 Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> Message-ID: <4AE6EB68.40807@compuscan.co.za> Modulok wrote: > List, > > I'm new to the list, (somewhat new to python too). My code feels > hacky. I'd like to know if there is a more eloquent way (more below). > If not, a general thumbs up from more experienced programmers would be > great! > > Assume I have a dict, 'foo'. I also have my own class, 'Bar', which > subclasses (i.e. is a derived class) of a dict. How do I eloquently > get foo into an instace of Bar? Example: > > > ### BEGIN CODE: > class Bar(dict): > pass # Act like a dict for now. > > foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return value. > myvar = Bar() > # The hacky feeling part: > for k,v in foo.items(): myvar[k] = v > > ### END CODE > > Obviously I can put the dict into an instance variable, but then > methods like 'keys()' and such won't work. If that makes any sense... > > Thanks guys! > -Modulok- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You can use the built-in function for dictionaries called update. So >>> class Bar(dict): >>> pass >>> foo = {'a':100, 'b':200, 'c': 300} >>> myvar = Bar() >>> myvar.update(foo) >>> myvar {'a': 100, 'c': 300, 'b': 200} -- Kind Regards, Christian Witts From bibsmendez at gmail.com Tue Oct 27 14:21:18 2009 From: bibsmendez at gmail.com (bibi midi) Date: Tue, 27 Oct 2009 09:21:18 -0400 Subject: [Tutor] Compute data usage from log In-Reply-To: <4AE6EA80.6000202@compuscan.co.za> References: <4AE55BEA.9010305@compuscan.co.za> <4AE6E009.6060905@compuscan.co.za> <4AE6EA80.6000202@compuscan.co.za> Message-ID: Yep it works! I understand now it iterates on each line and replaces the old elements with the new ones. In the end you get the latest date of the last line of log. I will work on the exception handling and other refinements. Thanks. On Tue, Oct 27, 2009 at 8:41 AM, Christian Witts wrote: > > >> for line in open(log_file): >> last_log_date = ' '.join(line.split(' ')[:3] >> >> which would take the first 3 elements in your list and combine >> them again. Of course this is again just a simple representation >> of what to do. >> >> -- Kind Regards, >> Christian Witts >> >> >> >> >> >> -- >> Best Regards, >> bibimidi >> >> Sent from Riyadh, 01, Saudi Arabia >> > > > Hi Bibi, > > Yeah there was a missing parenthesis, I was just typing away. > As for knowing if you're on the last line of your log file, basically what > will happen is for every line you iterate through it will parse the first 3 > elements of your line and use that for the last_log_date. > If you know for certain that every line will start with the time stamp then > it will work fine, if that is not the case then you will need to build in > some checking to ensure you get the correct information. > > -- > Kind Regards, > Christian Witts > > > -- Best Regards, bibimidi -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Tue Oct 27 14:25:13 2009 From: washakie at gmail.com (John) Date: Tue, 27 Oct 2009 14:25:13 +0100 Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: <4AE6EB68.40807@compuscan.co.za> References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> <4AE6EB68.40807@compuscan.co.za> Message-ID: I use a 'SuperDict' all the time in my code. Not sure it's a good idea, but I find it convenient. Also, I wouldn't mind comments on why/why not to use something like this: class SuperDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value def set_with_dict(self,D): """ set attributes with a dict """ for k in D.keys(): self.__setattr__(k,D[k]) Here's the original thread (NOTE: I have also been trying to use more structured arrays as recommended by one poster): http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-this-one-may-take-some-thought--%29-td23759398.html On Tue, Oct 27, 2009 at 1:45 PM, Christian Witts wrote: > Modulok wrote: > >> List, >> >> I'm new to the list, (somewhat new to python too). My code feels >> hacky. I'd like to know if there is a more eloquent way (more below). >> If not, a general thumbs up from more experienced programmers would be >> great! >> >> Assume I have a dict, 'foo'. I also have my own class, 'Bar', which >> subclasses (i.e. is a derived class) of a dict. How do I eloquently >> get foo into an instace of Bar? Example: >> >> >> ### BEGIN CODE: >> class Bar(dict): >> pass # Act like a dict for now. >> >> foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return >> value. >> myvar = Bar() >> # The hacky feeling part: >> for k,v in foo.items(): myvar[k] = v >> >> ### END CODE >> >> Obviously I can put the dict into an instance variable, but then >> methods like 'keys()' and such won't work. If that makes any sense... >> >> Thanks guys! >> -Modulok- >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > You can use the built-in function for dictionaries called update. So > > >>> class Bar(dict): > >>> pass > > > >>> foo = {'a':100, 'b':200, 'c': 300} > >>> myvar = Bar() > >>> myvar.update(foo) > >>> myvar > {'a': 100, 'c': 300, 'b': 200} > > -- > Kind Regards, > Christian Witts > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Tue Oct 27 16:20:58 2009 From: jfabiani at yolo.com (John) Date: Tue, 27 Oct 2009 08:20:58 -0700 Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> <4AE6EB68.40807@compuscan.co.za> Message-ID: <200910270820.59031.jfabiani@yolo.com> On Tuesday 27 October 2009 06:25:13 am John wrote: > I use a 'SuperDict' all the time in my code. Not sure it's a good idea, but > I find it convenient. Also, I wouldn't mind comments on why/why not to use > something like this: > > class SuperDict(dict): > def __getattr__(self, attr): > return self[attr] > def __setattr__(self, attr, value): > self[attr] = value > > def set_with_dict(self,D): > """ set attributes with a dict """ > for k in D.keys(): > self.__setattr__(k,D[k]) > > Here's the original thread (NOTE: I have also been trying to use more > structured arrays as recommended by one poster): > http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-th >is-one-may-take-some-thought--%29-td23759398.html > > On Tue, Oct 27, 2009 at 1:45 PM, Christian Witts wrote: > > Modulok wrote: > >> List, > >> > >> I'm new to the list, (somewhat new to python too). My code feels > >> hacky. I'd like to know if there is a more eloquent way (more below). > >> If not, a general thumbs up from more experienced programmers would be > >> great! > >> > >> Assume I have a dict, 'foo'. I also have my own class, 'Bar', which > >> subclasses (i.e. is a derived class) of a dict. How do I eloquently > >> get foo into an instace of Bar? Example: > >> > >> > >> ### BEGIN CODE: > >> class Bar(dict): > >> pass # Act like a dict for now. > >> > >> foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return > >> value. > >> myvar = Bar() > >> # The hacky feeling part: > >> for k,v in foo.items(): myvar[k] = v > >> > >> ### END CODE > >> > >> Obviously I can put the dict into an instance variable, but then > >> methods like 'keys()' and such won't work. If that makes any sense... > >> > >> Thanks guys! > >> -Modulok- > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > > > > You can use the built-in function for dictionaries called update. So > > > > >>> class Bar(dict): > > >>> pass > > >>> > > >>> > > >>> foo = {'a':100, 'b':200, 'c': 300} > > >>> myvar = Bar() > > >>> myvar.update(foo) > > >>> myvar > > > > {'a': 100, 'c': 300, 'b': 200} > > > > -- > > Kind Regards, > > Christian Witts Hey guru's could one of you explain why such a subclass is needed. How would it be used. I'm not sure but does not the deepcopy() work as above? Thanks Johnf From srilyk at gmail.com Tue Oct 27 16:44:47 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 27 Oct 2009 10:44:47 -0500 Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: <200910270820.59031.jfabiani@yolo.com> References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> <4AE6EB68.40807@compuscan.co.za> <200910270820.59031.jfabiani@yolo.com> Message-ID: <333efb450910270844x1dfce669uf94e347cbd3b8109@mail.gmail.com> On Tue, Oct 27, 2009 at 10:20 AM, John wrote: > > Hey guru's could one of you explain why such a subclass is needed. How > would > it be used. I'm not sure but does not the deepcopy() work as above? A subclass is useful for when you want to do pretty much what another class does, only with some modifications. My favorite example (and the easiest to understand) deals with shapes: class Shape: def __init__(self): self.sides = 0 self.area = 0 class Triangle(Shape): Shape.__init__(self) def __init__(self, base=0, height=0): self.sides = 3 self.area = base/2*height class Circle(Shape): Shape.__init__(self) def __init__(self, radius): self.sides = 1 self.area = 2*3.14*radius There are many other times when subclasses are useful, but that's a nice simple example. The "is-a" relationship can tell you when it's useful to have a superclass. "This collection is a list of (un)ordered elements" would tell you it should be a list. Though, TBH most python objects are so "batteries" included that I have little (no) reason to subclass - my only real exception is GUI programming. Here's something Google pulled up on the subject: http://www.gidnetwork.com/b-137.html HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Oct 27 17:14:58 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 27 Oct 2009 11:14:58 -0500 Subject: [Tutor] Function design In-Reply-To: <9b00d1a90910270432r8fe5b2t5a252a14858684f1@mail.gmail.com> References: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> <4AE62F09.9090109@ieee.org> <9b00d1a90910270432r8fe5b2t5a252a14858684f1@mail.gmail.com> Message-ID: <4AE71C82.1070004@ieee.org> Benno Lang wrote: > On Tue, Oct 27, 2009 at 8:21 AM, Dave Angel wrote: > >> I agree with Luke's comments. But I'd like to point out an apparent bug (I >> haven't tried the code, this is just by inspection). >> >> You use the test >> if '0' in row[.....] >> >> that's not going to check for a zero value, it's going to check for a zero >> digit character somewhere in the value. So 504 would also be recognized, as >> well as 540. >> > > I thought this sounded rather fishy, along the following lines: > row is a list, so slicing it returns a list, so 'in' should compare > the list elements (i.e. the strings contained therein) with '0'; this > seems perfectly normal. > > I have checked, and thankfully the world is not upside down. It would > only work the way you describe if row was a string, or if 'in' called > itself recursively when it found a list. > > HTH, > benno > > You are quite right, of course. I somehow missed that it was a slice, and took it instead to be a simple subscript. But if the file contained 0.00 as one of its items, this code would still have the other problem I mentioned. DaveA From davea at ieee.org Tue Oct 27 17:24:51 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 27 Oct 2009 11:24:51 -0500 Subject: [Tutor] Compute data usage from log In-Reply-To: References: <4AE55BEA.9010305@compuscan.co.za> <4AE6E009.6060905@compuscan.co.za> <4AE6EA80.6000202@compuscan.co.za> Message-ID: <4AE71ED3.9010804@ieee.org> (For some reason you keep top-posting. Add your comments to the end, or inline if appropriate) bibi midi wrote: > Yep it works! I understand now it iterates on each line and replaces the old > elements with the new ones. In the end you get the latest date of the last > line of log. > > I will work on the exception handling and other refinements. Thanks. > > > > On Tue, Oct 27, 2009 at 8:41 AM, Christian Witts wrote: > > >> >> >>> for line in open(log_file): >>> last_log_date = ' '.join(line.split(' ')[:3] >>> >>> > In an earlier example, you already had a for loop on the log_file so the last line would still be in the variable "line". If you put the date logic right after the loop, there'd be nothing wrong with using the last line that way. Beats going back through the file and repeating it all again. DaveA From asterix09 at petlover.com Tue Oct 27 16:35:09 2009 From: asterix09 at petlover.com (asterix09 at petlover.com) Date: Tue, 27 Oct 2009 11:35:09 -0400 Subject: [Tutor] New to Python Message-ID: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> Hi there, How do you connect to a different server using python? (I have not used python before) Your help would be much appreciated. Kindest Regards, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Oct 27 17:53:27 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 27 Oct 2009 11:53:27 -0500 Subject: [Tutor] New to Python In-Reply-To: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> Message-ID: <333efb450910270953l1d01a180s33c471ee3d9ae273@mail.gmail.com> On Tue, Oct 27, 2009 at 10:35 AM, wrote: > Hi there, > > How do you connect to a different server using python? (I have not used > python before) > What kind of server? What do you ultimately want to do? see: http://catb.org/~esr/faqs/smart-questions.html#beprecise for more info about asking good questions. We can't help you if we don't know what you want. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Oct 27 18:16:38 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Oct 2009 13:16:38 -0400 Subject: [Tutor] New to Python In-Reply-To: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> Message-ID: <1c2a2c590910271016t792bd5d0sc2a5212c464fc331@mail.gmail.com> On Tue, Oct 27, 2009 at 11:35 AM, wrote: > Hi there, > > How do you connect to a different server using python? (I have not used > python before) What kind of connection? The Python standard library includes modules which support raw sockets, http, ftp, smtp, xml-rpc and probably a few others. Paramiko is an add-on that supports ssh2 connection. Kent From wescpy at gmail.com Tue Oct 27 18:18:17 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 27 Oct 2009 10:18:17 -0700 Subject: [Tutor] ANN: Python course, San Francisco, Nov 9-11 In-Reply-To: <78b3a9580910271004ve2afee8j3b222c374dea0d7@mail.gmail.com> References: <78b3a9580910271004ve2afee8j3b222c374dea0d7@mail.gmail.com> Message-ID: <78b3a9580910271018p3d479f10n4196de9e2c469adb@mail.gmail.com> hey gang, not sure i made the original announcement on this list a few months ago, but if you're on this list because you need to learn Python as quickly and as in-depth as possible for an immediate need, i have few more openings in my upcoming course in San Francisco, and below is the reminder i've just sent out recently to the community at-large: *FINAL REMINDER* come join us for another hardcore Python training course in San Francisco coming up in a few weeks! we have a few more slots available. bring your co-workers to take advantage of our multiple registration discount. we also feature a steeper discount for those who are primary/secondary teachers, students, as well as to those who have been more severely impacted by the economy. here is my original announcement for more info: http://mail.python.org/pipermail/python-list/2009-September/196228.html hope to meet you soon! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ?http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Tue Oct 27 18:40:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Oct 2009 17:40:04 -0000 Subject: [Tutor] New to Python References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> Message-ID: wrote > How do you connect to a different server using python? > (I have not used python before) Have you programmed before? If so in what languages? If you are a complete novice any kind of network programming is quite a challenge. If you are experienced can you give us a bit more context? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 27 18:45:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Oct 2009 17:45:41 -0000 Subject: [Tutor] How to load a dict into a dict subclass? References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com><4AE6EB68.40807@compuscan.co.za> <200910270820.59031.jfabiani@yolo.com> Message-ID: "John" wrote >> > >>> class Bar(dict): >> > >>> pass >> > >>> >> > >>> foo = {'a':100, 'b':200, 'c': 300} >> > >>> myvar = Bar() >> > >>> myvar.update(foo) >> > >>> myvar >> > >> > {'a': 100, 'c': 300, 'b': 200} > > Hey guru's could one of you explain why such a subclass is needed. How > would > it be used. I'm not sure but does not the deepcopy() work as above? This particular subclass does nothing different to the normal dict so its never needed. But it's only a demo of how to use the standard dict methods in a subclass. In general you might subclass a dict if you wanted to change the behaviour of some specific method, or maybe add some new methods. Or maybe you wanted a dictionary that could take a list as a key... or even take a list of keys and return a list of values. Lots of reasons for wanting to modify the standard dict behaviour. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Oct 27 18:49:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Oct 2009 17:49:33 -0000 Subject: [Tutor] How to load a dict into a dict subclass? References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> <4AE6EB68.40807@compuscan.co.za> <200910270820.59031.jfabiani@yolo.com> <333efb450910270844x1dfce669uf94e347cbd3b8109@mail.gmail.com> Message-ID: "Wayne" wrote > My favorite example (and the easiest to understand) deals with shapes: > > class Shape: > def __init__(self): > self.sides = 0 > self.area = 0 > > class Triangle(Shape): > Shape.__init__(self) > def __init__(self, base=0, height=0): > self.sides = 3 > self.area = base/2*height Shouldn't the Shape.__init__() call be inside the constructor? Or is there some deep subtle thing going on here that I'm missing? Also how does subclassing Shape add any value here since we just create local instance vars for sides and area anyway if they don't already exist? Or is this a case of simplifying an example one step too far? Confusedly, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eduardo.susan at gmail.com Tue Oct 27 19:08:19 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 27 Oct 2009 12:08:19 -0600 Subject: [Tutor] Function design In-Reply-To: <4AE71C82.1070004@ieee.org> References: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> <4AE62F09.9090109@ieee.org> <9b00d1a90910270432r8fe5b2t5a252a14858684f1@mail.gmail.com> <4AE71C82.1070004@ieee.org> Message-ID: <9356b9f30910271108m38156791ma3d5da830f023d3b@mail.gmail.com> On Tue, Oct 27, 2009 at 10:14 AM, Dave Angel wrote: > Benno Lang wrote: >> >> On Tue, Oct 27, 2009 at 8:21 AM, Dave Angel wrote: >> >>> >>> I agree with Luke's comments. ?But I'd like to point out an apparent bug >>> (I >>> haven't tried the code, this is just by inspection). >>> >>> You use the test >>> ? ?if '0' in row[.....] >>> >>> that's not going to check for a zero value, it's going to check for a >>> zero >>> digit character somewhere in the value. ?So 504 would also be recognized, >>> as >>> well as 540. >>> >> >> I thought this sounded rather fishy, along the following lines: >> row is a list, so slicing it returns a list, so 'in' should compare >> the list elements (i.e. the strings contained therein) with '0'; this >> seems perfectly normal. >> >> I have checked, and thankfully the world is not upside down. It would >> only work the way you describe if row was a string, or if 'in' called >> itself recursively when it found a list. >> >> HTH, >> benno >> >> > > You are quite right, of course. ?I somehow missed that it was a slice, and > took it instead to be a simple subscript. > > But if the file contained ?0.00 as one of its items, this code would still > have the other problem I mentioned. > > DaveA > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for your pointers, Dave. Actually the csv file have data like this: CAOCA-SD3,OCA - Sign Design Elements Vol. 3,0,0,0,0,0,0,0,0,0,0,0,0 At first I thought that the csv module would do type coercion and my original code was: if 0 in row but nothing was caught. so I change it to: if '0' in row and all was well. Especially to Luke and Alan: Yes. A function returning the number of rows with zeros seems like a sensible decision. I'm enjoying the input from this community. I first started diving into programming using AutoHotkey, for a lot of automation stuff on windows. Autohotkey is very much procedure oriented, and you can even record macros. The scripting language allows functions and several other advanced features. Sometimes I have a need and think. Let me quick do this using either Autohotkey or Python. Sometimes both. I am glad that especially being exposed to Python I am learning how to design my code for reuse, making things more flexible, etc. Thanks again. Regards, Eduardo www.expresssignproducts.com From eduardo.susan at gmail.com Tue Oct 27 19:15:00 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 27 Oct 2009 12:15:00 -0600 Subject: [Tutor] Compute data usage from log In-Reply-To: References: <4AE55BEA.9010305@compuscan.co.za> Message-ID: <9356b9f30910271115t650ad311t6690a750f1ebdb2c@mail.gmail.com> On Tue, Oct 27, 2009 at 5:33 AM, bibi midi wrote: > #!/usr/bin/env python > # -*- coding: utf-8 -*- > > ''' > Calculate internet data consumption > of service provider > Code as per help of python tutor mailing list > Created: 26-Oct-2009 > > ''' > > intro = raw_input('press enter to view your internet data consumption: ') > log_file = '/home/bboymen/mobily.data.plan' > total_consumed = 0 > for line in open(log_file): > total_consumed += int(line.split(' ')[9]) > > > total_consumed = total_consumed/1000000.0 > print "total data consumed is: %0.3f MB\n" % total_consumed > > > #TODO: > #1) show the list comprehension alternative method > #2) add exception handling e.g. when log_file cant be found or when key > interrupt is pressed > > # or when index[9] is not a number, etc > #3) print latest date of calculated data > > I'm working on TODO no. 3 e.g. I want to show the latest date when wvdial > generated the ppp data. This is normally the date of last line of the ppd: > > Oct 14 11:03:45 cc000002695 pppd[3092]: Sent 3489538 bytes, received > 43317854 bytes. > ^^^^^^^^^ > > For the exception handling i *think* i just use the general exception method > e.g. will catch all kinds of error. I really dont know what other errors > will show up aside from the ones i listed in the TODO. Advise is > appreciated. > > > > > > On Mon, Oct 26, 2009 at 2:12 PM, Luke Paireepinart > wrote: >> >> >> On Mon, Oct 26, 2009 at 3:20 AM, Christian Witts >> wrote: >>> >>> fInput = open('/path/to/log.file', 'rb') >>> total_usage = 0 >>> for line in fInput: >>> ? total_usage += int(line.split(' ')[9].strip()) >>> print total_usage >> >> It's actually bad to assign a variable to the file object in this case >> (flinput = ....) because Python will automatically close a file after you're >> done with it if you iterate over it directly, but if you include a reference >> it will stay open until the python program ends or you explicitly call >> flinput.close().? It doesn't matter much in this example but in general it >> is good practice to either >> 1) call foo.close() immediately after you're done using a file object, or >> 2) don't alias the file object and just over it directly so Python will >> auto-close it. >> >> Therefore a better (and simpler) way to do the above would be: >> >> total_usage = 0 >> for line in open('/path/to/log.file'): >> ? ? total_usage += int(line.split(' ')[9]) >> >> Also note you don't need to strip the input because int() coersion ignores >> whitespace anyway. And additionally you shouldn't be opening this in binary >> mode unless you're sure you want to, and I'm guessing the log file is ascii >> so there's no need for the 'rb'.? (reading is default so we don't specify an >> 'r'.) >> >> >> And since I like list comprehensions a lot, I'd probably do it like this >> instead: >> >> total_usage = sum([int(line.split(' ')[9]) for line in >> open('/path/to/log.file')]) >> >> Which incidentally is even shorter, but may be less readable if you don't >> use list comprehensions often. >> >> Also, the list comprehension version is likely to be more efficient, both >> because of the use of sum rather than repeated addition (sum is implemented >> in C) and because list comprehensions in general are a tad faster than >> explicit iteration, if i recall correctly (don't hold me to that though, I >> may be wrong.) >>> >>> Of course this has no error checking and or niceties, but I will leave >>> that up to you. >> >> The same applies to my modifications. >> >> Good luck, and let us know if you need anything else! >> >> -Luke > > > > -- > Best Regards, > bibimidi > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I think you could benefit a lot from the code examples given by Dave Beazley in his presentation about generators. There are scripts that deal with just about exactly what you're looking for. Very informative material: http://www.dabeaz.com/generators/ See the presentation slides HTH Eduardo From fomcl at yahoo.com Tue Oct 27 20:02:13 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 27 Oct 2009 12:02:13 -0700 (PDT) Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: Message-ID: <410239.80603.qm@web110712.mail.gq1.yahoo.com> I thought reimplementing dict was a matter of defining a __dict__ attribute in the Bar class? And isn't the normal dict inherited anyway? (through __super__) Or, if one would want to disable inheritance of the normal dict, one could use __slots__. Right? Or did I misinterpret the New Testament of my Python Bible? Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Before you criticize someone, walk a mile in their shoes, that way when you do criticize them, you're a mile away and you have their shoes! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- On Tue, 10/27/09, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] How to load a dict into a dict subclass? > To: tutor at python.org > Date: Tuesday, October 27, 2009, 6:45 PM > > "John" > wrote > > >> > >>> class Bar(dict): > >> > >>>? ???pass > >> > >>> > >> > >>> foo = {'a':100, 'b':200, 'c': > 300} > >> > >>> myvar = Bar() > >> > >>> myvar.update(foo) > >> > >>> myvar > >> > > >> > {'a': 100, 'c': 300, 'b': 200} > > > > Hey guru's could one of you explain why such a > subclass is needed.? How would > > it be used.? I'm not sure but does not the > deepcopy() work as above? > > This particular subclass does nothing different to the > normal dict so its > never needed. But it's only a demo of how to use the > standard dict > methods in a subclass. > > In general you might subclass a dict if you wanted to > change the > behaviour of some specific method, or maybe add some new > methods. > Or maybe you wanted a dictionary that could take a list as > a key... > or even take a list of keys and return a list of values. > > Lots of reasons for wanting to modify the standard dict > behaviour. > > -- Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From jonesv76 at gmail.com Tue Oct 27 20:15:20 2009 From: jonesv76 at gmail.com (Vincent Jones) Date: Tue, 27 Oct 2009 15:15:20 -0400 Subject: [Tutor] Error Message-ID: I created database using the 'python manage.py sycdb' then proceeded to 'python manage.py sql bookmarks' and i receive this error: Error: App with label bookmarks could not be found. Are you sure your INSTALLED_APPS settings is correct? I go to Settings py and the INSTALLED_APPS is 'django_bookmarks.bookmarks', I also looked in the directory 'django_bookmarks' and there is a directory bookmarks within it so what am i doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Oct 27 20:36:55 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 27 Oct 2009 14:36:55 -0500 Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> <4AE6EB68.40807@compuscan.co.za> <200910270820.59031.jfabiani@yolo.com> <333efb450910270844x1dfce669uf94e347cbd3b8109@mail.gmail.com> Message-ID: <333efb450910271236nd2d4819xd7fe9702625da4ce@mail.gmail.com> On Tue, Oct 27, 2009 at 12:49 PM, Alan Gauld wrote: > > "Wayne" wrote > >> My favorite example (and the easiest to understand) deals with shapes: >> >> class Shape: >> def __init__(self): >> self.sides = 0 >> self.area = 0 >> >> class Triangle(Shape): >> Shape.__init__(self) >> def __init__(self, base=0, height=0): >> self.sides = 3 >> self.area = base/2*height >> > > Shouldn't the Shape.__init__() call be inside the constructor? > Or is there some deep subtle thing going on here that I'm missing? > > Also how does subclassing Shape add any value here since we just create > local instance vars for sides and area anyway > if they don't already exist? > > Or is this a case of simplifying an example one step too far? > > Confusedly, > > Probably, to all of the above it's applicable to - I've (1) been coding in C++ all morning, (2) was kinda in a hurry, and (3) haven't seen the *actual* example I saw in my CS class for at least a year - it was just the concept of using subclasses that stayed with me. There's probably a wealth of better information out there for the curious individual, and I probably should have just grabbed a link. I'm presuming if you were really doing something like that, the Shape class would take more arguments for instantiation, as well as do some other more useful things. Doh! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Tue Oct 27 20:42:53 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 27 Oct 2009 13:42:53 -0600 Subject: [Tutor] Function design In-Reply-To: <4AE71C82.1070004@ieee.org> References: <9356b9f30910261208l60c36cabj3ad88ca5babafcad@mail.gmail.com> <4AE62F09.9090109@ieee.org> <9b00d1a90910270432r8fe5b2t5a252a14858684f1@mail.gmail.com> <4AE71C82.1070004@ieee.org> Message-ID: <9356b9f30910271242q26b056cfn534a461167ae4073@mail.gmail.com> On Tue, Oct 27, 2009 at 10:14 AM, Dave Angel wrote: > > But if the file contained ?0.00 as one of its items, this code would still > have the other problem I mentioned. > > DaveA > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yes. I noticed that in another file: I had to change the line to: if '0' in row[:lastcolumn] or '0.0' in row[:lastcolumn]: I tried to express that by doing this: if '0' or '0.0' in row[:lastcolumn]: and I got very wrong results... Ouch! Don't think python is that close to English... Eduardo From kent37 at tds.net Tue Oct 27 21:57:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Oct 2009 16:57:25 -0400 Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: <410239.80603.qm@web110712.mail.gq1.yahoo.com> References: <410239.80603.qm@web110712.mail.gq1.yahoo.com> Message-ID: <1c2a2c590910271357v68e31736i164d2d0a0d8aa61b@mail.gmail.com> On Tue, Oct 27, 2009 at 3:02 PM, Albert-Jan Roskam wrote: > I thought reimplementing dict was a matter of defining a __dict__ attribute in the Bar class? And isn't the normal dict inherited anyway? (through __super__) > > Or, if one would want to disable inheritance of the normal dict, one could use __slots__. Right? > > Or did I misinterpret the New Testament of my Python Bible? You are confusing the __dict__ attribute of most objects with the dict (dictionary) type. The OP is interested in subclassing the dict type. Kent From emile at fenx.com Wed Oct 28 00:49:52 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 27 Oct 2009 16:49:52 -0700 Subject: [Tutor] Error In-Reply-To: References: Message-ID: On 10/27/2009 12:15 PM Vincent Jones said... > I created database using the 'python manage.py sycdb' You're likely to get answers quickly on the django mailing list. Emile From erimendz at gmail.com Wed Oct 28 04:29:37 2009 From: erimendz at gmail.com (Eri Mendz) Date: Wed, 28 Oct 2009 06:29:37 +0300 Subject: [Tutor] Compute data usage from log In-Reply-To: <4AE71ED3.9010804@ieee.org> References: <4AE55BEA.9010305@compuscan.co.za> <4AE6E009.6060905@compuscan.co.za> <4AE6EA80.6000202@compuscan.co.za> <4AE71ED3.9010804@ieee.org> Message-ID: <88d91f010910272029x503971a0wc81243ef4475454@mail.gmail.com> On Tue, Oct 27, 2009 at 7:24 PM, Dave Angel wrote: > (For some reason you keep top-posting. ?Add your comments to the end, or > inline if appropriate) > Hi Dave, Noted the top posting thing thanks for reminding :-) > > In an earlier example, you already had a for loop on the log_file so the > last line would still be in the variable "line". ?If you put the date logic > right after the loop, there'd be nothing wrong with using the last line that > way. ? Beats going back through the file and repeating it all again. > > DaveA Yes i agree. I put the date variable after last line of the for loop. And it works as expected. -- Best Regards From modulok at gmail.com Wed Oct 28 08:46:09 2009 From: modulok at gmail.com (Modulok) Date: Wed, 28 Oct 2009 01:46:09 -0600 Subject: [Tutor] How to load a dict into a dict subclass? In-Reply-To: <4AE6EB68.40807@compuscan.co.za> References: <64c038660910270525o785eccefm2a901d3a8c560cee@mail.gmail.com> <4AE6EB68.40807@compuscan.co.za> Message-ID: <64c038660910280046m2a8b0d93wb3e20b5cf98cdaa6@mail.gmail.com> ... >> Assume I have a dict, 'foo'. I also have my own class, 'Bar', which >> subclasses (i.e. is a derived class) of a dict. How do I eloquently >> get foo into an instace of Bar? Example: >> >> >> ### BEGIN CODE: >> class Bar(dict): >> pass # Act like a dict for now. >> >> foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return >> value. >> myvar = Bar() >> # The hacky feeling part: >> for k,v in foo.items(): myvar[k] = v >> >> ### END CODE >> > You can use the built-in function for dictionaries called update. So > > >>> class Bar(dict): > >>> pass > > >>> foo = {'a':100, 'b':200, 'c': 300} > >>> myvar = Bar() > >>> myvar.update(foo) > >>> myvar > {'a': 100, 'c': 300, 'b': 200} ... Thanks guys! Christian, that's just what I was looking for. Thank you! -Modulok- From srilyk at gmail.com Wed Oct 28 11:05:38 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 28 Oct 2009 05:05:38 -0500 Subject: [Tutor] Fwd: New to Python In-Reply-To: <8CC25AB05638F8C-DB0-101E@web-mmc-m03.sysops.aol.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> <333efb450910270953l1d01a180s33c471ee3d9ae273@mail.gmail.com> <8CC25AB05638F8C-DB0-101E@web-mmc-m03.sysops.aol.com> Message-ID: <333efb450910280305h565a9d9dndb10a6171c32e14e@mail.gmail.com> Remember to hit Reply to all - Forwarding your message onto the list ---------- Forwarded message ---------- From: Date: Wed, Oct 28, 2009 at 1:00 AM Subject: Re: [Tutor] New to Python To: srilyk at gmail.com Hi Wayne, I will try as best to explain what I need to do. I have a log file. In that log file thre contains text. Something along the lines of this. 115=WAS 115=GAD 115=TRE I need to search that log file (thought of using grep) and write each text after the "=" sign to another text file. So the other text file (call it "* List*") will contain a list of all the differernt values for 115. After I have created that, i then need to run a script that will run through the latest log file and compare the *List *from the log file and any new 115=... values that are not in the* List *text file must be added, vice versa. End result is that I want to track and see how many values I can get in the 115=... The log file is siuated on a different server/machine on my network, so I want the script to be able to copy the log file from the server to my machine. I hope that makes sense. Many thanks for your help. -----Original Message----- From: Wayne To: asterix09 at petlover.com Cc: tutor at python.org Sent: Tue, Oct 27, 2009 6:53 pm Subject: Re: [Tutor] New to Python On Tue, Oct 27, 2009 at 10:35 AM, wrote: > Hi there, > > How do you connect to a different server using python? (I have not used > python before) > What kind of server? What do you ultimately want to do? see: http://catb.org/~esr/faqs/smart-questions.html#beprecise for more info about asking good questions. We can't help you if we don't know what you want. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From mahasen_d at yahoo.com Wed Oct 28 06:44:40 2009 From: mahasen_d at yahoo.com (Mahasen Dehideniya) Date: Tue, 27 Oct 2009 22:44:40 -0700 (PDT) Subject: [Tutor] Access PostGreSQL 8.3 by python 2.5 Message-ID: <897802.87764.qm@web63205.mail.re1.yahoo.com> Hi , I'm try to access PostGreSQL 8.3 by python 2.5. I'm working on winXP. I use pg module. At the first time i get error that no found dll. when i add C:\Program Files\PostgreSQL\8.3\bin to? the path variable i able to fixed it. After that? i get following error. ? >>> import pg Traceback (most recent call last): ? File "", line 1, in ??? import pg ? File "C:\Python25\Lib\site-packages\pg.py", line 21, in ??? from _pg import * ImportError: DLL load failed with error code 182 ? Can any one tell me how I fixed this error? ? Thank in advance. ? Mahasen -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Oct 28 12:18:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Oct 2009 07:18:04 -0400 Subject: [Tutor] New to Python In-Reply-To: <8CC25AB49AD018C-DB0-1021@web-mmc-m03.sysops.aol.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> <1c2a2c590910271016t792bd5d0sc2a5212c464fc331@mail.gmail.com> <8CC25AB49AD018C-DB0-1021@web-mmc-m03.sysops.aol.com> Message-ID: <1c2a2c590910280418g21990500g35e1507d3d98b1bd@mail.gmail.com> Forwarding to the list with my reply (please use Reply All to reply to the list): On Wed, Oct 28, 2009 at 2:01 AM, wrote: > Hi Kent, > > Thank you for replying to my request, really appreciate it. > > I am not familiar with all your connections that you have mentioned below. > > What I can tell you which I hope can help is that I have a log file on a > different server/machine on a network which I would like to copy and paste > on my machine? How would you copy the file if you did it by hand? Is the server file system accessible to your machine? If so, you can copy it with shutil.copyfile() or just open it and process it directly. Kent From kent37 at tds.net Wed Oct 28 12:40:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Oct 2009 07:40:19 -0400 Subject: [Tutor] Access PostGreSQL 8.3 by python 2.5 In-Reply-To: <897802.87764.qm@web63205.mail.re1.yahoo.com> References: <897802.87764.qm@web63205.mail.re1.yahoo.com> Message-ID: <1c2a2c590910280440i531c82e9h633f4f9570d897a6@mail.gmail.com> On Wed, Oct 28, 2009 at 1:44 AM, Mahasen Dehideniya wrote: > Hi , > > I'm try to access PostGreSQL 8.3 by python 2.5. I'm working on winXP. > > I use pg module. > > At the first time i get error that no found dll. when i add C:\Program > Files\PostgreSQL\8.3\bin to? the path variable i able to fixed it. > > After that? i get following error. > > > >>>> import pg > > Traceback (most recent call last): > ? File "", line 1, in > ??? import pg > ? File "C:\Python25\Lib\site-packages\pg.py", line 21, in > ??? from _pg import * > ImportError: DLL load failed with error code 182 > > > > Can any one tell me how I fixed this error? Here is someone with the same error who traced it to conflicting versions of a supporting DLL: http://mailman.vex.net/pipermail/pygresql/2008-March/001942.html From davea at ieee.org Wed Oct 28 13:16:43 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 28 Oct 2009 07:16:43 -0500 Subject: [Tutor] New to Python In-Reply-To: References: Message-ID: <4AE8362B.6090007@ieee.org> > > Remember to hit Reply to all > > - Forwarding your message onto the list > > ---------- Forwarded message ---------- > From: > Date: Wed, Oct 28, 2009 at 1:00 AM > Subject: Re: [Tutor] New to Python > To: srilyk at gmail.com > > > Hi Wayne, > > I will try as best to explain what I need to do. > > I have a log file. In that log file thre contains text. Something along the > lines of this. > > 115=WAS > 115=GAD > 115=TRE > > I need to search that log file (thought of using grep) and write each text > after the "=" sign to another text file. So the other text file (call it "* > List*") will contain a list of all the differernt values for 115. > > After I have created that, i then need to run a script that will run through > the latest log file and compare the *List *from the log file and any new > 115=... values that are not in the* List *text file must be added, vice > versa. > > End result is that I want to track and see how many values I can get in the > 115=... > > The log file is siuated on a different server/machine on my network, so I > want the script to be able to copy the log file from the server to my > machine. > > I hope that makes sense. > > Many thanks for your help. > > -----Original Message----- > From: Wayne > To: asterix09 at petlover.com > Cc: tutor at python.org > Sent: Tue, Oct 27, 2009 6:53 pm > Subject: Re: [Tutor] New to Python > > On Tue, Oct 27, 2009 at 10:35 AM, wrote: > > >> Hi there, >> >> How do you connect to a different server using python? (I have not used >> python before) >> >> > > What kind of server? What do you ultimately want to do? > > see: http://catb.org/~esr/faqs/smart-questions.html#beprecise > > for more info about asking good questions. We can't help you if we don't > know what you want. > -Wayne > > > Did you look up the smart-questions url? Since you're trying to connect from one Windows XP machine to another Windows XP or Server 2003 machine on the same network, the simplest answer is to use UNC names, which are machine-name, share-name, and path, all rolled into one string with two leading backslashes. In that case, you can do an open something like the following: infile = open(r"\\myserver\share3\system\logs\mylog.txt", "r") Notice the r" which indicates a raw string, so you wouldn't need to double the backslashes. DaveA From asterix09 at petlover.com Wed Oct 28 16:16:20 2009 From: asterix09 at petlover.com (asterix09 at petlover.com) Date: Wed, 28 Oct 2009 11:16:20 -0400 Subject: [Tutor] New to Python In-Reply-To: <1c2a2c590910280418g21990500g35e1507d3d98b1bd@mail.gmail.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> <1c2a2c590910271016t792bd5d0sc2a5212c464fc331@mail.gmail.com> <8CC25AB49AD018C-DB0-1021@web-mmc-m03.sysops.aol.com> <1c2a2c590910280418g21990500g35e1507d3d98b1bd@mail.gmail.com> Message-ID: <8CC25F8BCA25149-FB4-13E1@web-mmc-d12.sysops.aol.com> Well I would have to remote to the machine that contains the log file and copy it from there. -----Original Message----- From: Kent Johnson To: asterix09 at petlover.com Cc: *tutor python Sent: Wed, Oct 28, 2009 1:18 pm Subject: Re: [Tutor] New to Python Forwarding to the list with my reply (please use Reply All to reply to he list): On Wed, Oct 28, 2009 at 2:01 AM, wrote: Hi Kent, Thank you for replying to my request, really appreciate it. I am not familiar with all your connections that you have mentioned below. What I can tell you which I hope can help is that I have a log file on a different server/machine on a network which I would like to copy and paste on my machine? How would you copy the file if you did it by hand? Is the server file ystem accessible to your machine? If so, you can copy it with hutil.copyfile() or just open it and process it directly. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Oct 28 16:51:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Oct 2009 11:51:26 -0400 Subject: [Tutor] New to Python In-Reply-To: <8CC25F8BCA25149-FB4-13E1@web-mmc-d12.sysops.aol.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> <1c2a2c590910271016t792bd5d0sc2a5212c464fc331@mail.gmail.com> <8CC25AB49AD018C-DB0-1021@web-mmc-m03.sysops.aol.com> <1c2a2c590910280418g21990500g35e1507d3d98b1bd@mail.gmail.com> <8CC25F8BCA25149-FB4-13E1@web-mmc-d12.sysops.aol.com> Message-ID: <1c2a2c590910280851la9f081cq619cb3e4bc537240@mail.gmail.com> On Wed, Oct 28, 2009 at 11:16 AM, wrote: > Well I would have to remote to the machine that contains the log file and > copy it from there. You are not being very helpful. What does "remote to the machine" mean? What OS are you running? Some details would help. Kent PS Please don't top-post. > > > -----Original Message----- > From: Kent Johnson > To: asterix09 at petlover.com > Cc: *tutor python > Sent: Wed, Oct 28, 2009 1:18 pm > Subject: Re: [Tutor] New to Python > > Forwarding to the list with my reply (please use Reply All to reply to > the list): > > On Wed, Oct 28, 2009 at 2:01 AM, wrote: >> Hi Kent, >> >> Thank you for replying to my request, really appreciate it. >> >> I am not familiar with all your connections that you have mentioned below. >> >> What I can tell you which I hope can help is that I have a log file on a >> different server/machine on a network which I would like to copy and paste >> on my machine? > > How would you copy the file if you did it by hand? Is the server file > system accessible to your machine? If so, you can copy it with > shutil.copyfile() or just open it and process it directly. > > Kent > From cspears2002 at yahoo.com Wed Oct 28 17:17:11 2009 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 28 Oct 2009 09:17:11 -0700 (PDT) Subject: [Tutor] PyQT forum? Message-ID: <451454.98643.qm@web51610.mail.re2.yahoo.com> I'm starting to learn PyQt. Can anyone recommend a good mailing list or forum? Thanks. "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "There is no such thing as luck; there is only adequate or inadequate preparation to cope with a statistical universe." -Robert A. Heinlein, "Have Space Suit - Will Travel" From timomlists at gmail.com Wed Oct 28 19:52:24 2009 From: timomlists at gmail.com (Timo List) Date: Wed, 28 Oct 2009 19:52:24 +0100 Subject: [Tutor] Generating unique ID Message-ID: Hello, I'm writing an application which will hold a database of people. Ofcourse, people can have the same name, so I want to stock them with an unique ID. I've searched and found some things: - uuid.uuid4() - id(name) - os.urandom(n) But they seem overkill to me. Well, maybe not id(). What should I use the best for this? Maybe examples of other programs that do something alike? Thanks, Timo -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Oct 28 20:07:08 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 28 Oct 2009 14:07:08 -0500 Subject: [Tutor] Generating unique ID In-Reply-To: References: Message-ID: <333efb450910281207u73835237n585685a05a62277@mail.gmail.com> On Wed, Oct 28, 2009 at 1:52 PM, Timo List wrote: > Hello, > > I'm writing an application which will hold a database of people. Ofcourse, > people can have the same name, so I want to stock them with an unique ID. > > I've searched and found some things: > - uuid.uuid4() > - id(name) > - os.urandom(n) > > But they seem overkill to me. Well, maybe not id(). > > What should I use the best for this? Maybe examples of other programs that > do something alike? You could use SQLite... I believe it supports autoincrement. If you just want a random number, you can use the random library. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Wed Oct 28 20:07:48 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Wed, 28 Oct 2009 15:07:48 -0400 Subject: [Tutor] Generating unique ID In-Reply-To: References: Message-ID: > I'm writing an application which will hold a database of people. Ofcourse, > people can have the same name, so I want to stock them with an unique ID. > If you're using an actual database rather than a plain old text file, you can let the database do the work for you. Most flavors (sqlite, postgresql, mysql, oracle) have an autoincrement option that will generate unique IDs for you when you insert new records. Below are the docs for sqlite that explain the feature: http://www.sqlite.org/autoinc.html From nrhird at gmail.com Wed Oct 28 22:15:11 2009 From: nrhird at gmail.com (Nick Hird) Date: Wed, 28 Oct 2009 17:15:11 -0400 Subject: [Tutor] Can python determine Battery or AC Power? Message-ID: Is there a way in python to tell if the power source for a laptop is ac or battery? I am trying to write a small script to print out my system stats and would like to know if the laptop is on battery power or using ac power. I just dont know enough python to know where to look for that info. Thanks! -Nick From rabidpoobear at gmail.com Wed Oct 28 22:19:09 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 28 Oct 2009 16:19:09 -0500 Subject: [Tutor] Can python determine Battery or AC Power? In-Reply-To: References: Message-ID: If you're on Windows and you can find an example using the Win32 api (in C++ for example) you can use pywin32 module to do the same thing through python. It's a little complicated sometimes though. So what O.S. are you on? On Wed, Oct 28, 2009 at 4:15 PM, Nick Hird wrote: > Is there a way in python to tell if the power source for a laptop is > ac or battery? I am trying to write a small script to print out my > system stats and would like to know if the laptop is on battery power > or using ac power. I just dont know enough python to know where to > look for that info. > > Thanks! > -Nick > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nrhird at gmail.com Wed Oct 28 22:28:47 2009 From: nrhird at gmail.com (Nick Hird) Date: Wed, 28 Oct 2009 17:28:47 -0400 Subject: [Tutor] Can python determine Battery or AC Power? In-Reply-To: References: Message-ID: I am running Windows XP. On Wed, Oct 28, 2009 at 5:19 PM, Luke Paireepinart wrote: > If you're on Windows and you can find an example using the Win32 api (in C++ > for example) you can use pywin32 module to do the same thing through > python.? It's a little complicated sometimes though.? So what O.S. are you > on? > > On Wed, Oct 28, 2009 at 4:15 PM, Nick Hird wrote: >> >> Is there a way in python to tell if the power source for a laptop is >> ac or battery? I am trying to write a small script to print out my >> system stats and would like to know if the laptop is on battery power >> or using ac power. I just dont know enough python to know where to >> look for that info. >> >> Thanks! >> -Nick >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > -- --Nick From rabidpoobear at gmail.com Wed Oct 28 22:30:40 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 28 Oct 2009 16:30:40 -0500 Subject: [Tutor] Can python determine Battery or AC Power? In-Reply-To: References: Message-ID: On Wed, Oct 28, 2009 at 4:28 PM, Nick Hird wrote: > I am running Windows XP. > My advice applies then -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Wed Oct 28 18:34:02 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 28 Oct 2009 13:34:02 -0400 Subject: [Tutor] Sorting points on a 2D plane Message-ID: <1256751243.5636.161.camel@bermanrl-desktop> Hi, I am working on a practice problem called 'POINTS' on the CodeChef site:http://www.codechef.com/problems/POINTS/. This simply wants the sum of the distances between a number of points on a 2 dimensional plane. Looking at the problem, the algorithm to define the sum of the distances between all the points is not really difficult.The challenge is in ordering the points given the following rules: 1) You cannot move to a point with a lesser X value as compared to the X value of the point you are on. 2) For points having the same X value you need to visit the point with the greatest Y value before visiting the new point with the same X value. The least X takes precedence over the greatest Y. In any given test case there can be from 2 to 100000 points. The X and Y coordinates of each point will be between 0 and 10000 both inclusive. OK. The rules are established. A properly constructed algorithm will work for 10 points as well as 10000 points given it is properly constructed. My point of confusion is in ordering the points. Given a very simple example set of points: 0 5 0 1 0 2 2 1 2 3 5 2 5 1 The arrangement should be, 0 5 0 2 0 1 2 3 2 1 5 2 5 1 My solution is to first sort all the X values which would give me 0,0,0,2,2,5,5. I then will look at the Y values associated with the X value so I know that I am going to sort 3 Y values in reverse order for X = 0 and then append the Y value to each X point. What I am looking for is a better, faster approach. I think there would be a way to build a dictionary but you can't use the X values as keys since keys must be unique. So, any help to point me in a better faster direction will be truly appreciated. Thanks, Robert From rabidpoobear at gmail.com Thu Oct 29 01:03:22 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 28 Oct 2009 18:03:22 -0600 Subject: [Tutor] Sorting points on a 2D plane In-Reply-To: References: <1256751243.5636.161.camel@bermanrl-desktop> Message-ID: Oops I replied off list twice. (i wish they would just munge the addresses *grumble**grumble*) On Wed, Oct 28, 2009 at 11:34 AM, Robert Berman wrote: Hi, What I am looking for is a better, faster approach. I think there would be a way to build a dictionary but you can't use the X values as keys since keys must be unique. Why can't you use the X values? Just key to a list. Eg. for the data 0 5 0 2 0 1 2 3 2 1 5 2 5 1 Your dictionary would look like: {0:[5,2,1], 2:[3,1], 5:[2,1]} After sorting the sublists you could use itertools to reassemble the original coordinates fairly easily but I still don't think this will be the most optimal way. You can't get around sorting to sort values. So perhaps you could give us the exact code you did (on pastebin if it's long, try to cut out unnecessary cruft before posting) so we can help you make it more efficient. This should be extremely fast if you're doing the sorting correctly. Python's sort is really really optimized. Also, if you can upload a sample input file with a large dataset and indicate your current running time on the data set and what you're trying to achieve it will be easier to figure out how to improve your algorithm. -Luke > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Oct 29 01:53:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Oct 2009 00:53:08 -0000 Subject: [Tutor] Can python determine Battery or AC Power? References: Message-ID: "Nick Hird" wrote I am running Windows XP. > On Wed, Oct 28, 2009 at 4:15 PM, Nick Hird wrote: >> >> Is there a way in python to tell if the power source for a laptop is >> ac or battery? Search Microsoft Developer site (MSDN) for GetSystemPowerStatus which is the function that tests for battery or AC among other things. HTH, Alan G From alan.gauld at btinternet.com Thu Oct 29 01:56:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Oct 2009 00:56:53 -0000 Subject: [Tutor] Sorting points on a 2D plane References: <1256751243.5636.161.camel@bermanrl-desktop> Message-ID: "Robert Berman" wrote > constructed. My point of confusion is in ordering the points. Given a > very simple example set of points: > The arrangement should be, > > 0 5 > 0 2 > 0 1 > 2 3 > 2 1 > 5 2 > 5 1 > You might find the itertools.groupby function does most of what you need? HTH, Alan G. From kent37 at tds.net Thu Oct 29 03:21:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Oct 2009 22:21:20 -0400 Subject: [Tutor] Sorting points on a 2D plane In-Reply-To: <1256751243.5636.161.camel@bermanrl-desktop> References: <1256751243.5636.161.camel@bermanrl-desktop> Message-ID: <1c2a2c590910281921n55314c08i21b53b779734b7a4@mail.gmail.com> On Wed, Oct 28, 2009 at 1:34 PM, Robert Berman wrote: > Hi, > > I am working on a practice problem called 'POINTS' on the CodeChef > site:http://www.codechef.com/problems/POINTS/. This simply wants the sum > of the distances between a number of points on a 2 dimensional plane. > Looking at the problem, the algorithm to define the sum of the distances > between all the points is not really difficult.The challenge is in > ordering the points given the following rules: > 1) ?You cannot move to a point with a lesser X value as compared to > the ?X value of the point you are on. > 2) ?For points having the same X value you need to visit the point with > the greatest Y value before visiting the new point with the same X > value. The least X takes precedence over the greatest Y. > > In any given test case there can be from 2 to 100000 points. The X and Y > coordinates of each point will be between 0 and 10000 both inclusive. > > OK. The rules are established. A properly constructed algorithm will > work for 10 points as well as 10000 points given it is properly > constructed. My point of confusion is in ordering the points. Given a > very simple example set of points: > > 0 5 > 0 1 > 0 2 > 2 1 > 2 3 > 5 2 > 5 1 > > > The arrangement should be, > > 0 5 > 0 2 > 0 1 > 2 3 > 2 1 > 5 2 > 5 1 > > My solution is to first sort all the X values which would give me > 0,0,0,2,2,5,5. I then will look at the Y values associated with the X > value so I know that I am going to sort 3 Y values in reverse order for > X = 0 and then append the Y value to each X point. There are two easy ways to do this. One is similar to what you describe, but you sort first by Y value (descending) then sort by X value ascending. Python sort will preserve the order of equal items so the X sort preserves the descending Y sort and you get what you want. operator.itemgetter() is a convenience function for generating a key extraction function. In [3]: data Out[3]: [[0, 5], [0, 1], [0, 2], [2, 1], [2, 3], [5, 2], [5, 1]] In [4]: from operator import itemgetter In [5]: data.sort(key=itemgetter(1), reverse=True) In [6]: data Out[6]: [[0, 5], [2, 3], [0, 2], [5, 2], [0, 1], [2, 1], [5, 1]] In [7]: data.sort(key=itemgetter(0)) In [8]: data Out[8]: [[0, 5], [0, 2], [0, 1], [2, 3], [2, 1], [5, 2], [5, 1]] The other way to do this is to make a key that negates Y: In [10]: data.sort(key=lambda (x,y): (x, -y)) In [11]: data Out[11]: [[0, 5], [0, 2], [0, 1], [2, 3], [2, 1], [5, 2], [5, 1]] Kent From modulok at gmail.com Thu Oct 29 07:10:29 2009 From: modulok at gmail.com (Modulok) Date: Thu, 29 Oct 2009 00:10:29 -0600 Subject: [Tutor] Generating unique ID In-Reply-To: References: Message-ID: <64c038660910282310l1eb3b368id2ad32a4f60c95a0@mail.gmail.com> > I'm writing an application which will hold a database of people. Ofcourse, > people can have the same name, so I want to stock them with an unique ID. > > I've searched and found some things: > - uuid.uuid4() > - id(name) > - os.urandom(n) > > But they seem overkill to me. Well, maybe not id(). > > What should I use the best for this? Maybe examples of other programs that > do something alike? Use the auto-increment feature of your database database management backend. (Assuming you're using a database backend like MySQL, postgresql, etc.) In MySQL your database description would look something like this (with any other fields you need): # MySQL table description: CREATE TABLE IF NOT EXISTS mytable ( `uid` BIGINT unsigned NOT NULL auto_increment unique, `uname` CHAR(32) NOT NULL default "guest", PRIMARY KEY (`uid`)); You could use MySQLdb (third party python module) to talk to the MySQL process with Python. Other database managers have similar abilities. >> os.urandom(n) Random numbers are random, NOT unique. If you're using your own backend, like a text file or whatever, stop. Take the time to learn to use a database manager like postgresql or MySQL or whatever. They have already solved many of the problems you're now facing. It will be well worth the time and frustration. Otherwise, you'll have to parse your database and get the previously used value and then increment that. However, this solution will fail if there are multiple processes, or threads accessing the data concurrently. To solve that problem you'll have to introduce some manner of mutex to gurantee that only one process has access to the unique data at any given time. Things get complicated. All of these problems have already been solved with other database managers. Use them! In a pinch, with a low volume database for non-critical data, you could probably get away with using a Unix epoch style timestamp with sufficient granularity. But even this is in no way, "guaranteed" to be unique. It's just, "probably unique". It would look like this: >>> import time >>> time.time() 1256796357.661967 If it absolutely must be unique, use a database manager that can make that guarantee. Best of luck! -Modulok- From timomlists at gmail.com Thu Oct 29 10:06:02 2009 From: timomlists at gmail.com (Timo) Date: Thu, 29 Oct 2009 10:06:02 +0100 Subject: [Tutor] Generating unique ID In-Reply-To: <64c038660910282310l1eb3b368id2ad32a4f60c95a0@mail.gmail.com> References: <64c038660910282310l1eb3b368id2ad32a4f60c95a0@mail.gmail.com> Message-ID: <4AE95AFA.10904@gmail.com> Thanks for all the answers. I'm using SQLite as database and will try the ROWID. Timo Modulok schreef: >> I'm writing an application which will hold a database of people. Ofcourse, >> people can have the same name, so I want to stock them with an unique ID. >> >> I've searched and found some things: >> - uuid.uuid4() >> - id(name) >> - os.urandom(n) >> >> But they seem overkill to me. Well, maybe not id(). >> >> What should I use the best for this? Maybe examples of other programs that >> do something alike? >> > > Use the auto-increment feature of your database database management > backend. (Assuming you're using a database backend like MySQL, > postgresql, etc.) In MySQL your database description would look > something like this (with any other fields you need): > > # MySQL table description: > > CREATE TABLE IF NOT EXISTS mytable ( > `uid` BIGINT unsigned NOT NULL auto_increment unique, > `uname` CHAR(32) NOT NULL default "guest", > PRIMARY KEY (`uid`)); > > > You could use MySQLdb (third party python module) to talk to the MySQL > process with Python. Other database managers have similar abilities. > > >>> os.urandom(n) >>> > > Random numbers are random, NOT unique. > > If you're using your own backend, like a text file or whatever, stop. > Take the time to learn to use a database manager like postgresql or > MySQL or whatever. They have already solved many of the problems > you're now facing. It will be well worth the time and frustration. > > Otherwise, you'll have to parse your database and get the previously > used value and then increment that. However, this solution will fail > if there are multiple processes, or threads accessing the data > concurrently. To solve that problem you'll have to introduce some > manner of mutex to gurantee that only one process has access to the > unique data at any given time. Things get complicated. All of these > problems have already been solved with other database managers. Use > them! > > In a pinch, with a low volume database for non-critical data, you > could probably get away with using a Unix epoch style timestamp with > sufficient granularity. But even this is in no way, "guaranteed" to be > unique. It's just, "probably unique". It would look like this: > > >>>> import time >>>> time.time() >>>> > 1256796357.661967 > > If it absolutely must be unique, use a database manager that can make > that guarantee. > > Best of luck! > -Modulok- > From bermanrl at cfl.rr.com Thu Oct 29 13:35:59 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 29 Oct 2009 08:35:59 -0400 Subject: [Tutor] Sorting points on a 2D plane In-Reply-To: <1c2a2c590910281921n55314c08i21b53b779734b7a4@mail.gmail.com> References: <1256751243.5636.161.camel@bermanrl-desktop> <1c2a2c590910281921n55314c08i21b53b779734b7a4@mail.gmail.com> Message-ID: <1256819759.5636.206.camel@bermanrl-desktop> Kent and Alan, Thank you both for providing me with tools I can use to develop the sort portion of my algorithm. They are invaluable. I really appreciate Luke's willingness to examine and advise on the full algorithm and once it is written (only the function that determines distance between two points is written and working) I will definitely add it to pastebin and ask for your suggestions as well as the suggestions and comments from the group. Again, thank you for your help. Robert From asterix09 at petlover.com Thu Oct 29 07:04:09 2009 From: asterix09 at petlover.com (asterix09 at petlover.com) Date: Thu, 29 Oct 2009 02:04:09 -0400 Subject: [Tutor] New to Python In-Reply-To: <1c2a2c590910280851la9f081cq619cb3e4bc537240@mail.gmail.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> <1c2a2c590910271016t792bd5d0sc2a5212c464fc331@mail.gmail.com> <8CC25AB49AD018C-DB0-1021@web-mmc-m03.sysops.aol.com> <1c2a2c590910280418g21990500g35e1507d3d98b1bd@mail.gmail.com> <8CC25F8BCA25149-FB4-13E1@web-mmc-d12.sysops.aol.com> <1c2a2c590910280851la9f081cq619cb3e4bc537240@mail.gmail.com> Message-ID: <8CC2674C3AD16DB-E2C-2140@web-mmc-d11.sysops.aol.com> I am running Windows Vista. Do you know what remote desktop is? This is the tool I use to connect to my other severs on the network or alternatively I use my "Run" option (Start/Run) where you add in the IP address and connect to the server. I want to use python to do this for me. I can do it with a batch file. This is what I am looking to do. I have a log file. In this log file contains the following text: 115=ABS 115=DRF 115=HSD Lets call this log file A. I am looking to run s script that will search this log file and take all the text after the "=" sign (ABS/DRF..etc) and paste that into another text file, call it text file B. Once that it done I will need to compare other log files to file B and any new text after "=" that is not in the text file B must be added and anything that is must be ignored. The goal is that in these log files there will be multiple different text for 115=..etc. I need to create a list/mini database for them. So every day I need to run a script against a logfile to search for any new text. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu Oct 29 15:47:00 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 Oct 2009 14:47:00 +0000 Subject: [Tutor] New to Python In-Reply-To: <8CC2674C3AD16DB-E2C-2140@web-mmc-d11.sysops.aol.com> References: <8CC253233B88B6B-17C-564@web-mmc-d03.sysops.aol.com> <1c2a2c590910271016t792bd5d0sc2a5212c464fc331@mail.gmail.com> <8CC25AB49AD018C-DB0-1021@web-mmc-m03.sysops.aol.com> <1c2a2c590910280418g21990500g35e1507d3d98b1bd@mail.gmail.com> <8CC25F8BCA25149-FB4-13E1@web-mmc-d12.sysops.aol.com> <1c2a2c590910280851la9f081cq619cb3e4bc537240@mail.gmail.com> <8CC2674C3AD16DB-E2C-2140@web-mmc-d11.sysops.aol.com> Message-ID: <4AE9AAE4.4090307@timgolden.me.uk> asterix09 at petlover.com wrote: > I am running Windows Vista. OK. Definite points for giving useful info up front. > > Do you know what remote desktop is? Yes. > This is the tool I use to connect to my other severs on > the network or alternatively I use my "Run" option (Start/Run) > where you add in the IP address and connect to the server. Uh-oh; not so clear. There's quite a difference between rdp and a file-server connection. But ok... > I want to use python to do this for me. To do *what* for you? Control a remote desktop? Start a remote folder in explorer? > I can do it with a batch file. Can you show us the batch file? > This is what I am looking to do. [... snip stuff about a log file ...] Have I missed something? What does this have to do with the previous stuff about remote desktops and connecting to servers? I'm sorry, asterix09, I'm sure we're willing to help you, but you seem to be confusing several things at once here. I'm going to have a stab at what you're talking about and let's see how close I get: * You have several log files on some remote machines * The log files contain lines of text of the form: aaa=bbb * You want to perform some kind of comparison of this content, building up a database of some underspecified structure. Am I close? TJG From alan.gauld at btinternet.com Thu Oct 29 17:00:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Oct 2009 16:00:00 -0000 Subject: [Tutor] Generating unique ID References: <64c038660910282310l1eb3b368id2ad32a4f60c95a0@mail.gmail.com> <4AE95AFA.10904@gmail.com> Message-ID: "Timo" wrote > I'm using SQLite as database and will try the ROWID. Take a look at my working with databases topic under the heading Linking Data Across Tables which gives an exampler and discussion of using an autoincementing key in SqlLite. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cfuller084 at thinkingplanet.net Thu Oct 29 18:28:14 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 29 Oct 2009 12:28:14 -0500 Subject: [Tutor] PyQT forum? In-Reply-To: <451454.98643.qm@web51610.mail.re2.yahoo.com> References: <451454.98643.qm@web51610.mail.re2.yahoo.com> Message-ID: <200910291228.14774.cfuller084@thinkingplanet.net> Start with the main site. There are links to wikis/mailing lists/etc there. http://www.riverbankcomputing.co.uk/software/pyqt/ Also, you might be interested in the fully-free alternate, PySide, sponsored by Nokia: http://www.pyside.org/ Cheers On Wednesday 28 October 2009 11:17, Christopher Spears wrote: > I'm starting to learn PyQt. Can anyone recommend a good mailing list or > forum? > > Thanks. > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be > a color television set." -David Bowie > > "Who dares wins" > -British military motto > > "There is no such thing as luck; there is only adequate or inadequate > preparation to cope with a statistical universe." -Robert A. Heinlein, > "Have Space Suit - Will Travel" > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From walksloud at gmail.com Thu Oct 29 22:30:53 2009 From: walksloud at gmail.com (Andre Walker-Loud) Date: Thu, 29 Oct 2009 17:30:53 -0400 Subject: [Tutor] optional sys.argv parsing Message-ID: <25C6D1F1-102F-43A0-9F8A-5656920DA81D@gmail.com> Hi All, I have a simple question. I am writing a little program that will make some plots of data files. I want to have optional args to pass, for example to specify the plot ranges. I have never written a script/ code that takes optional args (but I have used plenty) - so I am feeling a little sluggish writing a good sys.argv reader. I have the following few lines I made, but I am wondering if any of you have suggestions for how to make this better (ie more slick, more readable, more general etc) Thanks, Andre >>> import sys if len(sys.argv) < 2: print('no data file specified') sys.exit(-1) elif len(sys.argv) > 2: if sys.argv.count('-x') > 1: print('error: multiple instances of "-x xmin xmax"') sys.exit(-1) elif sys.argv.count('-x') == 1: xrange = sys.argv.index('-x') if sys.argv.count('-y') > 1: print('error: multiple instances of "-y ymin ymax"') sys.exit(-1) elif sys.argv.count('-y') == 1: yrange = sys.argv.index('-y') else: xrange = 0 yrange = 0 if xrange != 0: xmin = float(sys.argv[xrange+1]) xmax = float(sys.argv[xrange+2]) else: xmin = "x-min determined from data file" xmax = "x-max determined from data file" if yrange != 0: ymin = float(sys.argv[yrange+1]) ymax = float(sys.argv[yrange+2]) else: ymin = "y-min determined from data file" ymax = "y-max determined from data file" From sander.sweers at gmail.com Thu Oct 29 23:31:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 29 Oct 2009 23:31:16 +0100 Subject: [Tutor] optional sys.argv parsing In-Reply-To: <25C6D1F1-102F-43A0-9F8A-5656920DA81D@gmail.com> References: <25C6D1F1-102F-43A0-9F8A-5656920DA81D@gmail.com> Message-ID: <1256855476.5645.22.camel@infirit.homelinux.org> On Thu, 2009-10-29 at 17:30 -0400, Andre Walker-Loud wrote: > I have a simple question. I am writing a little program that will > make some plots of data files. I want to have optional args to pass, > for example to specify the plot ranges. I have never written a script/ > code that takes optional args (but I have used plenty) - so I am > feeling a little sluggish writing a good sys.argv reader. I have the > following few lines I made, but I am wondering if any of you have > suggestions for how to make this better (ie more slick, more readable, > more general etc) You are a perfect candidate for the optparse module [1] which will do the heavy lifting for you. Example code relating to your code below. ------ >>> from optparse import OptionParser >>> parser = OptionParser() >>> parser.add_option('-f', '--file', action='store', type='string', dest='filename', help='Explain your filename')