From ricaraoz at gmail.com Sat Sep 1 00:50:35 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 31 Aug 2007 19:50:35 -0300 Subject: [Tutor] Starting classes In-Reply-To: <46D87095.9000407@brunson.com> References: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> <46D87095.9000407@brunson.com> Message-ID: <46D89B3B.1020107@bigfoot.com> Eric Brunson wrote: > Ara Kooser wrote: >> Hello, >> I read Alan Gauld's and How to Think Like a Computer Scientist >> section on classes. So I tried to write a simple room class. My goal >> is to write a short text adventure using classes. Here is the code: >> >> class Area: >> def _init_(self, name, description): >> > > Not enough underscores, you need two before and after the word "init". > >> self.name = name >> >> >> def look(here): >> "Look around the place you are in" >> print here.description >> >> >> outside1 = Area("Outside") >> outside1.description = "You are standing outside with the town gate to >> your back" >> > > Why not: > > outside1 = Area( "Outside", "You are standing outside..." ) > > and store self.description in the constructor? To do that you'll need the line : self.description = description right after the line assigning name to self.name. > > > >> self.contents.append("dirt") >> > > What is self? You've only defined self in the class methods and you're > outside the class definition. Was that just a cut and paste error? > >> look(bedroom) >> > > You'll get another error here, I think you want: outside1.look( bedroom ) But bedroom MUST be created before that. > >> I get the following error. >> Traceback (most recent call last): >> File "/Users/ara/Documents/text_advent.py", line 11, in >> outside1 = Area("Outside") >> TypeError: this constructor takes no arguments >> >> Do the outside1 = Area("Outside) need to be nested in the class or can >> they be outside of it? >> > > No, that's correct, because you are instantiating the class and naming > that instance "outside1". > >> Thank you. >> >> Ara >> >> >> >> > > Hope that all helps, > e. > From alan.gauld at btinternet.com Sat Sep 1 01:14:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 00:14:48 +0100 Subject: [Tutor] Starting classes References: Message-ID: wrote > def look(here): > "Look around the place you are in" > print here.description > > Not sure if this works as is, I believe it depends on the > interpreter, but > it is customary to use the word self as the first parameter, It is just a custom and 'here' is as good a name as any since its refering to the place object - ie here... But self is more conventional and using here might confuse some readers. The interpreters should all be happy enough with either name. Alan G From alan.gauld at btinternet.com Sat Sep 1 01:20:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 00:20:58 +0100 Subject: [Tutor] problem resulting from installing 3.0 References: <20070831203855.35FF31E4006@bag.python.org> Message-ID: "Dick Moores" wrote > and ulipad.pyw. How can I get back to where I was before, without > that annoying console opening? Sorry, no idea - thats why I never install alpha software! :-) > PYTHONPATH: > E:\Python25\;E:\PythonWork\;E:\Programs\Ulipad3.7\ > > And another question is, exactly what should go into PYTHONPATH? > I've > never been clear about that. Its what goes into sys.path. In other words its where your local modules are stored. Using an environment variable rather than a path file, as is often suggested, allows each user to have their own module library, and even multiple libraries by using a script to launch Python that redefines PYTHONPATH before starting Python. Or you can do it manually. Much more flexible. I'm a big fan of environment variables! Alan G From carroll at tjc.com Sat Sep 1 02:17:55 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 31 Aug 2007 17:17:55 -0700 (PDT) Subject: [Tutor] Python 3000 has just become less mythical Message-ID: The first Alpha release of Python 3000 was released today: http://python.org/download/releases/3.0/ Guido's post: http://www.artima.com/weblogs/viewpost.jsp?thread=213583 From kent37 at tds.net Sat Sep 1 02:22:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Aug 2007 20:22:27 -0400 Subject: [Tutor] Starting classes In-Reply-To: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> References: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> Message-ID: <46D8B0C3.4010709@tds.net> Ara Kooser wrote: > def look(here): > "Look around the place you are in" > print here.description This is technicaly OK but conventionally the first argument to a method is 'self'. Since you are learning it would be good to keep to the convention. > outside1 = Area("Outside") > outside1.description = "You are standing outside with the town gate to > your back" > self.contents.append("dirt") > > > look(bedroom) Maybe you mean bedroom.look() or outside1.look() Kent From kent37 at tds.net Sat Sep 1 02:25:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Aug 2007 20:25:58 -0400 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <20070831203855.35FF31E4006@bag.python.org> References: <20070831203855.35FF31E4006@bag.python.org> Message-ID: <46D8B196.5010307@tds.net> Dick Moores wrote: > XP, Python 2.5.1 > > I installed 3.0 alpha out of curiosity in a separate folder from > 2.5.1. Then I found that both 2.5.1's IDLE and my main Python editor > Ulipad would no longer open. My first idea was that the installation > of 3.0 somehow changed my path. But it didn't. After uninstalling > 3.0, and fiddling with the path and PYTHONPATH, IDLE and Ulipad now > open, but the console opens first. The files executed are idle.pyw > and ulipad.pyw. How can I get back to where I was before, without > that annoying console opening? A guess - check the file association for .pyw files. Make sure they are associated with pythonw, not python. Kent From rdm at rcblue.com Sat Sep 1 02:54:45 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 31 Aug 2007 17:54:45 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: References: <20070831203855.35FF31E4006@bag.python.org> Message-ID: <20070901005453.64CA21E4006@bag.python.org> At 04:20 PM 8/31/2007, you wrote: >"Dick Moores" wrote > > > and ulipad.pyw. How can I get back to where I was before, without > > that annoying console opening? > >Sorry, no idea - thats why I never install alpha software! :-) > > > PYTHONPATH: > > E:\Python25\;E:\PythonWork\;E:\Programs\Ulipad3.7\ > > > > And another question is, exactly what should go into PYTHONPATH? > > I've > > never been clear about that. > >Its what goes into sys.path. > >In other words its where your local modules are stored. Using an >environment variable rather than a path file, as is often suggested, >allows each user to have their own module library, and even >multiple libraries by using a script to launch Python that redefines >PYTHONPATH before starting Python. Or you can do it manually. >Much more flexible. I'm a big fan of environment variables! I don't think I follow you, Alan. I thought I was using environment variables. In XP, System Properties | Advanced | Environment Variables | System Variables. That's where path and PYTHONPATH are. There are subfolders with local modules in E:\PythonWork\. Do I have to list them too? And modules such as datetime.py, and random.py?are not local? I'm guessing not. Here what the sys.path doc says: ===================================== path A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH. A program is free to modify this list for its own purposes. Changed in version 2.3: Unicode strings are no longer ignored. ======================================= And my PYTHONPATH again: E:\Python25\;E:\PythonWork\;E:\Programs\Ulipad3.7\. It seems that all subfolders of Python25/ would be initialized by default. I'm thinking that maybe if I uninstall and then reinstall 2.5.1. The problem I asked about would clear up. Thoughts about this, anyone? Thanks, Dick >Alan G > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Sat Sep 1 03:03:04 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 31 Aug 2007 18:03:04 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <46D8B196.5010307@tds.net> References: <20070831203855.35FF31E4006@bag.python.org> <46D8B196.5010307@tds.net> Message-ID: <20070901010314.C16271E4006@bag.python.org> At 05:25 PM 8/31/2007, Kent Johnson wrote: >Dick Moores wrote: >>XP, Python 2.5.1 >>I installed 3.0 alpha out of curiosity in a separate folder from >>2.5.1. Then I found that both 2.5.1's IDLE and my main Python >>editor Ulipad would no longer open. My first idea was that the >>installation of 3.0 somehow changed my path. But it didn't. After >>uninstalling 3.0, and fiddling with the path and PYTHONPATH, IDLE >>and Ulipad now open, but the console opens first. The files >>executed are idle.pyw and ulipad.pyw. How can I get back to where I >>was before, without that annoying console opening? > >A guess - check the file association for .pyw files. Make sure they >are associated with pythonw, not python. Yes! Thanks, Kent. Dick From pine508 at hotmail.com Sat Sep 1 07:55:34 2007 From: pine508 at hotmail.com (Che M) Date: Sat, 01 Sep 2007 01:55:34 -0400 Subject: [Tutor] date matching with python and sqlite3 Message-ID: I'm trying to allow users to select data from an sqlite database using Python by choosing either a date or a range of dates. I'm stuck at just allowing the to select data that entered the database "today" and return values from a column called duration. I have this mess at the moment: #assume they have already chosen this self.datechoice to be today if self.datechoice == "today": todaystring = str(datetime.datetime.today()) today = todaystring[0:10] cur.execute('SELECT duration FROM datatable WHERE date =' + '"' + today + '"') The 3rd line is a way to take just the first part 10 chars of the datetime.today string, so instead of "2007-09-01 12:00:03" it would be just "2007-09-01", since I just want to match it to today, not a particular time during today. But this only works if the dates have been saved that way--typically they are saved with the time as well, so this method is not good and obviously not the right way to do it. I can tell I am going about this totally wrongly and that I should be able to use either the Python datetime functions or SQLite's date functions much better, so any insight would be appreciated. Thank you. _________________________________________________________________ A place for moms to take a break! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From alan.gauld at btinternet.com Sat Sep 1 10:08:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 09:08:53 +0100 Subject: [Tutor] problem resulting from installing 3.0 References: <20070831203855.35FF31E4006@bag.python.org> <20070901005453.64CA21E4006@bag.python.org> Message-ID: "Dick Moores" wrote > > > And another question is, exactly what should go into PYTHONPATH? > > >Its what goes into sys.path. > > >In other words its where your local modules are stored. > >Much more flexible. I'm a big fan of environment variables! > > I don't think I follow you, Alan. I thought I was > using environment variables. You are, but you asked about what should go in PYTHONPATH I was pointing out the advantages of using PYHONPATH over just putting a path file into your installation, which is another way of telling Python where too look. I wasn't suggesting that you weren't doing it, merely affirming that its a good idea. > There are subfolders with local modules in > E:\PythonWork\. Do I have to list them too? Thats exactly what should be in there. > modules such as datetime.py, and random.py-are not local? These would more typically be installed in the site-packages folder within your installation since they are not your own scripts. But if you chodse to store them outside the Python folders then yes you could point to their folders too. HTH, Alan G From pluijzer at gmail.com Sat Sep 1 13:46:38 2007 From: pluijzer at gmail.com (Righard/Riku van Roy) Date: Sat, 01 Sep 2007 11:46:38 +0000 Subject: [Tutor] date matching with python and sqlite3 In-Reply-To: References: Message-ID: <1188647198.3315.9.camel@iisjmii.TeleWell.gateway> I sorry, maybe I am stupid at the moment but I cannot follow your question,.... 1) User can select a date, or a range of dates. 2) At the moment you are only able to let the user select a date that has entered the database today. 3) A value from a table called duratation will be returned for the selected date? 4) It will only work if the date is saved in this? "2007-09-01", way., What other way can the date be saved? 5) You want to now how you can improve your program? Can you give some more info please, again sorry if others understeand it perfectly, Righard Op za, 01-09-2007 te 01:55 -0400, schreef Che M: > I'm trying to allow users to select data from an sqlite database using > Python by choosing either a date or a range of dates. I'm stuck at just > allowing the to select data that entered the database "today" and return > values from a column called duration. I have this mess at the moment: > > #assume they have already chosen this self.datechoice to be today > > if self.datechoice == "today": > todaystring = str(datetime.datetime.today()) > today = todaystring[0:10] > cur.execute('SELECT duration FROM datatable WHERE date =' + '"' + today > + '"') > > The 3rd line is a way to take just the first part 10 chars of the > datetime.today string, so > instead of 2007-09-01it would be just "2007-09-01", since I just > want > to match it to today, not a particular time during today. But this only > works if the > dates have been saved that way--typically they are saved with the time as > well, so > this method is not good and obviously not the right way to do it. > > I can tell I am going about this totally wrongly and that I should be able > to use either > the Python datetime functions or SQLite's date functions much better, so any > insight > would be appreciated. Thank you. > > _________________________________________________________________ > A place for moms to take a break! > http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From seancron at gmail.com Sat Sep 1 00:54:02 2007 From: seancron at gmail.com (Sean Cronin) Date: Fri, 31 Aug 2007 18:54:02 -0400 Subject: [Tutor] parsing response from SOAPpy request Message-ID: I'm using SOAPpy to access weather data from the NOAA National Digital Forecast Database XML Web Service [1] and I've been having trouble figuring out how to parse the data. The response comes back as XML document but when I check it with type(result) it shows the the response is a string. Does anyone have any suggestions on getting relevant data? I've attached a sample SOAP response to this post. Thanks, -Sean -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070831/69697610/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: response.txt Url: http://mail.python.org/pipermail/tutor/attachments/20070831/69697610/attachment.txt From pluijzer at gmail.com Sat Sep 1 15:29:32 2007 From: pluijzer at gmail.com (Righard/Riku van Roy) Date: Sat, 01 Sep 2007 13:29:32 +0000 Subject: [Tutor] Is there any logic in this? Message-ID: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> If you copy a list into another variable, and then change the second one, the first gets changed aswell, for example: >>> a = [10, 40, 30, 20] >>> b = a >>> b.sort() >>> a [10, 20, 30, 40] >>> b [10, 20, 30, 40] or: >>> a = [10, 40, 30, 20] >>> b = a >>> b[0] = 99 >>> a [99, 40, 30, 20] >>> b [99, 40, 30, 20] this happens with dictionary's too, but not with intergers, it is not that this is a problem because I can just use... >>> b = a[:] ...but I wonder if there is any logic behind this, I cannot find a practical use for it, just problems. thx, Righard From jim at well.com Sat Sep 1 16:50:53 2007 From: jim at well.com (jim stockford) Date: Sat, 1 Sep 2007 07:50:53 -0700 Subject: [Tutor] Is there any logic in this? In-Reply-To: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> Message-ID: <682433d724bbd619b0559f2aa2e4795d@well.com> seems to me this is an artifact of the language. reading right to left: "make a list that contains 10,40,30,20, then create a name 'a' to be used as a label to identify that list, then (next line) create a label 'b' to attach to whatever is the thing 'a' refers to, then (next line) modify the thing via 'b' (e.g. b.sort)." the essence is to allow multiple names for things without clogging up memory with a lot of copies and to have a uniform mechanism of referencing anything (i.e. any "object", for everything in Python is an object, hence the utility of a uniform mechanism. the effect is programmers have to know this is the case. those who have the old style "C head" using the model of a variable name representing an area in memory where assignment copies data to a new area in memory with the other variable name will get caught on this until they catch on. I'll be very grateful for any criticism of the above. On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote: > If you copy a list into another variable, and then change the second > one, the first gets changed aswell, for example: > >>>> a = [10, 40, 30, 20] >>>> b = a >>>> b.sort() >>>> a > [10, 20, 30, 40] >>>> b > [10, 20, 30, 40] > > or: > >>>> a = [10, 40, 30, 20] >>>> b = a >>>> b[0] = 99 >>>> a > [99, 40, 30, 20] >>>> b > [99, 40, 30, 20] > > this happens with dictionary's too, but not with intergers, it is not > that this is a problem because I can just use... > >>>> b = a[:] > > ...but I wonder if there is any logic behind this, I cannot find a > practical use for it, just problems. > > thx, Righard > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pluijzer at gmail.com Sat Sep 1 17:02:01 2007 From: pluijzer at gmail.com (Righard/Riku van Roy) Date: Sat, 01 Sep 2007 15:02:01 +0000 Subject: [Tutor] Is there any logic in this? In-Reply-To: <682433d724bbd619b0559f2aa2e4795d@well.com> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> <682433d724bbd619b0559f2aa2e4795d@well.com> Message-ID: <1188658921.3315.27.camel@iisjmii.TeleWell.gateway> Thanks for your explenation, so essentialy a = b, copys the pointer of a to b rather than the actual content. This explains why a[:] does work. Do you have an explenation why this is not the case with integers ie. >>> a, b = 10, a >>> b = b + 10 >>> a, b (10, 20) thx Op za, 01-09-2007 te 07:50 -0700, schreef jim stockford: > seems to me this is an artifact of the language. > reading right to left: > "make a list that contains 10,40,30,20, then create a > name 'a' to be used as a label to identify that list, then > (next line) create a label 'b' to attach to whatever is > the thing 'a' refers to, then (next line) modify the thing > via 'b' (e.g. b.sort)." > the essence is to allow multiple names for things > without clogging up memory with a lot of copies and > to have a uniform mechanism of referencing anything > (i.e. any "object", for everything in Python is an object, > hence the utility of a uniform mechanism. > the effect is programmers have to know this is the > case. those who have the old style "C head" using the > model of a variable name representing an area in > memory where assignment copies data to a new area > in memory with the other variable name will get caught > on this until they catch on. > > I'll be very grateful for any criticism of the above. > > > > On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote: > > > If you copy a list into another variable, and then change the second > > one, the first gets changed aswell, for example: > > > >>>> a = [10, 40, 30, 20] > >>>> b = a > >>>> b.sort() > >>>> a > > [10, 20, 30, 40] > >>>> b > > [10, 20, 30, 40] > > > > or: > > > >>>> a = [10, 40, 30, 20] > >>>> b = a > >>>> b[0] = 99 > >>>> a > > [99, 40, 30, 20] > >>>> b > > [99, 40, 30, 20] > > > > this happens with dictionary's too, but not with intergers, it is not > > that this is a problem because I can just use... > > > >>>> b = a[:] > > > > ...but I wonder if there is any logic behind this, I cannot find a > > practical use for it, just problems. > > > > thx, Righard > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Sat Sep 1 17:36:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Sep 2007 11:36:16 -0400 Subject: [Tutor] Is there any logic in this? In-Reply-To: <682433d724bbd619b0559f2aa2e4795d@well.com> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> <682433d724bbd619b0559f2aa2e4795d@well.com> Message-ID: <46D986F0.3060505@tds.net> jim stockford wrote: > seems to me this is an artifact of the language. 'artifact of the language' to me implies some sort of unintended consequence. In fact it is fundamental to the way assignment works in Python. This is good reading: http://tinyurl.com/ysz8sr > reading right to left: > "make a list that contains 10,40,30,20, then create a > name 'a' to be used as a label to identify that list, then > (next line) create a label 'b' to attach to whatever is > the thing 'a' refers to, then (next line) modify the thing > via 'b' (e.g. b.sort)." Yes > the effect is programmers have to know this is the > case. those who have the old style "C head" using the > model of a variable name representing an area in > memory where assignment copies data to a new area > in memory with the other variable name will get caught > on this until they catch on. Yes. If you think of variables as containers for values in Python you will be sorry, it is not a model that works. We had a really good discussion of this not too long ago but I can't find it in the archives. Does anyone have a link? Kent From bhaaluu at gmail.com Sat Sep 1 17:38:44 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 1 Sep 2007 11:38:44 -0400 Subject: [Tutor] game programming python Message-ID: Greetings, I recently found a rather obscure book that looks pretty good. The Reader Level is Beginner to Advanced, so I thought I'd share it with the list (something for everyone). Game Programming, The L Line, The Express Line To Learning. Andy Harris. Published by Wiley in February 1995. ISBN: 978-0-470-06822-9 http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470068221.html The above site has downloadable source code, PowerPoint slides (viewable with Open Office Impress), as well as excerpts and supplementary materials: (Appendix D is a tutorial on how to create your own game graphics and sounds using free software: the Gimp and Audacity). This book focuses on Game Programming with Python and the pyGame module. I found a copy online for about USD$15, so look around. This book seems to be well written, and it covers a lot of ground. If you're interested in learning Python game programming, take a look at this one! Happy Programming! -- bhaaluu at gmail dot com From alan.gauld at btinternet.com Sat Sep 1 18:05:07 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 17:05:07 +0100 Subject: [Tutor] Is there any logic in this? References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> Message-ID: "Righard/Riku van Roy" wrote > If you copy a list into another variable, and then change the second > one, the first gets changed as well, for example: > >>>> a = [10, 40, 30, 20] >>>> b = a This is not a copy its a name assignment. You have created a list object and assigned the name 'a' to it. Then you created a new name 'b' and told it to refer to the same object as 'a'. You did not create any new objects, you did not copy any objects. To copy a list in Python you must use the copy function or use a slice [:] (as you do below). You can check this with the id() function in Python: >>> a = [1,2,3] >>> b = a >>> id(a) 24474288 >>> id(b) 24474288 So they have the same id, they are the same object. > this happens with dictionary's too, but not with intergers, It does happen with integers (and strings etc) too. But integers and strings are immutable, you cannot change the object you can only create new objects. >>> x = 42 >>> y = x >>> id(x) 10835268 >>> id(y) 10835268 Notice the same id, the same object b.sort() changes the data ordering inside the list object. It does not change the list object itself. >>> b.sort() >>> id(b) 24474288 Still the same id as above, the same object. Only the data contained by the list has changed. You can do that because lists are mutable, they can be changed. But integers are not mutable, you can only create new integers: >>> y = 2*x >>> id(y) 10836748 A different id, we have created a new integer object >>>> b = a[:] Thats correct, here you really do create a copy of a. > ...but I wonder if there is any logic behind this, I cannot find a > practical use for it, just problems. There are a few situations where it is useful, but mainly it saves memory. However I don't think the memory saving is the main reason its built that way, its a model of thinking about names that moves us away from thinking about variable names as being aliaes for memory locations. It makes the computing machine more abstract and therefore more portable and keeps p[rogrammes focused on solving core problems rather than directing the computers mechanism. PS. For an entirely different explanation of Python's naming concept try reading the section on variables in my raw materials tutor topic... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Sep 1 18:09:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 17:09:21 +0100 Subject: [Tutor] parsing response from SOAPpy request References: Message-ID: "Sean Cronin" wrote > The response comes back as XML document but when I check it with > type(result) it shows the the response is a string. Thats right the string is the XML document, just as if you had read it from a file with the read() method. > Does anyone have any suggestions on getting relevant data? You need to parse the xml. The classic way to do that is using DOM or sax parsing, but Python now has the ElementTree parser which is usually much easier to use. Look at the module docs and for a lot more detail visit the ElementTree homepage: http://effbot.org/zone/element-index.htm HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pine508 at hotmail.com Sat Sep 1 18:51:13 2007 From: pine508 at hotmail.com (Che M) Date: Sat, 01 Sep 2007 12:51:13 -0400 Subject: [Tutor] date matching with python and sqlite3 In-Reply-To: Message-ID: Re: date matching with python and sqlite3 >I sorry, maybe I am stupid at the moment but I cannot follow your >question,.... I'm sorry, I didn't describe that too clearly...have coffee now, let's try that again. The user will have a choicebox that has options of "today", "this week", "this month", etc., as well as a way to just provide a range of dates, e.g. "Jan 1 2007--Apr 15 2007". The point is I want them to be able to get data from the database for whatever time period they want. Let's say the data is type of fruit they ate on various dates. So they would put in "this month" and it would return all the fruit that was eaten that month. And every time they indicate they ate a fruit, they enter it into the database and Python will save it as a datetime object, which has the format 2007-09-01 12:00:00. My trouble is in how to write the SQL statements to match the date(s) they need while ignoring the time part of the datetime. For example, the code I have for matching to "today" doesn't work because it will match a date saved as "2007-09-01" but not "2007-09-01 12:03:03", and it is this 2nd format that the datetime object takes. I also prefer that format, actually, in case I later want to sort by time of day. Again, this is the non-working and inelegant code: if self.datechoice == "today": todaystring = str(datetime.datetime.today()) today = todaystring[0:10] cur.execute('SELECT duration FROM datatable WHERE date =' + '"' + today + '"') I'm sure there is an easy way to do this since both Python and SQLite have date functions, but I have just had trouble understanding the SQlite documentation. Sorry if this is more an SQLite concern than a Python concern, but it is sort of on the border. If this is still unclear I will try again. Thanks! _________________________________________________________________ Get a FREE small business Web site and more from Microsoft? Office Live! http://clk.atdmt.com/MRT/go/aub0930003811mrt/direct/01/ From brunson at brunson.com Sat Sep 1 18:24:24 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 01 Sep 2007 10:24:24 -0600 Subject: [Tutor] parsing response from SOAPpy request In-Reply-To: References: Message-ID: <46D99238.6090505@brunson.com> Alan Gauld wrote: > "Sean Cronin" wrote > > >> The response comes back as XML document but when I check it with >> type(result) it shows the the response is a string. >> > > Thats right the string is the XML document, just as if you had read it > from a file with the read() method. > > >> Does anyone have any suggestions on getting relevant data? >> > > You need to parse the xml. > > The classic way to do that is using DOM or sax parsing, Bleah. ;-) > but > Python now has the ElementTree parser which is usually > much easier to use. Look at the module docs and for a lot > more detail visit the ElementTree homepage: > > http://effbot.org/zone/element-index.htm > I've used ElementTree a tiny bit, but preferred BeautifulSoup as it seemed more "pythonic" to me. You should look at both and pick the one that suits you. BeautifulSoup has the advantage of not choking on choking on XML that is not well formed. e. From jim at well.com Sat Sep 1 20:43:51 2007 From: jim at well.com (jim stockford) Date: Sat, 1 Sep 2007 11:43:51 -0700 Subject: [Tutor] Is there any logic in this? In-Reply-To: <1188658921.3315.27.camel@iisjmii.TeleWell.gateway> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> <682433d724bbd619b0559f2aa2e4795d@well.com> <1188658921.3315.27.camel@iisjmii.TeleWell.gateway> Message-ID: <7d5a55d1c9c6b8623472b195f7168d64@well.com> essentially right reinterpretation. I believe Pythonists use the term "bind" to describe the action of what we're used to thinking of as the assignment operator = the name 'a' is bound to the list, in your former example. Everything is an object in Python, including integers. Every object persists until there are no names bound to it, in which case the object is permanently out of scope and eligible for garbage collection. but... Objects for the small integers remain in scope always. your example is interesting, but reading right to left doesn't work well, which bothers me. I read your first line as "make 'a' reference the integer object 10, then make 'b' reference whatever 'a' references, then (next line) add 10 to whatever 'b' references, but oops: under the hood the Python interpreting system must as its first principle keep common sense--the human wants to add 10 to 'b' so 'b' will now reference the integer object that matches 10 + 10. I totally made the above explanation up, so it's a good target for skepticism. I hate not being able to read from right to left in a procrustean manner. The compromise is read the right side of the "assignment" operator and then the left side and do what common sense expects. I hope one of the p-t gurus will explain better. On Sep 1, 2007, at 8:02 AM, Righard/Riku van Roy wrote: > Thanks for your explenation, so essentialy a = b, copys the pointer of > a > to b rather than the actual content. This explains why a[:] does work. > > Do you have an explenation why this is not the case with integers ie. > >>>> a, b = 10, a >>>> b = b + 10 >>>> a, b > (10, 20) > > thx > > > Op za, 01-09-2007 te 07:50 -0700, schreef jim stockford: >> seems to me this is an artifact of the language. >> reading right to left: >> "make a list that contains 10,40,30,20, then create a >> name 'a' to be used as a label to identify that list, then >> (next line) create a label 'b' to attach to whatever is >> the thing 'a' refers to, then (next line) modify the thing >> via 'b' (e.g. b.sort)." >> the essence is to allow multiple names for things >> without clogging up memory with a lot of copies and >> to have a uniform mechanism of referencing anything >> (i.e. any "object", for everything in Python is an object, >> hence the utility of a uniform mechanism. >> the effect is programmers have to know this is the >> case. those who have the old style "C head" using the >> model of a variable name representing an area in >> memory where assignment copies data to a new area >> in memory with the other variable name will get caught >> on this until they catch on. >> >> I'll be very grateful for any criticism of the above. >> >> >> >> On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote: >> >>> If you copy a list into another variable, and then change the second >>> one, the first gets changed aswell, for example: >>> >>>>>> a = [10, 40, 30, 20] >>>>>> b = a >>>>>> b.sort() >>>>>> a >>> [10, 20, 30, 40] >>>>>> b >>> [10, 20, 30, 40] >>> >>> or: >>> >>>>>> a = [10, 40, 30, 20] >>>>>> b = a >>>>>> b[0] = 99 >>>>>> a >>> [99, 40, 30, 20] >>>>>> b >>> [99, 40, 30, 20] >>> >>> this happens with dictionary's too, but not with intergers, it is not >>> that this is a problem because I can just use... >>> >>>>>> b = a[:] >>> >>> ...but I wonder if there is any logic behind this, I cannot find a >>> practical use for it, just problems. >>> >>> thx, Righard >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dkuhlman at rexx.com Sat Sep 1 20:09:51 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 1 Sep 2007 11:09:51 -0700 Subject: [Tutor] parsing response from SOAPpy request In-Reply-To: <46D99238.6090505@brunson.com> References: <46D99238.6090505@brunson.com> Message-ID: <20070901180951.GA76332@cutter.rexx.com> On Sat, Sep 01, 2007 at 10:24:24AM -0600, Eric Brunson wrote: > Alan Gauld wrote: > > "Sean Cronin" wrote > > > > > >> The response comes back as XML document but when I check it with > >> type(result) it shows the the response is a string. > >> > > > > Thats right the string is the XML document, just as if you had read it > > from a file with the read() method. > > > > > >> Does anyone have any suggestions on getting relevant data? > >> > > > > You need to parse the xml. > > > > The classic way to do that is using DOM or sax parsing, > > Bleah. ;-) I don't understand this. The response comes back as the value of a function/method call. You should not have to look at XML (text) at all, unless something goes wrong and you need to do debugging. This is the point of using SOAPpy. XML is the underlying (and mostly hidden) data representation that is sent "across the wire". But, you deal with Python and SOAPpy. It translates your function calls into XML, sends it to a SOAP server, receives an (XML) response, and translates that XML response back into Python objects. Currently, I do not have SOAPpy installed. But last time I used it, I did not parse XML. For an example, in the SOAPpy distribution, look at tests/cardClient.py. It makes SOAP requests, and receives the responses to those requests, but it does not (directly) generate or parse XML. SOAPpy does that for you. You have most likely already looked at those examples. So, maybe there is something that I don't understand about your question? Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Sun Sep 2 00:13:09 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 23:13:09 +0100 Subject: [Tutor] parsing response from SOAPpy request References: <46D99238.6090505@brunson.com> <20070901180951.GA76332@cutter.rexx.com> Message-ID: "Dave Kuhlman" wrote >> >> The response comes back as XML document but when I check it with >> >> type(result) it shows the the response is a string. > This is the point of using SOAPpy. XML is the underlying (and > mostly hidden) data representation that is sent "across the wire". > But, you deal with Python and SOAPpy. It translates your function > calls into XML, sends it to a SOAP server, receives an (XML) > response, and translates that XML response back into Python > objects. That's how it usually works where the return values are simple objects like strings, integers, dates, even lists of things. But Web Services are sometimes defined to return an XML document as the return object. This is usually because the exact content is undefined or there is a lot of it in complex structures. When that happens Python hands you a string, which happens to be an XML document. The XML envelope that surrounds the SOAP message is correctly stripped away by SOAPpy but the string thats left is itself an XML document. Its nothing to do with SOAPpy per se, any SOAP implementation will do the same, it's what the web service returns. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Sep 2 00:17:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 23:17:10 +0100 Subject: [Tutor] Is there any logic in this? References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway><682433d724bbd619b0559f2aa2e4795d@well.com><1188658921.3315.27.camel@iisjmii.TeleWell.gateway> <7d5a55d1c9c6b8623472b195f7168d64@well.com> Message-ID: "jim stockford" wrote > your example is interesting, but reading right to left > doesn't work well, which bothers me. It works OK if you treat the entire right hand side as an expression that evaluates to a value which is bound to the name on the left. In the list cae the sort method works in-place so the list object never changes. In the integer case two integers get added together to make a new integer. The new value is bound to the name. > I hate not being able to read from right to left in a > procrustean manner. The compromise is read the > right side of the "assignment" operator and then > the left side and do what common sense expects. You can read from right to left but you just have to do it under the rules of Python :-) Alan G. From ghashsnaga at gmail.com Sun Sep 2 00:23:56 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Sat, 1 Sep 2007 16:23:56 -0600 Subject: [Tutor] Further into classes Message-ID: <2107481c0709011523i497f57f0y3ae34f885fa0f132@mail.gmail.com> Thank you for the help on getting started on classes. I have a basic understanding of how they are used and I reread the tutorials again. So I have a class set up and running. My question is how you append a list (such as self.contents = [ ]) using a method like def AddObject? The code I am trying is below but it is not working. I am really sure I am not going about this the right way. Thank you. Ara ##################################################################### #Text Advenuture #By Ara Kooser #Thanks to Chris, e., and Steven at python tutor #################################################################### class Area: #What makes it an area? def __init__(self, name, description): #Number of arguements in the _init_ must be defined self.name = name self.description = description self.contents = [] #Methods. What you can do. def AddObject(self,thing): #pass self.contents.append() def look(self): print "Look around the place you are in" print "You are in the",self.name print self.description def search(self): print "You search the area and find..." print self.contents first_instance = Area("Outside", "You are standing outside") first_instance.AddObject("Stick") first_instance.look() first_instance.search() second_instance = Area("Inside", "You are standing inside") second_instance.AddObject("Iron pot") second_instance.look() second_instance.search() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From ricaraoz at gmail.com Sun Sep 2 00:41:48 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Sep 2007 19:41:48 -0300 Subject: [Tutor] files Message-ID: <46D9EAAC.1030209@bigfoot.com> Hi, I am in doubt : >>> In = open(r'E:\MyDir\MyDoc.txt', 'rb') >>> Out = open(r'E:\MyDir\MyUpperDoc.txt', 'wb') >>> Out.write(In.read().upper()) >>> In.close() >>> Out.close() Pretty simple program. The question is : If 'In' is a HUGE file, how does Python process it? Does it treat it as a stream and passes bytes to 'Out' as soon as they are coming in, or does it read the whole file into memory and then passes the whole file to 'Out'? If the answer is the first choice I would like to know how to instruct Python to do the second choice. TIA From alan.gauld at btinternet.com Sun Sep 2 01:46:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 00:46:54 +0100 Subject: [Tutor] Further into classes References: <2107481c0709011523i497f57f0y3ae34f885fa0f132@mail.gmail.com> Message-ID: "Ara Kooser" wrote > So I have a class set up and running. My question is how you append > a > list (such as self.contents = [ ]) using a method like def > AddObject? > class Area: > #Methods. What you can do. > def AddObject(self,thing): > #pass > self.contents.append() > You are almost there but you need to pass 'thing' to the append: self.contents.append(thing) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Sep 2 01:51:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 00:51:45 +0100 Subject: [Tutor] files References: <46D9EAAC.1030209@bigfoot.com> Message-ID: "Ricardo Ar?oz" wrote >>>> In = open(r'E:\MyDir\MyDoc.txt', 'rb') >>>> Out = open(r'E:\MyDir\MyUpperDoc.txt', 'wb') >>>> Out.write(In.read().upper()) >>>> In.close() >>>> Out.close() > > Pretty simple program. The question is : If 'In' is a HUGE file, how > does Python process it? Exactly as it does for a small file... :-) > Does it treat it as a stream and passes bytes to > 'Out' as soon as they are coming in, or does it read the whole file > into > memory and then passes the whole file to 'Out'? You have told it to do the latter. read() reads the whole file into a string so Out.write(In.read().upper()) Is exactly the same as temp = In.read() temp = temp.upper() Out.write(temp) Just because you put it in one line doesn't chanhge how Python interprets it. > If the answer is the first choice I would like to know how to > instruct > Python to do the second choice. I'm guessing you mean this the other way around? You can read the file line by line for line in In: Out.write(line.upper()) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From gslindstrom at gmail.com Sun Sep 2 02:52:51 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sat, 1 Sep 2007 19:52:51 -0500 Subject: [Tutor] PyCon 2008 - Call for Tutorial Topics Message-ID: Hello All, We are still soliciting ideas for tutorials to put on at PyCon in Chicago next spring. PyCon is all about our community; under the direction of the PSF, planned, organized and run by volunteers just like you. We are asking for topics that you want to see covered on the tutorial day (the day preceding the "official" conference). There is an additional charge for these classes but they are taught by instructors who really know their topics. The following ideas have been requested (nothing has been scheduled, yet): - Testing strategies - Intermediate Python - Database - How to "think" in Python 3000 - Using Cheeseshop - SOAP/.Net (Iron Python?) - Programming Contest We need more ideas before we start putting things together. What do *you* want to see? This is your chance to learn from the experts (or, maybe, *you* would like to present a class). Let me know what class would entice you to attend the tutorials. Greg Lindstrom Tutorial Coordinator, PyCon 2008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070901/63370c8c/attachment.htm From ricaraoz at gmail.com Sun Sep 2 02:53:16 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Sep 2007 21:53:16 -0300 Subject: [Tutor] files In-Reply-To: References: <46D9EAAC.1030209@bigfoot.com> Message-ID: <46DA097C.4010601@bigfoot.com> Alan Gauld wrote: > "Ricardo Ar?oz" wrote > >>>>> In = open(r'E:\MyDir\MyDoc.txt', 'rb') >>>>> Out = open(r'E:\MyDir\MyUpperDoc.txt', 'wb') >>>>> Out.write(In.read().upper()) >>>>> In.close() >>>>> Out.close() >> Pretty simple program. The question is : If 'In' is a HUGE file, how >> does Python process it? > > Exactly as it does for a small file... :-) > >> Does it treat it as a stream and passes bytes to >> 'Out' as soon as they are coming in, or does it read the whole file >> into >> memory and then passes the whole file to 'Out'? > > You have told it to do the latter. > read() reads the whole file into a string so > > Out.write(In.read().upper()) > > Is exactly the same as > > temp = In.read() > temp = temp.upper() > Out.write(temp) > > Just because you put it in one line doesn't chanhge how > Python interprets it. > >> If the answer is the first choice I would like to know how to >> instruct >> Python to do the second choice. > > I'm guessing you mean this the other way around? > > You can read the file line by line > > for line in In: > Out.write(line.upper()) > > HTH, Thanks a lot. From seancron+pythontutor at gmail.com Sun Sep 2 05:32:11 2007 From: seancron+pythontutor at gmail.com (Sean Cronin[tutor]) Date: Sat, 1 Sep 2007 23:32:11 -0400 Subject: [Tutor] Best way to construct this Message-ID: Hi, I'm trying to create a desktop weather program using the weather.gov SOAP XML feed[1] and (after I get the insides all sorted out) Tkinter. However, this is my first major program and I was wondering if anyone could offer me some guidance in the construction of it. I have settled on using SOAPpy for the SOAP interface and pyXML to parse the resulting XML, but I am having trouble figuring out what the most efficient way of parsing the XML and arranging my program. Right now I have two modules named libndfdsoap and weatherpy. Module libndfdsoap contains one function that gets the XML and saves it to a file named weather.xml. Module weatherpy contains some constants and a class for parsing the XML with different functions for find different data types. I am using xml.dom.minidom and using childNodes to narrow down to the values that I need and then storing that in a dictionary. Here's a snippet of the code: class ByDayXMLParse: """Contains functions for parsing the NDFD XML""" def __init__(self, path_to_xml_file): global data, maxtempdata, maxtempnode data = minidom.parse(path_to_xml_file) #Dictionary in which the max temps are going to be stored in the format #{1: day1temp, 2: day2temp, ...} maxtempdata = {} #Less typing for me :) maxtempnode = data.childNodes[0].childNodes[3].childNodes[9 ].childNodes[1] def maxTemp(self, path_to_xml_file): x = 3 y = 1 while x < 16: maxtempdata[y] = maxtempnode.childNodes[x].childNodes[0].data x, y = x + 2, y + 1 I've tried putting the XML parsing code in libndfdsoap but by doing so I couldn't access the resulting data. I can't help but feel like I'm missing something that will make my life a whole lot easier. Any help would be greatly appreciated. -Sean [1] http://www.weather.gov/forecasts/xml/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070901/377b6f56/attachment.htm From alan.gauld at btinternet.com Sun Sep 2 10:12:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 09:12:40 +0100 Subject: [Tutor] Best way to construct this References: Message-ID: "Sean Cronin[tutor]" wrote > Right now I have two modules named libndfdsoap and weatherpy. > Module > libndfdsoap contains one function that gets the XML and saves it to > a file > named weather.xml. Seems fair enough. > Module weatherpy contains some constants and a class for > parsing the XML with different functions for find different data > types. The idea of a class is that it hoolds the data plus the functions that operate *on that data*. Thus it would be more normal to put your global data into the class itself. > > class ByDayXMLParse: The name is a verb, which does not suggest an Object. Normally classes are nouns since nouns epresent things. What kind of thing is this class representing? It could be an XML Weather document maybe? In which case I'd expect it to have a parse() method and the constructor would just open the related file. > """Contains functions for parsing the NDFD XML""" > def __init__(self, path_to_xml_file): > global data, maxtempdata, maxtempnode Its very unusual to have a lot of global variables in a class. These could all be internal attributes. That would give the advantage of allowing you to have multiple instances and parse them concurrently whereas here the instances would be sharing data. > data = minidom.parse(path_to_xml_file) > #Dictionary in which the max temps are going to be stored in the > format > #{1: day1temp, 2: day2temp, ...} > maxtempdata = {} > #Less typing for me :) > maxtempnode = data.childNodes[0].childNodes[3].childNodes[9 > ].childNodes[1] > Personally I'd probably make the parse method separate from init. I'd just get init to open the file. It could then call parse as a last line, but by taking parse outside init it gives the option of reparsing the file later, if for example you suspect the data has become corrupted somehow. In pseudo code: class Weather: def init(self, fname): self.filename = fname self.data = None self.maxtemp = None self.maxnode = None self.parse() def parse(self): self.data = minidom.parse(self.filename) etc as before def maxTemp(self): # no path needed since its stored in the object > I've tried putting the XML parsing code in libndfdsoap but by doing > so I > couldn't access the resulting data. You could put the functions there and use module cvariables to hold the result, but more usually you would just return the values and the importing module (weather in this case would store them) ## in weather code import libndfdsoap as soap mylocalvar = soap.myparsingfunc() However I actually think that would be a mistake since you are then taking a potentially reusable module which simply calls a web service and stores the result and putting a lot of application specific parsing functions into it. I prefer your approach of building a weather module that reads the file and keeps the weather specific parsing functions separate from fetching the data. > I can't help but feel like I'm missing > something that will make my life a whole lot easier. I think you are on the right track but you probably want to think a bit more about your class as representing an object and what kind of things you you want to do to that object. You can then put the code that instantiates the object and calls its methods outside in your modules driver code - and eventually into your Tkinter GUI module. HTH, Alan G. From varsha.purohit at gmail.com Sun Sep 2 11:12:52 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 02:12:52 -0700 Subject: [Tutor] Accessing Values of specific column in a 2D list or array Message-ID: Hello, Suppose i have a 2D list(grid) like grid = [[1,1,2,7,6,9],\ [,9,1,1,1,9,1],\ [8,1,2,0,0,4],\ [1,4,1,1,8,5]] how can i access to all the elements of the list from column no. 5. output should be like [6,9,0,8]... thanks,- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/e8945213/attachment.htm From varsha.purohit at gmail.com Sun Sep 2 11:13:59 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 02:13:59 -0700 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: References: Message-ID: Hello, Suppose i have a 2D list(grid) like grid = [[1,1,2,7,6,9],\ [,9,1,1,1,9,1],\ [8,1,2,0,0,4],\ [1,4,1,1,8,5]] how can i access to all the elements of the list from column no. 5. output should be like [6,9,0,8]... thanks,- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/dc8e68ec/attachment.htm From rdm at rcblue.com Sun Sep 2 11:48:19 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 02:48:19 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: References: <20070831203855.35FF31E4006@bag.python.org> <20070901005453.64CA21E4006@bag.python.org> Message-ID: <20070902094848.80E021E4006@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/625bc948/attachment.htm From eric at abrahamsen.com Sun Sep 2 12:37:43 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sun, 2 Sep 2007 18:37:43 +0800 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: References: Message-ID: <3610DA67-FBC9-4A8E-9E87-ECFF24017BD0@abrahamsen.com> > grid = [[1,1,2,7,6,9],\ > [,9,1,1,1,9,1],\ > [8,1,2,0,0,4],\ > [1,4,1,1,8,5]] > > how can i access to all the elements of the list from column no. 5. > > output should be like [6,9,0,8]... Your basic tool is sub-indexing: you can reach items in the sub-lists by using grid[x][x]. So use a 'for' loop to get sub-index four of every item in grid. The most compact way is with a list comprehension: grid = [[1,1,2,7,6,9],[9,1,1,1,9,1],[8,1,2,0,0,4],[1,4,1,1,8,5]] fifth_col = [grid[x][4] for x in range(len(grid))] print fifth_col There might be a more graceful replacement for the range(len(grid)) part. Yrs, Eric From ricaraoz at gmail.com Sun Sep 2 12:45:32 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 07:45:32 -0300 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: References: Message-ID: <46DA944C.4020201@bigfoot.com> Varsha Purohit wrote: > > > Hello, > Suppose i have a 2D list(grid) like > > grid = [[1,1,2,7,6,9],\ > [,9,1,1,1,9,1],\ > [8,1,2,0,0,4],\ > [1,4,1,1,8,5]] > > how can i access to all the elements of the list from column no. 5. > > output should be like [6,9,0,8]... > COL = 5 [i[COL-1] for i in grid] From eric at abrahamsen.com Sun Sep 2 12:50:50 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sun, 2 Sep 2007 18:50:50 +0800 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: <46DA944C.4020201@bigfoot.com> References: <46DA944C.4020201@bigfoot.com> Message-ID: <8ECDE71C-DF89-4C8C-A2A1-CBBD44C2D52A@abrahamsen.com> > > COL = 5 > [i[COL-1] for i in grid] Should have guessed... From kent37 at tds.net Sun Sep 2 14:40:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Sep 2007 08:40:53 -0400 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <20070902094848.80E021E4006@bag.python.org> References: <20070831203855.35FF31E4006@bag.python.org> <20070901005453.64CA21E4006@bag.python.org> <20070902094848.80E021E4006@bag.python.org> Message-ID: <46DAAF55.7000200@tds.net> Dick Moores wrote: > At 01:08 AM 9/1/2007, Alan Gauld wrote: > >> "Dick Moores" wrote >> >> > > > And another question is, exactly what should go into PYTHONPATH? >> > >> > >Its what goes into sys.path. PYTHONPATH is for your own customizations of sys.path, it is not the entirety of sys.path. AFAIK you don't have to define it at all if you don't want to use it. If you have a dir containing modules that you want to be able to import directly, e.g. mine/ util.py foo.py and in code you want to say import util, foo then put /path/to/mine/ in PYTHONPATH. If you have a package - a dir of modules that go together, that you want to import as a package, e.g. my-packages/ mine/ __init__.py util.py foo.py then you import them as from mine import util you still put /path/to/mine/ in PYTHONPATH but now it is the dir containing the package rather than the dir containing the module. __init__.py signals to Python that the containing dir should be treated as a package. It is independent of PYTHONPATH. There are quite a few ways to get a module into the search path, modifying PYTHONPATH is just one way. Some others: - create a site-packages/ dir in the Python lib dir. Put your modules and packages there and they will be found by Python. - add a .pth file to site-packages/ that contains the path to the dir you want to add to sys.path - modify sys.path directly in code. You can do this in a specific application or you can create site-packages/sitecustomize.py and do site-wide customizations there. Kent From alan.gauld at btinternet.com Sun Sep 2 16:10:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 15:10:54 +0100 Subject: [Tutor] Accessing Values of specific column in a 2D list or array References: Message-ID: "Varsha Purohit" wrote > grid = [[1,1,2,7,6,9],\ > [,9,1,1,1,9,1],\ > [8,1,2,0,0,4],\ > [1,4,1,1,8,5]] You don't need the '\' characters, the fact that the closing bracket has not been reached means Python will ignore the newline characters. > how can i access to all the elements of the list from column no. 5. > > output should be like [6,9,0,8]... Others have already shown but the easiest way to build a list from another list is via a list comprehension so: col5 = [row[4] for row in grid] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Sep 2 16:15:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 15:15:48 +0100 Subject: [Tutor] problem resulting from installing 3.0 References: <20070831203855.35FF31E4006@bag.python.org> <20070901005453.64CA21E4006@bag.python.org> <20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> Message-ID: "Kent Johnson" wrote > PYTHONPATH is for your own customizations of sys.path, it is not the > entirety of sys.path. AFAIK you don't have to define it at all if > you > don't want to use it. All true. The point of PYTHONPATH is that you could have several users all running python on the same box (either concurrently on a server or different users ion the same PC at different times) PYTHONPATH allows each user to have their own custom additions to sys.path. > There are quite a few ways to get a module into the search path, > modifying PYTHONPATH is just one way. Some others: > - create a site-packages/ dir in the Python lib dir. Put your > modules > and packages there and they will be found by Python. Usually used for non standard packages like wxPython, pyGame etc that all users will want to have available > - add a .pth file to site-packages/ that contains the path to the > dir > you want to add to sys.path Similar to above but allows different Python installs on the same machine to share the same library. > - modify sys.path directly in code. This is best if only one (or a very few) application needs access to the modules. Especially if they are intended to mask standard modules like os. So use PYTHONPATH for individual tailoring and sitepackages etc for site wide changes. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sun Sep 2 16:54:20 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 07:54:20 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <46DAAF55.7000200@tds.net> References: <20070831203855.35FF31E4006@bag.python.org> <20070901005453.64CA21E4006@bag.python.org> <20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> Message-ID: <20070902145457.8825B1E4006@bag.python.org> Thanks, Kent. At 05:40 AM 9/2/2007, Kent Johnson wrote: >There are quite a few ways to get a module into the search path, >modifying PYTHONPATH is just one way. Some others: >- create a site-packages/ dir in the Python lib dir. Put your >modules and packages there and they will be found by Python. You mean such as site-packages\mine? That was working until I tried blanking PYTHONPATH, which previously contained E:\Python25\lib\site-packages\mine\ >- add a .pth file to site-packages/ that contains the path to the >dir you want to add to sys.path I tried this with no PYTHONPATH. I put pointers.pth in site-packages\ with the single line, E:\PythonWork\Functions\ . Functions\ contains functions.py . However, >>> import functions Traceback (most recent call last): File "", line 1, in ? ImportError: No module named functions I also tried putting an __init__.py in Functions\ >>> from Functions import functions Traceback (most recent call last): File "", line 1, in ? ImportError: No module named Functions >>> Please tell me where I went wrong. >- modify sys.path directly in code. You can do this in a specific >application or you can create site-packages/sitecustomize.py and do >site-wide customizations there. And also, please, show me what site-packages\sitecustomize.py should contain to make E:\PythonWork\Functions\functions.py importable (with no .pth file and no PYTHONPATH) Dick From kent37 at tds.net Sun Sep 2 17:17:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Sep 2007 11:17:49 -0400 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <20070902145457.8825B1E4006@bag.python.org> References: <20070831203855.35FF31E4006@bag.python.org> <20070901005453.64CA21E4006@bag.python.org> <20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> <20070902145457.8825B1E4006@bag.python.org> Message-ID: <46DAD41D.9010508@tds.net> Dick Moores wrote: > Thanks, Kent. > > At 05:40 AM 9/2/2007, Kent Johnson wrote: >> There are quite a few ways to get a module into the search path, >> modifying PYTHONPATH is just one way. Some others: >> - create a site-packages/ dir in the Python lib dir. Put your >> modules and packages there and they will be found by Python. > > You mean such as site-packages\mine? That was working until I tried > blanking PYTHONPATH, which previously contained > E:\Python25\lib\site-packages\mine\ You need to be clear on the difference between a module and a package. A module is a single python file, imported by its name. A package is a directory containing python files. The package dir must contain a file named __init__.py, which signals to Python that the dir is a package. Modules within a package are imported by packagename.modulename. This might help: http://docs.python.org/tut/node8.html If you put site-packages\mine\ in PYTHONPATH, you are telling Python to look inside mine\ for modules and modules are imported by their simple name. If you just put mine\ in site-packages, you are saying that mine is a *package* so it must contain __init__.py and modules within it will be imported by compound name mine.mymodule. > >> - add a .pth file to site-packages/ that contains the path to the >> dir you want to add to sys.path > > I tried this with no PYTHONPATH. I put pointers.pth in site-packages\ > with the single line, E:\PythonWork\Functions\ . Functions\ contains > functions.py . However, > >>> import functions > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named functions Don't know why this didn't work. Does the Functions dir appear on sys.path? > I also tried putting an __init__.py in Functions\ > >>> from Functions import functions > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named Functions In this case E:\PythonWork\ should be in sys.path so the *package* Functions will be found. Kent From rdm at rcblue.com Sun Sep 2 18:01:33 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 09:01:33 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <46DAD41D.9010508@tds.net> References: <20070831203855.35FF31E4006@bag.python.org> <20070901005453.64CA21E4006@bag.python.org> <20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> <20070902145457.8825B1E4006@bag.python.org> <46DAD41D.9010508@tds.net> Message-ID: <20070902160141.D0CDD1E4006@bag.python.org> At 08:17 AM 9/2/2007, Kent Johnson wrote: >Dick Moores wrote: >> >>>- add a .pth file to site-packages/ that contains the path to the >>>dir you want to add to sys.path >>I tried this with no PYTHONPATH. I put pointers.pth in >>site-packages\ with the single line, E:\PythonWork\Functions\ . >>Functions\ contains functions.py . However, >> >>> import functions >>Traceback (most recent call last): >> File "", line 1, in ? >>ImportError: No module named functions > >Don't know why this didn't work. Does the Functions dir appear on sys.path? It does now with Command Prompt (still with no PYTHONPATH): E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg C:\WINDOWS\system32\python25.zip E:\Python25\DLLs E:\Python25\lib E:\Python25\lib\plat-win E:\Python25\lib\lib-tk E:\Python25 E:\Python25\lib\site-packages E:\Python25\lib\site-packages\PIL E:\PythonWork\Functions E:\Python25\lib\site-packages\win32 E:\Python25\lib\site-packages\win32\lib E:\Python25\lib\site-packages\Pythonwin E:\Python25\lib\site-packages\wx-2.8-msw-unicode >>> But not with IDLE, nor with Ulipad. Here's Ulipad's sys.path E:\Programs\Ulipad3.7\packages E:\Programs\Ulipad3.7\plugins E:\Programs\Ulipad3.7\modules E:\Programs\Ulipad3.7 E:\Programs\Ulipad3.7 E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg C:\WINDOWS\system32\python24.zip E:\Programs\Ulipad3.7 E:\Python24\DLLs E:\Python24\lib E:\Python24\lib\plat-win E:\Python24\lib\lib-tk E:\Python24 E:\Python24\lib\site-packages E:\Python24\lib\site-packages\wx-2.6-msw-ansi And import functions fails with both IDLE and Ulipad: >>> import functions Traceback (most recent call last): File "", line 1, in ? ImportError: No module named functions >>> but works in Command Prompt. I put a file, tester.py, in E:\PythonWork\TestA with the only lines: from functions import cube print cube(123) testor.py runs OK in Ulipad and Command Prompt, but not with IDLE. Well, I've learned a lot. Seems I'd better go back to using just PYTHONPATH. And this time I'll know what I'm doing, thanks to Kent and Alan. Dick From seancron+pythontutor at gmail.com Sun Sep 2 18:37:04 2007 From: seancron+pythontutor at gmail.com (Sean Cronin[tutor]) Date: Sun, 2 Sep 2007 12:37:04 -0400 Subject: [Tutor] Best way to construct this Message-ID: Hey, Thanks Alan for the help on the classes. This is my first time using them (in case you couldn't tell :) ). However, I can't understand why you want to make a separate function called parse. What I am trying to do by having different functions in the class like maxtemp, and mintemp, is to allow my self to be able to parse only for certain data, instead of having one giant function that parses for everything. That way I have the option of being able to selectively parse the data. It also gives me the option as you said of being able to reparse the data later if it became corrupted somehow. Also, where should I put the value for the maxtempnode since you set them equal to none in the pseudo code you sent. >class Weather: > def init(self, fname): > self.filename = fname > self.data = None > self.maxtemp = None > self.maxnode = None Should I change the None to what their values should be, or should I do that at some point later in the code? Thanks, -Sean -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/fc37cd6c/attachment.htm From varsha.purohit at gmail.com Sun Sep 2 19:12:18 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 10:12:18 -0700 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: References: Message-ID: Thanks Eric and Alan i did that with while loop. I donno i was getting an error while using a for loop for subindexing. Here is what i did i=0 selectCols=0 arr2=[] while icolID is the value of the requested column to print. which remains the same throughout the iteration of while. On 9/2/07, Alan Gauld wrote: > > > "Varsha Purohit" wrote > > > grid = [[1,1,2,7,6,9],\ > > [,9,1,1,1,9,1],\ > > [8,1,2,0,0,4],\ > > [1,4,1,1,8,5]] > > You don't need the '\' characters, the fact that the closing > bracket has not been reached means Python will ignore > the newline characters. > > > how can i access to all the elements of the list from column no. 5. > > > > output should be like [6,9,0,8]... > > Others have already shown but the easiest way to build a list > from another list is via a list comprehension so: > > col5 = [row[4] for row in grid] > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Varsha Purohit, Graduate Student, San Diego State University -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/e5be1f7c/attachment.htm From ricaraoz at gmail.com Sun Sep 2 19:52:50 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 14:52:50 -0300 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: References: Message-ID: <46DAF872.1080604@bigfoot.com> Varsha Purohit wrote: > Thanks Eric and Alan i did that with while loop. I donno i was getting > an error while using a for loop for subindexing. Here is what i did > > i=0 > selectCols=0 > arr2=[] > while i selectCols=grid[i][colID] > i+=1 > arr2.append(selectCols) > > print "col",colID,"values :",arr2 > How about : print 'Col', colID, 'values :', ', '.join([str(i[colID]) for i in grid]) From simong1080 at gmail.com Sun Sep 2 19:10:17 2007 From: simong1080 at gmail.com (shimon gurman) Date: Sun, 2 Sep 2007 19:10:17 +0200 Subject: [Tutor] Backupfile program. Help. Thanks. Message-ID: <6f4832f90709021010j2a9708e0rce1f79f6a42e1f95@mail.gmail.com> Can someone explain to me why this program isnt working? i.e. I always get 'backup failed'? This is a program from byte of python tutorial and im using windows xp. import os, time source = ['d:\\python'] target_directory = 'd:\\python1' target = target_directory + time.strftime('%Y%m%d_%H%M%S') + '.zip' zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) print zip_command if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/3419ec32/attachment.htm From ricaraoz at gmail.com Sun Sep 2 21:01:02 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 16:01:02 -0300 Subject: [Tutor] Backupfile program. Help. Thanks. In-Reply-To: <6f4832f90709021010j2a9708e0rce1f79f6a42e1f95@mail.gmail.com> References: <6f4832f90709021010j2a9708e0rce1f79f6a42e1f95@mail.gmail.com> Message-ID: <46DB086E.8010700@bigfoot.com> shimon gurman wrote: > Can someone explain to me why this program isnt working? i.e. I always get 'backup failed'? > This is a program from byte of python tutorial and im using windows xp. > > > > > import os, time > > > > source = ['d:\\python'] > > > target_directory = 'd:\\python1' > > target = target_directory + time.strftime('%Y%m%d_%H%M%S') + '.zip' > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > print zip_command > > > if os.system(zip_command) == 0: > print 'Successful backup to', target > else: > print 'Backup FAILED' > try (I'm guessing) : target_directory = 'd:\\python1\\' and / or zip_command = 'zip -qr "%s" "%s"' % (target, ' '.join(source)) (your second %s was not enclosed in ", besides it's probably better to use " than ', can't remember right now) Are you sure that is a '-qr' or should it be '-pr'? I can not check it because I use 7-zip (here p would set password and r recurse directories). From alan.gauld at btinternet.com Sun Sep 2 21:11:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 20:11:54 +0100 Subject: [Tutor] Best way to construct this References: Message-ID: "Sean Cronin[tutor]" wrote > (in case you couldn't tell :) ). However, I can't understand why > you want > to make a separate function called parse. OK, I want to make a separate *method* called parse, not a function. Methods are what you have inside classes. You send messages to instances and those messages cause methods to be executed. That's an important concept to get your head around. It's not the same as simply functions. Why have a separate parse method? Three reasons: 1) It keeps the init method simple. init methods are for initialising the state of the object, they should not normally contain any complex code. 2) If, after creating an instance of your class and working with it the data gets corrupted for any reason you can reinstate the original data by calling the parse method. 3) If you should ever have reason to subclass this class having the parse method available as a method allws you to have a new parse algorithm (maybe using a different parser) without having to change the rest of the code. OTOH is the parsing is the same but the other methods change you can leave it as is. If the parsing is in the init then you can almost guarantee that the init will change and you will have to rewrite the parse code in each suib class. > different functions in the class like maxtemp, and mintemp, is to > allow my > self to be able to parse only for certain data, Thats fine, although maxtemp is an attribute not a function/method. > instead of having one giant function that parses for everything. > That > way I have the option of being able to selectively parse the data. > It also gives me the option as you said of being able to reparse the > data later if it became corrupted somehow. I'm not sure how. Your original function did the parsing in the init method and set the values of maxtemp nodede etc from the resultant parse tree. > Also, where should I put the value for the maxtempnode since > you set them equal to none in the pseudo code you sent. I initialised tem to None because you can't set their values till after parsing the file. Thus you would have to set up the max etc in the parse method. >>class Weather: >> def init(self, fname): >> self.filename = fname >> self.data = None >> self.maxtemp = None >> self.maxnode = None > > Should I change the None to what their values should be, or should I > do that > at some point later in the code? Reading your code it looked like the values were dependent on the parsed file. If you know before parsing what they are then I'd make them parameters of init with defaults: def __Iinit__(self, fname, max=42, min=0, node=???): self.filename = fname self.data = None self.maxtemp = max self.mintemp = min self.maxnode = node I'm not sure enough of how your class will be used to know which solution fits best. However the main point is that classes are not just collections of functions - thats what modules are for - they are supposed to be representations of whole entities within your program - objects. The objects have behaviours - their methods and they manage data for you (via the methods). Thus you should think carefully about what objects your class represents and what purpose those objects serve (what are their responsibilities?). HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jim at well.com Sun Sep 2 21:46:57 2007 From: jim at well.com (jim stockford) Date: Sun, 2 Sep 2007 12:46:57 -0700 Subject: [Tutor] about modules, classes, methods, functions Message-ID: <830f90023849591ba15846a08e0d316c@well.com> I've gotten red-eyed looking through google pages to find answers. I've read the python.org docs and tutorials entirely (some parts very quickly). If I write a little .py file, its name is __main__ assuming no big nit-picks in the claim above, is __main__ a class? What exactly does it mean "module" and how is that different from a class. Is it sufficient to define a class as some executable code that gets run when it's loaded? Someone has so defined, but I don't think it's sufficient. classic definition of a function is some code that takes arguments and returns a single value. What's the definition of a function in python? how is a method different from a function? Is it just that a method is a member of a class, i.e. can a class have both methods and functions? thanks in advance. jim From davmillar at gmail.com Sun Sep 2 19:24:33 2007 From: davmillar at gmail.com (David Millar) Date: Sun, 2 Sep 2007 13:24:33 -0400 Subject: [Tutor] Condensing Some Massive Code Message-ID: Hello. I'm working on a text adventure game right now, and I seem to be kind of stuck. There's a huge chunk of code called moreaction() that pulls scripted events for certain locations. It's ever-changing so I'm not looking for specifics, but can anyone suggest good ways to clean up or condense the code without sacrificing clarity? The latest version of the source is found at http://thegriddle.net/python/v006.txt Any help is much appreciated :) - Dave M. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/c9c20904/attachment-0001.htm From kent37 at tds.net Sun Sep 2 23:45:52 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Sep 2007 17:45:52 -0400 Subject: [Tutor] about modules, classes, methods, functions In-Reply-To: <830f90023849591ba15846a08e0d316c@well.com> References: <830f90023849591ba15846a08e0d316c@well.com> Message-ID: <46DB2F10.1070309@tds.net> jim stockford wrote: > I've gotten red-eyed looking through google pages > to find answers. I've read the python.org docs and > tutorials entirely (some parts very quickly). > > If I write a little .py file, its name is __main__ > > assuming no big nit-picks in the claim above, > is __main__ a class? No, it is a module. > What exactly does it mean "module" and how > is that different from a class. A module corresponds to a single file of source code. A class is...well, the object created when you execute a 'class' statement. Classes are defined in modules. I'm struggling with this one. How do you see them as the same? They both contain and organize functions but the way they are used is very different. > Is it sufficient to define a class as some executable > code that gets run when it's loaded? Someone has > so defined, but I don't think it's sufficient. Any executable code? No. A class is a particular kind of object, created (usually) by a class statement. > classic definition of a function is some code that > takes arguments and returns a single value. What's > the definition of a function in python? That sounds OK. > > how is a method different from a function? Is it > just that a method is a member of a class, Yes. > i.e. can > a class have both methods and functions? A class can have static methods and class methods which are functions but not the same as normal methods. Kent From varsha.purohit at gmail.com Mon Sep 3 00:21:17 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 15:21:17 -0700 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings Message-ID: Hello, i have again very basic question in python string management. I am not able to understand how find and index works and what do they actually return. >>> line = "this is varsha" >>> print line.find("is") 2 >>> print line.rfind("is") 5 >>> print line.rfind("varsha") 8 >>> print line.index("varsha") 8 what does 2 in first line signifies... and why rfind gave 5 as an output... can anybody pls explain me what exactly is interpreter tryin to return..... -- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/9c8726bc/attachment.htm From alan.gauld at btinternet.com Mon Sep 3 00:20:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 23:20:52 +0100 Subject: [Tutor] about modules, classes, methods, functions References: <830f90023849591ba15846a08e0d316c@well.com> Message-ID: "jim stockford" wrote > If I write a little .py file, its name is __main__ > > assuming no big nit-picks in the claim above, > is __main__ a class? No, its the name of your module when its run as a script rather than imported. Its assigned by the interpreter. (At least i assumev you haven't literally called your file __main__.py, that might cause Python some confusion!) > What exactly does it mean "module" and how > is that different from a class. A module is a file which contains code. That code could define functions and/or classes It could also define variables as well as contain executable code (loops etc) > Is it sufficient to define a class as some executable > code that gets run when it's loaded? Someone has > so defined, but I don't think it's sufficient. A class definition is executable just like a function definition. But the execution of the code produces a class object. By calling that class object you create an instance of the class (also, somewhat confusingly called an Object) > classic definition of a function is some code that > takes arguments and returns a single value. What's > the definition of a function in python? Pretty much the same. But in the event that the function does not explicitly return a value Python provides a default return of None. Also python return values can include tuples which appear like multiple return values: def maxmin(aSequence): mx = max(aSequence) mn = min(aSequence) return mx,mn x,n = maxmin([1,2,3,4,5,6,7]) > how is a method different from a function? Is it > just that a method is a member of a class, i.e. can > a class have both methods and functions? It differs in several ways. The primary one is that it is defined inside a class. Also the first parameter is the instance to which the method applies at run time and is not explicitly given at execution time. class C: def meth(self,x): print x c = C() c.meth(42) So meth is defined with two parameters but called with one. In pure OOP terms there is another important difference between a method and a function. A function is always called by name but a method is called by sending a "message" to an object. There is nothing in OOP theory (and in some languages in practice) that says the method must have the same name as the message Thus: class C: def _aMethod(self): print 'aMethod is running' foo = _aMethod c = C() c._aMethod() c.foo() Here we send two messages to c but both execute the same method. Other languages (eg. Lisp, Objective C, Eiffel) allow us to explicitly name the method invoked by a message and have the two take different names. Python doesn't support that. Note: The concept of sending a message as distinct from calling a method is quite fundamental to thinking about objects as dynamic emntities within a program. In a theoretically pure OOP environment each object would be a separate process and the messages would be literal inter-process messages. But such a pure approach would be utterly impractical on todays technology - far too slow. However the concept is extremely important in computer science terms since such a machine can be represented mathematically and simulations can be created in much the same way as electronic engineers can build and execute models of circuits. Many software engineering academics believe that this may be the key to building truly reliable and predictable large scale software systems. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ricaraoz at gmail.com Mon Sep 3 01:03:42 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 20:03:42 -0300 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings In-Reply-To: References: Message-ID: <46DB414E.4010509@bigfoot.com> Varsha Purohit wrote: > Hello, > i have again very basic question in python string management. > > I am not able to understand how find and index works and what do they > actually return. > >>>> line = "this is varsha" >>>> print line.find("is") > 2 >>>> print line.rfind("is") > 5 >>>> print line.rfind("varsha") > 8 >>>> print line.index("varsha") > 8 > > what does 2 in first line signifies... and why rfind gave 5 as an output... > > can anybody pls explain me what exactly is interpreter tryin to return..... > Sure. The 2 in first line means the string 'is' begins in line[2] that would be the 'is' in 'this' (remember line's first character 't' is line[0]). OTOH rfind looks for the first appearance of 'is' in line but starting from the right, that would be the word 'is' which starts at line[5]. As there is only one occurrence of 'varsha' in line both methods, find and rfind will give the same answer : 8. >From Python 2.5 documentation : index( sub[, start[, end]]) Like find(), but raise ValueError when the substring is not found. HTH From varsha.purohit at gmail.com Mon Sep 3 01:48:56 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 16:48:56 -0700 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings In-Reply-To: <46DB414E.4010509@bigfoot.com> References: <46DB414E.4010509@bigfoot.com> Message-ID: Thanks guys it was really helpful.... i m just a beginner in python start to program since two days back. So finding little difficulty with some concepts. On 9/2/07, Ricardo Ar?oz wrote: > > Varsha Purohit wrote: > > Hello, > > i have again very basic question in python string management. > > > > I am not able to understand how find and index works and what do they > > actually return. > > > >>>> line = "this is varsha" > >>>> print line.find("is") > > 2 > >>>> print line.rfind("is") > > 5 > >>>> print line.rfind("varsha") > > 8 > >>>> print line.index("varsha") > > 8 > > > > what does 2 in first line signifies... and why rfind gave 5 as an > output... > > > > can anybody pls explain me what exactly is interpreter tryin to > return..... > > > Sure. > The 2 in first line means the string 'is' begins in line[2] that would > be the 'is' in 'this' (remember line's first character 't' is line[0]). > OTOH rfind looks for the first appearance of 'is' in line but starting > from the right, that would be the word 'is' which starts at line[5]. > As there is only one occurrence of 'varsha' in line both methods, find > and rfind will give the same answer : 8. > > From Python 2.5 documentation : > > index( sub[, start[, end]]) > Like find(), but raise ValueError when the substring is not found. > > > > HTH > > -- Varsha Purohit, Graduate Student, San Diego State University -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/4ab34417/attachment.htm From alan.gauld at btinternet.com Mon Sep 3 01:48:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 00:48:49 +0100 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings References: <46DB414E.4010509@bigfoot.com> Message-ID: "Ricardo Ar?oz" wrote >>From Python 2.5 documentation : > > index( sub[, start[, end]]) > Like find(), but raise ValueError when the substring is not found. As opposed to find() which returns -1 when the string is not found. That means you can use try/except with index but must check for -1 with find: if 'foo'.find('q') == -1: print 'oops!' as opposed to try: 'foo'.index('q') except ValueErrror: print 'oops!' Which style is best will depend on what you are doing. HTH, Alan g From ricaraoz at gmail.com Mon Sep 3 02:00:30 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 21:00:30 -0300 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings In-Reply-To: References: <46DB414E.4010509@bigfoot.com> Message-ID: <46DB4E9E.4010008@bigfoot.com> Varsha Purohit wrote: > > Thanks guys it was really helpful.... i m just a beginner in python > start to program since two days back. So finding little difficulty with > some concepts. > Don't worry, I'm a 20 days "old timer". ;c) From alan.gauld at btinternet.com Mon Sep 3 02:28:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 01:28:03 +0100 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings References: <46DB414E.4010509@bigfoot.com> <46DB4E9E.4010008@bigfoot.com> Message-ID: "Ricardo Ar?oz" wrote >> Thanks guys it was really helpful.... i m just a beginner in >> python >> start to program since two days back. So finding little difficulty >> with >> some concepts. >> > > Don't worry, I'm a 20 days "old timer". ;c) And I've been using Python for over 10 years now and still manage to pick up at least one new idea every week on this list! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From trey at opmstech.org Mon Sep 3 02:31:42 2007 From: trey at opmstech.org (Trey Keown) Date: Sun, 2 Sep 2007 19:31:42 -0500 (CDT) Subject: [Tutor] replacement for .mainloop() in Tk Message-ID: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> Okay, I'm making a program that turns xml code into python code. Here's the an example of input- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~ And here would be the corresponding output (well, what I've got so far...) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from Tkinter import * import tkFileDialog #<<<<
>>>># self = Tk() self.title("Example Window Title") self.iconbitmap("e.ico") #<<<<>>>># #<<<<>>>># #<<<<>>>># #<<<<>>>># ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now, as you probably see, there isn't a "self.mainloop()" function in the output. My question is- *Is there any other thing I could use instead of ".mainloop()" to make a window come up? Because I noticed that only one window can be up at a time that has a ".mainloop()" attribute. From rdm at rcblue.com Mon Sep 3 03:36:29 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 18:36:29 -0700 Subject: [Tutor] What's up with Python 2.5.1's IDLE? Message-ID: <20070903013638.687341E4006@bag.python.org> Under Kent's tutelage, I've been experimenting with having no PYTHONDOC, and instead putting a .pth file in E:\Python25\lib\site-packages\ I named pointers.pth. The contents of pointers.pth is: E:\Python25\ E:\PythonWork\ E:\PythonWork\Functions\ E:\Python25\lib\site-packages\ E:\Python25\lib\site-packages\mine Here's what the Command Prompt shell shows for sys.path: E:\Python25>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from sys import path >>> for x in path: ... print x ... E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg C:\WINDOWS\system32\python25.zip E:\Python25\DLLs E:\Python25\lib E:\Python25\lib\plat-win E:\Python25\lib\lib-tk E:\Python25 E:\Python25\lib\site-packages E:\Python25\lib\site-packages\PIL E:\PythonWork E:\PythonWork\Functions E:\Python25\lib\site-packages E:\Python25\lib\site-packages\mine E:\Python25\lib\site-packages\win32 E:\Python25\lib\site-packages\win32\lib E:\Python25\lib\site-packages\Pythonwin E:\Python25\lib\site-packages\wx-2.8-msw-unicode >>> All good. However, this is what IDLE's shell shows for sys.path: >>> from sys import path >>> for x in path: print x E:\Python25\Lib\idlelib E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg C:\WINDOWS\system32\python24.zip E:\Python25\Lib\idlelib E:\Python24\DLLs E:\Python24\lib E:\Python24\lib\plat-win E:\Python24\lib\lib-tk E:\Python24 E:\Python24\lib\site-packages E:\Python24\lib\site-packages\wx-2.6-msw-ansi I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell show all those things from 2.4, and only shows the path to itself in 2.5.1? I like the editing ease of having a .pth file rather than a troublesome-to-edit PYTHONDOC, but I need to first clear up the problem with IDLE (which works fine with a PYTHONDOC). Thanks, Dick Moores XP, Python 2.5.1 From alan.gauld at btinternet.com Mon Sep 3 09:25:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 08:25:11 +0100 Subject: [Tutor] replacement for .mainloop() in Tk References: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > from Tkinter import * > import tkFileDialog > #<<<<
>>>># > self = Tk() Using self here is a little bit unconventional sinmce its not in a class. That could confuse some readers. > self.title("Example Window Title") > self.iconbitmap("e.ico") > #<<<<>>>># > #<<<<>>>># > #<<<<>>>># > #<<<<>>>># > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Now, as you probably see, there isn't a "self.mainloop()" > function in the output. My question is- > *Is there any other thing I could use instead of ".mainloop()" to > make a > window come up? Because I noticed that only one window can be up at > a time > that has a ".mainloop()" attribute. I'm not sure what you mean by that. You can have as many windows as you like but there can only be one mainloop call, usually on the top level tk object not on a window at all. The mainloop is the event loop of the program. Without that Tk cannot capture any events and hence can't do anything. But why would having a mainloop be a problem? You can call it at the end of your code. (In fact you can call it at the beginning if you like! The end is just convention - and it does make inserting new controls etc less problematic) I'm slightly confused by what you are asking. What is the problem that you think you have? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Sep 3 09:39:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 08:39:16 +0100 Subject: [Tutor] What's up with Python 2.5.1's IDLE? References: <20070903013638.687341E4006@bag.python.org> Message-ID: "Dick Moores" wrote > Under Kent's tutelage, I've been experimenting with having no > PYTHONDOC, I assume you mean PYTHONPATH? > and instead putting a .pth file in > E:\Python25\lib\site-packages\ I named pointers.pth. I obviously failed to convince you of the superior flexibility of using PYTHONPATH for your personal libs :-) If your PC is only usd by you and you only have one user account then that probably isn't a problem, except you lose the flexibility of changing PYTHONPATH dynamically during a session using SET. > The contents of > pointers.pth is: > E:\Python25\ > E:\PythonWork\ > E:\PythonWork\Functions\ > E:\Python25\lib\site-packages\ > E:\Python25\lib\site-packages\mine I would have expected Python to load the Python25 stuff itself. You should only need the pointers file to contain the pointers to the non standard directories (just as you would in PYTHONPATH) > Here's what the Command Prompt shell shows for sys.path: > E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg > E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg > C:\WINDOWS\system32\python25.zip > E:\Python25\DLLs > E:\Python25\lib > E:\Python25\lib\plat-win > E:\Python25\lib\lib-tk > E:\Python25 > E:\Python25\lib\site-packages > E:\Python25\lib\site-packages\PIL > E:\PythonWork > E:\PythonWork\Functions > E:\Python25\lib\site-packages > E:\Python25\lib\site-packages\mine > E:\Python25\lib\site-packages\win32 > E:\Python25\lib\site-packages\win32\lib > E:\Python25\lib\site-packages\Pythonwin > E:\Python25\lib\site-packages\wx-2.8-msw-unicode > >>> > All good. Not quite all good - you have multiple entries for site-packages... > However, this is what IDLE's shell shows for sys.path: > > E:\Python25\Lib\idlelib > E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg > C:\WINDOWS\system32\python24.zip > E:\Python25\Lib\idlelib > E:\Python24\DLLs > E:\Python24\lib > E:\Python24\lib\plat-win > E:\Python24\lib\lib-tk > E:\Python24 > E:\Python24\lib\site-packages > E:\Python24\lib\site-packages\wx-2.6-msw-ansi > > I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell > show all those things from 2.4, and only shows the path to itself in > 2.5.1? It looks like IDLE has its own mechanism for populating sys.path and it may be reading something in the Registry. This might be a question to ask on the IDLE mailing list? > I like the editing ease of having a .pth file rather than a > troublesome-to-edit PYTHONDOC, but I need to first clear up the > problem with IDLE (which works fine with a PYTHONDOC). I'm not sure I understand what you mean by the editing ease? You can change PYTHONPATH with a simple SET command (albeit temporarily) and 3 mouse clicks takes you to the dialog editor. HTH, Alan G From kent37 at tds.net Mon Sep 3 12:31:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Sep 2007 06:31:35 -0400 Subject: [Tutor] replacement for .mainloop() in Tk In-Reply-To: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> References: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> Message-ID: <46DBE287.6080006@tds.net> Trey Keown wrote: > Okay, I'm making a program that turns xml code into python code. > > And here would be the corresponding output (well, what I've got so far...) > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > from Tkinter import * > import tkFileDialog > #<<<<
>>>># > self = Tk() > self.title("Example Window Title") > self.iconbitmap("e.ico") > #<<<<>>>># > #<<<<>>>># > #<<<<>>>># > #<<<<>>>># > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > Now, as you probably see, there isn't a "self.mainloop()" function in the > output. Why not just out put the mainloop() before <> ? You might be interested in http://www.bitflipper.ca/rapyd/ though it seems to store its data in pickles, not xml. Kent From kent37 at tds.net Mon Sep 3 12:34:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Sep 2007 06:34:19 -0400 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: <20070903013638.687341E4006@bag.python.org> References: <20070903013638.687341E4006@bag.python.org> Message-ID: <46DBE32B.3070809@tds.net> Dick Moores wrote: > However, this is what IDLE's shell shows for sys.path: > >>> from sys import path > >>> for x in path: > print x > > > E:\Python25\Lib\idlelib > E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg > C:\WINDOWS\system32\python24.zip > E:\Python25\Lib\idlelib > E:\Python24\DLLs > E:\Python24\lib > E:\Python24\lib\plat-win > E:\Python24\lib\lib-tk > E:\Python24 > E:\Python24\lib\site-packages > E:\Python24\lib\site-packages\wx-2.6-msw-ansi > > I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell > show all those things from 2.4, and only shows the path to itself in 2.5.1? It looks to me like IDLE is running under 2.4 but using the IDLE package from 2.5. Kent From srikanth007m at gmail.com Mon Sep 3 15:40:27 2007 From: srikanth007m at gmail.com (chinni) Date: Mon, 3 Sep 2007 06:40:27 -0700 Subject: [Tutor] indexing elements Message-ID: Hi all, i had some doubt about this line can any body clarify this plz....... endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th'] + ['st'] -- Best Regards, M.Srikanth Kumar, Jr.Software Developer, Google India Pvt Ltd.., HYDERABAD. Phone no: +91-9866774007 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070903/18dbcce8/attachment.html From ghashsnaga at gmail.com Mon Sep 3 19:47:09 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Mon, 3 Sep 2007 11:47:09 -0600 Subject: [Tutor] More class questions Message-ID: <2107481c0709031047t53332fb8q185fe92c396d6c8@mail.gmail.com> Hello again, Thank you again for your help. I have classes somewhat figured out and I am beginning to understand the syntax involved in using them. What I have so far is a very simple text adventure with two rooms, two items, and some exits. Two question which relates directly to classes: Do you create all your instances at the end of the program or just as needed? Can you call functions from other classes within a class (So I create an Object class for items and I want then instances to appear in the Room class as they are called). Third question. Using function I understand how to move a player around in different rooms using raw_input and if statements but how do you do that with classes. I created a player class and I want one of the methods to be moving from room to room. Or should movement be a separate class? I am looking at the code that Paul McGuire wrote for using pyparsing and I don't quite understand how it all works. I have to book Game Programming: The L line coming in two weeks. I am just trying to get a head start. Thank you. Ara CODE BELOW ##################################################################### #Text Advenuture - Roguelike #By Ara Kooser #Thanks to Chris, e.,Tino and Steven at python tutor #################################################################### class Player: #What makes this a player. pass #def Move(self): class Area: #What makes it an area? def __init__(self, name, description): #Number of arguements in the _init_ there must be defined self.name = name self.description = description self.contents = [] self.paths = [None,None,None,None] #Methods. What you can do. def AddObject(self,thing): self.contents.append(thing) def AddPaths(self,direction): self.paths.append(direction) def look(self): print "Look around the place you are in" print "You are in the",self.name print self.description print "Your exits are:" print self.paths def search(self): print "You search the area and find..." print self.contents ############################################################################### # MAIN # Start of program ############################################################################### first_instance = Area("Outside", "You are standing outside") first_instance.AddObject("Stick") first_instance.AddPaths("North") first_instance.look() first_instance.search() print print second_instance = Area("Inside", "You are standing inside") second_instance.AddObject("Iron pot") second_instance.AddPaths("South") second_instance.look() second_instance.search() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From dos.fool at gmail.com Mon Sep 3 22:06:48 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 3 Sep 2007 14:06:48 -0600 Subject: [Tutor] checking if a number is evan or odd Message-ID: hello just a quick check in, it's about the same program i was asking about before ive let it sit for a few days now and i reached a number to high to convert to a decimal by adding 0.0 here's the program: count=1 numstart=268549802 number=0 high=0 a=0 while 1==1: numstart=numstart+1 number=numstart count=1 while number !=1: if number/2 == (number+0.0)/2: number=number/2 else: number=(number*3)+1 count=count+1 if count > a: a=count print numstart,":",count after a few days i got this error: Traceback (most recent call last): File "homework6high.py", line 11, in if number/2 == (number+0.0)/2: OverflowError: long int too large to convert to float just wondering if theirs a way to check if a larger number is even or odd thanks From orest.kozyar at gmail.com Mon Sep 3 22:08:20 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Mon, 3 Sep 2007 16:08:20 -0400 Subject: [Tutor] Metaclass programming Message-ID: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> I have the following code: class meta(type): def __call__(cls, *args, **kwargs): argnames = inspect.getargspec(cls.__init__)[0] for i, value in enumerate(args): kwargs[argnames[i]] = value return type.__call__(cls, kwargs) class test(object): __metaclass__ = meta def __init__(self, x, y, **kwargs): pass However, inspect.getargspec(cls.__init__) appears to return only the arguments of the meta __init__ rather than the test __init__. Is there any way I can get access to the test __init__ function from the metaclass? Orest From jdoege at da-test.com Tue Sep 4 00:15:52 2007 From: jdoege at da-test.com (Jason Doege) Date: Mon, 3 Sep 2007 18:15:52 -0400 Subject: [Tutor] Dynamically changing a class Message-ID: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> Hi All, I'd like to change the behavior of a class' member function dynamically such that, once changed, all objects of the type would see the new behavior. For instance: >>> class MyClass (object) : def mfunc(self, data): print 'pre change behavior' >>> aMyClassObj = MyClass() >>> aMyClassObj.mfunc(data) pre change behavior >>> def MyClass.mfunc(self, data): #this does not work :-( print 'post change behavior' >>> aMyClassObj.mfunc(data) post change behavior Does anyone have any guidance on how to accomplish this? I'd also like to be able to add and delete attributes, similarly. Best regards, Jason Doege From washakie at gmail.com Tue Sep 4 01:37:57 2007 From: washakie at gmail.com (John) Date: Mon, 3 Sep 2007 16:37:57 -0700 Subject: [Tutor] binary data struct module Message-ID: Hello, I have an unformatted mixed type binary file I'm trying to read into Python. So far, I've gotten as far as: f2=file(infile,'rb') Dfmt=['3i','13s','7i','2f','2i','2f','2i','i'] #format for binary reading first bits if f2: print infile + ' has been opened' #for ft in Dfmt: # print ft a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt) for ln in a: print ln Which gives me: /cygdrive/c/washakie/binfile has been opened (21, 20060612, 0) ('Version 4.3',) (21, 12, -86400, -86400, -900, 12, 24) (-179.0, -90.0) (360, 180) (1.0, 1.0) (24, 16) (3,) however, how can I now assign variables based on the 'generator object' a? What exactly is this? When I try to do something like: print a[0] or print a(0) I get the error: Traceback (most recent call last): File "readheader.py", line 20, in print a[0] TypeError: 'generator' object is unsubscriptable My question is, how can I now work with 'a' so that i can use the values? Thanks! -- 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070903/be71470e/attachment.htm From kent37 at tds.net Tue Sep 4 03:38:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Sep 2007 21:38:38 -0400 Subject: [Tutor] indexing elements In-Reply-To: References: Message-ID: <46DCB71E.3020604@tds.net> chinni wrote: > Hi all, > > i had some doubt about this line can any body clarify this plz....... > endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * > ['th'] + ['st'] You can try it in the interactive interpreter: In [8]: endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th'] + ['st'] In [10]: print endings ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'] Kent From witham.ian at gmail.com Tue Sep 4 04:41:57 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 4 Sep 2007 14:41:57 +1200 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: References: Message-ID: Hi Max, A better way to check if a number is odd or even would be to find the remainder after it is divided by two. for instance: 4 divided by 2 = 2 with 0 remainder 5 divided by 2 = 2 with 1 remainder 6 divided by 2 = 3 with 0 remainder 7 divided by 2 = 3 with 1 remainder As well as the floor division operator '/', Python has another operator for finding the remainder (or 'modulus') On 9/4/07, max baseman wrote: > > hello just a quick check in, it's about the same program i was asking > about before ive let it sit for a few days now and i reached a number > to high to convert to a decimal by adding 0.0 > here's the program: > > count=1 > numstart=268549802 > number=0 > high=0 > a=0 > while 1==1: > numstart=numstart+1 > number=numstart > count=1 > while number !=1: > if number/2 == (number+0.0)/2: > number=number/2 > else: > number=(number*3)+1 > count=count+1 > if count > a: > a=count > print numstart,":",count > > > after a few days i got this error: > > Traceback (most recent call last): > File "homework6high.py", line 11, in > if number/2 == (number+0.0)/2: > OverflowError: long int too large to convert to float > > just wondering if theirs a way to check if a larger number is even or > odd > > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/d1c8c3bc/attachment.htm From witham.ian at gmail.com Tue Sep 4 04:53:36 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 4 Sep 2007 14:53:36 +1200 Subject: [Tutor] indexing elements In-Reply-To: References: Message-ID: Hi, I'm not too sure what your asking here, your code assigns the following to endings: ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'] This is what we would expect.. 17 * ['th'] causes 17 repetitions of 'th' in the list. certain operators, like the multiplication operator in your example, have additional behavior depending on what kind of data they are applied to. The repetition operator binds closer than the '+' as the following brackets show. endings = ['st', 'nd', 'rd'] + (17 * ['th']) + ['st', 'nd', 'rd'] + (7 * ['th']) + ['st'] Ian. On 9/4/07, chinni wrote: > > Hi all, > > i had some doubt about this line can any body clarify this plz....... > endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * > ['th'] + ['st'] > > -- > Best Regards, > M.Srikanth Kumar, > Jr.Software Developer, > Google India Pvt Ltd.., > HYDERABAD. > Phone no: +91-9866774007 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/01920139/attachment.htm From dos.fool at gmail.com Tue Sep 4 05:58:43 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 3 Sep 2007 21:58:43 -0600 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: <46DCC1BE.4030900@exemail.com.au> References: <46DCC1BE.4030900@exemail.com.au> Message-ID: cool thanks the problem was from a math book imp 1 but i already did the work i was just interested in what number had the most steps i could fin wanted to get to 1000 imagine how dismayed i was when it crashed at 965 On Sep 3, 2007, at 8:23 PM, Andrew James wrote: > I'd just go with > > if number%2 == 0: > number = number/2 > > Why do you need to convert it to a float? > > Off topic: > Is this a PE problem? I remember doing the same thing. > > max baseman wrote: >> hello just a quick check in, it's about the same program i was >> asking about before ive let it sit for a few days now and i >> reached a number to high to convert to a decimal by adding 0.0 >> here's the program: >> >> count=1 >> numstart=268549802 >> number=0 >> high=0 >> a=0 >> while 1==1: >> numstart=numstart+1 >> number=numstart >> count=1 >> while number !=1: >> if number/2 == (number+0.0)/2: >> number=number/2 >> else: >> number=(number*3)+1 >> count=count+1 >> if count > a: >> a=count >> print numstart,":",count >> >> >> after a few days i got this error: >> >> Traceback (most recent call last): >> File "homework6high.py", line 11, in >> if number/2 == (number+0.0)/2: >> OverflowError: long int too large to convert to float >> >> just wondering if theirs a way to check if a larger number is even >> or odd >> >> thanks >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> From trey at opmstech.org Tue Sep 4 07:16:57 2007 From: trey at opmstech.org (Trey Keown) Date: Tue, 4 Sep 2007 00:16:57 -0500 (CDT) Subject: [Tutor] Need some help with wxPython... Message-ID: <60287.68.191.136.241.1188883017.squirrel@webmail.opmstech.org> Hey all, I'm starting to drift away from Tkinter and enter the realm of wxPython. I've recently written a simple text editor in Tkinter, and I would like to know if anyone knows of a good example of a simple wxPython text editor (with the lines properly indented!!!), because all the examples I can find are improperly indented, or just don't work. Or perhaps a tutorial that covers all I need to know for making a text editor would work. Thanks for any help, Trey K. aka thetechgeek From alan.gauld at btinternet.com Tue Sep 4 10:23:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:23:01 +0100 Subject: [Tutor] More class questions References: <2107481c0709031047t53332fb8q185fe92c396d6c8@mail.gmail.com> Message-ID: "Ara Kooser" wrote > What I have so far is a very simple text adventure with two rooms, > two > items, and some exits. So presumably you have a Room class, an Item class and maybe an Exit class? > Two question which relates directly to classes: Do you create all > your instances at the end of the program or just as needed? You create objects as needed. There is no mystery you have been using objects almost since you started using Python. Strings are objects and you create them as you need them. Same with Files. Your own classes are no different except that the instantiation mechanism is a little bit different. > call functions from other classes within a class Yes, If your Room class contains a list of Items you can send messages to thoise items from your Room methods.: class Item: def __innit__(self,n): self.n = n def say(self): print 'item', n class Room: def __init__(self,id) self.items = [Item(42),Item(26)] self.id = id def describe(self): print 'Room:',self.id,'has:' for item in items: item.say() r = R('hall') r.describe() Notice that Room.describe calls the Item.say method... Also note that the Room constructor creates two instances of Item. > Third question. Using function I understand how to move a player > around in different rooms using raw_input and if statements but how > do > you do that with classes. You have a Player class and it has a move method. You create instances of players and ask them to move. If they are in a Room you move within the room - perhaps you move to an exit which will in turn return a new room which you assign to the player. Something like: class Exit: def __init__(self, toRroom) self.room = toRoom def pass(self): return self.room class Player: def __init__(self,location=None): self.location = location def move(self, direction): exit = self.location.exitAt(direction) self.location = exit.pass() Now when you call move('N') the player goes tonthe North exit and passes throough to the room on the other side. > I created a player class and I want one of > the methods to be moving from room to room. > Or should movement be a separate class? I doubt it, movement is an action not an object (usually), its a behaviour of other objects. If more than players can move you may create a Movableobject superclass and inherit the movement methods from that. > I am looking at the code that Paul McGuire wrote for using > pyparsing and I don't quite understand how it all works. I have to > book Game Programming: The L line coming in two weeks. I am just > trying to get a head start. Sorry, cant help there. Alan G. From alan.gauld at btinternet.com Tue Sep 4 10:37:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:37:30 +0100 Subject: [Tutor] Need some help with wxPython... References: <60287.68.191.136.241.1188883017.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > know if anyone knows of a good example of a simple wxPython text > editor wxPython comes with examples of text editors etc. It uses the amazing Scinitill widget upon which Pythonwin and Scite are both based. But look at the Py package which includes PyCrust, PyAlaMode and their widgets: ...Python24\Lib\site-packages\wx-2.8-msw-ansi\wx\py Also if you get serious about using wxPython get the book! It is invaluable. Alan G From alan.gauld at btinternet.com Tue Sep 4 10:43:12 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:43:12 +0100 Subject: [Tutor] binary data struct module References: Message-ID: "John" wrote > a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt) > for ln in a: print ln > > Which gives me: > > /cygdrive/c/washakie/binfile has been opened > (21, 20060612, 0) > ('Version 4.3',) > (21, 12, -86400, -86400, -900, 12, 24) > > however, how can I now assign variables based on the 'generator > object' a? > What exactly is this? When I try to do something like: > > My question is, how can I now work with 'a' so that i can use the > values? You akready have in your for loop. You printed the values. There is nothing to stop you assigning them to variables. You will need to figure out what each line contains (which line you are on) and unpack the values from the tuples. Alternatively put them into a list: values = [ln for ln in a] Now you can use indexing: theDate = values[1][1] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Tue Sep 4 10:50:45 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 04 Sep 2007 01:50:45 -0700 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: References: <20070903013638.687341E4006@bag.python.org> Message-ID: <20070904085057.548141E400B@bag.python.org> At 12:39 AM 9/3/2007, Alan Gauld wrote: >"Dick Moores" wrote > > > Under Kent's tutelage, I've been experimenting with having no > > PYTHONDOC, > >I assume you mean PYTHONPATH? Yes. Careless of me. > > and instead putting a .pth file in > > E:\Python25\lib\site-packages\ I named pointers.pth. > >I obviously failed to convince you of the superior flexibility >of using PYTHONPATH for your personal libs :-) >If your PC is only usd by you and you only have one >user account then that probably isn't a problem, I'm the only user. >except you lose the flexibility of changing PYTHONPATH >dynamically during a session using SET. Could you show me how to use SET? And an example where it would be useful? > > The contents of > > pointers.pth is: > > E:\Python25\ > > E:\PythonWork\ > > E:\PythonWork\Functions\ > > E:\Python25\lib\site-packages\ > > E:\Python25\lib\site-packages\mine > >I would have expected Python to load the Python25 stuff itself. >You should only need the pointers file to contain the pointers >to the non standard directories (just as you would in PYTHONPATH) > > > this is what IDLE's shell shows for sys.path: > > > > E:\Python25\Lib\idlelib > > E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg > > C:\WINDOWS\system32\python24.zip > > E:\Python25\Lib\idlelib > > E:\Python24\DLLs > > E:\Python24\lib > > E:\Python24\lib\plat-win > > E:\Python24\lib\lib-tk > > E:\Python24 > > E:\Python24\lib\site-packages > > E:\Python24\lib\site-packages\wx-2.6-msw-ansi > > > > I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell > > show all those things from 2.4, and only shows the path to itself in > > 2.5.1? > >It looks like IDLE has its own mechanism for populating sys.path >and it may be reading something in the Registry. This might be >a question to ask on the IDLE mailing list? I couldn't find an IDLE list other than the one for IDLE developers (could I, as a lowly user, ask a question there?). But yours and Kent's hints and a lot of help from the developer of Ulipad (Ulipad was showing similar problems with what its shell showed for sys.path--lots if 2.4 stuff) led me to reinstalling 2.5.1 and uninstalling 2.4, plus doing some registry editing. I think I've finally succeeded. Here's what I have for my .pth file (I cut out some of what I had before, thanks to your comment): E:\PythonWork\Functions\ E:\Python25\lib\site-packages\mine And IDLE's shell now shows me this for sys.path: IDLE 1.2.1 >>> import functions >>> from sys import path >>> for x in path: print x E:\Python25\Lib\idlelib E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg C:\WINDOWS\system32\python25.zip E:\Python25\DLLs E:\Python25\lib E:\Python25\lib\plat-win E:\Python25\lib\lib-tk E:\Python25 E:\Python25\lib\site-packages E:\Python25\lib\site-packages\PIL E:\PythonWork\Functions E:\Python25\lib\site-packages\mine E:\Python25\lib\site-packages\win32 E:\Python25\lib\site-packages\win32\lib E:\Python25\lib\site-packages\Pythonwin E:\Python25\lib\site-packages\wx-2.8-msw-unicode >>> And a similar good result with Ulipad. > > I like the editing ease of having a .pth file rather than a > > troublesome-to-edit PYTHONDOC > >I'm not sure I understand what you mean by the editing ease? >You can change PYTHONPATH with a simple SET command >(albeit temporarily) and 3 mouse clicks takes you to the dialog >editor. Yes, I guess you're right. Still, with no clicks and a shortcut key I can get directly to pointer.pth in Textpad . From alan.gauld at btinternet.com Tue Sep 4 10:52:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:52:42 +0100 Subject: [Tutor] Dynamically changing a class References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> Message-ID: "Jason Doege" wrote > I'd like to change the behavior of a class' member function > dynamically > such that, once changed, all objects of the type would see the new > behavior. >>>> class MyClass (object) : > def mfunc(self, data): > print 'pre change behavior' > >>>> aMyClassObj = MyClass() >>>> aMyClassObj.mfunc(data) > pre change behavior >>>> def MyClass.mfunc(self, data): #this does not work :-( > print 'post change behavior' You need to do it thusly: def newfunc(self, data): print 'post change' MyClass.mfunc = newfunc That seems to work. I'm slightly surprised since I didn't know if it would, but it seems to! Alan G From alan.gauld at btinternet.com Tue Sep 4 10:54:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:54:27 +0100 Subject: [Tutor] indexing elements References: Message-ID: "chinni" wrote > > i had some doubt about this line can any body clarify this > plz....... > endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 > * ['th'] > + ['st'] Using the interpreter: >>> endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + >>> 7 * ['th'] + ['st'] >>> endings ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th'] What are your doubts? Alan G. From alan.gauld at btinternet.com Tue Sep 4 11:00:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 10:00:53 +0100 Subject: [Tutor] checking if a number is evan or odd References: Message-ID: Max, > just wondering if theirs a way to check if a larger number is even > or > odd I notice this is homework so I won't give a direct answer. But look at the mod operator '%' - It returns the remainder of an integer division. An even number is exactly divisible by 2. HTH, Alan G. "max baseman" wrote > about before ive let it sit for a few days now and i reached a > number > to high to convert to a decimal by adding 0.0 Thats a terrible way to convert to a float. Just use the float function (actually a type): f = float(anInt) But to determine if its odd/even you don't need to use floats at all. > here's the program: > > count=1 > numstart=268549802 > number=0 > high=0 > a=0 > while 1==1: > numstart=numstart+1 > number=numstart > count=1 > while number !=1: > if number/2 == (number+0.0)/2: > number=number/2 > else: > number=(number*3)+1 > count=count+1 > if count > a: > a=count > print numstart,":",count Hmm, I have no idea what this is doing... > > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dianahawks at optusnet.com.au Tue Sep 4 11:14:54 2007 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Tue, 4 Sep 2007 19:14:54 +1000 Subject: [Tutor] searching a text file Message-ID: <003101c7eed4$166f7870$5595693a@SNNECCM> Dear list, I have been teaching Python with minimal knowledege myself!! I need to be able to search a text file that perhaps contains names and scores. How do I find a particular name, change the score and then save the changes back to the text file again?? Thanks for any help. Diana -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/43c9ffef/attachment.htm From alan.gauld at btinternet.com Tue Sep 4 11:35:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 10:35:24 +0100 Subject: [Tutor] What's up with Python 2.5.1's IDLE? References: <20070903013638.687341E4006@bag.python.org> <20070904085057.548141E400B@bag.python.org> Message-ID: "Dick Moores" wrote >>except you lose the flexibility of changing PYTHONPATH >>dynamically during a session using SET. > > Could you show me how to use SET? And an example where it would be > useful? Imagine you are in a DOS command session C:> SET PYTHONPATH=C:\MYNEWFOLDER;%PYTHONPATH% prepends a folder to PYTHONPATH Now next time you run Python it will pick up the extra folder C:> SET PYTHONPATH displays the current value finally C:>SET PYTHONPATH=%PYTHONPATH:Python25=Python24% edits the existing path to substitute Python24 for each occurence of python25 SET /P allows multi line entry. SET is quite surprisingly powerful. Try HELP SET for more info The big downside is that these changes only apply to the current environment. (Which is the point of an *environment* variable after all :-) You still need to edit the variable if you want a permanant change Alan G From alan.gauld at btinternet.com Tue Sep 4 11:39:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 10:39:22 +0100 Subject: [Tutor] searching a text file References: <003101c7eed4$166f7870$5595693a@SNNECCM> Message-ID: "Diana Hawksworth" wrote > How do I find a particular name, change the score and then save > the changes back to the text file again?? iterate over the file checking (and modifying) each line write the line back out: Pseudo code Out = open('foo.txt','w') for line in file('foo.txt'): if 'somestring' in line: line = 'I changed it\n' Out.write(line) Out.close() You will find much more on this in my file handling topic in my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Tue Sep 4 11:53:05 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 04 Sep 2007 02:53:05 -0700 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: References: <20070903013638.687341E4006@bag.python.org> <20070904085057.548141E400B@bag.python.org> Message-ID: <20070904095315.1D3F01E400B@bag.python.org> At 02:35 AM 9/4/2007, Alan Gauld wrote: >"Dick Moores" wrote > > >>except you lose the flexibility of changing PYTHONPATH > >>dynamically during a session using SET. > > > > Could you show me how to use SET? And an example where it would be > > useful? > >Imagine you are in a DOS command session > >C:> SET PYTHONPATH=C:\MYNEWFOLDER;%PYTHONPATH% > >prepends a folder to PYTHONPATH >Now next time you run Python it will pick up the extra folder > >C:> SET PYTHONPATH > >displays the current value > >finally > >C:>SET PYTHONPATH=%PYTHONPATH:Python25=Python24% > >edits the existing path to substitute Python24 for each occurence of >python25 > >SET /P > >allows multi line entry. > >SET is quite surprisingly powerful. You've given me a new toy! Thanks. >Try HELP SET for more info That's a LOT of info! >The big downside is that these changes only apply to the current >environment. (Which is the point of an *environment* variable after >all :-) >You still need to edit the variable if you want a permanant change Just to make sure I understand, do you mean that the effects of using SET do not last between rebootings? Thanks, Alan. Dick From kent37 at tds.net Tue Sep 4 13:46:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 07:46:20 -0400 Subject: [Tutor] binary data struct module In-Reply-To: References: Message-ID: <46DD458C.404@tds.net> John wrote: > f2=file(infile,'rb') > > Dfmt=['3i','13s','7i','2f','2i','2f','2i','i'] #format for binary > reading first bits > > if f2: > print infile + ' has been opened' > #for ft in Dfmt: > # print ft > a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt) > for ln in a: print ln however, how can I now assign variables based on the 'generator object' > a? What exactly is this? a is a generator which is an iterable object. Access to its values is through the iterator protocol such as the for loop you use. > My question is, how can I now work with 'a' so that i can use the values? Use a list comprehension instead of a generator expression: a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt] This creates a list instead of a generator object. Kent From kent37 at tds.net Tue Sep 4 14:02:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 08:02:59 -0400 Subject: [Tutor] Metaclass programming In-Reply-To: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> References: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> Message-ID: <46DD4973.9090409@tds.net> Orest Kozyar wrote: > I have the following code: > > class meta(type): > > def __call__(cls, *args, **kwargs): > argnames = inspect.getargspec(cls.__init__)[0] > for i, value in enumerate(args): > kwargs[argnames[i]] = value This could be written kwargs.update(zip(argnames, args)) > return type.__call__(cls, kwargs) You are passing kwargs as a positional argument to __call__(); i.e. passing the dict as an ordinary parameter. To use kwargs as the keyword dict for the call, use the syntax type.__call__(cls, **kwargs) > class test(object): > > __metaclass__ = meta > > def __init__(self, x, y, **kwargs): > pass > > However, inspect.getargspec(cls.__init__) appears to return only the > arguments of the meta __init__ rather than the test __init__. Is there any > way I can get access to the test __init__ function from the metaclass? It works for me: import inspect class meta(type): def __call__(cls, *args, **kwargs): print inspect.getargspec(cls.__init__) return type.__call__(cls, *args, **kwargs) class test(object): __metaclass__ = meta def __init__(self, x, y, **kwargs): pass test(1, 2) prints (['self', 'x', 'y'], None, 'kwargs', None) I think the problem is elsewhere in your code. When I use return type.__call__(cls, kwargs) I get TypeError: __init__() takes exactly 3 arguments (2 given) because test.__init__() is still expecting the two required positional arguments. Why are you doing this? Kent From wormwood_3 at yahoo.com Tue Sep 4 15:06:49 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 4 Sep 2007 06:06:49 -0700 (PDT) Subject: [Tutor] Integer ID Caching Message-ID: <833966.63555.qm@web32415.mail.mud.yahoo.com> I came across the topic of internal Python IDs recently, and learned that the internal numeric ids of small integers are cached to increase speed. I had read that as of 2.5, this applied to integers between -1 and 100. However, doing some quick tests, this seems not to be accurate: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 10 >>> b = 10 >>> print id(a), id(b) 135716556 135716556 >>> c = 250 >>> d = 250 >>> print id(c), id(d) 135719604 135719604 >>> e = 300 >>> f = 300 >>> print id(e), id(f) 135718812 135718824 So the upper end of the interning range appears to be between 250 and 300, not 100. Does anyone know the exact number, when it changed, and if a decision has been made for future changes? I was unable to find anything specific to this in the documentation. Thanks as always, Sam From kent37 at tds.net Tue Sep 4 15:25:17 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 09:25:17 -0400 Subject: [Tutor] Integer ID Caching In-Reply-To: <833966.63555.qm@web32415.mail.mud.yahoo.com> References: <833966.63555.qm@web32415.mail.mud.yahoo.com> Message-ID: <46DD5CBD.6060003@tds.net> wormwood_3 wrote: > I came across the topic of internal Python IDs recently, and learned that the internal numeric ids of small integers are cached to increase speed. I had read that as of 2.5, this applied to integers between -1 and 100. However, doing some quick tests, this seems not to be accurate: > > Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a = 10 >>>> b = 10 >>>> print id(a), id(b) > 135716556 135716556 >>>> c = 250 >>>> d = 250 >>>> print id(c), id(d) > 135719604 135719604 >>>> e = 300 >>>> f = 300 >>>> print id(e), id(f) > 135718812 135718824 > > So the upper end of the interning range appears to be between 250 and 300, not 100. > > Does anyone know the exact number, From Python-2.5.1/Objects/intobject.c: #ifndef NSMALLPOSINTS #define NSMALLPOSINTS 257 #endif #ifndef NSMALLNEGINTS #define NSMALLNEGINTS 5 #endif #if NSMALLNEGINTS + NSMALLPOSINTS > 0 /* References to small integers are saved in this array so that they can be shared. The integers that are saved are those in the range -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). */ > when it changed, Python 2.4.1 has #ifndef NSMALLPOSINTS #define NSMALLPOSINTS 100 Here is the actual changeset: http://svn.python.org/view?rev=42552&view=rev which references this RFE which includes the reason for the change: http://bugs.python.org/issue1436243 and if a decision has been made for future changes? I doubt it, it will change in response to some unanticipated future requirement, just as it did in this case. Kent From orest.kozyar at gmail.com Tue Sep 4 15:41:51 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Tue, 4 Sep 2007 09:41:51 -0400 Subject: [Tutor] Metaclass programming In-Reply-To: <46DD4973.9090409@tds.net> References: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> <46DD4973.9090409@tds.net> Message-ID: <003701c7eef9$5ac277f0$bd32000a@issphoenix> > This could be written > kwargs.update(zip(argnames, args)) Nice trick! Thanks for the pointer. > > return type.__call__(cls, kwargs) > > You are passing kwargs as a positional argument to __call__(); i.e. > passing the dict as an ordinary parameter. To use kwargs as > the keyword dict for the call, use the syntax > type.__call__(cls, **kwargs) Great, I did not realize that ** was part of the syntax so couldn't figure out what the issue was. It works smoothly now. > I think the problem is elsewhere in your code. You're right. I just figured out that for some reason, when I use the SQLAlchemy mapper() function to map my classes to the corresponding table object, it seems to affect inspect.getargspec(). For example: from sqlalchemy.orm import mapper from sqlalchemy import Table, MetaData import inspect class Foo: def __init__(self, x, y): pass print inspect.getargspec(Foo.__init__) >> (['self', 'x', 'y'], None, None, None) metadata = MetaData() foo_table = Table('foo', metadata) mapper(Foo, foo_table) print inspect.getargspec(Foo.__init__) >> (['instance'], 'args', 'kwargs', None) I'm not sure why this would be the case, but is a bit frustrating since I do need the names of the positional arguments sometimes. > Why are you doing this? Partially as an exercise to help me better understand Python inspection as well as metaclass programming. I also am using it in a EntitySingleton metaclass that I adapted from the SQLAlchemy wiki (http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject). Some of my classes have unique constraints, and I want the metaclass to check these unique constraints and return an object from the database if an object meeting these constraints already exists. For example: class User: __unique__ = ['firstname', 'lastname'] __metaclass__ = EntitySingleton def __init__(self, firstname, lastname, password): pass The metaclass knows what the "unique" constraints are based on the __unique__ list, but needs to use inspect.getargspec() to get the variable names and match them up with the *args list that EntitySingleton.__call__ recieves. At least, that's how I'm trying to do it, but I expect this might not be the best way to do it? Either case, when the class is mapped to a database table, I lose all this information, so will need to figure out a different way of approaching this. Orest From srikanth007m at gmail.com Tue Sep 4 15:57:04 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 4 Sep 2007 06:57:04 -0700 Subject: [Tutor] advanced sorting Message-ID: In Advance Sorting by giving the keywords to sort the list.But, iam getting the fallowing errors >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] >>> x.sort(key=len) Traceback (most recent call last): File "", line 1, in ? TypeError: sort() takes no keyword arguments >>> x.sort(reverse=True) Traceback (most recent call last): File "", line 1, in ? TypeError: sort() takes no keyword arguments -Best Regards, M.srikanth. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/09c67891/attachment.htm From kent37 at tds.net Tue Sep 4 16:12:10 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 10:12:10 -0400 Subject: [Tutor] advanced sorting In-Reply-To: References: Message-ID: <46DD67BA.5010308@tds.net> chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments Are you using an old version of Python? Support for sort(key=fn) was added in Python 2.4. Kent From alan.gauld at btinternet.com Tue Sep 4 17:16:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 16:16:28 +0100 Subject: [Tutor] What's up with Python 2.5.1's IDLE? References: <20070903013638.687341E4006@bag.python.org><20070904085057.548141E400B@bag.python.org> <20070904095315.1D3F01E400B@bag.python.org> Message-ID: "Dick Moores" wrote > Just to make sure I understand, do you mean that the effects of > using > SET do not last between rebootings? Correct, they only work on the current environment. Very useful if you have two environments such as development and test. You can just swap environment values etc to toggle between them. But any permanaent changes must be added to the Env variables via the dialog box. Alan G From brunson at brunson.com Tue Sep 4 21:39:06 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 04 Sep 2007 13:39:06 -0600 Subject: [Tutor] advanced sorting In-Reply-To: References: Message-ID: <46DDB45A.4060502@brunson.com> What version of python are you using? chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments > > > -Best Regards, > M.srikanth. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From noufal at airtelbroadband.in Tue Sep 4 21:30:44 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 05 Sep 2007 01:00:44 +0530 Subject: [Tutor] advanced sorting In-Reply-To: References: Message-ID: <46DDB264.7010006@airtelbroadband.in> chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments > > Seems to work fine for me. What version of Python are you using? >>> x=['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] >>> x.sort(reverse=True) >>> x ['will', 'srikanth', 'muppandam', 'kumar', 'be', 'a'] >>> -- ~noufal From dos.fool at gmail.com Wed Sep 5 00:19:30 2007 From: dos.fool at gmail.com (max baseman) Date: Tue, 4 Sep 2007 16:19:30 -0600 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: References: Message-ID: <9DE3FA2B-90AB-4F44-9B0C-590C63E5482F@gmail.com> cool thanks thats what i changed it to than just now i changed to do something else and instead of leaving the program running for 4 or 5 days as i had been i got my answer in less than a second ^_^" i realized that i was wasting way to much time checking every possible answer because the number is jumping around so much so instead i wrote a real quick program infact i wrote it in interactive that just starts at 1 and works the problem backwards for how ever long i tell it to :)) thanks for considering the homework, but this time you did'nt have to worry i did the homework last week i was just doing this for fun, it randomly asked something like "what about a number that takes 100 steps to get to 1" and i thought what about 1000 :)) now i have one running looking for a number that takes 1000000 steps unfortunately i dont think ill get any extra credit for doing any of this lol here is the program sorry copying it from interactive: >>> number=1 >>> count=1000 >>> count=0 >>> while count < 1000: ... if (number*2)%2 == 0: ... number=number*2 ... else: ... number=(number-1)/3.0 ... count=count+1 ... print number On Sep 4, 2007, at 3:00 AM, Alan Gauld wrote: > Max, > >> just wondering if theirs a way to check if a larger number is even >> or >> odd > > I notice this is homework so I won't give a direct answer. > But look at the mod operator '%' - It returns the remainder > of an integer division. An even number is exactly divisible > by 2. > > HTH, > > Alan G. > > "max baseman" wrote > >> about before ive let it sit for a few days now and i reached a >> number >> to high to convert to a decimal by adding 0.0 > > Thats a terrible way to convert to a float. Just use the float > function > (actually a type): > > f = float(anInt) > > But to determine if its odd/even you don't need to use floats at all. > > >> here's the program: >> >> count=1 >> numstart=268549802 >> number=0 >> high=0 >> a=0 >> while 1==1: >> numstart=numstart+1 >> number=numstart >> count=1 >> while number !=1: >> if number/2 == (number+0.0)/2: >> number=number/2 >> else: >> number=(number*3)+1 >> count=count+1 >> if count > a: >> a=count >> print numstart,":",count > > > Hmm, I have no idea what this is doing... > >> >> thanks >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ricaraoz at gmail.com Tue Sep 4 15:59:37 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 04 Sep 2007 10:59:37 -0300 Subject: [Tutor] Dynamically changing a class In-Reply-To: References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> Message-ID: <46DD64C9.605@bigfoot.com> Alan Gauld wrote: > "Jason Doege" wrote > >> I'd like to change the behavior of a class' member function >> dynamically >> such that, once changed, all objects of the type would see the new >> behavior. > >>>>> class MyClass (object) : >> def mfunc(self, data): >> print 'pre change behavior' >> >>>>> aMyClassObj = MyClass() >>>>> aMyClassObj.mfunc(data) >> pre change behavior >>>>> def MyClass.mfunc(self, data): #this does not work :-( >> print 'post change behavior' > > You need to do it thusly: > > def newfunc(self, data): > print 'post change' > MyClass.mfunc = newfunc > > That seems to work. > I'm slightly surprised since I didn't know if it would, but it seems > to! > So lets take it a notch up. Wanted to change the mfunc method but ONLY for an instance, not a class: >>> MyObj = MyClass() >>> MyObj.mfunc(data) pre change behavior >>> MyObj.mfunc = newfunc >>> MyObj.mfunc(data) Traceback (most recent call last): File "", line 1, in TypeError: newfunc() takes exactly 2 arguments (1 given) and this did not work (mfunc will ask for 2 parameters). So I tried : >>> MyObj.mfunc = newfunc(MyObj) Traceback (most recent call last): File "", line 1, in NameError: name 'Myobj' is not defined this didn't work either. Any ideas? From ricaraoz at gmail.com Tue Sep 4 16:02:36 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 04 Sep 2007 11:02:36 -0300 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: References: <20070903013638.687341E4006@bag.python.org> <20070904085057.548141E400B@bag.python.org> Message-ID: <46DD657C.6030409@bigfoot.com> Alan Gauld wrote: > "Dick Moores" wrote > >>> except you lose the flexibility of changing PYTHONPATH >>> dynamically during a session using SET. >> Could you show me how to use SET? And an example where it would be >> useful? > > Imagine you are in a DOS command session > > C:> SET PYTHONPATH=C:\MYNEWFOLDER;%PYTHONPATH% > > prepends a folder to PYTHONPATH > Now next time you run Python it will pick up the extra folder > > C:> SET PYTHONPATH > > displays the current value > > finally > > C:>SET PYTHONPATH=%PYTHONPATH:Python25=Python24% > > edits the existing path to substitute Python24 for each occurence of > python25 > > SET /P > > allows multi line entry. > > SET is quite surprisingly powerful. > Try HELP SET for more info > > The big downside is that these changes only apply to the current > environment. (Which is the point of an *environment* variable after > all :-) > You still need to edit the variable if you want a permanant change > > Alan G > > I seem to remember there was a way (in the wds console) to set it permanent. Wasn't it 'EXPORT' or something? From alan.gauld at btinternet.com Wed Sep 5 01:35:34 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 4 Sep 2007 23:35:34 +0000 (GMT) Subject: [Tutor] What's up with Python 2.5.1's IDLE? Message-ID: <202134.80506.qm@web86113.mail.ird.yahoo.com> >> The big downside is that these changes only apply to the current >> environment. (Which is the point of an *environment* variable after >> all :-) > >I seem to remember there was a way (in the wds console) to set it > permanent. Wasn't it 'EXPORT' or something? I think you might be thinking about the Linux/Unix Bourne/Bash/Korn shell where export can be used to export an environment variable to the parent environment? I'm not aware of any such command in anty version of DOS. But then I'm hardly a DOS Guru either! Alan G. From kent37 at tds.net Wed Sep 5 02:12:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 20:12:39 -0400 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: <9DE3FA2B-90AB-4F44-9B0C-590C63E5482F@gmail.com> References: <9DE3FA2B-90AB-4F44-9B0C-590C63E5482F@gmail.com> Message-ID: <46DDF477.5050708@tds.net> max baseman wrote: > here is the program sorry copying it from interactive: > > >>> number=1 > >>> count=1000 > >>> count=0 > >>> while count < 1000: > ... if (number*2)%2 == 0: This will always be true, you multiply by two then check if the result is divisible by two. Kent > ... number=number*2 > ... else: > ... number=(number-1)/3.0 > ... count=count+1 > ... print number From kent37 at tds.net Wed Sep 5 02:21:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 20:21:05 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DD64C9.605@bigfoot.com> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <46DD64C9.605@bigfoot.com> Message-ID: <46DDF671.9090607@tds.net> Ricardo Ar?oz wrote: > So lets take it a notch up. > Wanted to change the mfunc method but ONLY for an instance, not a class: > >>>> MyObj = MyClass() >>>> MyObj.mfunc(data) > pre change behavior >>>> MyObj.mfunc = newfunc >>>> MyObj.mfunc(data) > Traceback (most recent call last): > File "", line 1, in > TypeError: newfunc() takes exactly 2 arguments (1 given) I believe the correct way to do this is to use the __get__() method of the function object to create a bound method and assign that to the instance attribute: In [13]: class MyClass(object): pass ....: In [14]: myObj = MyClass() In [15]: def newfunc(self): ....: print 'post change behavior' ....: ....: All functions are descriptors. The __get__() method returns a bound method: In [16]: newfunc.__get__? Type: method-wrapper Base Class: String Form: Namespace: Interactive Docstring: descr.__get__(obj[, type]) -> value In [17]: newfunc.__get__(myObj, MyClass) Out[17]: > Assigning the bound method to myObj.mfunc has the desired behaviour: In [18]: myObj.mfunc = newfunc.__get__(myObj, MyClass) In [19]: myObj.mfunc() post change behavior I have a writeup of descriptors here: http://personalpages.tds.net/~kent37/kk/00008.html You can also use types.MethodType to do the same thing: In [20]: from types import MethodType In [21]: MethodType(newfunc, myObj, MyClass) Out[21]: > Kent From trey at opmstech.org Wed Sep 5 02:49:49 2007 From: trey at opmstech.org (Trey Keown) Date: Tue, 4 Sep 2007 19:49:49 -0500 (CDT) Subject: [Tutor] Problems with wx in Vista... Message-ID: <61395.68.191.136.241.1188953389.squirrel@webmail.opmstech.org> Although I should have expected at least a few problems, I have a question about a glitch in vista using a wx-implemented script. Here's the example script- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #!/usr/bin/python # togglebuttons.py import wx class ToggleButtons(wx.Dialog): def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size=(300, 200)) self.colour = wx.Colour(0, 0, 0) wx.ToggleButton(self, 1, 'red', (20, 25)) wx.ToggleButton(self, 2, 'green', (20, 60)) wx.ToggleButton(self, 3, 'blue', (20, 100)) self.panel = wx.Panel(self, -1, (150, 20), (110, 110), style=wx.SUNKEN_BORDER) self.panel.SetBackgroundColour(self.colour) self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleRed, id=1) self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleGreen, id=2) self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleBlue, id=3) self.Centre() self.ShowModal() self.Destroy() def ToggleRed(self, event): green = self.colour.Green() blue = self.colour.Blue() if self.colour.Red(): self.colour.Set(0, green, blue) else: self.colour.Set(255, green, blue) self.panel.SetBackgroundColour(self.colour) def ToggleGreen(self, event): red = self.colour.Red() blue = self.colour.Blue() if self.colour.Green(): self.colour.Set(red, 0, blue) else: self.colour.Set(red, 255, blue) self.panel.SetBackgroundColour(self.colour) def ToggleBlue(self, event): red = self.colour.Red() green = self.colour.Green() if self.colour.Blue(): self.colour.Set(red, green, 0) else: self.colour.Set(red, green, 255) self.panel.SetBackgroundColour(self.colour) app = wx.App(0) ToggleButtons(None, -1, 'togglebuttons.py') app.MainLoop() =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= This makes a window pop up with 3 buttons that changes the color of a box. Now, my question is, is this a vista-specific problem, am I just doing something wrong, or is the example messed up. Note- the name I saved the program as is testwx.py Thanks for any help From srikanth007m at gmail.com Wed Sep 5 06:12:37 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 4 Sep 2007 21:12:37 -0700 Subject: [Tutor] advanced sorting Message-ID: Hi, i am using a macpro version(10.4.11) and python version is "2.3.5" Message: 10 Date: Wed, 05 Sep 2007 01:00:44 +0530 From: Noufal Ibrahim Subject: Re: [Tutor] advanced sorting To: srikanthkumar007m at rediffmail.com Cc: tutor at python.org Message-ID: <46DDB264.7010006 at airtelbroadband.in> Content-Type: text/plain; charset=ISO-8859-1; format=flowed chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: sort() takes no keyword arguments > > Seems to work fine for me. What version of Python are you using? >>> x=['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] >>> x.sort(reverse=True) >>> x ['will', 'srikanth', 'muppandam', 'kumar', 'be', 'a'] >>> -- ~noufal -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/02125a2a/attachment.htm From srikanth007m at gmail.com Wed Sep 5 06:43:34 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 4 Sep 2007 21:43:34 -0700 Subject: [Tutor] Plz help me from this Message-ID: Hi All, I Want to write a python script to change the permissions(chmod) and owner(chown) and group(chgrp) of a file on unix, script as to read from the /etc/passwd for displaying available users on the machine and from /etc/groups it as to display the available groups and user has to give the mode and owner name and group name from the list. Can i implement this in python or in shell scripting Can any one please suggest me from doing this...:) -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/3355c174/attachment-0001.htm From clsdaniel at gmail.com Wed Sep 5 08:26:06 2007 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 4 Sep 2007 23:26:06 -0700 Subject: [Tutor] Plz help me from this In-Reply-To: References: Message-ID: <4fae7dfa0709042326s45995722ia581ea8a64fc4602@mail.gmail.com> Yes is very possible to do this with python. Checkout the os.system and os.popen functions to run external commands (chmod, chown). Reading the list of users and groups should be easy, just open the file and read line by line and parse, you can do it as simple as splitting the line on colon character (:) and parsing the resulting list. It seems you will also need some form of UI, simple print and raw_input may do the trick. On 9/4/07, chinni wrote: > Hi All, > > > I Want to write a python script to change the permissions(chmod) and > owner(chown) and group(chgrp) of a file on unix, > script as to read from the /etc/passwd for displaying available users on the > machine and from /etc/groups it as to display the available groups and user > has to give the mode and owner name and group name from the list. > > Can i implement this in python or in shell scripting > Can any one please suggest me from doing this...:) > > -- > Best Regards, > M.Srikanth Kumar, > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From steve at alchemy.com Wed Sep 5 08:27:54 2007 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 04 Sep 2007 23:27:54 -0700 Subject: [Tutor] Plz help me from this In-Reply-To: References: Message-ID: <46DE4C6A.1080301@alchemy.com> chinni wrote: > Hi All, > > > I Want to write a python script to change the permissions(chmod) and > owner(chown) and group(chgrp) of a file on unix, > script as to read from the /etc/passwd for displaying available users on > the machine and from /etc/groups it as to display the available groups > and user has to give the mode and owner name and group name from the list. > > Can i implement this in python or in shell scripting > Can any one please suggest me from doing this...:) This would be a lot easier to do with Python than shell, although it's certainly possible to do in either. For a start, check out the "nis" module in the standard library. nis.cat('passwd') and nis.cat('group') should be useful in getting the list of valid inputs. From there, you can create some sort of GUI or text-based selection code, or at least let the user type in the names they want and validate it against what's in NIS. If your system doesn't use NIS, you can see the 'pwd', 'spwd' and 'grp' modules instead. They'll get you what you need directly from the /etc files, but a little less conveniently. Then once you have your input from the user, it's just a simple matter of calling os.chmod() and os.chown() to make the changes. (Note that os.chown() changes the owner and/or group in one call.) HTH --steve From steve at alchemy.com Wed Sep 5 08:29:37 2007 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 04 Sep 2007 23:29:37 -0700 Subject: [Tutor] Plz help me from this In-Reply-To: <4fae7dfa0709042326s45995722ia581ea8a64fc4602@mail.gmail.com> References: <4fae7dfa0709042326s45995722ia581ea8a64fc4602@mail.gmail.com> Message-ID: <46DE4CD1.8020907@alchemy.com> Carlos Daniel Ruvalcaba Valenzuela wrote: > Yes is very possible to do this with python. > > Checkout the os.system and os.popen functions to run external commands > (chmod, chown). While those are ways of calling external commands, it is best to use built-in language features like os.chmod() and os.chown() whenver possible. They will be much faster and less prone to errors and security issues. From alan.gauld at btinternet.com Wed Sep 5 09:21:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Sep 2007 08:21:56 +0100 Subject: [Tutor] Problems with wx in Vista... References: <61395.68.191.136.241.1188953389.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > Although I should have expected at least a few problems, I have a > question > about a glitch in vista using a wx-implemented script. So give us a clue, what is the glitch? > Here's the example script- > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= snipped > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > This makes a window pop up with 3 buttons that changes the color of > a box. > Now, my question is, is this a vista-specific problem It sounds like its doing the right thing? What did you expect it to do? Alan G From alan.gauld at btinternet.com Wed Sep 5 09:28:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Sep 2007 08:28:55 +0100 Subject: [Tutor] advanced sorting References: Message-ID: "chinni" wrote > i am using a macpro version(10.4.11) and python version is "2.3.5" Thats the problem, you need Python v2.4 to use the key= feature of sort. There is a way to modify sort behaviour in older versions of Python The docs say: ------------------------------ The sort() method takes an optional argument specifying a comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. Note that this slows the sorting process down considerably;..... As an example of using the cmpfunc argument to the sort() method, consider sorting a list of sequences by the second element of that list: def mycmp(a, b): return cmp(a[1], b[1]) mylist.sort(mycmp) ----------------------------------- Check your v2.3.5 Library Reference docs for more details. http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html#l2h-220 HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Sep 5 09:40:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Sep 2007 08:40:58 +0100 Subject: [Tutor] Dynamically changing a class References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> Message-ID: "Kent Johnson" wrote >> Wanted to change the mfunc method but ONLY for an instance, not a >> class: > > I believe the correct way to do this is to use the __get__() method > of > the function object to create a bound method and assign that to the > instance attribute: Wow! Another new trick. I've never noticed __get__ before. Time for some playing I think. Thanks Kent, Alan G From ndoe_jtk_05 at yahoo.co.id Wed Sep 5 10:22:14 2007 From: ndoe_jtk_05 at yahoo.co.id (Ndoe jtki) Date: Wed, 5 Sep 2007 15:22:14 +0700 (ICT) Subject: [Tutor] Drag image Message-ID: <121.18941.qm@web45404.mail.sp1.yahoo.com> i want to drag image for my tasks in my college,but i can't understand following example in wx.python 2.6 Docs demo and tool. Have you another simple example for drag image? Thanks --------------------------------- Bergabunglah dengan orang-orang yang berwawasan, di bidang Anda di Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/7ee079f0/attachment.htm From ricaraoz at gmail.com Wed Sep 5 11:58:12 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 05 Sep 2007 06:58:12 -0300 Subject: [Tutor] Dynamically changing a class In-Reply-To: References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> Message-ID: <46DE7DB4.8030307@bigfoot.com> Alan Gauld wrote: > "Kent Johnson" wrote > >>> Wanted to change the mfunc method but ONLY for an instance, not a >>> class: >> I believe the correct way to do this is to use the __get__() method >> of >> the function object to create a bound method and assign that to the >> instance attribute: > > Wow! Another new trick. I've never noticed __get__ before. That'd be two this week ;-) > Time for some playing I think. Yep. And once you've got it pls explain it too me, too lazy today to pick the manual. :) Any easier way? > > Thanks Kent, > > Alan G > From kent37 at tds.net Wed Sep 5 12:36:40 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 06:36:40 -0400 Subject: [Tutor] advanced sorting In-Reply-To: References: Message-ID: <46DE86B8.2020602@tds.net> Alan Gauld wrote: > There is a way to modify sort behaviour in older versions of Python > The docs say: > ------------------------------ > The sort() method takes an optional argument specifying a > comparison function of two arguments Another way to do this is with the 'Decorate-Sort-Undecorate' idiom. I talk about it here: http://personalpages.tds.net/~kent37/kk/00007.html Kent From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= Wed Sep 5 12:55:10 2007 From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?=) Date: Wed, 05 Sep 2007 13:55:10 +0300 Subject: [Tutor] searching a text file In-Reply-To: References: <003101c7eed4$166f7870$5595693a@SNNECCM> Message-ID: <46DE8B0E.7050408@saudi.net.sa> Alan Gauld wrote: > "Diana Hawksworth" wrote > >> How do I find a particular name, change the score and then save >> the changes back to the text file again?? > > iterate over the file checking (and modifying) each line > write the line back out: > > Pseudo code > > Out = open('foo.txt','w') BEWARE: this will truncate the file immediately, erasing all the data in it!!! Use a temporary file and after you finish processing the data in the original file, move (or rename) the temporary file to the original name. > for line in file('foo.txt'): > if 'somestring' in line: > line = 'I changed it\n' > Out.write(line) > > Out.close() > > You will find much more on this in my file handling topic in my > tutorial. > > Ziyad. From kent37 at tds.net Wed Sep 5 13:22:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 07:22:23 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DE7DB4.8030307@bigfoot.com> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> <46DE7DB4.8030307@bigfoot.com> Message-ID: <46DE916F.509@tds.net> Ricardo Ar?oz wrote: > Yep. And once you've got it pls explain it too me, too lazy today to > pick the manual. :) I included a link to my explanation previously. I'm too lazy to try to do better. > Any easier way? Easier how? I don't know what could be easier to implement than a single function call. What did you have in mind? These are all equivalent, take your pick: myObj.mfunc = newfunc.__get__(myObj, MyClass) myObj.mfunc = types.MethodType(newfunc, myObj, MyClass) myObj.mfunc = new.instancemethod(newfunc, myObj, MyClass) For my own interest I looked into how these are actually implemented with an eye to which one might be preferred. new.instancemethod has the advantage of being documented in the library reference but the source says it is deprecated and it is a synonym for types.MethodType (in new.py). types.MethodType is defined in types.py as MethodType = type(_x._m) where _x is a class and _m is a method; i.e. types.MethodType is literally 'the type of a bound method'. It is fairly explicit at the point of use - 'give me a method'. newfunc.__get__ is defined by func_descr_get() in Objects/funcobject.c. It delegates to PyMethod_New() so it is essentially calling MethodType. It's a bit obscure at the point of use. So I guess I prefer MethodType(newfunc, myObj, MyClass) Kent From kent37 at tds.net Wed Sep 5 13:33:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 07:33:37 -0400 Subject: [Tutor] searching a text file In-Reply-To: <46DE8B0E.7050408@saudi.net.sa> References: <003101c7eed4$166f7870$5595693a@SNNECCM> <46DE8B0E.7050408@saudi.net.sa> Message-ID: <46DE9411.4080301@tds.net> ???? ?? ????????? ??????? wrote: > Alan Gauld wrote: >> "Diana Hawksworth" wrote >> >>> How do I find a particular name, change the score and then save >>> the changes back to the text file again?? >> iterate over the file checking (and modifying) each line >> write the line back out: >> >> Pseudo code >> >> Out = open('foo.txt','w') > BEWARE: this will truncate the file immediately, erasing all the data in > it!!! > > Use a temporary file and after you finish processing the data in the > original file, move (or rename) the temporary file to the original name. The fileinput module can help with this. It lets you edit a file line-by-line, in place, with a backup: import fileinput for line in fileinput.input('test.txt', inplace=1, backup='.bak'): if 'somestring' in line: line = 'I changed it\n' print line, Kent From jdoege at da-test.com Wed Sep 5 16:59:47 2007 From: jdoege at da-test.com (Jason Doege) Date: Wed, 5 Sep 2007 10:59:47 -0400 Subject: [Tutor] Dynamically changing a class Message-ID: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> Thanks for the good and useful information on this. Now for the why... I am building an API and for various reasons I have chosen Python to implement it. I'd like to separate the implementation from the interface as, for instance, C++ does with separate .hpp and .cpp files. Apart from defining a class with a bunch of empty methods and then redefining them, I have not seen a good way to do this in Python. Can you recommend the Pythonic way to do this? Best regards, Jason Doege From kent37 at tds.net Wed Sep 5 17:33:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 11:33:26 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> References: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> Message-ID: <46DECC46.7060209@tds.net> Jason Doege wrote: > Thanks for the good and useful information on this. Now for the why... > > I am building an API and for various reasons I have chosen Python to > implement it. I'd like to separate the implementation from the interface > as, for instance, C++ does with separate .hpp and .cpp files. Apart from > defining a class with a bunch of empty methods and then redefining them, > I have not seen a good way to do this in Python. Can you recommend the > Pythonic way to do this? For smaller projects don't bother. For large projects Zope Interface seems to be popular: http://wiki.zope.org/Interfaces/FrontPage PyProtocols is similar but no longer actively developed: http://peak.telecommunity.com/PyProtocols.html A different approach, perhaps more Pythonic, is for consumers to check what kind of thing they are given. One way to do this is here: http://oakwinter.com/code/typecheck/ You might also be interested in http://www.python.org/dev/peps/pep-0246/ http://www.python.org/dev/peps/pep-3107/ Kent From washakie at gmail.com Wed Sep 5 22:56:33 2007 From: washakie at gmail.com (John) Date: Wed, 5 Sep 2007 13:56:33 -0700 Subject: [Tutor] more on reading binary... a better way? Message-ID: Hello everyone, Here's my solution for reading binary data (unformatted mixed types) and packing it into a dictionary. It works, but somehow doesn't seem so 'pythonic'. Just seeking comments on how I might make it more efficient. Thanks! def readheader(filename): import struct I={0:'rl',1:'ibdate',2:'ibtime',3:'version',4:'void1',5:'void2',6:'loutstep',7:'loutaver',8:'loutsample',9:'void3',10:'void4',11:'outlon0',12:'oulat0',13:'numxgrid',14:'numygrid',15:'dxout',16:'dyout',17:'void5',18:'void6',19:'numzgrid'} B={} f2=file(filename,'rb') #Define Header format Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i'] #format for binary reading first bits if f2: print filename + ' has been opened' #create a dictionary from header file a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt] for i in range(len(a)): B[I[i]]=a[i][0] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/4bdfaca9/attachment.htm From the.tobmeister at gmail.com Wed Sep 5 23:28:10 2007 From: the.tobmeister at gmail.com (Toby Holland) Date: Wed, 5 Sep 2007 17:28:10 -0400 Subject: [Tutor] The IF statement Message-ID: Hi gang, Just doing what I can to understand as I study I have been reading about testing modules this is the statement that I have been given if __name__ == "__main__": I understand that all modules have a built in attribute __name__, but what does the __main__ have to do with this attribute. Is it saying that __name__ is the same as __main__? I know that if the module is imported then __name__is the moules file name, but is this just for the script that your writing while using that module or is it just to show that the module was imported? correct me if I'm wrong please, the modules file name is __main__ when its being used as a stand alone program? If this is the case the difference is whether or not the module is a program by itself or intigrated with a script that is what determines its name (i.e. __name__ and __main__) I hope this question makes senses thanks for the help!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/f3a8e0b2/attachment-0001.htm From tinoloc at gmail.com Wed Sep 5 23:28:09 2007 From: tinoloc at gmail.com (Tino Dai) Date: Wed, 5 Sep 2007 17:28:09 -0400 Subject: [Tutor] Condensing Some Massive Code In-Reply-To: References: Message-ID: On 9/2/07, David Millar wrote: > > Hello. I'm working on a text adventure game right now, and I seem to be > kind of stuck. There's a huge chunk of code called moreaction() that pulls > scripted events for certain locations. It's ever-changing so I'm not looking > for specifics, but can anyone suggest good ways to clean up or condense the > code without sacrificing clarity? The latest version of the source is found > at http://thegriddle.net/python/v006.txt Any help is much appreciated :) - > Dave M. I just took a look at the code, it seems that you are in if-then hell. I think that I have a solution for you that improve the readability of the code. It's using multiple dictionaries to get you out of if-then hell. Let's say we have: sceneDict = {} # We populate these with the difference scene numbers. In the sceneDict, we have eventDict if there are any events. Lets say we take your first piece of code: if thescene == 3: if event[1] == 0: global choins choins = choins - 10 add_item("BEAN",1) map[2].add_opt("NORTH",4) map[2].set_desc("You are just outside a nasty looking movie theatre. Shady Latin gang members have a shell game set up nearby, and from previous experiences you know to avoid gambling like the plague.") event[1] = 1 elif event[1] == 1: map[3].set_desc("You walk up to the gangsters and the boss guy says 'Get lost, fool!'") event[1] = 2 elif event[1] == 3: map[3].set_desc("You walk up to the gangsters but they tell you to get lost.") if (inventory.has_key("ARMONDO'S NOTE") == 0): print "\nYou walk up to the gangsters and flash a picture of Candy in front of them. 'Woah, is that Candy?' the boss guy asks. I ain't seen her since high school!' He scribbles something on the back of a receipt for frozen wonton burrito meals, and you do the math and realize that he wants you to give candy the number." add_item("ARMONDO'S NOTE",1) elif event[1] == 4: print "\nYou see Candy with Armondo, and they wave you over. 'Hey, thanks for hooking us up again! And sorry Armondo took your choins in his little game, teehee!' She hands you 5 choins. 'Uhh, he took 10 choins from me, not fi-' 'SHUT UP RUBE!' Candy laughs at Armondo and kisses him on the cheek. 'We're going to the back seat of Armondo's car for coffee. See ya! They walk away and get into Armondo's car, which starts bucking around a bit. Then it suddenly starts up and leaves, opening the street to the south." choins += 5 map[2].rem_opt("TALK") map[2].add_opt("SOUTH",15) map[1].add_opt("ORDER",16) elif thescene == 6: map[5].rem_opt("EAST") add_item('MAIN MAP',1) add_recipe('ICED COFFEE','COFFEE','ICE',1) add_recipe('ESPRESSO','COFFEE','BEAN',2) add_recipe('CAPPUCCINO','ESPRESSO','MILK',2) add_recipe('CREAMY COFFEE','COFFEE','MILK',1) elif thescene == 8: if event[1] >= 3 and (book.has_key("SYRUP") == 0): print "\n'PROTIP!' 'Huh?' you respond. 'PROTIP! CANDY and WATER make various sugary SYRUPS to add to your drinks!' Wow. Interesting." add_recipe('SYRUP','CANDY','WATER',1) disp_menu(0) sceneDict = { 3:"" , 6:"",8:""} sceneDict[3] = { 0:"",1:"",2:"",4:""} # The key 3 points to a dictionary of event dictionary. I have to research how to get the values of these dictionary to be executeable code :). Tell me what you think (by the way, you will need one or two if statements and perhaps an try-except block to make this code work). More tonight or if Kent, Alan or Bob want to step in. :) -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/577cfd95/attachment-0001.htm From kent37 at tds.net Thu Sep 6 00:03:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 18:03:36 -0400 Subject: [Tutor] The IF statement In-Reply-To: References: Message-ID: <46DF27B8.5040609@tds.net> Toby Holland wrote: > Hi gang, > > Just doing what I can to understand as I study > > > I have been reading about testing modules this is the statement that I > have been given > > if __name__ == "__main__": > > > I understand that all modules have a built in attribute __name__, but > what does the __main__ have to do with this attribute. Is it saying > that __name__ is the same as __main__? Yes. Note that __name__ is a variable and "__main__" is a string. So this says that the value of the variable __name__ is the string "__main__". > I know that if the module is imported then __name__is the moules file > name, It is the module name which is not quite the same as the file name. __file__ has the file name. > but is this just for the script that your writing while using that > module or is it just to show that the module was imported? It is a way to tell if the module was imported or run directly as a script. > correct me if I'm wrong please, the modules file name is __main__ when > its being used as a stand alone program? The modules name, not the file name; otherwise yes. > If this is the case the difference is whether or not the module is a > program by itself or intigrated with a script that is what determines > its name (i.e. __name__ and __main__) Yes. It is handy to be able to write a module so it can be used by being imported into another module, or by being run on its own. When run on its own it might provide a simple command line interface or run unit tests or whatever the developer finds useful. When imported as a library for another module then this behaviour is not wanted so it is hidden by the if __name__ == '__main__': condition. Kent From ricaraoz at gmail.com Thu Sep 6 00:41:09 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 05 Sep 2007 19:41:09 -0300 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DE916F.509@tds.net> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> <46DE7DB4.8030307@bigfoot.com> <46DE916F.509@tds.net> Message-ID: <46DF3085.1060501@bigfoot.com> Kent Johnson wrote: > Ricardo Ar?oz wrote: > >> Yep. And once you've got it pls explain it too me, too lazy today to >> pick the manual. :) > > I included a link to my explanation previously. I'm too lazy to try to > do better. > LOL, too tired yesterday to even think straight. Thanks for your answer. From alan.gauld at btinternet.com Thu Sep 6 01:29:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Sep 2007 00:29:53 +0100 Subject: [Tutor] more on reading binary... a better way? References: Message-ID: "John" wrote > packing it into a dictionary. It works, but somehow doesn't seem so > 'pythonic'. Just seeking comments on how I might make it more > efficient. I don't think its too bad but I'd probably try reading all the data in one go. > #Define Header format > Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i'] Dfmt = "iii13siiiiiiiiiiiiiiii" ln = 19 * struct.calcsize('i') + struct.calcsize('13s') a = struct.unpack(Dfmt,f2.read(ln)) Which should return a tuple of all your values in one go. Now you can go straight to the last for loop below... All untested of course! :-) > #format for binary reading first bits > if f2: > print filename + ' has been opened' > #create a dictionary from header file > a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt] > for i in range(len(a)): > B[I[i]]=a[i][0] -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Sep 6 02:26:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 20:26:53 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DECC46.7060209@tds.net> References: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> <46DECC46.7060209@tds.net> Message-ID: <46DF494D.7020507@tds.net> Kent Johnson wrote: > Jason Doege wrote: >> I am building an API and for various reasons I have chosen Python to >> implement it. I'd like to separate the implementation from the interface >> as, for instance, C++ does with separate .hpp and .cpp files. Apart from >> defining a class with a bunch of empty methods and then redefining them, >> I have not seen a good way to do this in Python. Can you recommend the >> Pythonic way to do this? > > For smaller projects don't bother. A bit more on this...it is common for Python APIs to be defined by convention, documentation and example rather than by code artifacts such as formal interfaces. In Python itself, examples are file-like objects, sequences, mappings, iterators, decorators, descriptors and context managers, to name the ones that come to immediately mind. All of these are defined more-or-less clearly by documentation and usage. A more extensive example is Python DB-API which defines a way to interface to a database. This is defined entirely by the spec: http://www.python.org/dev/peps/pep-0249/ Kent From kent37 at tds.net Thu Sep 6 02:44:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 20:44:07 -0400 Subject: [Tutor] Metaclass programming In-Reply-To: <003701c7eef9$5ac277f0$bd32000a@issphoenix> References: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> <46DD4973.9090409@tds.net> <003701c7eef9$5ac277f0$bd32000a@issphoenix> Message-ID: <46DF4D57.3040207@tds.net> Orest Kozyar wrote: > You're right. I just figured out that for some reason, when I use the > SQLAlchemy mapper() function to map my classes to the corresponding table > object, it seems to affect inspect.getargspec(). > > For example: > > from sqlalchemy.orm import mapper > from sqlalchemy import Table, MetaData > import inspect > > class Foo: > def __init__(self, x, y): > pass > > print inspect.getargspec(Foo.__init__) > >>> (['self', 'x', 'y'], None, None, None) > > metadata = MetaData() > foo_table = Table('foo', metadata) > mapper(Foo, foo_table) > > print inspect.getargspec(Foo.__init__) > >>> (['instance'], 'args', 'kwargs', None) > > I'm not sure why this would be the case, but is a bit frustrating since I do > need the names of the positional arguments sometimes. I can't be sure without looking at the code but it looks like SA is decorating the class methods; this usually loses the signature of the method. The problem is described here: http://www.phyast.pitt.edu/~micheles/python/documentation.html#statement-of-the-problem >> Why are you doing this? > > Partially as an exercise to help me better understand Python inspection as > well as metaclass programming. Note that there is no metaclass in the above code, unless mapper() is introducing one behind the scene... I also am using it in a EntitySingleton > metaclass that I adapted from the SQLAlchemy wiki > (http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject). Some of my > classes have unique constraints, and I want the metaclass to check these > unique constraints and return an object from the database if an object > meeting these constraints already exists. > > For example: > > class User: > __unique__ = ['firstname', 'lastname'] > __metaclass__ = EntitySingleton > > def __init__(self, firstname, lastname, password): > pass > > The metaclass knows what the "unique" constraints are based on the > __unique__ list, but needs to use inspect.getargspec() to get the variable > names and match them up with the *args list that EntitySingleton.__call__ > recieves. At least, that's how I'm trying to do it, but I expect this might > not be the best way to do it? Either case, when the class is mapped to a > database table, I lose all this information, so will need to figure out a > different way of approaching this. You should probably look for a different way to do it. Depending on your tolerance for hacks, it may be possible to work around the decorator. The original function is probably contained within the closure of the decorator and you can dig it out. For example, make a simple decorator and decorate a function: In [5]: def deco(f): ...: def _deco(*args, **kwds): ...: print 'about to call', f.__name__ ...: f(*args, **kwds) ...: return _deco ...: In [6]: @deco ...: def f(): print 'foo here' ...: Hey, it works! In [7]: f() about to call f foo here but the decorated function has the signature of the decoration: In [8]: import inspect In [9]: inspect.getargspec(f) Out[9]: ([], 'args', 'kwds', None) If we dig hard enough we can find the original and get its signature: In [11]: f.func_closure Out[11]: (,) In [14]: f.func_closure[0].cell_contents Out[14]: In [15]: inspect.getargspec(f.func_closure[0].cell_contents) Out[15]: ([], None, None, None) In [16]: f.func_closure[0].cell_contents.__name__ Out[16]: 'f' I don't think I would want to rely on this in production code though... Kent From kent37 at tds.net Thu Sep 6 02:57:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 20:57:02 -0400 Subject: [Tutor] Condensing Some Massive Code In-Reply-To: References: Message-ID: <46DF505E.6010107@tds.net> David Millar wrote: > Hello. I'm working on a text adventure game right now, and I seem to be > kind of stuck. There's a huge chunk of code called moreaction() that > pulls scripted events for certain locations. It's ever-changing so I'm > not looking for specifics, but can anyone suggest good ways to clean up > or condense the code without sacrificing clarity? The latest version of > the source is found at http://thegriddle.net/python/v006.txt Any help is > much appreciated :) - Dave M. One way to help with this is to use functions and a dispatch table. For example instead of elif lookup == "COVER": print "\nYou close the book and stare dumbly at the cover, sideways:" return elif lookup == "TOC": print "\nYou glance over the table of contents. You have recipes for the following:" b = book.keys() b.sort() for r in b: print "*",r, print "*" return elif lookup == "SYRUP": print "\n* SYRUP *" print "* SYRUP is an interesting drink." return you could write def cover(): print "\nYou close the book and stare dumbly at the cover, sideways:" def toc(): print "\nYou close the book and stare dumbly at the cover, sideways:" return elif lookup == "TOC": print "\nYou glance over the table of contents. You have recipes for the following:" b = book.keys() b.sort() for r in b: print "*",r, print "*" def syrup(): print "\n* SYRUP *" print "* SYRUP is an interesting drink." return dispatch = dict(COVER=cover, TOC=toc, SYRUP=syrup) fn = dispatch[lookup] fn() That is the basic idea. There are a lot of possible complications and variations. If some of the functions need arguments, you need to make a common protocol for passing arguments and returning values. You might want to make the functions methods of a class so they can share state. Clever use of introspection can make the dispatch table unnecessary. You might want to look at the cmd module in the Python standard library as an example of this approach. Kent From saradhi.dinavahi at gmail.com Thu Sep 6 04:07:41 2007 From: saradhi.dinavahi at gmail.com (saradhi dinavahi) Date: Wed, 5 Sep 2007 21:07:41 -0500 Subject: [Tutor] Importing Excel sheet data Message-ID: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> hello all, I am new to the Python Programming. I want to Import Excel sheet data using Python. Can any one please provide me the code and explain the basic steps and method of executing the code. Thank You All -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/486c77b9/attachment.htm From witham.ian at gmail.com Thu Sep 6 05:06:50 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 6 Sep 2007 15:06:50 +1200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> Message-ID: Hi, You should look at the 'csv' module in the Python Standard Library. If you export your excel data to csv format, you can easily import the data in to python using the csv module. Ian On 9/6/07, saradhi dinavahi wrote: > > hello all, > > I am new to the Python Programming. I want to Import Excel sheet data > using Python. Can any one please provide me the code and explain the basic > steps and method of executing the code. > > Thank You All > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/8a34f219/attachment.htm From witham.ian at gmail.com Thu Sep 6 05:24:55 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 6 Sep 2007 15:24:55 +1200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> Message-ID: HI Saradhi, I too am fairly new to Python, but I use the csv module successfully for my work. Could you be a little more specific as to what your requirements are and where you are finding difficulty? Ian. On 9/6/07, saradhi dinavahi wrote: > > hi Ian , > > I have read the CSV module. But I felt difficult to write a code for my > requirement. > > Thank You. > > > On 9/5/07, Ian Witham wrote: > > > > Hi, > > > > You should look at the 'csv' module in the Python Standard Library. If > > you export your excel data to csv format, you can easily import the data in > > to python using the csv module. > > > > Ian > > > > On 9/6/07, saradhi dinavahi < saradhi.dinavahi at gmail.com > wrote: > > > > > > hello all, > > > > > > I am new to the Python Programming. I want to Import Excel sheet data > > > using Python. Can any one please provide me the code and explain the basic > > > steps and method of executing the code. > > > > > > Thank You All > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/4ba60d24/attachment-0001.htm From david.bear at asu.edu Thu Sep 6 05:51:10 2007 From: david.bear at asu.edu (David Bear) Date: Wed, 05 Sep 2007 20:51:10 -0700 Subject: [Tutor] unicode encoding hell Message-ID: <3408212.QD0Uz6TdxC@teancum> I'm using universal feed parser to grab an rss feed. I'm carefull not to use any sys.out, print, file write ops, etc, UNLESS I use a decode('utf-i') to convert the unicode string I get from feed parser to utf-8. However, I'm still getting the blasted decode error stating that one of the items in the unicode string is out range. I've checked the encoding from the feed and it does indeed say it is utf-8. The content-type header is set to application/rss+xml . I am using the following syntax on a feedparser object: feedp.entry.title.decode('utf-8', 'xmlcharrefreplace') I assume it would take any unicode character and 'do the right thing', including replacing higher ordinal chars with xml entity refs. But I still get UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 31: ordinal not in range(128) Clearly, I completely do not understand how unicode is working here. Can anyone enlighten me? -- David Bear College of Public Programs at Arizona State University From witham.ian at gmail.com Thu Sep 6 06:14:37 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 6 Sep 2007 16:14:37 +1200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709052032y209fa9bg3b9b470585dc9b05@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> <1f51e43b0709052032y209fa9bg3b9b470585dc9b05@mail.gmail.com> Message-ID: Hi Saradhi, The first step is to export your excel data to the .csv format. This is done in Excel from the file menu. CSV means "comma separated values". If you have exported the data correctly it may look something like this: "8803","16/9/2007","299000","BEO","13B Mandeville Crescent","Grenada Village","2.00PM","","3" "8844","16/9/2007","599000","BEO","89 Kahu Road","Paremata","2.00PM","","4" "8855","16/9/2007","370000","BEO","8 Salford Street","Newlands","2.00PM ","","2" Lots of values, separated by commas, often with quotation marks containing the values. The code I use to import this type of data looks like this: >>> import csv >>> oh_reader = csv.reader(open('openhomes.csv', 'U'), dialect='excel') >>> for row in oh_reader: print row ['8803', '16/9/2007', '299000', 'BEO', '13B Mandeville Crescent', 'Grenada Village', '2.00PM', '', '3'] ['8844', '16/9/2007', '599000', 'BEO', '89 Kahu Road', 'Paremata', '2.00PM', '', '4'] ['8855', '16/9/2007', '370000', 'BEO', '8 Salford Street', 'Newlands', ' 2.00PM', '', '2'] There is all my data in list format. There is also another class in csv called DictReader which presents your data in dictionary form. To do this you must provide a list of 'keys' to use for your dictionary. Think of these keys as being analogous to a header row in excel. eg: my_header_row = ['list_number', ' >>> my_header_row = ['list_number', 'date', 'price', 'price2', 'add1', 'add2', 'start', 'finish', 'bedrooms'] >>> dict_reader = csv.DictReader(open('openhomes.csv', 'U'), my_header_row, dialect='excel') >>> for row in dict_reader: print row {'finish': '', 'add2': 'Grenada Village', 'add1': '13B Mandeville Crescent', 'price': '299000', 'list_number': '8803', 'start': '2.00PM', 'bedrooms': '3', 'date': '16/9/2007', 'price2': 'BEO'} {'finish': '', 'add2': 'Paremata', 'add1': '89 Kahu Road', 'price': '599000', 'list_number': '8844', 'start': '2.00PM', 'bedrooms': '4', 'date': '16/9/2007', 'price2': 'BEO'} {'finish': '', 'add2': 'Newlands', 'add1': '8 Salford Street', 'price': '370000', 'list_number': '8855', 'start': '2.00PM', 'bedrooms': '2', 'date': '16/9/2007', 'price2': 'BEO'} And there is my data in dictionary format. CSV also has tools for exporting both lists and dicts to csv format again, and from there you can import the data back to excel. I hope I have been helpful to you. Ian. On 9/6/07, saradhi dinavahi wrote: > > Hi Ian, > > I have read the Python CSV module .But I cant understand to use that > module to Import Excel Sheet data.As I am new to the Python programming , > I dont know the way to write code using that module to meet my > requirement. > > On 9/5/07, Ian Witham wrote: > > > > HI Saradhi, > > > > I too am fairly new to Python, but I use the csv module successfully for > > my work. Could you be a little more specific as to what your requirements > > are and where you are finding difficulty? > > > > Ian. > > > > On 9/6/07, saradhi dinavahi wrote: > > > > > > hi Ian , > > > > > > I have read the CSV module. But I felt difficult to write a code for > > > my requirement. > > > > > > Thank You. > > > > > > > > > On 9/5/07, Ian Witham wrote: > > > > > > > > Hi, > > > > > > > > You should look at the 'csv' module in the Python Standard Library. > > > > If you export your excel data to csv format, you can easily import the data > > > > in to python using the csv module. > > > > > > > > Ian > > > > > > > > On 9/6/07, saradhi dinavahi < saradhi.dinavahi at gmail.com > wrote: > > > > > > > > > > hello all, > > > > > > > > > > I am new to the Python Programming. I want to Import Excel sheet > > > > > data using Python. Can any one please provide me the code and explain the > > > > > basic steps and method of executing the code. > > > > > > > > > > Thank You All > > > > > > > > > > > > > > > _______________________________________________ > > > > > Tutor maillist - Tutor at python.org > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/fc691c9d/attachment.htm From janos.juhasz at VELUX.com Thu Sep 6 08:55:12 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 6 Sep 2007 08:55:12 +0200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: Message-ID: Dear Saradhi, I am using COM on Win32 for this, based on the sample of Mark Hammond & Andy Robinson in the "Programing Python on Win32" book. That is a fairly simple way to do that. The code itself can be downloaded from http://examples.oreilly.com/pythonwin32/ppw32_samples.zip You can find some information about it googling for EasyExcel. The book itself is an essential to work on win32 with python. # My personal favorite chapters are the ones about double-entry bookkeeping :) > Date: Wed, 5 Sep 2007 21:07:41 -0500 > From: "saradhi dinavahi" > I am new to the Python Programming. I want to Import Excel sheet data using > Python. Can any one please provide me the code and explain the basic steps > and method of executing the code. Janos Juhasz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/d0d93d4e/attachment.htm From steve at alchemy.com Thu Sep 6 08:59:11 2007 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 05 Sep 2007 23:59:11 -0700 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> Message-ID: <46DFA53F.1050504@alchemy.com> saradhi dinavahi wrote: > I am new to the Python Programming. I want to Import Excel sheet data > using Python. Can any one please provide me the code and explain the > basic steps and method of executing the code. If you can get your Excel data into CSV format, the csv module others have already mentioned is a great way to go. It makes it very easy to read and write CSV-format files, which can be used with other spreadsheets and other programs, too. However, if you need to create or input actual Excel worksheets, which contain more than simple data tables like CSV supports, check out a third-party module called pyExcelerator. http://sourceforge.net/projects/pyexcelerator From kent37 at tds.net Thu Sep 6 12:38:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 06:38:46 -0400 Subject: [Tutor] Importing Excel sheet data In-Reply-To: References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> Message-ID: <46DFD8B6.1080608@tds.net> Ian Witham wrote: > HI Saradhi, > > I too am fairly new to Python, but I use the csv module successfully for > my work. Could you be a little more specific as to what your > requirements are and where you are finding difficulty? > > Ian. > > On 9/6/07, *saradhi dinavahi* > wrote: > > hi Ian , > > I have read the CSV module. But I felt difficult to write a code for > my requirement. For reading only there is also xlrd: http://www.lexicon.net/sjmachin/xlrd.htm The csv module was recently covered here: http://blog.doughellmann.com/2007/08/pymotw-csv.html If you are having trouble with the basics you would do well to read one of the tutorials here or an introductory book: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers BTW we usually bottom post on this list. http://catb.org/jargon/html/B/bottom-post.html Kent From kent37 at tds.net Thu Sep 6 12:45:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 06:45:08 -0400 Subject: [Tutor] unicode encoding hell In-Reply-To: <3408212.QD0Uz6TdxC@teancum> References: <3408212.QD0Uz6TdxC@teancum> Message-ID: <46DFDA34.3020200@tds.net> David Bear wrote: > feedp.entry.title.decode('utf-8', 'xmlcharrefreplace') > > I assume it would take any unicode character and 'do the right thing', > including replacing higher ordinal chars with xml entity refs. But I still > get > > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in > position 31: ordinal not in range(128) > > Clearly, I completely do not understand how unicode is working here. Can > anyone enlighten me? It sounds like you already have Unicode. Notice that you are trying to decode but the error is for encoding. In [17]: u'\u2019'.decode('utf-8') ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) : 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128) decode() goes towards unicode, encode() goes away from unicode. Kent From wormwood_3 at yahoo.com Thu Sep 6 15:40:21 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 6 Sep 2007 06:40:21 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <178570.97550.qm@web32401.mail.mud.yahoo.com> I am trying to figure out the optimal way to make socket connections (INET) and check for timeouts. The socket module has settimeout(timeout) and setdefaulttimeout(timeout). However, so far as I can tell, these apply to socket objects. The type of socket connection I want to make is getfqdn(address). So I can set the default timeout for socket, but not a socket object (makes sense so far). I cannot use the getfqdn(address) method on a socket object, I have to use it on socket. This means (as I understand it thus far), that while I can set a timeout value for socket objects, this will not apply to when I use the getfqdn() method, which is where I need a timeout check! Some example code for the steps so far: >>> import socket >>> conn = socket.socket() >>> conn.setdefaulttimeout(2.0) Traceback (most recent call last): File "", line 1, in AttributeError: '_socketobject' object has no attribute 'setdefaulttimeout' >>> socket.setdefaulttimeout(2.0) >>> conn.getfqdn("64.33.212.2") Traceback (most recent call last): File "", line 1, in AttributeError: '_socketobject' object has no attribute 'getfqdn' >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' >>> # Disconnected network connection here ... >>> socket.getfqdn("64.33.212.2") '64.33.212.2' >>> # Reconnected network connection here >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' After I disconnected my network connection and called getfqdn(), it returned the IP address I called it with after about 25 seconds. So the default timeout was ignored? Is there some other way to call this function so that I can check for timeouts? Should I instead just put my network calls in a thread and see how long they take, stopping them after a certain period? Thanks for any help. -Sam From fiyawerx at gmail.com Thu Sep 6 17:35:14 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Thu, 6 Sep 2007 11:35:14 -0400 Subject: [Tutor] Python / CGI Message-ID: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Hi guys, quick question, I've been trying to learn python lately, and have written a few little apps to help with some day to day stuff I do, and recently my fiance asked me if it was possible to come up with a simple web based schedule she can use with the other teachers in her school to schedule library time. (She's the librarian). Basically, it will be a small calendar like app that will have 'slots' teachers can sign up for. It doesn't sound like it would be too complicated, and may be a good learning project. I was wondering if python as cgi would be good for this, and if there are any pitfalls I need to watch out for before I start delving into it. I'm also fairly new to writing my own html so will basically be learning it all from scratch. TIA, Lee McClintock -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/7c460fdf/attachment.htm From connorsml at gmail.com Thu Sep 6 17:44:52 2007 From: connorsml at gmail.com (Michael Connors) Date: Thu, 6 Sep 2007 16:44:52 +0100 Subject: [Tutor] Python / CGI In-Reply-To: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: Hi, If you have your own server to run it on, I think it would make sense to use one of the Python web frameworks that are out there. I used cherrypy for my first web-based python project and I found it very easy to learn and develop in quickly. Regards, Michael On 06/09/07, Fiyawerx wrote: > > Hi guys, quick question, I've been trying to learn python lately, and have > written a few little apps to help with some day to day stuff I do, and > recently my fiance asked me if it was possible to come up with a simple web > based schedule she can use with the other teachers in her school to schedule > library time. (She's the librarian). Basically, it will be a small calendar > like app that will have 'slots' teachers can sign up for. It doesn't sound > like it would be too complicated, and may be a good learning project. I was > wondering if python as cgi would be good for this, and if there are any > pitfalls I need to watch out for before I start delving into it. I'm also > fairly new to writing my own html so will basically be learning it all from > scratch. > > TIA, > Lee McClintock > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/20e6eff5/attachment.htm From fiyawerx at gmail.com Thu Sep 6 17:57:55 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Thu, 6 Sep 2007 11:57:55 -0400 Subject: [Tutor] Python / CGI In-Reply-To: References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <1b31ae500709060857u674045f8l8334896ec502f320@mail.gmail.com> Thanks Michael, I'll be using my dreamhost account, and I'm pretty sure cherrypy works there, will check into it. On 9/6/07, Michael Connors wrote: > > Hi, > If you have your own server to run it on, I think it would make sense to > use one of the Python web frameworks that are out there. I used cherrypy for > my first web-based python project and I found it very easy to learn and > develop in quickly. > Regards, > Michael > > On 06/09/07, Fiyawerx wrote: > > > Hi guys, quick question, I've been trying to learn python lately, and > > have written a few little apps to help with some day to day stuff I do, and > > recently my fiance asked me if it was possible to come up with a simple web > > based schedule she can use with the other teachers in her school to schedule > > library time. (She's the librarian). Basically, it will be a small calendar > > like app that will have 'slots' teachers can sign up for. It doesn't sound > > like it would be too complicated, and may be a good learning project. I was > > wondering if python as cgi would be good for this, and if there are any > > pitfalls I need to watch out for before I start delving into it. I'm also > > fairly new to writing my own html so will basically be learning it all from > > scratch. > > > > TIA, > > Lee McClintock > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > Michael Connors > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/1c331fc4/attachment.htm From brunson at brunson.com Thu Sep 6 18:07:32 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 06 Sep 2007 10:07:32 -0600 Subject: [Tutor] Python / CGI In-Reply-To: References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <46E025C4.6010000@brunson.com> Michael Connors wrote: > Hi, > If you have your own server to run it on, I think it would make sense > to use one of the Python web frameworks that are out there. I used > cherrypy for my first web-based python project and I found it very > easy to learn and develop in quickly. That's debatable. I find the frameworks to be overly complicated and obfuscated. They're great when you're going through the tutorials, but try to do something "outside the box" and I find myself digging through documentation for longer than it would take me to write it from scratch. For this you'd need: some sort of backing store and some display routines with a simple interface to click on a slot and enter your name in it. I think I could write it in about 75 lines of python. Maybe 50. Just my opinion, e. > Regards, > Michael > > On 06/09/07, *Fiyawerx* > wrote: > > Hi guys, quick question, I've been trying to learn python lately, > and have written a few little apps to help with some day to day > stuff I do, and recently my fiance asked me if it was possible to > come up with a simple web based schedule she can use with the > other teachers in her school to schedule library time. (She's the > librarian). Basically, it will be a small calendar like app that > will have 'slots' teachers can sign up for. It doesn't sound like > it would be too complicated, and may be a good learning project. I > was wondering if python as cgi would be good for this, and if > there are any pitfalls I need to watch out for before I start > delving into it. I'm also fairly new to writing my own html so > will basically be learning it all from scratch. > > TIA, > Lee McClintock > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Michael Connors > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Sep 6 18:25:52 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 12:25:52 -0400 Subject: [Tutor] Python / CGI In-Reply-To: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <46E02A10.6040507@tds.net> Fiyawerx wrote: > Hi guys, quick question, I've been trying to learn python lately, and > have written a few little apps to help with some day to day stuff I do, > and recently my fiance asked me if it was possible to come up with a > simple web based schedule she can use with the other teachers in her > school to schedule library time. (She's the librarian). Basically, it > will be a small calendar like app that will have 'slots' teachers can > sign up for. It doesn't sound like it would be too > complicated, and may be a good learning project. I would look for prior art, myself. This sounds like a project that could easily get complicated. Here are some promising links: http://python.about.com/b/a/000088.htm http://www.schooltool.org/products/schooltool-calendar For that matter you might find that Google Calendar does everything you need: http://www.google.com/calendar It has a Python API FWIW: http://code.google.com/apis/calendar/overview.html Kent From kent37 at tds.net Thu Sep 6 18:39:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 12:39:02 -0400 Subject: [Tutor] Python / CGI In-Reply-To: <46E025C4.6010000@brunson.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <46E025C4.6010000@brunson.com> Message-ID: <46E02D26.9090300@tds.net> Eric Brunson wrote: > Michael Connors wrote: >> Hi, >> If you have your own server to run it on, I think it would make sense >> to use one of the Python web frameworks that are out there. I used >> cherrypy for my first web-based python project and I found it very >> easy to learn and develop in quickly. > > That's debatable. I find the frameworks to be overly complicated and > obfuscated. They're great when you're going through the tutorials, but > try to do something "outside the box" and I find myself digging through > documentation for longer than it would take me to write it from scratch. Hmm. As my boss likes to say, "Reasonable people may disagree." I have been developing with Django for about six months now and I love it. Much of what I have wanted to do is directly supported and easy in Django; sometimes I have to push at it but only a few times have I really felt like I was trying to make it do something it really didn't want to do. I find both the documentation and code informative and easy to read. Kent From brunson at brunson.com Thu Sep 6 18:57:58 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 06 Sep 2007 10:57:58 -0600 Subject: [Tutor] Python / CGI In-Reply-To: <46E02D26.9090300@tds.net> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <46E025C4.6010000@brunson.com> <46E02D26.9090300@tds.net> Message-ID: <46E03196.60509@brunson.com> Kent Johnson wrote: > Eric Brunson wrote: > >> Michael Connors wrote: >> >>> Hi, >>> If you have your own server to run it on, I think it would make sense >>> to use one of the Python web frameworks that are out there. I used >>> cherrypy for my first web-based python project and I found it very >>> easy to learn and develop in quickly. >>> >> That's debatable. I find the frameworks to be overly complicated and >> obfuscated. They're great when you're going through the tutorials, but >> try to do something "outside the box" and I find myself digging through >> documentation for longer than it would take me to write it from scratch. >> > > Hmm. As my boss likes to say, "Reasonable people may disagree." I have > been developing with Django for about six months now and I love it. Much > of what I have wanted to do is directly supported and easy in Django; > sometimes I have to push at it but only a few times have I really felt > like I was trying to make it do something it really didn't want to do. I > find both the documentation and code informative and easy to read. > I'll admit, though I looked at it briefly, Django was not one of the frameworks I spent much time on (didn't care for the templating style). I do most of my web development to run under mod_python and I've developed my own libraries to do what I need to do the way I think it should be done. :-) From david.bear at asu.edu Thu Sep 6 19:40:34 2007 From: david.bear at asu.edu (David Bear) Date: Thu, 06 Sep 2007 10:40:34 -0700 Subject: [Tutor] getting iteration level Message-ID: <9103560.YZBuXKBE9u@teancum> Lets say I have a list object that I iterate over like this: for item in myList: process(item) During execution of the for loop something happens and I want to know how many items have be iterated over, how do I find out? Without resorting to some counter inside the loop, is there some python object I can ask? -- David Bear College of Public Programs at Arizona State University From eike.welk at gmx.net Thu Sep 6 19:12:16 2007 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 06 Sep 2007 19:12:16 +0200 Subject: [Tutor] Dynamically changing a class In-Reply-To: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> References: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> Message-ID: <200709061912.16530.eike.welk@gmx.net> On Wednesday 05 September 2007 16:59, Jason Doege wrote: > Thanks for the good and useful information on this. Now for the > why... > > I am building an API and for various reasons I have chosen Python > to implement it. I'd like to separate the implementation from the > interface as, for instance, C++ does with separate .hpp and .cpp > files. Apart from defining a class with a bunch of empty methods > and then redefining them, I have not seen a good way to do this in > Python. Can you recommend the Pythonic way to do this? > If you want to describe the data and validate it, Enthought traits may be interesting for you: http://code.enthought.com/traits/ They additionally have a library that can automatically generate a graphical user interface to change the data of a traits using class. Regards, Eike. From eric at ericwalstad.com Thu Sep 6 19:53:27 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Thu, 06 Sep 2007 10:53:27 -0700 Subject: [Tutor] Python / CGI In-Reply-To: References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <46E03E97.3050808@ericwalstad.com> Michael Connors wrote: > Hi, > If you have your own server to run it on, I think it would make sense to > use one of the Python web frameworks that are out there. I used cherrypy > for my first web-based python project and I found it very easy to learn > and develop in quickly. > Regards, > Michael I'd argue that sticking with a Python CGI would be a great way to start because the OP can focus on the basics rather than on the framework API. The Python CGI stuff I've written in the past was helpful in my understanding of how and why Django works the way it does. After his Web Calendar is functioning as a CGI he'll have lots of ideas on how to improve it. A framework might help at that point. This article looks like it might have some useful information: [http://python.about.com/od/advancedpython/ss/howtocal.htm] Sounds like a fun project. Eric. From kent37 at tds.net Thu Sep 6 19:55:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 13:55:45 -0400 Subject: [Tutor] getting iteration level In-Reply-To: <9103560.YZBuXKBE9u@teancum> References: <9103560.YZBuXKBE9u@teancum> Message-ID: <46E03F21.7000605@tds.net> David Bear wrote: > Lets say I have a list object that I iterate over like this: > > for item in myList: > process(item) > > During execution of the for loop something happens and I want to know how > many items have be iterated over, how do I find out? Without resorting to > some counter inside the loop, is there some python object I can ask? Use enumerate(), it generates the list index for you: for i, item in enumerate(myList): process(item) print 'processed item', i Kent From wormwood_3 at yahoo.com Thu Sep 6 22:46:08 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 6 Sep 2007 13:46:08 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <469084.61038.qm@web32405.mail.mud.yahoo.com> Since no one bit on this yet, let me simplify to the core issue I am having: What is the best practice for checking for network connectivity errors when making network calls? Is it better to wrap the functions that make said calls in threads and time them? Or to use timeout variables for modules like socket? Something else? I found some good general info here: http://www.onlamp.com/pub/a/python/2003/11/06/python_nio.html But I have had a hard time finding info on network error handling specifically. Thoughts? ______________________________________ ----- Original Message ---- From: wormwood_3 To: Python Tutorlist Sent: Thursday, September 6, 2007 9:40:21 AM Subject: [Tutor] Socket Timeout Handling I am trying to figure out the optimal way to make socket connections (INET) and check for timeouts. The socket module has settimeout(timeout) and setdefaulttimeout(timeout). However, so far as I can tell, these apply to socket objects. The type of socket connection I want to make is getfqdn(address). So I can set the default timeout for socket, but not a socket object (makes sense so far). I cannot use the getfqdn(address) method on a socket object, I have to use it on socket. This means (as I understand it thus far), that while I can set a timeout value for socket objects, this will not apply to when I use the getfqdn() method, which is where I need a timeout check! Some example code for the steps so far: >>> import socket >>> conn = socket.socket() >>> conn.setdefaulttimeout(2.0) Traceback (most recent call last): File "", line 1, in AttributeError: '_socketobject' object has no attribute 'setdefaulttimeout' >>> socket.setdefaulttimeout(2.0) >>> conn.getfqdn("64.33.212.2") Traceback (most recent call last): File "", line 1, in AttributeError: '_socketobject' object has no attribute 'getfqdn' >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' >>> # Disconnected network connection here ... >>> socket.getfqdn("64.33.212.2") '64.33.212.2' >>> # Reconnected network connection here >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' After I disconnected my network connection and called getfqdn(), it returned the IP address I called it with after about 25 seconds. So the default timeout was ignored? Is there some other way to call this function so that I can check for timeouts? Should I instead just put my network calls in a thread and see how long they take, stopping them after a certain period? Thanks for any help. -Sam _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Thu Sep 6 22:59:58 2007 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 6 Sep 2007 13:59:58 -0700 Subject: [Tutor] Python / CGI In-Reply-To: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <20070906205958.GB14020@dragon.alchemy.com> On Thu, Sep 06, 2007 at 11:35:14AM -0400, Fiyawerx wrote: > recently my fiance asked me if it was possible to come up with a simple web > based schedule she can use with the other teachers in her school to schedule > library time. (She's the librarian). Basically, it will be a small calendar > like app that will have 'slots' teachers can sign up for. It doesn't sound I wrote something like that in a couple of hours using straight Python, so I know it's doable. I haven't checked out any of the frameworks, but it would be really interesting to see what it would take to build a couple of apps in Django or whatever. If you're interested in just banging out a Python app, though, my experience was writing a calendaring tool for a group of my friends who get together once a month or so for gaming days. The app displays a year's calendar (any year desired) and shows what days we're playing or not. You click on a link to get a version of that calendar view with "slots" open for you to vote on which days you prefer or which you can't play on. Then I have an admin view which displays all the votes, and lets me make the "play/not play" decision for each date, which is what is displayed in the normal calendar view. The whole thing only took 318 lines of straight Python code, including all the HTML displayed on all those forms. The "calendar" module is your friend for apps like this, by the way :) -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From alan.gauld at btinternet.com Fri Sep 7 01:41:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 00:41:32 +0100 Subject: [Tutor] Socket Timeout Handling References: <469084.61038.qm@web32405.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > Since no one bit on this yet, let me simplify to the core issue I am > having: That may be because your question ventures into fairly deep areas of networking that most folk who are just learning Python(ie readers of this list) have probably not encountered. I've used python for network programming but not extensively and certainly not for hard core production use so can't help you. Similarly I've used sockets extesively from C/C++ but I'm not sure how well that transfers to Python without doing more digging than I hsave time for right now. If you do want to get into depth on Python networking you may find the A-Press book Python Network Programming useful - I do regularly :-). However the only information I could see about timeouts there was related to socket.settimeout() which ISTR you didn't want to/couldn't use... > What is the best practice for checking for network connectivity > errors when making network calls? Is it better to wrap the functions > that make said calls in threads and time them? > Or to use timeout variables for modules like socket? Personally if i was doingt that I'd almost certainy put it in a thread and apply a timeout within the thread. but not having tried that I don't know how easy it would be! > But I have had a hard time finding info on network error handling > specifically. The A-Press book does devote several pages in total to socket error handling including connection errors, timeout errors and transmission errors. > > I am trying to figure out the optimal way to make socket connections > (INET) and check for timeouts. The socket module has > settimeout(timeout) > and setdefaulttimeout(timeout). However, so far as I can tell, these > apply > to socket objects. The type of socket connection I want to make is > getfqdn(address). I don't understand, getfqdn() returns a domain name not an a socket? > So I can set the default timeout for socket, but not a socket object > (makes sense so far). I cannot use the getfqdn(address) method on > a socket object, I have to use it on socket. Sorry it's not making sense to me, getfqdn takes a host name not a socket. >>>> import socket >>>> conn = socket.socket() >>>> conn.setdefaulttimeout(2.0) setdefaulttimout is a function in the socket module not a method of socket. Thus you woulfd call that before reating a new socket: >>> socket.setdefaulttimeout(5) # set default t/o of 5 secs >>> conn = socket.socket() # with timeout of 5 >>>> socket.setdefaulttimeout(2.0) >>>> conn.getfqdn("64.33.212.2") Again getfqdn is a function in the socket module not a method. But if you give it an IP saddress it will just return that IP address! >>>> socket.getfqdn("64.33.212.2") > '64-33-212-2.customers.pingtone.net' OK, Apparently it will give you more... :-) >>>> # Disconnected network connection here > ... >>>> socket.getfqdn("64.33.212.2") > '64.33.212.2' > After I disconnected my network connection and called getfqdn(), > it returned the IP address I called it with after about 25 seconds. > So the default timeout was ignored? Yes because there was no socket being created it was doing a name lookup using standard DNS etc, and with the network disconnected timed out at the OS level I suspect. If you want to control the DNS lookup you will need to cofde that manually I suspect. (As I say, this is way deeper than I've needed to peer into these type of operations, the defaults have worked for me!) > Is there some other way to call this function so that I can check > for timeouts? Should I instead just put my network calls in a > thread and see how long they take, stopping them after a certain > period? I don't think that would necessarily help here. What are you trying to do? Establish a socket connection to something or just do a name check that times out more quickly?(or slowly) > Thanks for any help. Not sure how much help, not even sure I understand what you are up to, but it might spark an idea... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Sep 7 01:50:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 00:50:31 +0100 Subject: [Tutor] Python / CGI References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: "Fiyawerx" wrote > Hi guys, quick question, I've been trying to learn python lately, > and have > written a few little apps to help with some day to day stuff I do, > and > recently my fiance asked me if it was possible to come up with a > simple web > based schedule she can use with the other teachers in her school to > schedule > library time. > wondering if python as cgi would be good for this, and if there are > any > pitfalls I need to watch out for before I start delving into it. If you want to do it as a learning excercise then I recommend using vanilla CGI. Everyone should write a couple of CGI apps to understand what really goes on. But two is enough and then move onto a framework for the sake of your sanity! Django has gotten a mention, personally I've been using TurboGears a bit and like it. Its an amalgamation of CherryPy (already mentioned) to convert http requests into python method calls with kid for templating (aka isolating your HTML from your code) and SQL Objects for providing OO style database access - you may not even need this, flat files may be adequate.(It can also use SQL Alchemy for this but I've not used it) www.turbogears.org But frankly all web objects provide the same basic features and for "conventional" web apps there is little to choose IMHO! ) And not just in Python, the same applies to Ruby on Rails, Struts(Java), IBM Websphere etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cspears2002 at yahoo.com Fri Sep 7 02:13:09 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 6 Sep 2007 17:13:09 -0700 (PDT) Subject: [Tutor] manually sorting variables Message-ID: <618185.53245.qm@web51609.mail.re2.yahoo.com> I'm working out of Core Python Programming (2nd Edition) by Wesley Chun. Here is the problem: Have the user enter three numeric values and store them in three different variables. Without using lists or sorting algorithms, manually sort these three numbers from smallest to largest. Here is what I have so far: #!/usr/bin/env python def smallest_var(x,y): if x < y: return x elif y < x: return y else: print "x equals y" var1 = raw_input("Enter a number for var1: ") var2 = raw_input("Enter a number for var2: ") var3 = raw_input("Enter a number for var3: ") small = smallest_var(var1, var2) #print small_var_1 smallest = smallest_var(small, var3) print smallest I'm not sure what the next step would be. If I was using a list, I could try to remove the smallest variable and then just compare the two remaining variables. Any hints? "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 "I generally know what I'm doing." -Buster Keaton From kent37 at tds.net Fri Sep 7 03:12:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 21:12:49 -0400 Subject: [Tutor] manually sorting variables In-Reply-To: <618185.53245.qm@web51609.mail.re2.yahoo.com> References: <618185.53245.qm@web51609.mail.re2.yahoo.com> Message-ID: <46E0A591.9030002@tds.net> Christopher Spears wrote: > I'm working out of Core Python Programming (2nd > Edition) by Wesley Chun. > > Here is the problem: > > Have the user enter three numeric values and store > them in three different variables. Without using > lists or sorting algorithms, manually sort these three > numbers from smallest to largest. > > Here is what I have so far: > #!/usr/bin/env python > > def smallest_var(x,y): > if x < y: > return x > elif y < x: > return y > else: > print "x equals y" > > var1 = raw_input("Enter a number for var1: ") > var2 = raw_input("Enter a number for var2: ") > var3 = raw_input("Enter a number for var3: ") > > small = smallest_var(var1, var2) > #print small_var_1 > smallest = smallest_var(small, var3) > print smallest > > I'm not sure what the next step would be. If I was > using a list, I could try to remove the smallest > variable and then just compare the two remaining > variables. Any hints? Do you know how to do a bubble sort? You could use comparison and swapping to sort the values so x is the smallest, y is the middle and z is the largest. I think it can be done with three comparisons and three or fewer swaps. Think of x, y and z as the three positions of a list. Kent From washakie at gmail.com Fri Sep 7 07:31:27 2007 From: washakie at gmail.com (John) Date: Thu, 6 Sep 2007 22:31:27 -0700 Subject: [Tutor] dynamic attribute assignment Message-ID: I've just noticed that you can use the import statement to import variables, such that a simple file such as vars.py: # File with predefined variables var1= 'some text' var2= 2 var3=['a','b','c'] Would then, upon import, provide: >>>vars.var1 'some text' >>>vars.var2 2 >>>vars.var3 ['a','b','c'] This is great, I had no idea! However, is there then a way to reassign or update the values? For instance, can you say: >>>vars.var1='some new text' ?? Just curious! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/1bd8e816/attachment.htm From alan.gauld at btinternet.com Fri Sep 7 09:08:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 08:08:05 +0100 Subject: [Tutor] manually sorting variables References: <618185.53245.qm@web51609.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote > Have the user enter three numeric values and store > them in three different variables. Without using > lists or sorting algorithms, manually sort these three > numbers from smallest to largest. Hmm, the restriction of not using a sorting algorithm is interesting. But if you only have three values its doable. With more than three I'm not sure how it would be done. > def smallest_var(x,y): So you can get the smallest var. Now if you could get the biggest then the one that's neither must be in the middle. You are then left with selecting one of 6 possible outcomes: 1,2,3, 1,3,2 2,1,3 2.3.1, 3,1,2 3,2,1 Does that help? Alternatively you could write a comparison function rather than a get smallest/get biggest. That way you can compare the original variables rather than creating new ones. > var1 = raw_input("Enter a number for var1: ") > var2 = raw_input("Enter a number for var2: ") > var3 = raw_input("Enter a number for var3: ") You should convert these to integers! > small = smallest_var(var1, var2) > #print small_var_1 > smallest = smallest_var(small, var3) > print smallest HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Sep 7 09:10:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 08:10:31 +0100 Subject: [Tutor] dynamic attribute assignment References: Message-ID: "John" wrote >>>>vars.var3 > ['a','b','c'] > > This is great, I had no idea! However, is there then a way to > reassign or > update the values? For instance, can you say: > >>>>vars.var1='some new text' Why not try it at the >>> prompt? Thats the great thing about python, its very easy to try things like that out and get a definitive answer! (Even faster than posting to a mailing list! :-) In this case its a yes... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From steve at alchemy.com Fri Sep 7 10:23:13 2007 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 07 Sep 2007 01:23:13 -0700 Subject: [Tutor] Python / CGI In-Reply-To: References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <20070906205958.GB14020@dragon.alchemy.com> Message-ID: <46E10A71.8090902@alchemy.com> John wrote: > Steve, > > If you're interested in just banging out a Python app, though, my > experience > was writing a calendaring tool for a group of my friends who get > together > [...] > This sounds very cool, is it something you could post? Okay. It's not the greatest implementation (as I said it was kind of a quick hack) but here it is... A few notes to help understand the app: It's a single stand-alone CGI script in Python, and serves the three calendar views (scheduled games, the form for players to vote on good dates, and a form for the admin to decide on the game dates based on the votes) within this one script. It stores the data for the calendar in a MySQL database. The users need to authenticate to the web server in order to get to the page, so we can look in the script's environment to see who they are (so we know who voted for what days, and who gets the admin access page). The admin (and only the admin) can add a "?for=username" to the URL to access the application as if they were one of the players (in case they can't get in to the calendar but wish to change their vote data). #!/usr/bin/python # # Display a calendar of our game days, allow "voting" for what days any person # is available or not. # import cgitb; cgitb.enable() import os import sys import calendar import datetime import cgi import MySQLdb monthnames = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') daynames = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat') calendar.setfirstweekday(6) # start weeks on Sunday currentdaybg = "#999933" votecolors = ( "#ff0000", "#00ff00", "#ffff00" ) form = cgi.FieldStorage() today = datetime.date.today() print "Content-Type: text/html\n" print '' if 'year' in form: year = int(form.getfirst('year')) if not 2000 < year < 2020: print "Sorry, we're not supporting that year right now." sys.exit(0) else: year = today.year print """""" if 'REMOTE_USER' not in os.environ: print "Sorry, this page cannot be used without authentication." sys.exit(0) me = os.environ['REMOTE_USER'] admin = (me == 'login-name-of-admin-1' or me == 'login-name-of-admin-2') #admin = False mode = 'normal' forWhom = None if admin and 'for' in form: me = form.getfirst('for') forWhom=me print "***",me,"***" if 'mode' in form: mode = form.getfirst('mode') if mode == 'admin' and not admin: print "Sorry, restricted access to this application is denied." sys.exit(0) if mode == 'admin' or mode == 'vote': print '
' if mode == 'vote': print '''

Voting For Game Dates

Generally, we play on Saturdays. If there's a special date we are considering playing on, such as a holiday, indicate your preference for that, but otherwise we're looking just for Saturdays.

Indicate your preferences by selecting the appropriate response under each date:

---: I am available, most likely, and willing to play that date.
Best: This date is particularly good for me. Please play on that date if possible.
NO: This date is not good, I most likely will not be able to play.
The default is "available", so if you're ok with playing any weekend in a month, just leave them all as "---". Don't mark them all as "best". The "best" setting is provided so that you can indicate unusually favorable dates, like when your SO is away or something.

When finished, click the "Save" button at the bottom. You'll be brought back to this form again in case you want to make more changes. Click the "Return to Calendar View" link (or navigate away from this page) when you're done and have saved all the changes you want to keep.

''' # # Connect to database # db = MySQLdb.connect(host='HHH', user='XXX', passwd='YYY', db='ZZZ') # # Accept updates from user # votelist = None if mode == 'vote' or mode == 'admin': for key in form: if len(key) == 4: try: vmonth = int(key[0:2]) vdate = int(key[2:4]) vv = form.getfirst(key) except: # must not be the four-digit key we're looking for continue if 1 <= vmonth <= 12 and 1 <= vdate <= 31: if votelist is None: votelist = [] if mode == 'vote': if vv == '-': pass # just let the old vote (if any) die elif vv == 'Y': votelist.append((datetime.date(year,vmonth,vdate), me, True)) elif vv == 'N': votelist.append((datetime.date(year,vmonth,vdate), me, False)) else: print "***WARNING*** Invalid vote field encountered; vote for %d/%d NOT counted.
" % (vmonth,vdate) elif mode == 'admin': if vv == '-': pass # just let the old vote (if any) die elif vv == 'P': votelist.append((datetime.date(year,vmonth,vdate), 'GAME', True)) elif vv == 'A': votelist.append((datetime.date(year,vmonth,vdate), 'GAME', False)) else: print "***WARNING*** Invalid schedule field encountered; setting for %d/%d NOT counted.
" % (vmonth,vdate) if votelist is not None: # # Record new list of votes for this user # if mode == 'admin': duser = 'GAME' else: duser = me q = db.cursor() q.execute('DELETE FROM votes WHERE vuser=%s AND vdate >= %s AND vdate <= %s', (duser, '%04d-01-01'%year, '%04d-12-31'%year)) q.executemany('INSERT INTO votes (vdate, vuser, vote) values (%s,%s,%s)', votelist) logfile = open("/var/log/gamecal", "a") print >>logfile, "%d %s %s %s" % (year, os.environ['REMOTE_USER'], duser, votelist) logfile.close() myvotes = {} allvotes = {} gamedates = {} if mode == 'vote': # # Get my votes from database to display # --> myvotes # maps 'mmdd':0/1 (0=no, 1=yes). Dates not in dict=no preference # q = db.cursor() q.execute('SELECT vdate, vote FROM votes WHERE vuser=%s AND vdate >= %s AND vdate <= %s', (me, '%04d-01-01'%year, '%04d-12-31'%year)) for vote in q.fetchall(): myvotes['%02d%02d' % (vote[0].month, vote[0].day)] = vote[1] if mode == 'admin': # # Get everyone's votes from database # --> gamedates # maps 'mmdd':'ALT'/'PRI' (alternate/primary play date) # --> allvotes # maps 'mmdd':(0/1/2, string) 0=no, 1=yes, 2=mixed; string describes votes collected # q = db.cursor() q.execute('SELECT vdate, vuser, vote FROM votes WHERE vdate >= %s AND vdate <= %s', ('%04d-01-01'%year, '%04d-12-31'%year)) for vote in q.fetchall(): key = '%02d%02d' % (vote[0].month, vote[0].day) if vote[1] == 'GAME': gamedates[key] = ('ALT','PRI')[vote[2]] elif key not in allvotes: allvotes[key] = [vote[2], "%s: %s" % (vote[1], ('no','best')[vote[2]])] else: if allvotes[key][0] != vote[2]: allvotes[key][0] = 2 allvotes[key][1] += "; %s: %s" % (vote[1], ('no','best')[vote[2]]) else: q = db.cursor() q.execute("SELECT vdate, vote FROM votes WHERE vdate >= %s AND vdate <= %s AND vuser='GAME'", ('%04d-01-01'%year, '%04d-12-31'%year)) for vote in q.fetchall(): key = '%02d%02d' % (vote[0].month, vote[0].day) gamedates[key] = ('ALT','PRI')[vote[1]] if mode == 'admin' or mode == 'vote': print '

Editing %d

' % year else: print '''
%d %d %d

''' % (year-1,year-1, year, year+1,year+1) print '''

''' for month in range(0, 12, 3): print "" caldates = [] # # Month Names # for m in range(0,3): print "" % monthnames[month+m] caldates.append(calendar.monthcalendar(year,month+m+1)) print "" # # Day Names # for m in range(0,3): for d in range(0,7): print "" % daynames[d] print "" print "" # # Dates # for week in range(0,max([len(i) for i in caldates])): print "" for m in range(0,3): if week >= len(caldates[m]): print "" else: for d in range(0,7): if caldates[m][week][d] == 0: print "" else: key = '%02d%02d' % (month+m+1, caldates[m][week][d]) if mode == 'admin' and key in allvotes: print "' % (allvotes[key][1], caldates[m][week][d]) elif key in gamedates: if gamedates[key] == 'PRI': print "" % caldates[m][week][d] else: print "" % caldates[m][week][d] else: if month+m+1 == today.month and caldates[m][week][d] == today.day and year == today.year: print "" % caldates[m][week][d] print "" print "" if mode == 'vote' or mode == 'admin': # make another row of voting buttons under the dates. print "" for m in range(0,3): if week >= len(caldates[m]): print "" else: for d in range(0,7): if caldates[m][week][d] == 0: print "" else: key = '%02d%02d' % (month+m+1, caldates[m][week][d]) print '' else: print '" print "" print "
 
%s   
%s
[%d](%d)" else: print "" print "%d
" if mode == 'admin' or mode == 'vote': if forWhom is not None: print '' % cgi.escape(forWhom) print '' % year print '' % mode print '
' print '

Return to calendar view (abandons unsaved changes!)' % year else: print 'Indicate your good/bad dates
' % year if admin: print 'Set Game Dates
' % year print '' if mode == 'admin': print ''' ''' % (currentdaybg, votecolors[1], votecolors[0], votecolors[2]) else: print ''' ''' % (currentdaybg, '#009900', '#000099') print '
     Today
     Preferred Date
     Problem Date
     Mixed Bag
     Today
     Play Date
     Alternate
' print "" ------------------------------------------------------------------------------ After I put that on the website, I wrote another script which runs out of cron and automatically sends out reminder messages to the players a few days in advance of a game date: #!/usr/bin/python # import sys import datetime import MySQLdb import smtplib # # The gamecal.votes table looks like this: # #+-------+-------------+------+-----+------------+-------+ #| Field | Type | Null | Key | Default | Extra | #+-------+-------------+------+-----+------------+-------+ #| vdate | date | NO | PRI | 0000-00-00 | | #| vuser | varchar(20) | NO | PRI | NULL | | #| vote | tinyint(1) | NO | | 0 | | #+-------+-------------+------+-----+------------+-------+ # # If the vuser is 'GAME', the "vote" indicates a scheduled # game date and not a player's vote. In this case, 'vote' # is 1 for a primary date and 0 for an alternate date. # db = MySQLdb.connect(host='HHH', user='XXX', passwd='YYY', db='ZZZ') today = datetime.date.today() query = db.cursor() query.execute(''' SELECT vdate, vote FROM votes WHERE vdate >= %s AND vdate < %s AND vuser='GAME' ORDER BY vdate ''', (today, today + datetime.timedelta(180))) gamedates = query.fetchall() query.close() db.close() msg = '''From: me at XXX.com To: our-game-mailing-list at XXX.com Subject: Reminder of Upcoming D&D Game ''' # # Find closest actual game date # nextGame = None for game in gamedates: if game[1] == 1: nextGame = (game[0] - today).days break if nextGame is not None: if nextGame == 2: msg += "This is an automated reminder that the next D&D game is nearly here!\n\n" elif nextGame == 6: msg += "This is an automated reminder of the upcoming D&D game in less than a week.\n\n" else: sys.exit(0) msg += "The next several game dates are:\n" msg += "Date----------- Days Notes------\n" for game in gamedates: msg += "%-15s %4d" % (game[0].strftime('%a %b %d %Y'), (game[0]-today).days) if game[1] == 0: msg += " (Alternate)" msg += '\n' msg += ''' Please remember that you can always check the schedule by visiting http://url-to-calendar-application You may also go to that webpage and indicate what days are particularly good or bad for you in the future. ''' mail = smtplib.SMTP('mailserver.XXX.com') mail.sendmail('me at XXX.com','our-game-mailing-list at XXX.com', msg) mail.quit() From mailinglistmatt at gmail.com Fri Sep 7 13:41:43 2007 From: mailinglistmatt at gmail.com (matte) Date: Fri, 7 Sep 2007 13:41:43 +0200 Subject: [Tutor] Problem with while loop Message-ID: Hi guys Please excuse me but I've been out of Python for a while since my laptop was stolen... I'm battling with a very basic while loop.... -------------- 8< ---------------------- #!/usr/bin/python from random import randint counter = 0 howmany = raw_input( "How many: " ) while counter < howmany: pin = randint(0000,9999) print pin counter += 1 -------------- 8< ---------------------- For some reason if I use an integer in place of "howmany" it works, but I'd like it to work as I can logically see it above. What am I missing ? -m -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/a8faff46/attachment.htm From connorsml at gmail.com Fri Sep 7 13:54:18 2007 From: connorsml at gmail.com (Michael Connors) Date: Fri, 7 Sep 2007 12:54:18 +0100 Subject: [Tutor] Problem with while loop In-Reply-To: References: Message-ID: I think it will work if you cast your input to an int: howmany = int(raw_input( "How many: " )) On 07/09/2007, matte wrote: > > Hi guys > > Please excuse me but I've been out of Python for a while since my laptop > was stolen... > > I'm battling with a very basic while loop.... > > -------------- 8< ---------------------- > #!/usr/bin/python > > from random import randint > > counter = 0 > > howmany = raw_input( "How many: " ) > > while counter < howmany: > > pin = randint(0000,9999) > print pin > counter += 1 > > -------------- 8< ---------------------- > > For some reason if I use an integer in place of "howmany" it works, but > I'd > like it to work as I can logically see it above. > > What am I missing ? > > -m > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/c8980748/attachment.htm From mailinglistmatt at gmail.com Fri Sep 7 14:25:47 2007 From: mailinglistmatt at gmail.com (matte) Date: Fri, 7 Sep 2007 14:25:47 +0200 Subject: [Tutor] Problem with while loop In-Reply-To: References: Message-ID: Perfect... Thanks very much for your help... On 9/7/07, Michael Connors wrote: > > I think it will work if you cast your input to an int: > howmany = int(raw_input( "How many: " )) Now I just need to figure out how to only get 4 digit pin numbers :) -m -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/2d8b379b/attachment.htm From connorsml at gmail.com Fri Sep 7 14:40:24 2007 From: connorsml at gmail.com (Michael Connors) Date: Fri, 7 Sep 2007 13:40:24 +0100 Subject: [Tutor] Problem with while loop In-Reply-To: References: Message-ID: You could use string formatting to output all pin numbers as 4 character strings. http://docs.python.org/lib/typesseq-strings.html On 07/09/2007, matte wrote: > > Perfect... > > Thanks very much for your help... > > On 9/7/07, Michael Connors wrote: > > > > I think it will work if you cast your input to an int: > > howmany = int(raw_input( "How many: " )) > > > Now I just need to figure out how to only get 4 digit pin numbers :) > > -m > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/3da1b1bc/attachment.htm From tinoloc at gmail.com Fri Sep 7 17:08:33 2007 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 7 Sep 2007 11:08:33 -0400 Subject: [Tutor] Multi-threading help Message-ID: Hi there, I'm working on a multi-threaded utility to monitor network connections between three machines The configuration of the three machines are: a web machine that feeds back to two machines for processing. Sometimes when the web connection is closed, the corresponding processes on the two backend machines don't close. How, I have the current set up is: class web: def __init__(self): def run(self,args): class mach1: def __init__(self): def run(self,args): class mach2: def __init__(self): def run(self,args): class target: def run(self,args): ... collect data from web, mach1, mach2 classes, monitor connections, yada yada yada My question is how to get the information to the target class. The target class must have the web, mach1, mach2 data sets before doing any sort of matching up of information. Now the ways that I have thought of are: -Directing sending the information to the target object (there will only be one) -Using the Observer pattern to send the information from the web, mach1, mach2 classes to the target object And other question that I do have are: -Is there a way to "block" run until I get information from the three other objects. Presently, I can only think of looping and polling to see if the information has come in yet. I'm sure there is a way because I have seen it used in the SocketHandler class. -Is there any way that I can be sure that two different objects are not writing to target at the same time? The present way that I'm thinking about is using locking. Thanks Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/e244c4f5/attachment.htm From fiyawerx at gmail.com Fri Sep 7 17:49:12 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Fri, 7 Sep 2007 11:49:12 -0400 Subject: [Tutor] Python / CGI In-Reply-To: <46E10A71.8090902@alchemy.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <20070906205958.GB14020@dragon.alchemy.com> <46E10A71.8090902@alchemy.com> Message-ID: <1b31ae500709070849k4d2c460rce9f59c006d1972d@mail.gmail.com> Wow, thanks for all the info guys, more than i was expecting :). After looking around at various options, I did download the python gdata module for google's calendar. What I'm thinking is, since my fiance has two schools, she can just log into her google account and create a calendar for each school. I'm going to try to make a custom cgi front-end that will pull the data, and offer 'slots' to sign up for. When you sign up for a slot, you have to use a username for the front-end, I'm thinking I can store them in a db. That way I don't have to worry about everyone needing google calendars to be able to access hers. So when someone picks a slot and submits it, the program behind the scenes will actually just use her google account to submit, and append the username to the entry, so you can tell who did what, but it still will only require one real google account. Gdata comes with some really nice samples, one that basically does any of the calendar functions i'm going to need, so I think I should bea ble to rip the code out of that module to use, so I still get to learn the cgi doing my front-end, but that way I know I have a well functioning back-end to easy some of my troubles. http://code.google.com/apis/calendar/developers_guide_python.html Here is a bit of the output from their 'sample' python script that comes with the package. -------- C:\Python25\gdata.py-1.0.8\samples\calendar>python calendarExample.py --user fiyawerx at gmail.com --pw xxxxxxx Printing allcalendars: Lee McClintock's Calendar List 0. Lee McClintock Printing owncalendars: Lee McClintock's Calendar List 0. Lee McClintock Events on Primary Calendar: Lee McClintock 0. Rent 0. fiyawerx at gmail.com Lee McClintock None Full text query for events on Primary Calendar: 'Tennis' Date range query for events on Primary Calendar: 2007-01-01 to 2007-07-01 0. Rent Start time: 2007-03-01 End time: 2007-03-02 Start time: 2007-06-01 End time: 2007-06-02 Start time: 2007-01-01 End time: 2007-01-02 Start time: 2007-05-01 End time: 2007-05-02 Start time: 2007-04-01 End time: 2007-04-02 Start time: 2007-02-01 End time: 2007-02-02 New single event inserted: http://www.google.com/calendar/feeds/default/private/full/cmvade9oqrd95oeaaf9b7ha5cc Event edit URL: http://www.google.com/calendar/feeds/default/private/full/cmvade9oqrd95oeaaf9b7ha5cc/63324787637 Event HTML URL: http://www.google.com/calendar/event?eid=Y212YWRlOW9xcmQ5NW9lYWFmOWI3aGE1Y2MgZml5YXdlcnhAbQ Updating title of event from:'One-time Tennis with Beth' to:'New title for single event' Adding 30 minute reminder to event Adding extended property to event: 'propname'='propvalue' New recurring event inserted: http://www.google.com/calendar/feeds/default/private/full/dpjp06smht75o466g8s0gfdnro Event edit URL: http://www.google.com/calendar/feeds/default/private/full/dpjp06smht75o466g8s0gfdnro/63324787638 Event HTML URL: http://www.google.com/calendar/event?eid=ZHBqcDA2c21odDc1bzQ2Nmc4czBnZmRucm9fMjAwNzA1MDEgZml5YXdlcnhAbQ Inserting Simple Web Content Event Inserting Web Content Gadget Event Lee McClintock's access control list 0. owner Role: http://schemas.google.com/gCal/2005#owner Scope user - fiyawerx at gmail.com 1. editor Role: http://schemas.google.com/gCal/2005#editor Scope user - poprockpixie at yahoo.com freebusy Role: http://schemas.google.com/gCal/2005#freebusy Scope user - user at gmail.com Creating new calendar with title "Little League Schedule" Updating the calendar titled "Little League Schedule" with the title "New Title" Subscribing to the calendar with ID: c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com Updating the calendar subscription with ID: c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com ------ So it seems it already has samples of anything I'm going to need to do. (Got a message that the mail bounced due to being too learge, cut out the quoted section) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/b00df54d/attachment-0001.htm From Jason.Timms at shawinc.com Fri Sep 7 17:55:16 2007 From: Jason.Timms at shawinc.com (Jason.Timms at shawinc.com) Date: Fri, 7 Sep 2007 11:55:16 -0400 Subject: [Tutor] Jason Timms is out of the office. Message-ID: I will be out of the office starting 09/07/2007 and will not return until 09/09/2007. I will respond to your message when I return. ********************************************************** Privileged and/or confidential information may be contained in this message. If you are not the addressee indicated in this message (or are not responsible for delivery of this message to that person) , you may not copy or deliver this message to anyone. In such case, you should destroy this message and notify the sender by reply e-mail. If you or your employer do not consent to Internet e-mail for messages of this kind, please advise the sender. Shaw Industries does not provide or endorse any opinions, conclusions or other information in this message that do not relate to the official business of the company or its subsidiaries. ********************************************************** From lawrence.barrott at btinternet.com Fri Sep 7 19:00:17 2007 From: lawrence.barrott at btinternet.com (Lawrence Barrott) Date: Fri, 7 Sep 2007 18:00:17 +0100 Subject: [Tutor] (no subject) Message-ID: <73E5623316494C47AAB09AEB6612567F@PC3> using the built in function "open" how do you specify non local files such as the C: drive without copying the program there thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/c6883d85/attachment.htm From alan.gauld at btinternet.com Fri Sep 7 20:13:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 19:13:31 +0100 Subject: [Tutor] (no subject) References: <73E5623316494C47AAB09AEB6612567F@PC3> Message-ID: "Lawrence Barrott" wrote > using the built in function "open" how do you specify non local > files such as the C: drive without copying the program there Just provide the full path to the file. f = open(r"C:\TEMP\somefile.txt") Note the use of raw to avoid problems with the DOS backslash character. Another option is to use forward slashes which python accepts too: f = open("C:/TEMP/somefile.txt") -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From aezell at gmail.com Fri Sep 7 20:28:34 2007 From: aezell at gmail.com (Alex Ezell) Date: Fri, 7 Sep 2007 13:28:34 -0500 Subject: [Tutor] Fun with Cookies Message-ID: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> Hi all, I am trying to create a cookie and send it a long with a request. I searched the archives and found this code from Kent Johnson: import cookielib, urllib2 cj = cookielib.CookieJar() cookie = cookielib.Cookie(...your cookie data here...) cj.set_cookie(cookie) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) data = urllib2.urlopen(...).read() It seemed to solve a problem I was having with SimpleCookie(), but I cannot figure out what I should put where Kent has written "...your cookie data here...". I have tried strings, SimpleCookie instances, etc. and I always get this error on that line: __init__() takes at least 17 arguments (2 given) Thanks for your time. Alex Ezell From kent37 at tds.net Fri Sep 7 20:58:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Sep 2007 14:58:35 -0400 Subject: [Tutor] Fun with Cookies In-Reply-To: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> References: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> Message-ID: <46E19F5B.7090608@tds.net> Alex Ezell wrote: > Hi all, > I am trying to create a cookie and send it a long with a request. > > I searched the archives and found this code from Kent Johnson: > > import cookielib, urllib2 > > cj = cookielib.CookieJar() > cookie = cookielib.Cookie(...your cookie data here...) > cj.set_cookie(cookie) > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > data = urllib2.urlopen(...).read() > > It seemed to solve a problem I was having with SimpleCookie(), but I > cannot figure out what I should put where Kent has written "...your > cookie data here...". I have tried strings, SimpleCookie instances, > etc. and I always get this error on that line: > > __init__() takes at least 17 arguments (2 given) The Cookie constructor is def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109=False, ) You should specify at least name, value, domain and path (all strings). The rest can be None. Kent From aezell at gmail.com Fri Sep 7 21:48:36 2007 From: aezell at gmail.com (Alex Ezell) Date: Fri, 7 Sep 2007 14:48:36 -0500 Subject: [Tutor] Fun with Cookies In-Reply-To: <46E19F5B.7090608@tds.net> References: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> <46E19F5B.7090608@tds.net> Message-ID: <71dd7f400709071248g1d73a72bje41e5c4074b60ea1@mail.gmail.com> Kent, Thanks so much. I will give that a try. Your name is all over these kinds of questions on the web. I guess you fought through it a while back? Here's where I show off my Python newb status. What's the best way to specify those attributes? If I only include the 4 you mention (name, value, domain and path), it seems messy to have a bunch of "None"s in there. Thanks again, Alex On 9/7/07, Kent Johnson wrote: > Alex Ezell wrote: > > Hi all, > > I am trying to create a cookie and send it a long with a request. > > > > I searched the archives and found this code from Kent Johnson: > > > > import cookielib, urllib2 > > > > cj = cookielib.CookieJar() > > cookie = cookielib.Cookie(...your cookie data here...) > > cj.set_cookie(cookie) > > > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > > urllib2.install_opener(opener) > > > > data = urllib2.urlopen(...).read() > > > > It seemed to solve a problem I was having with SimpleCookie(), but I > > cannot figure out what I should put where Kent has written "...your > > cookie data here...". I have tried strings, SimpleCookie instances, > > etc. and I always get this error on that line: > > > > __init__() takes at least 17 arguments (2 given) > > The Cookie constructor is > > def __init__(self, version, name, value, > port, port_specified, > domain, domain_specified, domain_initial_dot, > path, path_specified, > secure, > expires, > discard, > comment, > comment_url, > rest, > rfc2109=False, > ) > > You should specify at least name, value, domain and path (all strings). > The rest can be None. > > Kent > From kent37 at tds.net Fri Sep 7 22:03:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Sep 2007 16:03:00 -0400 Subject: [Tutor] Fun with Cookies In-Reply-To: <71dd7f400709071248g1d73a72bje41e5c4074b60ea1@mail.gmail.com> References: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> <46E19F5B.7090608@tds.net> <71dd7f400709071248g1d73a72bje41e5c4074b60ea1@mail.gmail.com> Message-ID: <46E1AE74.9060109@tds.net> Alex Ezell wrote: > Kent, > Thanks so much. I will give that a try. Your name is all over these > kinds of questions on the web. I guess you fought through it a while > back? I figured it out for part of the Python Challenge :-) http://www.pythonchallenge.com/ Don't know how it got all over the web though...it's not the first time it has come up here... > Here's where I show off my Python newb status. What's the best way to > specify those attributes? If I only include the 4 you mention (name, > value, domain and path), it seems messy to have a bunch of "None"s in > there. You have to include the None's. Kent From ricaraoz at gmail.com Sat Sep 8 02:04:50 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 07 Sep 2007 21:04:50 -0300 Subject: [Tutor] Problem with while loop In-Reply-To: References: Message-ID: <46E1E722.2090702@bigfoot.com> matte wrote: > Hi guys > > Please excuse me but I've been out of Python for a while since my laptop > was stolen... > > I'm battling with a very basic while loop.... > > -------------- 8< ---------------------- > #!/usr/bin/python > > from random import randint > > counter = 0 > > howmany = raw_input( "How many: " ) > > while counter < howmany: > > pin = randint(0000,9999) > print pin > counter += 1 > > -------------- 8< ---------------------- > > For some reason if I use an integer in place of "howmany" it works, but I'd > like it to work as I can logically see it above. > > What am I missing ? > raw_input returns a string. Have to convert it. BTW, instead of the while loop you might try this : for i in xrange(int(howmany)) : print randint(0000, 9999) saves you some code and a few variables. Or if what you want is a list for further processing : randomInts = [randint(0000, 9999) for i in xrange(int(howmany))] From trey at opmstech.org Sat Sep 8 02:47:05 2007 From: trey at opmstech.org (Trey Keown) Date: Fri, 7 Sep 2007 19:47:05 -0500 (CDT) Subject: [Tutor] WxPython Splashscreen? Message-ID: <61555.68.191.136.241.1189212425.squirrel@webmail.opmstech.org> Hey all, Does anyone know how to make a wxPython splashscreen? It would be great if you could show a (working) example, as I have googled this topic, yet have not found any working examples. Thanks. From cspears2002 at yahoo.com Sat Sep 8 07:24:40 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 7 Sep 2007 22:24:40 -0700 (PDT) Subject: [Tutor] rewriting script Message-ID: <877291.75369.qm@web51610.mail.re2.yahoo.com> I have written a script that reads and displays text files: #!/usr/bin/env python 'readTextFile.py -- read and display text file' import os # get filename while True: fname = raw_input('Enter file name: ') print if os.path.exists(fname): fobj = open(fname, 'r') for eachLine in fobj: print eachLine, fobj.close() else: print"*** File doesn't exist" break However, whenever I run the script, I get this result: io at io-station-1 ./chap3 314> python readTextFile1.py Enter file name: datefile Fri Sep 7 22:13:03 PDT 2007 Traceback (most recent call last): File "readTextFile1.py", line 13, in ? for eachLine in fobj: ValueError: I/O operation on closed file The original script appeared in 'Core Python Programming' in this form: #!/usr/bin/env python 'readTextFile.py -- read and display text file' # get filename fname = raw_input('Enter file name: ') print # attempt to open file for reading try: fobj = open(fname, 'r') except IOError, e: print"*** file open error:", e else: # display contents to the screen for eachLine in fobj: print eachLine, fobj.close() I modified the script as an answer to one of the end of chapter questions. Basically, I am supposed to rewrite the script, so that runs with 'try' and 'except'. What is causing the error message? I thought the file was opened earlier in the script. From silas428 at gmail.com Sat Sep 8 07:27:33 2007 From: silas428 at gmail.com (Ryan) Date: Fri, 07 Sep 2007 22:27:33 -0700 Subject: [Tutor] Python scripting Message-ID: <46E232C5.2050302@gmail.com> I am on a linux machine and I was wondering about python scripting. Mainly to get it up and running but also what can I do with it etc. Any help would be appreciated, Thnx From cspears2002 at yahoo.com Sat Sep 8 07:43:22 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 7 Sep 2007 22:43:22 -0700 (PDT) Subject: [Tutor] replacing while loop Message-ID: <28664.62638.qm@web51608.mail.re2.yahoo.com> I've been reading 'Core Python Programming (2nd Edition)'. I have been given the following script: #!/usr/bin/env python 'makeTextFile.py -- create text file' import os # get filename while True: fname = raw_input('Enter file name: ') if os.path.exists(fname): print"*** ERROR: '%s' already exists" % fname else: break # get file content (text) lines all = [] print "\nEnter lines ('.' by itself to quit).\n" # loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry) # write lines to file with NEWLINE line terminator fobj = open(fname, 'w') fobj.write('\n'.join(all)) fobj.close() print 'DONE!' I have been asked to replace this while loop with a try and except clause: while True: fname = raw_input('Enter file name: ') if os.path.exists(fname): print"*** ERROR: '%s' already exists" % fname else: break I'm not sure how to do this. I looked at the back of the book, and I don't see an exception that is raised when a previously existing file is found. Any hints? From steve at alchemy.com Sat Sep 8 07:51:32 2007 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 07 Sep 2007 22:51:32 -0700 Subject: [Tutor] rewriting script In-Reply-To: <877291.75369.qm@web51610.mail.re2.yahoo.com> References: <877291.75369.qm@web51610.mail.re2.yahoo.com> Message-ID: <46E23864.5080501@alchemy.com> Christopher Spears wrote: > I have written a script that reads and displays text > files: > > #!/usr/bin/env python > > 'readTextFile.py -- read and display text file' > > import os > > # get filename > while True: > fname = raw_input('Enter file name: ') > print > if os.path.exists(fname): > fobj = open(fname, 'r') > for eachLine in fobj: > print eachLine, > fobj.close() You're closing the file after reading the first line. You want that fobj.close() line to be outside the for loop (outdent one level) From trey at opmstech.org Sat Sep 8 07:52:42 2007 From: trey at opmstech.org (Trey Keown) Date: Sat, 8 Sep 2007 00:52:42 -0500 (CDT) Subject: [Tutor] Undo/Redo in wxpython? Message-ID: <62340.68.191.136.241.1189230762.squirrel@webmail.opmstech.org> What is the proper way to undo/redo changes in a text box? I read somewhere that the default undo depth is 1. How could I change this to, say, about 35? Here's a snippet of my code- #!/usr/bin/python import wx import os ... ... ... class MainWin(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(850, 450)) ... ... ... #Program body section start self.code = wx.TextCtrl(self, ID_TEXTBOX, size=(200, 130), style=wx.TE_MULTILINE) ... ... ... app = MyApp(redirect=True, filename = "_error.log") app.MainLoop() Now, how would it be possible for me to do undo/redo for the "self.code" TextCtrl widget? Help is greatly appreciated. From alan.gauld at btinternet.com Sat Sep 8 09:19:47 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:19:47 +0100 Subject: [Tutor] rewriting script References: <877291.75369.qm@web51610.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote >I have written a script that reads and displays text > files: > while True: > if os.path.exists(fname): > fobj = open(fname, 'r') > for eachLine in fobj: > print eachLine, > fobj.close() > However, whenever I run the script, I get this result: > for eachLine in fobj: > ValueError: I/O operation on closed file You are closing the file inside the for loop, before you finish processing it. That is one reason why iterating over the file like this is often more helpful: for line in open(fname): print line because that will automatically close the file after you are done iterating. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Sep 8 09:24:38 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:24:38 +0100 Subject: [Tutor] Python scripting References: <46E232C5.2050302@gmail.com> Message-ID: "Ryan" wrote >I am on a linux machine and I was wondering about python scripting. Python is usually installed on linux. Just type python at a shell prompt. > Mainly to get it up and running but also what can I do with > it etc. Any help would be appreciated, Thnx Python is probably installed or you can use your distros installer to get a package, eg rpm for it. So installation should be easy. Don't forget to get the documentation too, sometimes its a separate download on Linux. What you can do? It can replace a lot of shjell scripting for administrative tasks. It can create small tools, analyze text, or even create fiull blown applications.It depends on how skillful you become and how much time you have. Take a look on sourceforge for Python based projects. That should give you an idea of the potential. And visit the beginners pages of the Python web site for more info about Python and tutorial links to get you started. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Sep 8 09:31:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:31:42 +0100 Subject: [Tutor] replacing while loop References: <28664.62638.qm@web51608.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote > I have been asked to replace this while loop with a > try and except clause: > > while True: > fname = raw_input('Enter file name: ') > if os.path.exists(fname): > print"*** ERROR: '%s' already exists" % fname > else: > break > > I'm not sure how to do this. I looked at the back of > the book, and I don't see an exception that is raised > when a previously existing file is found. Any hints? The loop simply detects if the file exists *or not* If the file does not exist you exit the loop. Can you find a way using try/except to detect if the file does not exist? That will replace the body of the while loop, I can't think of any way to replace the loop itself with try./except... And I agree this is not an obvious place to use try/except. Your earlier example is more typical. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Sep 8 09:38:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:38:08 +0100 Subject: [Tutor] WxPython Splashscreen? References: <61555.68.191.136.241.1189212425.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > Does anyone know how to make a wxPython splashscreen? Using the wxSplashScreen widget? > not found any working examples. The wxPython book offers this: class SketchApp(wx.App): def OnInit(self): image = wx.image('splash.bmp', wx.BITMAP_TYPE_BMP) bmp = image.ConvertToBitmap() wx.SpashScreen(bmp,wx.SPLASH_NO_CENTER|wx.SPLAS_TIMEOUT,1000,None,-1) wx.Yield() frame = SketchFrame(None) etc... The book is invaluable for wxPython users. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Sep 8 09:50:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:50:40 +0100 Subject: [Tutor] Undo/Redo in wxpython? References: <62340.68.191.136.241.1189230762.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > What is the proper way to undo/redo changes in a text box? I read > somewhere that the default undo depth is 1. How could I change this > to, > say, about 35? I dunno, its not in the book ;-) But just typing dir(TextCtrl) showed those two methods... Unfortunately there is no real help() info just tat they take *args and **kwargs... And trying it at the >>> prompt yields t.Redo(35) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\wx-2.8-msw-ansi\wx\_controls.py", line 1888, in Redo return _controls_.TextCtrl_Redo(*args, **kwargs) TypeError: TextCtrl_Redo() takes exactly one argument (2 given) So now you know where the code is and can go take a peek... Or it might be one for the wxPython mailing list? Alan G. From paul at alanweberassociates.com Sat Sep 8 11:31:38 2007 From: paul at alanweberassociates.com (Paul McGuire) Date: Sat, 8 Sep 2007 04:31:38 -0500 Subject: [Tutor] More class questions Message-ID: <008801c7f1fb$0ee432b0$6500a8c0@AWA2> Ara - I found your question about the Pyparsing-based adventure game that I wrote. You can find more info on this from the presentation I made at PyCon'06, (http://www.python.org/pycon/2006/papers/4/). This link opens up at the title page, there are navigation controls in the lower right corner of the screen if you move your mouse over them. This program uses the following classes: - Room - Item - Player - Command The Room and Item instances are created during the game setup. Each Room contains pointers to neighboring rooms to the north, south, east, and west. Rooms also have a list of items that are currently in the room. As the game ensues, items can be picked up and dropped, so this list will change over time. I guess you could change the room connections also - wouldn't be hard - perhaps as a result of using a special Item while in the Room. Items are fairly passive, free-standing objects, containing some attributes, and a possible useAction. They don't have much behavior, they don't know what room they are in, they can be picked up, dropped, and used, and they have a name that describes them when you look in a room, or list your player's inventory. Player is the "status" object of the game. Player has an inventory of Items, and has a reference to the Room the player is currently in. I think an easy mistake when writing a game is to make the Player status and attributes global variables. This will work okay, but by keeping this info in an object, the game could easily extend to having multiple players, just by adding a second instance, and adding support for the players to take turns giving commands. Command is the class that actually makes things happen. Command itself is an "abstract" class, that defines the basic form of what different commands can do, and how they are created. There are several subclasses of Command: - TakeCommand - DropCommand - InventoryCommand - UseCommand - LookCommand - DoorsCommand - MoveCommand - HelpCommand - QuitCommand Commands are created based on the input that the game player types in at the game prompt (this is where pyparsing comes in). The pyparsing grammar parses the input string, and if it is a valid command, the grammar's parse actions create the appropriate Command subclass. For instance, typing in "help" will create a HelpCommand instance. Typing in "take shovel" will create a TakeCommand, with the target object of "shovel". After the Command is created, it is executed against the Player object. The results of the Command can: - have the Player take something from the current Room - have the Player drop something in his inventory, and leave it in the current Room - list the Player's inventory - etc. The MoveCommand will move the player to an adjoining room. To tie it all together, the game engine runs in a basic loop: # create a player, let's call him Bob player = Player("Bob") # give Bob the sword for protection player.take( Item.items["sword"] ) # read commands, and then invoke them on Bob (and his surroundings) while not player.gameOver: cmdstr = raw_input(">> ") cmd = parser.parseCmd(cmdstr) if cmd is not None: cmd.command( player ) And that's it. All of the logic about the moving from room to room is captured in the N,S,E,W references between Room objects. Moving Bob from room to room is done by MoveCommands, as they are dynamically created based on user input. I hope that gives you a little more idea of how the pyparsing adventure game works. -- Paul From ca17005 at bellsouth.net Sun Sep 9 04:43:48 2007 From: ca17005 at bellsouth.net (ca17005 at bellsouth.net) Date: Sat, 8 Sep 2007 22:43:48 -0400 Subject: [Tutor] inserting csv file into a sqlite3 memory connected table Message-ID: <20070909024355.6F4221E400D@bag.python.org> I am just getting started been though some tutorials for python and wx. I am basically just a visual basic person trying to learn python. Anyway I have spent hours experimenting with CSV and sqllite3 tutorial samples and misc snippets, Does anyone have any code samples that might get me going? From silas428 at gmail.com Sun Sep 9 21:26:56 2007 From: silas428 at gmail.com (Ryan) Date: Sun, 09 Sep 2007 12:26:56 -0700 Subject: [Tutor] Apache, CGI-BIN, Python Message-ID: <46E44900.6050003@gmail.com> I am running a Linux box and cannot find my Apache cgi-bin to put some python scripts in. I know I probably have to create one but don't know where and how. Also on my windows machine,where I do have the bin, and normally everything works fine except: #!c:/Python25/python import cgi reshtml = """Content-type: text/html\n\n" Hello Python

Welcome To A Python Script!

""" form = cgi.FieldStorage() #This is where everything goes wrong #I get error messages for either the lastname line or firstname lastname = form['lastname'].value firstname =form['firstname'].value message = firstname + " " + lastname print reshtml % message From steve at alchemy.com Mon Sep 10 00:02:19 2007 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 09 Sep 2007 15:02:19 -0700 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: <46E44900.6050003@gmail.com> References: <46E44900.6050003@gmail.com> Message-ID: <46E46D6B.6030007@alchemy.com> Ryan wrote: > I am running a Linux box and cannot find my Apache cgi-bin to put some > python scripts in. I know I probably have to create one but don't know > where and how. On Linux under Apache 2.2, I've seen it in /usr/lib/cgi-bin which always struck me as weird, but there you go. On BSD, it tends to live in /var/www/cgi-bin. YMMV. > > Also on my windows machine,where I do have the bin, and normally > everything works fine except: > > #!c:/Python25/python > import cgi > > reshtml = """Content-type: text/html\n\n" > > Hello Python > > >

Welcome To A Python Script!

> > """ > > form = cgi.FieldStorage() > > #This is where everything goes wrong > #I get error messages for either the lastname line or firstname > > lastname = form['lastname'].value > firstname =form['firstname'].value What error message do you get? I'd recommend, actually, using form.getfirst('lastname') instead. It's more robust in case there are multiple occurrences of a field on the form the user submits. You can also check to see if the form even has the fields you're trying to read, but again, knowing what error message you're getting would be very helpful to point you in the right direction on this. > message = firstname + " " + lastname > print reshtml % message I think you need a %s or something in the reshtml string, too. From spmcinerney at hotmail.com Mon Sep 10 02:31:19 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Sun, 09 Sep 2007 17:31:19 -0700 Subject: [Tutor] Suggested books for Agile Programming & Testing? Message-ID: Can anyone recommend me the best single must-read book for Agile Programming? Also Agile Testing. (If they compare Agile in general to the other methodologies, that would be great) Also, can anyone comment on the limits or caveats of agile development? Thanks, Stephen _________________________________________________________________ Kick back and relax with hot games and cool activities at the Messenger Caf?. http://www.cafemessenger.com?ocid=TXT_TAGHM_SeptHMtagline1 From lists at mostrom.pp.se Mon Sep 10 10:00:26 2007 From: lists at mostrom.pp.se (=?UTF-8?Q?Jan_Erik_Mostr=C3=B6?= =?UTF-8?Q?m?=) Date: Mon, 10 Sep 2007 10:00:26 +0200 Subject: [Tutor] Apache, CGI-BIN, Python Message-ID: Ryan 07-09-09 12:26 >I am running a Linux box and cannot find my Apache cgi-bin to >put some python scripts in. I know I probably have to create >one but don't know where and how. Look in Apaches config file, you should find something like this ScriptAlias /cgi-bin/ "/Library/WebServer/CGI-Executables/" this is from my Mac, on my debian machine it looks like this ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ And you can of course have different catalogs for different virtual domains jem -- Jan Erik Mostr?m, www.mostrom.pp.se From vishnu at montalvosystems.com Mon Sep 10 12:40:46 2007 From: vishnu at montalvosystems.com (Vishnu Mohan) Date: Mon, 10 Sep 2007 16:10:46 +0530 Subject: [Tutor] Problem with while loop In-Reply-To: References: Message-ID: <46E51F2E.2070602@montalvosystems.com> > Now I just need to figure out how to only get 4 digit pin numbers :) > Use regular expressions.... The following is the code with re. from random import randint import re counter = 0 pinPattern = re.compile(r'^\d{4}$') howmany = raw_input( "How many: " ) if pinPattern.match(howmany): while counter < int(howmany): pin = randint(0000,9999) print pin counter += 1 else: print "%s is not valid 4 digit integer"%howmany -vishnuMohan From connorsml at gmail.com Mon Sep 10 13:28:47 2007 From: connorsml at gmail.com (Michael Connors) Date: Mon, 10 Sep 2007 12:28:47 +0100 Subject: [Tutor] Problem with while loop In-Reply-To: <46E51F2E.2070602@montalvosystems.com> References: <46E51F2E.2070602@montalvosystems.com> Message-ID: Hi, I would do it as follows, adding 0s to front to make them valid PINs. while counter < howmany: pin = randint(0000,9999) print "%04i" % (pin) counter += 1 On 10/09/2007, Vishnu Mohan wrote: > > > > Now I just need to figure out how to only get 4 digit pin numbers :) > > > Use regular expressions.... > The following is the code with re. > > > from random import randint > import re > > counter = 0 > pinPattern = re.compile(r'^\d{4}$') > howmany = raw_input( "How many: " ) > if pinPattern.match(howmany): > while counter < int(howmany): > pin = randint(0000,9999) > print pin > counter += 1 > else: > print "%s is not valid 4 digit integer"%howmany > > > -vishnuMohan > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/d71b35db/attachment.htm From pilyad at gmail.com Mon Sep 10 12:51:16 2007 From: pilyad at gmail.com (Arvind Deshpande) Date: Mon, 10 Sep 2007 16:21:16 +0530 Subject: [Tutor] replacing while loop In-Reply-To: References: <28664.62638.qm@web51608.mail.re2.yahoo.com> Message-ID: <5d2af29a0709100351x7bbde0f4q8f7b83a2229e4f56@mail.gmail.com> Is this what you are looking for? #!/usr/bin/python 'makeTextFile.py -- create text file' import os # get filename #while True: # fname = raw_input('Enter file name: ') # if os.path.exists(fname): # print"*** ERROR: '%s' already exists" % fname # else: # break while True: fname = raw_input('Enter file name: ') try: fobj = open(fname, 'r') except: break # get file content (text) lines all = [] print "\nEnter lines ('.' by itself to quit).\n" # loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry) # write lines to file with NEWLINE line terminator fobj = open(fname, 'w') fobj.write('\n'.join(all)) fobj.close() print 'DONE!' -- Arvind Deshpande On 9/8/07, Alan Gauld wrote: > > "Christopher Spears" wrote > > > I have been asked to replace this while loop with a > > try and except clause: > > > > while True: > > fname = raw_input('Enter file name: ') > > if os.path.exists(fname): > > print"*** ERROR: '%s' already exists" % fname > > else: > > break > > > > I'm not sure how to do this. I looked at the back of > > the book, and I don't see an exception that is raised > > when a previously existing file is found. Any hints? > > The loop simply detects if the file exists *or not* > If the file does not exist you exit the loop. > Can you find a way using try/except to detect > if the file does not exist? > > That will replace the body of the while loop, > I can't think of any way to replace the loop itself > with try./except... > > And I agree this is not an obvious place to use > try/except. Your earlier example is more typical. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/517b0b39/attachment-0001.htm From sacharook at hotmail.co.uk Mon Sep 10 13:29:24 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Mon, 10 Sep 2007 12:29:24 +0100 Subject: [Tutor] Livewires Message-ID: Hi all just learning python really and been using the livewires tutorial / worksheets to get some experience. I have hit an issue which is just my lack of understanding around looping concepts and execution. My issue: in worksheet 5-robots.pdf attached, page 4 the challenge "Challenge: Write a loop that makes the circle move smoothly from (0,0) to (640,480): in other words, from the bottom leftto the top right of the screen." this has got me a bit stumped because its an (x,y) co-ordinate pair that I want to update. I think in a loop i need to draw a circle, move a circle, remove the circle. I thought I needed to for loops to iterate through two ranges but this is wrong, here is my code though! from livewires import *begin_graphics() allow_moveables()x=range(10,640,10)y=range(10,480,10) for xco in x: for yco in y: c = circle(xco,yco,5) move_to(c, xco,yco)# remove_from_screen(c) /*commented this out to see output on graphics window */end_graphics() Can anyone look at the worksheet challenge and my poor code and show me the error of my ways? :) I appreciate it may be my inexperience in program flow/logic which is the problem also, I don't my help or suggestion to improve in any area. Thanks for your help in advance Sacha _________________________________________________________________ The next generation of MSN Hotmail has arrived - Windows Live Hotmail http://www.newhotmail.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/9f0f42b4/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: 5-robots.pdf Type: application/pdf Size: 89940 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070910/9f0f42b4/attachment-0001.pdf From Dean.Gardner at barco.com Mon Sep 10 14:55:39 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Mon, 10 Sep 2007 14:55:39 +0200 Subject: [Tutor] Printing HTML files Message-ID: Hi I am currently trying to print out a html file that is essentially a summary table and I am running into problems. From the link below it seems that the method I am using to print the table doesn't handle column width and wrapping but confusingly we use a similar method elsewhere in the code and it works fine. This is the summary builder class TestingSummary: def __init__(self,records): self.records = records def splitRecordAndBuildSummaryText(self): summary_dict={} test_fields=[] keys=[] fields = ["TestedDate:","TestId:","Branch:","Version:","SpecId:","PassOrFail:"] records = self.records.split("\n\n") for record in records: record=record.split("\n") for item in record: if "TestId" in item: testid=record.pop(1) testid = testid.replace("TestId:","") for field in record: for item in fields: #print item field = field.replace(item,"") test_fields.append(field) summary_dict[testid]=test_fields test_fields = [] # print summary_dict summary = self.buildHtmlSummaryPage(summary_dict) return summary def buildHtmlSummaryPage(self,dict_of_summary): #print list_of_ids test_summary_details="" for key, value in dict_of_summary.items(): #print value #print details test_summary_details+="""%s%s%s%s\n""" % (key,value[3],value[-1],"".join(value[1]+value[2])) summary = "".join(["""\n""", """\n""", """\n""", """\n""", """\n""", """\n""", """\n""", """\n"""]) summary+=test_summary_details summary+="" return summary and the mechanism for printing def printSummary(self,summary): print_dialog = wx.PrintDialog(self) if print_dialog.ShowModal() == wx.ID_CANCEL: return print_dialog_data = print_dialog.GetPrintDialogData() printer = wx.Printer(print_dialog_data) printout = wx.html.HtmlPrintout("Printing Test Summary") # margins (top, bottom, left, right) printout.SetMargins(15, 15, 20, 20) #REMOVE #-----This was for testing purposes only htmlOutput = open("TestingSummary.html","w") htmlOutput.write(summary) htmlOutput.close() #------------------------------------------------- printout.SetHtmlText(summary) printout.SetFooter(self.HtmlFooterForPrint(1, 1)) printer.Print(self, printout, False) When I save the file as html the browser will open it fine and it is I expect but if I print it I end up with Testing Summary Tested by: Machine Name: TestIDSpecificationResultBuildID 000003 -0000-0009 Pass 0000 1111 000002 Specification-0000-0009 Pass 0000 1111 000001 Specification-0000-0009 Pass 0000 1111 http://archives.devshed.com/forums/python-122/printing-problem-1843805.h tml Am I doing something silly? Thanks Dean Gardner DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/e445bd08/attachment-0001.htm From christopher.henk at allisontransmission.com Mon Sep 10 15:33:39 2007 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Mon, 10 Sep 2007 09:33:39 -0400 Subject: [Tutor] Livewires In-Reply-To: Message-ID: tutor-bounces at python.org wrote on 09/10/2007 07:29:24 AM: > Hi all > > just learning python really and been using the livewires tutorial / worksheets to get some experience. > > I have hit an issue which is just my lack of understanding around looping concepts and execution. > > My issue: > > in worksheet 5-robots.pdf attached, page 4 the challenge > > "Challenge: Write a loop that makes the circle move smoothly from (0,0) to (640,480): in other words, from the bottom left > to the top right of the screen." > > this has got me a bit stumped because its an (x,y) co-ordinate pair that I want to update. > I think in a loop i need to draw a circle, move a circle, remove the circle. > > I thought I needed to for loops to iterate through two ranges but this is wrong, here is my code though! > > from livewires import * > begin_graphics() > > allow_moveables() > x=range(10,640,10) > y=range(10,480,10) > for xco in x: > for yco in y: > c = circle(xco,yco,5) > move_to(c, xco,yco) > # remove_from_screen(c) /*commented this out to see output on graphics window */ > end_graphics() > If I understand the requirements correctly: you are moving along the diagonal of the map. So say 100 time steps to move the distance. time step: 0 position: (0,0) time step: 1 position: (64,48) time step: 2 position: (128,96) ... so the new x and y move together with a different delta so that they reach their max at the same time. Your only loop would be what time step you are on. timesteps=100 x,y =0,0 deltax=640/timesteps deltay=480/timesteps for time in range (timesteps): c=circle(x,y,5) x+=deltax y+=deltay move_to(c,x,y) remove_from_screen(c) I would think that would do the trick. But I haven't had any coffee yet this morning, so if I missed something, let me know. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/d2da35b1/attachment.htm From tmikk at umn.edu Mon Sep 10 17:33:47 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Mon, 10 Sep 2007 10:33:47 -0500 Subject: [Tutor] Livewires In-Reply-To: References: Message-ID: <46E563DA.4090106@umn.edu> Hi Sacha, I am very much a beginner to Python myself, but I tried my hand on the Livewires modules. Here is how I solved the challenge. from livewires import * begin_graphics() allow_moveables() x=0 y=0 c = circle(x, y,5) while x < 640: x=x+5 y=y+3.822 move_to (c, x, y) time.sleep(0.1) Tonu sacha rook wrote: > Hi all > > just learning python really and been using the livewires tutorial / > worksheets to get some experience. > > I have hit an issue which is just my lack of understanding around > looping concepts and execution. > > My issue: > > in worksheet 5-robots.pdf attached, page 4 the challenge > > "Challenge: Write a loop that makes the circle move smoothly from > (0,0) to (640,480): in other words, from the bottom left > to the top right of the screen." > > this has got me a bit stumped because its an (x,y) co-ordinate pair > that I want to update. > I think in a loop i need to draw a circle, move a circle, remove the > circle. > > I thought I needed to for loops to iterate through two ranges but this > is wrong, here is my code though! > > from livewires import * > begin_graphics() > > allow_moveables() > x=range(10,640,10) > y=range(10,480,10) > for xco in x: > for yco in y: > c = circle(xco,yco,5) > move_to(c, xco,yco) > # remove_from_screen(c) /*commented this out to see output on > graphics window */ > end_graphics() > > Can anyone look at the worksheet challenge and my poor code and show > me the error of my ways? :) > I appreciate it may be my inexperience in program flow/logic which is > the problem also, I don't my help or suggestion to improve in any area. > Thanks for your help in advance > Sacha > > > > ------------------------------------------------------------------------ > Play Movie Mash-up and win BIG prizes! > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From lawrence.barrott at btinternet.com Mon Sep 10 22:02:46 2007 From: lawrence.barrott at btinternet.com (Lawrence Barrott) Date: Mon, 10 Sep 2007 21:02:46 +0100 Subject: [Tutor] Running other files Message-ID: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> is it possible to run other non-python files using python such as .exe or other files. Thanks, Lawrence -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/970b09af/attachment.htm From rikard.bosnjakovic at gmail.com Mon Sep 10 23:24:52 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Mon, 10 Sep 2007 23:24:52 +0200 Subject: [Tutor] Running other files In-Reply-To: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> References: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> Message-ID: On 10/09/2007, Lawrence Barrott wrote: > is it possible to run other non-python files using python such as .exe or > other files. Have a look at os.system(). -- - Rikard - http://bos.hack.org/cv/ From dos.fool at gmail.com Tue Sep 11 00:28:23 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 16:28:23 -0600 Subject: [Tutor] making math problems mmmm fun Message-ID: <1C99EFF7-A12C-4DEF-8595-B42DA3E3F103@gmail.com> hello all this is a homework in math i dont need to program it but i would like to :) so like any other time pleas dont just give a answer tutorials or a explanation. i dont like to use script something i dont understand :) thanks basically the problem is to find a bunch of ways to put 1,2,3,4,5 into different math problems to that equal 1-25, i haven't spent to much time thinking about how to do this but i cant think of a way to do it it without writing making the program rather long here is the page from the book for the rules i will be working on this for the next week or so thanks for any help :) . you may use any of the four basic arithmetic operations- addition, subtraction, multiplication, and division (according to the order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 expression for the number 1. . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression for the number 3 . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is a 1234 expression for 6 . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a 1234 expression for the number 26 . you may juxtapose two or more digits (that is put them next to each other) to form a number such as 12. for example 43-12 is a 1234 expression for 31 . you may use parentheses and brackets to change the meaning of a expression for example according to the rules of order of operations 1 +4x3? is a 1234 expression for 37. you can add parentheses and brackets to get [(1+4)x3]? which is a 1234 expression for 225 . must use 1,2,3,4 exactly once thanks for the help ill post if i find anything From dos.fool at gmail.com Tue Sep 11 00:22:06 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 16:22:06 -0600 Subject: [Tutor] making math problems mmmm fun Message-ID: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> hello all this is a homework in math i dont need to program it but i would like to :) so like any other time pleas dont just give a answer tutorials or a explanation. i dont like to use script something i dont understand :) thanks basically the problem is to find a bunch of ways to put 1,2,3,4,5 into different math problems to that equal 1-25, i haven't spent to much time thinking about how to do this but i cant think of a way to do it it without writing making the program rather long here is the page from the book for the rules i will be working on this for the next week or so thanks for any help :) . you may use any of the four basic arithmetic operations- addition, subtraction, multiplication, and division (according to the order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 expression for the number 1. . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression for the number 3 . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is a 1234 expression for 6 . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a 1234 expression for the number 26 . you may juxtapose two or more digits (that is put them next to each other) to form a number such as 12. for example 43-12 is a 1234 expression for 31 . you may use parentheses and brackets to change the meaning of a expression for example according to the rules of order of operations 1 +4x3? is a 1234 expression for 37. you can add parentheses and brackets to get [(1+4)x3]? which is a 1234 expression for 225 . must use 1,2,3,4 exactly once thanks for the help ill post if i find anything From abooth at stanford.edu Tue Sep 11 00:40:49 2007 From: abooth at stanford.edu (Ashley Booth) Date: Mon, 10 Sep 2007 15:40:49 -0700 Subject: [Tutor] Making a python script to feed files into another python script Message-ID: I am trying to create a script that will get files from a directory that the user specifies, then feeds the relevant input and output (which are input and output paths) into another python script whose path is also given by the user. I'm pretty lazy after all and I would rather spend my time making tools than doing the busy-work myself. So far I can get it to read the directory fine but it ends up just opening the script I want the files to be fed into instead of giving it the input and output to run and running it. Any ideas? Here is what I have so far: import sys, os indir = raw_input('input directory path ') # input directory script1 = os.system(raw_input('python script path ')) for j in os.listdir(indir): input = os.path.join(indir,j) output = os.path.join(indir,j.split('rovctd')[0]+'.txt') script1(input,output) If this is going to be too complicated, I would at least be happy with how to tack on the list directory stuff to then of the script1- it would not be a stand alone script but at least it would work. I tired to do that too but it only processed the first file in the directory instead of all of them. Thanks! From john at fouhy.net Tue Sep 11 01:11:00 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Sep 2007 11:11:00 +1200 Subject: [Tutor] Making a python script to feed files into another python script In-Reply-To: References: Message-ID: <5e58f2e40709101611q3898b627r73f5f260c38e21b2@mail.gmail.com> On 11/09/2007, Ashley Booth wrote: > I am trying to create a script that will get files from a directory > that the user specifies, then feeds the relevant input and output > (which are input and output paths) into another python script whose > path is also given by the user. I'm pretty lazy after all and I would > rather spend my time making tools than doing the busy-work myself. Hi Ashley, You've basically got two options: 1. You can build a command line and then use os.system to call it: script2 = raw_input('python script path:') input, output = # whatever os.system('python %s %s %s' % (script2, input, output)) 2. You can import your second script and call its main function directly. How well this works will depend on the structure of the second script. -- John. From wormwood_3 at yahoo.com Tue Sep 11 03:12:07 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 10 Sep 2007 18:12:07 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <841606.52273.qm@web32408.mail.mud.yahoo.com> Have not gotten any responses on this, nor very much by way of searching, which is strange and a little disappointing for such a seemingly basic thing. (May just be too obvious of a thing, so no one wanted to post the solution:-). ) But, I did find a decent recipe on ASPN that serves the purpose, so I will share in case others needed to do the same check as I did. Before I needed to make the network call in my program, I have the following: if checkURL('http://www.google.com/'): networkup = True else: networkup = False if networkup: print "Internet connection seems to be up." else: print "Internet connection seems to be down. Please check it", print "and retry." sys.exit() Then I continue with my network calls. The function I use is: def checkURL(url): """For checking internet connection. Taken from recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/101276""" try: p = urlparse(url) h = HTTP(p[1]) h.putrequest('HEAD', p[2]) h.endheaders() if h.getreply()[0] == 200: return 1 else: return 0 except: return 0 The nice thing about this check is that is just looks at the head of the site, and so is rather fast. One other consideration: While it is a rare day indeed that Google.com is ever down, to be even safer, would could check against several reliable sites, such as Amazon, Yahoo, w3c.org, etc. The status of each check could be put in a list, and if any list item was networkup, then the internet connection may be considered up. Hope someone finds this useful. -Sam _______________________ ----- Original Message ---- From: wormwood_3 To: Python Tutorlist Sent: Thursday, September 6, 2007 4:46:08 PM Subject: Re: [Tutor] Socket Timeout Handling Since no one bit on this yet, let me simplify to the core issue I am having: What is the best practice for checking for network connectivity errors when making network calls? Is it better to wrap the functions that make said calls in threads and time them? Or to use timeout variables for modules like socket? Something else? I found some good general info here: http://www.onlamp.com/pub/a/python/2003/11/06/python_nio.html But I have had a hard time finding info on network error handling specifically. Thoughts? ______________________________________ ----- Original Message ---- From: wormwood_3 To: Python Tutorlist Sent: Thursday, September 6, 2007 9:40:21 AM Subject: [Tutor] Socket Timeout Handling I am trying to figure out the optimal way to make socket connections (INET) and check for timeouts. The socket module has settimeout(timeout) and setdefaulttimeout(timeout). However, so far as I can tell, these apply to socket objects. The type of socket connection I want to make is getfqdn(address). So I can set the default timeout for socket, but not a socket object (makes sense so far). I cannot use the getfqdn(address) method on a socket object, I have to use it on socket. This means (as I understand it thus far), that while I can set a timeout value for socket objects, this will not apply to when I use the getfqdn() method, which is where I need a timeout check! Some example code for the steps so far: >>> import socket >>> conn = socket.socket() >>> conn.setdefaulttimeout(2.0) Traceback (most recent call last): File "", line 1, in AttributeError: '_socketobject' object has no attribute 'setdefaulttimeout' >>> socket.setdefaulttimeout(2.0) >>> conn.getfqdn("64.33.212.2") Traceback (most recent call last): File "", line 1, in AttributeError: '_socketobject' object has no attribute 'getfqdn' >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' >>> # Disconnected network connection here ... >>> socket.getfqdn("64.33.212.2") '64.33.212.2' >>> # Reconnected network connection here >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' After I disconnected my network connection and called getfqdn(), it returned the IP address I called it with after about 25 seconds. So the default timeout was ignored? Is there some other way to call this function so that I can check for timeouts? Should I instead just put my network calls in a thread and see how long they take, stopping them after a certain period? Thanks for any help. -Sam _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From wormwood_3 at yahoo.com Tue Sep 11 03:16:04 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 10 Sep 2007 18:16:04 -0700 (PDT) Subject: [Tutor] making math problems mmmm fun Message-ID: <824735.66478.qm@web32401.mail.mud.yahoo.com> Don't have any ideas to Pythonize this problem for you, but I must say that I hope this problem was listed in a chapter entitled "Cruel and Unusual"! -Sam ____________________________________ ----- Original Message ---- From: max baseman To: tutor at python.org Sent: Monday, September 10, 2007 6:28:23 PM Subject: [Tutor] making math problems mmmm fun hello all this is a homework in math i dont need to program it but i would like to :) so like any other time pleas dont just give a answer tutorials or a explanation. i dont like to use script something i dont understand :) thanks basically the problem is to find a bunch of ways to put 1,2,3,4,5 into different math problems to that equal 1-25, i haven't spent to much time thinking about how to do this but i cant think of a way to do it it without writing making the program rather long here is the page from the book for the rules i will be working on this for the next week or so thanks for any help :) . you may use any of the four basic arithmetic operations- addition, subtraction, multiplication, and division (according to the order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 expression for the number 1. . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression for the number 3 . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is a 1234 expression for 6 . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a 1234 expression for the number 26 . you may juxtapose two or more digits (that is put them next to each other) to form a number such as 12. for example 43-12 is a 1234 expression for 31 . you may use parentheses and brackets to change the meaning of a expression for example according to the rules of order of operations 1 +4x3? is a 1234 expression for 37. you can add parentheses and brackets to get [(1+4)x3]? which is a 1234 expression for 225 . must use 1,2,3,4 exactly once thanks for the help ill post if i find anything _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From wormwood_3 at yahoo.com Tue Sep 11 03:20:53 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 10 Sep 2007 18:20:53 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <15059.1222.qm@web32403.mail.mud.yahoo.com> I have thought up a project for myself that is rather beyond my current knowledge, but I think it will be fun and very informative. I'll leave out the details right now, but the task that will be the hardest is that I need some way to analyze an image for color patterns. I would like to be able to load an image file of some format, and be able to determine what color the pixels are, in short. From this, I need to generate statistics, such as what color is most common, find patterns in the image, etc. If anyone knows ANYTHING about this sort of analysis in Python, or even any helpful tutorials on image analysis that are more general, I would greatly appreciate it. My only lead right now is PIL, and I am not sure if it will meet my needs. Thanks, Sam From dos.fool at gmail.com Tue Sep 11 04:40:26 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 20:40:26 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <824735.66478.qm@web32401.mail.mud.yahoo.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> Message-ID: haha :) yeah it's the new imp stuff i like parts of the idea but other parts i really dislike basically it TRIES to make math more interactive and world like i really enjoy how most of it is really programable stuff :) where compared to normal math books it's a bit harder to program just a problem instead of a story but imp needs help with it's grading and teaching the grading is terrible i can get a A as long as i can explain and know how my way of doing it wrong "works" but will fail if i just write the write answer without explanation i dont mind the explanations bit but that what i write matters more than if i can do the work is odd adn i just haven't learned anything new yet :) On Sep 10, 2007, at 7:16 PM, wormwood_3 wrote: > Don't have any ideas to Pythonize this problem for you, but I must > say that I hope this problem was listed in a chapter entitled > "Cruel and Unusual"! > > -Sam > ____________________________________ > ----- Original Message ---- > From: max baseman > To: tutor at python.org > Sent: Monday, September 10, 2007 6:28:23 PM > Subject: [Tutor] making math problems mmmm fun > > hello all this is a homework in math i dont need to program it but i > would like to :) so like any other time pleas dont just give a > answer tutorials or a explanation. i dont like to use script > something i dont understand :) > > thanks > > basically the problem is to find a bunch of ways to put 1,2,3,4,5 > into different math problems to that equal 1-25, i haven't spent to > much time thinking about how to do this but i cant think of a way to > do it it without writing making the program rather long here is the > page from the book for the rules i will be working on this for the > next week or so thanks for any help :) > > > > > . you may use any of the four basic arithmetic operations- > addition, subtraction, multiplication, and division (according to the > order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 > expression for the number 1. > > . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression > for the number 3 > > . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is > a 1234 expression for 6 > > . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a > 1234 expression for the number 26 > > > . you may juxtapose two or more digits (that is put them next to > each other) to form a number such as 12. for example 43-12 is a 1234 > expression for 31 > > . you may use parentheses and brackets to change the meaning of a > expression for example according to the rules of order of operations 1 > +4x3? is a 1234 expression for 37. you can add parentheses and > brackets to get [(1+4)x3]? which is a 1234 expression for 225 > > . must use 1,2,3,4 exactly once > > > > thanks for the help ill post if i find anything > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From john at fouhy.net Tue Sep 11 04:47:22 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Sep 2007 14:47:22 +1200 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> References: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> Message-ID: <5e58f2e40709101947k9ca36f4lab9529e2273b9e6a@mail.gmail.com> On 11/09/2007, max baseman wrote: > basically the problem is to find a bunch of ways to put 1,2,3,4,5 > into different math problems to that equal 1-25, i haven't spent to > much time thinking about how to do this but i cant think of a way to > do it it without writing making the program rather long here is the > page from the book for the rules i will be working on this for the > next week or so thanks for any help :) I've seen this kind of problem before.. though not usually with quite as much freedom as this one :-) You could brute force it, by trying all possible combinations of numbers and operators. The only problem is that the freedom they give you means you get horrible combinatorial explosion. I'll give you my attempt at brute-force code. Basically, my thought process was: 1. Solve the problem for N digits by solving it for N-1 digits, then combining those solutions with the last remaining digit. 2. Because of non-commutivity and non-associativity, we need to pick do this for each possible digit we could remove, and for both directions. 3. If I stick to binary operators, I guarantee that the number of digits always reduces. So I will forget about factorial and square root for now. Anyway, here's my code. I'm happy to answer questions about it if you like. I guess I could be doing your homework for you, but only if you've got access to some pretty staunch hardware -- it's pretty snappy on [1, 2, 3], but if I try it on [1, 2, 3, 4] on my machine, python gets up to about 1.3GB memory usage before crashing with a MemoryError :-) ####### import operator binops = { 'add':operator.add, 'sub':operator.sub, 'mul':operator.mul, 'div':operator.truediv, 'pow':operator.pow, 'join':lambda x, y: int(str(x)+str(y)) } patterns = { 'add':'(%s) + (%s)', 'sub':'(%s) - (%s)', 'mul':'(%s) * (%s)', 'div':'(%s) / (%s)', 'pow':'(%s)^(%s)', 'join':'%s%s' } def combine(digits): """ digits :: set(int) output :: [ (value, expression) ] value :: int expression :: str -- string representation of math expression """ # We're going to solve this instance in terms of the solution # for a list with one fewer digit. # Because of non-commutativity, we have to do this twice for each # possible start digit. res = [] # Base case. if len(digits) == 1: return [(digit, str(digit)) for digit in digits] # Otherwise.. for digit in digits: remainder = digits - set([digit]) for val, exp in combine(remainder): for binop in binops: if binop == 'join': # Ensure we only join numbers, not expressions. try: int(exp) except ValueError: continue try: newval1 = binops[binop](digit, val) pattern1 = patterns[binop] % (str(digit), exp) res.append((newval1, pattern1)) except ZeroDivisionError: pass try: newval2 = binops[binop](val, digit) pattern2 = patterns[binop] % (exp, str(digit)) res.append((newval2, pattern2)) except ZeroDivisionError: pass return res if __name__ == '__main__': res = combine(set(range(1, 4))) From dos.fool at gmail.com Tue Sep 11 05:02:09 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 21:02:09 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <5e58f2e40709101947k9ca36f4lab9529e2273b9e6a@mail.gmail.com> References: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> <5e58f2e40709101947k9ca36f4lab9529e2273b9e6a@mail.gmail.com> Message-ID: wow this is a bit over my range of knowledge im impressed :) ill be happy to look at it but i think i will see if i can end up writing my own :) worse case ill do it by hand will not take long hmm wow thanks :) On Sep 10, 2007, at 8:47 PM, John Fouhy wrote: > ####### > import operator > > binops = { 'add':operator.add, > 'sub':operator.sub, > 'mul':operator.mul, > 'div':operator.truediv, > 'pow':operator.pow, > 'join':lambda x, y: int(str(x)+str(y)) > } > > patterns = { 'add':'(%s) + (%s)', > 'sub':'(%s) - (%s)', > 'mul':'(%s) * (%s)', > 'div':'(%s) / (%s)', > 'pow':'(%s)^(%s)', > 'join':'%s%s' > } > > def combine(digits): > """ digits :: set(int) > > output :: [ (value, expression) ] > value :: int > expression :: str -- string representation of math expression > """ > > # We're going to solve this instance in terms of the solution > # for a list with one fewer digit. > > # Because of non-commutativity, we have to do this twice for each > # possible start digit. > > res = [] > > # Base case. > if len(digits) == 1: > return [(digit, str(digit)) for digit in digits] > > # Otherwise.. > for digit in digits: > remainder = digits - set([digit]) > > for val, exp in combine(remainder): > for binop in binops: > if binop == 'join': > # Ensure we only join numbers, not expressions. > try: > int(exp) > except ValueError: > continue > > try: > newval1 = binops[binop](digit, val) > pattern1 = patterns[binop] % (str(digit), exp) > res.append((newval1, pattern1)) > except ZeroDivisionError: > pass > > try: > newval2 = binops[binop](val, digit) > pattern2 = patterns[binop] % (exp, str(digit)) > res.append((newval2, pattern2)) > except ZeroDivisionError: > pass > > return res > > if __name__ == '__main__': > res = combine(set(range(1, 4))) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/0e66d30b/attachment-0001.htm From alan.gauld at btinternet.com Sun Sep 9 16:15:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Sep 2007 15:15:03 +0100 Subject: [Tutor] inserting csv file into a sqlite3 memory connected table References: <20070909024355.6F4221E400D@bag.python.org> Message-ID: wrote > I am basically just a visual basic person trying to learn python. > > Anyway I have spent hours experimenting with CSV and sqllite3 > tutorial samples and misc snippets, Does anyone have any > code samples that might get me going? Doing what? Where are you having problems? Most tutorials will have code samples and snippets but unless we know what you are trying to do or not understanding we can't be more precise than point you at what you have probavbly already found. My tutorial has a database topic that uses SQLite. I donlt have anything on CSV but the module does have reasonable documentation. But are you trying to store a CSV file content in your database? Or convert a data table to a CSV format? or use a CSV to traslate between databases? We need a more specific question to direct our responses to your needs. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Sep 9 23:38:37 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Sep 2007 22:38:37 +0100 Subject: [Tutor] Apache, CGI-BIN, Python References: <46E44900.6050003@gmail.com> Message-ID: "Ryan" wrote >I am running a Linux box and cannot find my Apache cgi-bin to put >some > python scripts in. I know I probably have to create one but don't > know > where and how. I think there are several places that you can create cgi-bin depending on how you configure apache. But the place I usually see it is directly under the apache root directory - ie the one that is equivalent to / in the url. > everything works fine except: > > form = cgi.FieldStorage() > > #This is where everything goes wrong > #I get error messages for either the lastname line or firstname Can you tell us a) exactly what error messages and b) How you are invoking the script - where are the values supposed to be coming from? > lastname = form['lastname'].value > firstname =form['firstname'].value > message = firstname + " " + lastname > print reshtml % message HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From timmichelsen at gmx-topmail.de Tue Sep 11 00:33:24 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 11 Sep 2007 00:33:24 +0200 Subject: [Tutor] input file encoding Message-ID: Hello, I want to process some files encoded in latin-1 (iso-8859-1) in my python script that I write on Ubuntu which has UTF-8 as standard encoding. When I use the "print lines_in_myfile" is get some wired symbols. How shold I read those files in or convert their encoding to utf-8? Thanks in advance, Tim From kent37 at tds.net Mon Sep 10 03:15:56 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 09 Sep 2007 21:15:56 -0400 Subject: [Tutor] Suggested books for Agile Programming & Testing? In-Reply-To: References: Message-ID: <46E49ACC.3010507@tds.net> Stephen McInerney wrote: > > Can anyone recommend me the best single must-read book for Agile > Programming? Quoting myself from the archives: I recommend Robert Martin's "Agile Software Development: Principles, Patterns, and Practices" http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP This is the best book I know for learning object-oriented design the way I do it ;) - a very agile, pragmatic approach. It shows you the nitty-gritty details of how to create classes as you develop a solution. Also a good introduction to the agile development style. Much of the content of the book is available as essays on the ObjectMentor website: http://w ww.objectmentor.com/resources/listArticles?key=author&author=Robert%20C.%20Martin ----------------------------------- Some of the highlights from my bookshelf: Martin, Agile Software Development http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP Fowler, Refactoring: Improving the Design of Existing Code http://martinfowler.com/books.html#refactoring Beck, Extreme Programming Explained http://www.amazon.com/exec/obidos/ASIN/0201616416/ref%3Dnosim/armaties/102-7636110-6481700 Kent From alan.gauld at btinternet.com Tue Sep 11 01:13:57 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 00:13:57 +0100 Subject: [Tutor] Running other files References: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> Message-ID: "Rikard Bosnjakovic" wrote >> is it possible to run other non-python files using python such as >> .exe or >> other files. > > Have a look at os.system(). Or the more recent subprocess module which supercedes os.system etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brunson at brunson.com Tue Sep 11 06:41:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 10 Sep 2007 22:41:56 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: References: <824735.66478.qm@web32401.mail.mud.yahoo.com> Message-ID: <46E61C94.8000701@brunson.com> When you get done with this math problem you should consider a book on punctuation. Not using it makes your sentences run together and difficult to read. :-) Honestly, I just gave up after the first two lines. max baseman wrote: > haha :) yeah it's the new imp stuff i like parts of the idea but > other parts i really dislike basically it TRIES to make math more > interactive and world like i really enjoy how most of it is really > programable stuff :) where compared to normal math books it's a bit > harder to program just a problem instead of a story but imp needs > help with it's grading and teaching the grading is terrible i can get > a A as long as i can explain and know how my way of doing it wrong > "works" but will fail if i just write the write answer without > explanation i dont mind the explanations bit but that what i write > matters more than if i can do the work is odd > adn i just haven't learned anything new yet :) > > On Sep 10, 2007, at 7:16 PM, wormwood_3 wrote: > > >> Don't have any ideas to Pythonize this problem for you, but I must >> say that I hope this problem was listed in a chapter entitled >> "Cruel and Unusual"! >> >> -Sam >> ____________________________________ >> ----- Original Message ---- >> From: max baseman >> To: tutor at python.org >> Sent: Monday, September 10, 2007 6:28:23 PM >> Subject: [Tutor] making math problems mmmm fun >> >> hello all this is a homework in math i dont need to program it but i >> would like to :) so like any other time pleas dont just give a >> answer tutorials or a explanation. i dont like to use script >> something i dont understand :) >> >> thanks >> >> basically the problem is to find a bunch of ways to put 1,2,3,4,5 >> into different math problems to that equal 1-25, i haven't spent to >> much time thinking about how to do this but i cant think of a way to >> do it it without writing making the program rather long here is the >> page from the book for the rules i will be working on this for the >> next week or so thanks for any help :) >> >> >> >> >> . you may use any of the four basic arithmetic operations- >> addition, subtraction, multiplication, and division (according to the >> order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 >> expression for the number 1. >> >> . you may use exponents. for example, 2?? - 4 - 1 is a 1234 expression >> for the number 3 >> >> . you may use radicals for EX: ???4x2+1 is equal to 3 so 3+???4x2+1 is >> a 1234 expression for 6 >> >> . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a >> 1234 expression for the number 26 >> >> >> . you may juxtapose two or more digits (that is put them next to >> each other) to form a number such as 12. for example 43-12 is a 1234 >> expression for 31 >> >> . you may use parentheses and brackets to change the meaning of a >> expression for example according to the rules of order of operations 1 >> +4x3?? is a 1234 expression for 37. you can add parentheses and >> brackets to get [(1+4)x3]?? which is a 1234 expression for 225 >> >> . must use 1,2,3,4 exactly once >> >> >> >> thanks for the help ill post if i find anything >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Tue Sep 11 06:43:38 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 10 Sep 2007 22:43:38 -0600 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: References: <46E44900.6050003@gmail.com> Message-ID: <46E61CFA.4000901@brunson.com> Alan Gauld wrote: > "Ryan" wrote > > >> I am running a Linux box and cannot find my Apache cgi-bin to put >> some >> python scripts in. I know I probably have to create one but don't >> know >> where and how. >> > > I think there are several places that you can create cgi-bin depending > on how you configure apache. But the place I usually see it is > directly > under the apache root directory - ie the one that is equivalent to / > in > the url. > But, if you read the apache configuration files, it will tell you were it is. :-) > >> everything works fine except: >> >> form = cgi.FieldStorage() >> >> #This is where everything goes wrong >> #I get error messages for either the lastname line or firstname >> > > Can you tell us > a) exactly what error messages and > b) How you are invoking the script - where are the values > supposed to be coming from? > > >> lastname = form['lastname'].value >> firstname =form['firstname'].value >> message = firstname + " " + lastname >> print reshtml % message >> > > HTH, > > > From alan.gauld at btinternet.com Tue Sep 11 09:21:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:21:59 +0100 Subject: [Tutor] Socket Timeout Handling References: <841606.52273.qm@web32408.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > Have not gotten any responses on this, I did send you a response and it is listed on the gmane archive so if you didn't see it something has gone adrift somewhere. > But, I did find a decent recipe on ASPN that serves the purpose, The solution you posted seems to bear no resemblence to the problem you posted? How does this relate to setting socket timeouts or using getfqdn()? This solution simply does a ping on a site to see if the network is available. If you had asked how to check if you were connected to the network you likely would have gotten several responses! As ever, if you ask the wrong question you will get the wrong answer! :-) > def checkURL(url): > """For checking internet connection. Taken from recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/101276""" > try: > p = urlparse(url) > h = HTTP(p[1]) > h.putrequest('HEAD', p[2]) > h.endheaders() > if h.getreply()[0] == 200: return 1 > else: return 0 > except: > return 0 > > The nice thing about this check is that is just looks at the head of > the site, and so is rather fast. > I am trying to figure out the optimal way to make socket connections > (INET) and check for timeouts. The socket module has > settimeout(timeout) > and setdefaulttimeout(timeout). However, so far as I can tell, these > apply to socket objects. The type of socket connection I want to > make is getfqdn(address). So I can set the default timeout for > socket, > but not a socket object (makes sense so far). I cannot use the > getfqdn(address) method on a socket object, I have to use it on > socket. This means (as I understand it thus far), that while I can > set a timeout value for socket objects, this will not apply to when > I use the getfqdn() method, which is where I need a timeout check! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Sep 11 09:37:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:37:35 +0100 Subject: [Tutor] making math problems mmmm fun References: <1C99EFF7-A12C-4DEF-8595-B42DA3E3F103@gmail.com> Message-ID: "max baseman" wrote > basically the problem is to find a bunch of ways to put 1,2,3,4,5 > into different math problems to that equal 1-25, i haven't spent to > much time thinking about how to do this but i cant think of a way to > do it it without writing making the program rather long This is quite a difficult problem to program (cue someone with a really short solution! :-) Its similar in concept to decyphering codes, there are lots of possible permutations but only a few are viable. There are lots of rules too. The normal approach is to search for inconsistencies but because its math and operators can cancel each other out it will be hard to define consistency rules. If you only had the 4 operators or you weren't allowed to use parentheses it would be fairly doable but by adding parentheses and operators like factorials and finally juxtaposition I'm not sure I'd like to try coding it! I suspect this might be the kind of pattern spotting problem better suited to the human brain! Computers are best with large quantities of data composed in finite ways, brains are best at small data sets combined in many combinations. Alan G. > page from the book for the rules i will be working on this for the > next week or so thanks for any help :) > > . you may use any of the four basic arithmetic operations- > addition, subtraction, multiplication, and division (according to > the > order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 > expression for the number 1. > > . you may use exponents. for example, 2? - 4 - 1 is a 1234 > expression > for the number 3 > > . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is > a 1234 expression for 6 > > . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a > 1234 expression for the number 26 > > > . you may juxtapose two or more digits (that is put them next to > each other) to form a number such as 12. for example 43-12 is a 1234 > expression for 31 > > . you may use parentheses and brackets to change the meaning of a > expression for example according to the rules of order of operations > 1 > +4x3? is a 1234 expression for 37. you can add parentheses and > brackets to get [(1+4)x3]? which is a 1234 expression for 225 > > . must use 1,2,3,4 exactly once > > > > thanks for the help ill post if i find anything > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Sep 11 09:47:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:47:41 +0100 Subject: [Tutor] Making a python script to feed files into another pythonscript References: Message-ID: "Ashley Booth" wrote > So far I can get it to read the directory fine but it ends up just > opening the script I want the files to be fed into instead of giving > it the input and output to run and running it. Any ideas? > > Here is what I have so far: > > import sys, os > > indir = raw_input('input directory path ') # input directory > script1 = os.system(raw_input('python script path ')) os.system only returnms the error code of the operation not the results, so script1 will usually contain 0 (for success). You need to look at the subprocess module and the examples of replacing popen. Specifically using the communicate() method of Popen. > for j in os.listdir(indir): > input = os.path.join(indir,j) > output = os.path.join(indir,j.split('rovctd')[0]+'.txt') You might find os.path.basename more reliable here. > script1(input,output) This won't work see above. > If this is going to be too complicated, No, this is exactly the kind of thing Python is good at. > I would at least be happy with how to tack on the list > directory stuff to then of the script1- it would not be a > stand alone script but at least it would work. Sorry you lost me there. Which script? The one above or the ones you are trying to execute? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Sep 11 09:54:04 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 11 Sep 2007 07:54:04 +0000 (GMT) Subject: [Tutor] Fw: Apache, CGI-BIN, Python Message-ID: <767740.51285.qm@web86109.mail.ird.yahoo.com> Forwarding to the list.... NB Use Reply-All when replying to the tutor list. Alan G. ----- Forwarded Message ---- From: Ryan To: Alan Gauld Sent: Tuesday, 11 September, 2007 5:32:33 AM Subject: Re: [Tutor] Apache, CGI-BIN, Python Alan Gauld wrote: > "Ryan" wrote > > >> I am running a Linux box and cannot find my Apache cgi-bin to put >> some >> python scripts in. I know I probably have to create one but don't >> know >> where and how. >> > > I think there are several places that you can create cgi-bin depending > on how you configure apache. But the place I usually see it is > directly > under the apache root directory - ie the one that is equivalent to / > in > the url. > > >> everything works fine except: >> >> form = cgi.FieldStorage() >> >> #This is where everything goes wrong >> #I get error messages for either the lastname line or firstname >> > > Can you tell us > a) exactly what error messages and > b) How you are invoking the script - where are the values > supposed to be coming from? > > >> lastname = form['lastname'].value >> firstname =form['firstname'].value >> message = firstname + " " + lastname >> print reshtml % message >> > The HTML Doc: >

Enter your first name:

Error: Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, in handler module = page_cache[req] File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in __getitem__ return self._checkitem(name)[2] File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in _checkitem value = self.build(key, name, opened, entry) File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, in build return ModuleCache.build(self, key, req, opened, entry) File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in build exec opened in module.__dict__ File "/var/www/python/test1.py", line 16, in lastname = form['lastname'].value File "cgi.py", line 567, in __getitem__ raise KeyError, key KeyError: 'lastname' But I can get this script to work properly: def index(req): return "Test succesful"; > HTH, > > > From alan.gauld at btinternet.com Tue Sep 11 09:50:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:50:34 +0100 Subject: [Tutor] Image Analysis References: <15059.1222.qm@web32403.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > I need some way to analyze an image for color patterns. > > My only lead right now is PIL, and I am not sure if it will meet my > needs. PIL should be usable but I think there is also a Pyton wrapper for ImageMagick and I think it has some colour management type functions exposed too. Never tried any of this kind of thing though so I can't recommend anything with certainty. Alan G From mail at timgolden.me.uk Tue Sep 11 10:06:12 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Sep 2007 09:06:12 +0100 Subject: [Tutor] input file encoding In-Reply-To: References: Message-ID: <46E64C74.9030303@timgolden.me.uk> Tim Michelsen wrote: > Hello, > I want to process some files encoded in latin-1 (iso-8859-1) in my > python script that I write on Ubuntu which has UTF-8 as standard encoding. Not sure what you mean by "standard encoding" (is this an Ubuntu thing?) but essentially whenever you're pulling stuff into Python which is encoded and which you want to treat as Unicode, you need to decode it explicitly, either on a string-by-string basis or by using the codecs module to treat the whole of a file as encoded. In this case, assuming you have files in iso-8859-1, something like this: import codecs filenames = ['a.txt', 'b.txt', 'c.txt'] for filename in filenames: f = codecs.open (filename, encoding="iso-8859-1") text = f.read () # # If you want to re-encode this -- not sure why -- # you could do this: # text = text.encode ("utf-8") print repr (text) TJG From brunson at brunson.com Tue Sep 11 10:25:42 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 02:25:42 -0600 Subject: [Tutor] Fw: Apache, CGI-BIN, Python In-Reply-To: <767740.51285.qm@web86109.mail.ird.yahoo.com> References: <767740.51285.qm@web86109.mail.ird.yahoo.com> Message-ID: <46E65106.7050505@brunson.com> ALAN GAULD wrote: > Forwarding to the list.... > > NB Use Reply-All when replying to the tutor list. > > Alan G. > > ----- Forwarded Message ---- > From: Ryan > To: Alan Gauld > Sent: Tuesday, 11 September, 2007 5:32:33 AM > Subject: Re: [Tutor] Apache, CGI-BIN, Python > > Alan Gauld wrote: > >> "Ryan" wrote >> >> >> >>> I am running a Linux box and cannot find my Apache cgi-bin to put >>> some >>> python scripts in. I know I probably have to create one but don't >>> know >>> where and how. >>> >>> >> I think there are several places that you can create cgi-bin depending >> on how you configure apache. But the place I usually see it is >> directly >> under the apache root directory - ie the one that is equivalent to / >> in >> the url. >> >> >> >>> everything works fine except: >>> >>> form = cgi.FieldStorage() >>> >>> #This is where everything goes wrong >>> #I get error messages for either the lastname line or firstname >>> >>> >> Can you tell us >> a) exactly what error messages and >> b) How you are invoking the script - where are the values >> supposed to be coming from? >> >> >> >>> lastname = form['lastname'].value >>> firstname =form['firstname'].value >>> message = firstname + " " + lastname >>> print reshtml % message >>> >>> >> The HTML Doc: >> >> > > >
>

Enter your first name:

> > > > > > > > Error: > > Mod_python error: "PythonHandler mod_python.publisher" > You don't use the cgi module when using the mod_python publisher handler. Your function will be called with the form variables as named parameters, like this: def handle_form_input( req, firstname, lastname ): # do something here I would recommend giving defaults for the parameters so if the user doesn't submit a value it, it doesn't throw an exception, like this: def handle_form_input( req, firstname=None, lastname=None ): # whatever And, I've been known to simulate the cgi behavior like this: def handler_form_input( req, **form ): # access your form variables as an array print "You entered %s %s" % ( form[lastname], form[firstname] ) But, remember that this "form" is a simple dict, not a cgi.FieldStorage and I don't know what it does with multiple values with the same key. FieldStorage puts them in an array, you'd have to experiment with this in the publisher handler. See how much better answers you get when you ask good questions and include error messages. :-) Hope that helps, e. > Traceback (most recent call last): > > File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in HandlerDispatch > result = object(req) > > File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, in handler > module = page_cache[req] > > File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in __getitem__ > return self._checkitem(name)[2] > > File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in _checkitem > value = self.build(key, name, opened, entry) > > File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, in build > return ModuleCache.build(self, key, req, opened, entry) > > File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in build > exec opened in module.__dict__ > > File "/var/www/python/test1.py", line 16, in > lastname = form['lastname'].value > > File "cgi.py", line 567, in __getitem__ > raise KeyError, key > > KeyError: 'lastname' > > But I can get this script to work properly: > def index(req): > return "Test succesful"; > > > > >> HTH, >> >> >> >> > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Tue Sep 11 10:31:34 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 02:31:34 -0600 Subject: [Tutor] Fw: Apache, CGI-BIN, Python In-Reply-To: <46E65106.7050505@brunson.com> References: <767740.51285.qm@web86109.mail.ird.yahoo.com> <46E65106.7050505@brunson.com> Message-ID: <46E65266.1090106@brunson.com> Eric Brunson wrote: > ALAN GAULD wrote: > >> Forwarding to the list.... >> >> NB Use Reply-All when replying to the tutor list. >> >> Alan G. >> >> ----- Forwarded Message ---- >> From: Ryan >> To: Alan Gauld >> Sent: Tuesday, 11 September, 2007 5:32:33 AM >> Subject: Re: [Tutor] Apache, CGI-BIN, Python >> >> Alan Gauld wrote: >> >> >>> "Ryan" wrote >>> >>> >>> >>> >>>> I am running a Linux box and cannot find my Apache cgi-bin to put >>>> some >>>> python scripts in. I know I probably have to create one but don't >>>> know >>>> where and how. >>>> >>>> >>>> >>> I think there are several places that you can create cgi-bin depending >>> on how you configure apache. But the place I usually see it is >>> directly >>> under the apache root directory - ie the one that is equivalent to / >>> in >>> the url. >>> >>> >>> >>> >>>> everything works fine except: >>>> >>>> form = cgi.FieldStorage() >>>> >>>> #This is where everything goes wrong >>>> #I get error messages for either the lastname line or firstname >>>> >>>> >>>> >>> Can you tell us >>> a) exactly what error messages and >>> b) How you are invoking the script - where are the values >>> supposed to be coming from? >>> >>> >>> >>> >>>> lastname = form['lastname'].value >>>> firstname =form['firstname'].value >>>> message = firstname + " " + lastname >>>> print reshtml % message >>>> >>>> >>>> >>> The HTML Doc: >>> >>> >>> >> >> >>
>>

Enter your first name:

>> >> >> >> >> >> >> >> Error: >> >> Mod_python error: "PythonHandler mod_python.publisher" >> >> > > You don't use the cgi module when using the mod_python publisher > handler. Your function will be called with the form variables as named > parameters, like this: > > def handle_form_input( req, firstname, lastname ): > # do something here > > I would recommend giving defaults for the parameters so if the user > doesn't submit a value it, it doesn't throw an exception, like this: > > def handle_form_input( req, firstname=None, lastname=None ): > # whatever > > And, I've been known to simulate the cgi behavior like this: > > def handler_form_input( req, **form ): > # access your form variables as an array > print "You entered %s %s" % ( form[lastname], form[firstname] ) > > It's late, that should read: def handler_form_input( req, **form ): # access your form variables as a dict return "You entered %s %s" % ( form['lastname'], form['firstname'] ) > But, remember that this "form" is a simple dict, not a cgi.FieldStorage > and I don't know what it does with multiple values with the same key. > FieldStorage puts them in an array, you'd have to experiment with this > in the publisher handler. > > See how much better answers you get when you ask good questions and > include error messages. :-) > > Hope that helps, > e. > > > >> Traceback (most recent call last): >> >> File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in HandlerDispatch >> result = object(req) >> >> File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, in handler >> module = page_cache[req] >> >> File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in __getitem__ >> return self._checkitem(name)[2] >> >> File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in _checkitem >> value = self.build(key, name, opened, entry) >> >> File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, in build >> return ModuleCache.build(self, key, req, opened, entry) >> >> File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in build >> exec opened in module.__dict__ >> >> File "/var/www/python/test1.py", line 16, in >> lastname = form['lastname'].value >> >> File "cgi.py", line 567, in __getitem__ >> raise KeyError, key >> >> KeyError: 'lastname' >> >> But I can get this script to work properly: >> def index(req): >> return "Test succesful"; >> >> >> >> >> >>> HTH, >>> >>> >>> >>> >>> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From le.dahut at laposte.net Tue Sep 11 10:27:45 2007 From: le.dahut at laposte.net (le dahut) Date: Tue, 11 Sep 2007 10:27:45 +0200 Subject: [Tutor] file read and write Message-ID: <46E65181.6030605@laposte.net> I noticed that it is possible to write this : """ file('/tmp/myfile', 'w').write('Hello world\n') contnt = file('/tmp/sourcefile').read() """ instead of : """ fh = file('/tmp/myfile', 'w') fh.write('Hello world\n') fh.close() fh = file('/tmp/sourcefile') contnt = fh.read() fh.close() """ is there a reason not to use the first example ? K. From alan.gauld at btinternet.com Tue Sep 11 11:33:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 10:33:55 +0100 Subject: [Tutor] file read and write References: <46E65181.6030605@laposte.net> Message-ID: "le dahut" wrote >I noticed that it is possible to write this : > """ > file('/tmp/myfile', 'w').write('Hello world\n') > contnt = file('/tmp/sourcefile').read() > """ Yes, it just creates temporary objects and relies on garbage collection to close/dispose of them. > instead of : > """ > fh = file('/tmp/myfile', 'w') > fh.write('Hello world\n') > fh.close() > > fh = file('/tmp/sourcefile') > contnt = fh.read() > fh.close() > """ > > is there a reason not to use the first example ? Not really although its rather limited in what it can do for you. Also error handling will not be as robust since you can't check that the file was/was not created. But if you just want a very short file it's fine and in fact you will often see examples of s = open('foo.txt').read() in code, it is quite common, more so than the write version. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Sep 11 12:50:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 06:50:11 -0400 Subject: [Tutor] input file encoding In-Reply-To: <46E64C74.9030303@timgolden.me.uk> References: <46E64C74.9030303@timgolden.me.uk> Message-ID: <46E672E3.2050702@tds.net> Tim Golden wrote: > Tim Michelsen wrote: >> Hello, >> I want to process some files encoded in latin-1 (iso-8859-1) in my >> python script that I write on Ubuntu which has UTF-8 as standard encoding. > > Not sure what you mean by "standard encoding" (is this an Ubuntu > thing?) Probably referring to the encoding the terminal application expects - writing latin-1 chars when the terminal expects utf-8 will not work well. Python also has a default encoding but that is ascii unless you change it yourself. > In this case, assuming you have files in iso-8859-1, something > like this: > > > import codecs > > filenames = ['a.txt', 'b.txt', 'c.txt'] > for filename in filenames: > f = codecs.open (filename, encoding="iso-8859-1") > text = f.read () > # > # If you want to re-encode this -- not sure why -- This is needed to put the text into the proper encoding for the terminal. If you print a unicode string directly it will be encoded using the system default encoding (ascii) which will fail: In [13]: print u'\xe2' ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : 'ascii' codec can't encode character u'\xe2' in position 0: ordinal not in range(128) In [14]: print u'\xe2'.encode('utf-8') ? > # you could do this: > # text = text.encode ("utf-8") > print repr (text) No, not repr, that will print with \ escapes and quotes. In [15]: print repr(u'\xe2'.encode('utf-8')) '\xc3\xa2' And he may not want to change text itself to utf-8. Just print text.encode('utf-8') Kent From mail at timgolden.me.uk Tue Sep 11 12:58:37 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Sep 2007 11:58:37 +0100 Subject: [Tutor] input file encoding In-Reply-To: <46E672E3.2050702@tds.net> References: <46E64C74.9030303@timgolden.me.uk> <46E672E3.2050702@tds.net> Message-ID: <46E674DD.1060108@timgolden.me.uk> Kent Johnson wrote: > Tim Golden wrote: >> Not sure what you mean by "standard encoding" (is this an Ubuntu >> thing?) > > Probably referring to the encoding the terminal application expects - > writing latin-1 chars when the terminal expects utf-8 will not work well. Ah, I see. I'm so used to Windows where there is, technically an encoding for the console window, but you can't really do anything about it (apart from the awkward chcp) and it isn't really in your face. I do *use* Linux sometimes, but I don't really think in it :) >> Tim Golden >> # you could do this: >> # text = text.encode ("utf-8") >> print repr (text) > > No, not repr, that will print with \ escapes and quotes. I knew that (no, honestly ;). Since I wasn't sure what the OP was after, I was using repr to *show* the escapes and quotes really to indicate that he may not have wanted them! (All right, I'll shut up now). Thanks for clarifying, Kent. TJG From kent37 at tds.net Tue Sep 11 13:45:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 07:45:38 -0400 Subject: [Tutor] file read and write In-Reply-To: <46E65181.6030605@laposte.net> References: <46E65181.6030605@laposte.net> Message-ID: <46E67FE2.80503@tds.net> le dahut wrote: > I noticed that it is possible to write this : > """ > file('/tmp/myfile', 'w').write('Hello world\n') ISTM I have had trouble with this. I always explicitly close a file that is open for writing. > contnt = file('/tmp/sourcefile').read() I use this often but never in any kind of loop where multiple files are being read. Note that the behaviour of the garbage collector is implementation-dependent. It is an implementation detail of CPython that GC is implemented with reference counting and objects are disposed when there are no longer any references to them. Jython uses Java's GC which does not behave the same way; PyPy and IronPython may have different GC as well. So if you want your code to be portable between implementations of Python you should not rely on this behaviour. Kent From kent37 at tds.net Tue Sep 11 13:59:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 07:59:35 -0400 Subject: [Tutor] input file encoding In-Reply-To: <46E674DD.1060108@timgolden.me.uk> References: <46E64C74.9030303@timgolden.me.uk> <46E672E3.2050702@tds.net> <46E674DD.1060108@timgolden.me.uk> Message-ID: <46E68327.5010404@tds.net> Tim Golden wrote: > Ah, I see. I'm so used to Windows where there is, technically an encoding > for the console window, but you can't really do anything about > it (apart from the awkward chcp) and it isn't really in your face. I > do *use* Linux sometimes, but I don't really think in it :) Actually you would run into the same problems on Windows if you tried to print UTF-8 or Unicode data. The only reason the Windows encoding is not in your face is that enough data is in ascii/latin-1/cp1252 that you can coast along in blissful ignorance. As soon as you have to deal with text in Japanese/Chinese/Korean/Russian/Turkish/Arabic/Greek/Hebrew/Thai/Klingon/etc you will have a rude awakening and a quick lesson in encoding awareness. Kent From dos.fool at gmail.com Tue Sep 11 14:24:16 2007 From: dos.fool at gmail.com (max baseman) Date: Tue, 11 Sep 2007 06:24:16 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <46E61C94.8000701@brunson.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> <46E61C94.8000701@brunson.com> Message-ID: <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> lol sorry i was born with bad grammar and hand writing (although it's the bit after being born that matters) On Sep 10, 2007, at 10:41 PM, Eric Brunson wrote: > > When you get done with this math problem you should consider a book > on punctuation. Not using it makes your sentences run together and > difficult to read. :-) Honestly, I just gave up after the first two > lines. > > max baseman wrote: >> haha :) yeah it's the new imp stuff i like parts of the idea but >> other parts i really dislike basically it TRIES to make math >> more interactive and world like i really enjoy how most of it is >> really programable stuff :) where compared to normal math books >> it's a bit harder to program just a problem instead of a story >> but imp needs help with it's grading and teaching the grading is >> terrible i can get a A as long as i can explain and know how my >> way of doing it wrong "works" but will fail if i just write the >> write answer without explanation i dont mind the explanations bit >> but that what i write matters more than if i can do the work is odd >> adn i just haven't learned anything new yet :) >> >> On Sep 10, 2007, at 7:16 PM, wormwood_3 wrote: >> >> >>> Don't have any ideas to Pythonize this problem for you, but I >>> must say that I hope this problem was listed in a chapter >>> entitled "Cruel and Unusual"! >>> >>> -Sam >>> ____________________________________ >>> ----- Original Message ---- >>> From: max baseman >>> To: tutor at python.org >>> Sent: Monday, September 10, 2007 6:28:23 PM >>> Subject: [Tutor] making math problems mmmm fun >>> >>> hello all this is a homework in math i dont need to program it but i >>> would like to :) so like any other time pleas dont just give a >>> answer tutorials or a explanation. i dont like to use script >>> something i dont understand :) >>> >>> thanks >>> >>> basically the problem is to find a bunch of ways to put 1,2,3,4,5 >>> into different math problems to that equal 1-25, i haven't spent to >>> much time thinking about how to do this but i cant think of a way to >>> do it it without writing making the program rather long here is the >>> page from the book for the rules i will be working on this for the >>> next week or so thanks for any help :) >>> >>> >>> >>> >>> . you may use any of the four basic arithmetic operations- >>> addition, subtraction, multiplication, and division (according to >>> the >>> order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 >>> expression for the number 1. >>> >>> . you may use exponents. for example, 2?? - 4 - 1 is a 1234 >>> expression >>> for the number 3 >>> >>> . you may use radicals for EX: ???4x2+1 is equal to 3 so 3+???4x2 >>> +1 is >>> a 1234 expression for 6 >>> >>> . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a >>> 1234 expression for the number 26 >>> >>> >>> . you may juxtapose two or more digits (that is put them next to >>> each other) to form a number such as 12. for example 43-12 is a 1234 >>> expression for 31 >>> >>> . you may use parentheses and brackets to change the meaning of a >>> expression for example according to the rules of order of >>> operations 1 >>> +4x3?? is a 1234 expression for 37. you can add parentheses and >>> brackets to get [(1+4)x3]?? which is a 1234 expression for 225 >>> >>> . must use 1,2,3,4 exactly once >>> >>> >>> >>> thanks for the help ill post if i find anything >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From wormwood_3 at yahoo.com Tue Sep 11 14:37:21 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 11 Sep 2007 05:37:21 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <998382.86173.qm@web32408.mail.mud.yahoo.com> >I did send you a response and it is listed on the gmane archive >so if you didn't see it something has gone adrift somewhere. Just searched all my mail, for some reason I did not get this. I will check the archive. Thanks! >The solution you posted seems to bear no resemblence >to the problem you posted? How does this relate to setting >socket timeouts or using getfqdn()? Initially I was asking about how to set socket timeouts. But my general query was just suggestions on how best to detect internet connection upness. Since I "did not" get any responses to the question in the form of socket timeouts in particular, I resent the question in a more general form. It was that form that my last reply was to address. You are right on what it does. I thought at first it would be best to use something native to the classes/functions I was using in the standard library if possible. The solution I ended up with was more general, but serves the purpose. -Sam From rabidpoobear at gmail.com Tue Sep 11 14:38:33 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 11 Sep 2007 07:38:33 -0500 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> <46E61C94.8000701@brunson.com> <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> Message-ID: <46E68C49.30205@gmail.com> max baseman wrote: > lol sorry i was born with bad grammar and hand writing (although it's > the bit after being born that matters) > Just imagine you're talking instead of writing. Everywhere you'd put a pause, put a comma. If it seems like the end of a sentence, put a period. In most cases, even bad punctuation will be better than no punctuation. People's inner monologues will just take on a Christopher Walken accent as they read over your e-mails, but this is arguably not a bad thing. Grammar is something you can learn, not something inborn. Now is as good a time as any to start learning it. -Luke From wormwood_3 at yahoo.com Tue Sep 11 14:59:45 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 11 Sep 2007 05:59:45 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <5957.71351.qm@web32415.mail.mud.yahoo.com> Ok, just found your message in the archives. Thanks very much for that! By way of response-- >>That may be because your question ventures into fairly deep areas of >> networking >> that most folk who are just learning Python(ie readers of this list) >> have probably >> not encountered. True enough:-) I am learning this as I go. >>If you do want to get into depth on Python networking you may find the >> A-Press book Python Network Programming useful - I do regularly :-). I came across it a few times, was not sure if it would be as useful as more general books, but I think I will get it soon. >> However the only information I could see about timeouts there was >>related to socket.settimeout() which ISTR you didn't want to/couldn't >>use... The docs show there is settimeout() and setdefaulttimeout(). I will try to explain below why I did not think I could use these. I might have been wrong... > What is the best practice for checking for network connectivity > errors when making network calls? Is it better to wrap the functions > that make said calls in threads and time them? > Or to use timeout variables for modules like socket? >> Personally if i was doingt that I'd almost certainy put it in a thread >> and apply a timeout within the thread. but not having tried that I >> don't >> know how easy it would be! A friend shared an implementation of this with me that works well. I have attached it. Maybe you will find it useful! > I am trying to figure out the optimal way to make socket connections > (INET) and check for timeouts. The socket module has > settimeout(timeout) > and setdefaulttimeout(timeout). However, so far as I can tell, these > apply > to socket objects. The type of socket connection I want to make is > getfqdn(address). >> I don't understand, getfqdn() returns a domain name not an a socket? Yes. Example: >>> import socket >>> socket.getfqdn("64.233.169.99") 'yo-in-f99.google.com' And therein lies the rub! The main function of the script I have this in is to go through a list of IP addresses, and find their FQDN, and other information. It is at this step, when I get the FQDN, that I wanted to do some find of timeout setting. But since it is *not* a socket object, I cannot use settimeout()... > So I can set the default timeout for socket, but not a socket object > (makes sense so far). I cannot use the getfqdn(address) method on > a socket object, I have to use it on socket. >> Sorry it's not making sense to me, getfqdn takes a host name not a >> socket. Exactly my problem:-) >> setdefaulttimout is a function in the socket module not a method of >> socket. >> Thus you woulfd call that before reating a new socket: Thanks for the clarification, I will try this. >> What are you trying to do? Establish a socket connection to something >> or just do a name check that times out more quickly?(or slowly) Just trying to get the FQDNs from a list of IPs, and want to have some sane error handling in place in case my connection dies during the queries. Thanks! -------------- next part -------------- A non-text attachment was scrubbed... Name: TimeoutThread.py Type: text/x-python Size: 1432 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070911/36d5c88e/attachment-0001.py From janos.juhasz at VELUX.com Tue Sep 11 15:31:44 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 11 Sep 2007 15:31:44 +0200 Subject: [Tutor] Unicode question In-Reply-To: Message-ID: Dear All, I would like to convert my DOS txt file into pdf with reportlab. The file can be seen correctly in Central European (DOS) encoding in Explorer. My winxp uses cp852 as default codepage. When I open the txt file in notepad and set OEM/DOS script for terminal fonts, it shows the file correctly. I tried to convert the file with the next way: from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize PAGE_HEIGHT=defaultPageSize[1] styles = getSampleStyleSheet() def MakePdfInvoice(InvoiceNum, page): style = styles["Normal"] PdfInv = [Spacer(0,0)] PdfInv.append(Preformatted(page, styles['Normal'])) doc = SimpleDocTemplate(InvoiceNum) doc.build(PdfInv) if __name__ == '__main__': content = open('invoice01_0707.txt').readlines() page = ''.join(content[:92]) page = unicode(page, 'Latin-1') MakePdfInvoice('test.pdf', page) But it made funny chars somewhere. I tried it so eighter if __name__ == '__main__': content = open('invoice01_0707.txt').readlines() page = ''.join(content[:92]) page = page.encode('cp852') MakePdfInvoice('test.pdf', page) But it raised exception: debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run exec cmd in globals, locals File "D:\devel\reportlab\MakePdfInvoice.py", line 18, in ? page = page.encode('cp852') File "c:\Python24\lib\encodings\cp852.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 112: ordinal not in range(128) >>> May someone point me where I made it wrong ? Best regards, Janos Juhasz From kent37 at tds.net Tue Sep 11 15:49:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 09:49:24 -0400 Subject: [Tutor] Unicode question In-Reply-To: References: Message-ID: <46E69CE4.9000803@tds.net> J?nos Juh?sz wrote: > Dear All, > > I would like to convert my DOS txt file into pdf with reportlab. > The file can be seen correctly in Central European (DOS) encoding in > Explorer. > > My winxp uses cp852 as default codepage. > > When I open the txt file in notepad and set OEM/DOS script for terminal > fonts, it shows the file correctly. > > I tried to convert the file with the next way: > > from reportlab.platypus import * > from reportlab.lib.styles import getSampleStyleSheet > from reportlab.rl_config import defaultPageSize > PAGE_HEIGHT=defaultPageSize[1] > > styles = getSampleStyleSheet() > > def MakePdfInvoice(InvoiceNum, page): > style = styles["Normal"] > PdfInv = [Spacer(0,0)] > PdfInv.append(Preformatted(page, styles['Normal'])) > doc = SimpleDocTemplate(InvoiceNum) > doc.build(PdfInv) > > if __name__ == '__main__': > content = open('invoice01_0707.txt').readlines() > page = ''.join(content[:92]) > page = unicode(page, 'Latin-1') Why latin-1? Try page = unicode(page, 'cp852') > MakePdfInvoice('test.pdf', page) > > But it made funny chars somewhere. > > I tried it so eighter > > if __name__ == '__main__': > content = open('invoice01_0707.txt').readlines() > page = ''.join(content[:92]) > page = page.encode('cp852') Use decode() here, not encode(). decode() goes towards Unicode encode() goes away from Unicode As a mnemonic I think of Unicode as pure unencoded data. (This is *not* accurate, it is a memory aid!) Then it's easy to remember that decode() removes encoding == convert to Unicode, encode() adds encoding == convert from Unicode. > MakePdfInvoice('test.pdf', page) > > But it raised exception: > debugger.run(codeObject, __main__.__dict__, start_stepping=0) > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line > 60, in run > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line > 631, in run > exec cmd in globals, locals > File "D:\devel\reportlab\MakePdfInvoice.py", line 18, in ? > page = page.encode('cp852') > File "c:\Python24\lib\encodings\cp852.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 112: > ordinal not in range(128) When you call encode on a string (instead of a unicode object) the string is first decoded to Unicode using ascii encoding. This usually fails. Kent From jecarnell at saintfrancis.com Tue Sep 11 15:45:30 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Tue, 11 Sep 2007 08:45:30 -0500 Subject: [Tutor] Image Analysis In-Reply-To: Message-ID: "wormwood_3" wrote > I need some way to analyze an image for color patterns. > > My only lead right now is PIL, and I am not sure if it will meet my > needs. I am using PIL and numpy ##### something hat at least looks sorta like import numpy import PIL myImage = Image.open("C:\\file.bmp") myImage.assarray(stuff) I can't remember the code and am at work, but this will give you a big array to work with. Each pixel for RGB looks kind of like [100,150,250] then each line is in a matrix etc. It's a bit of a pain traversing the matrices, but you can do anything you would do to an array. Pyro Robotics also has a small tutorial about this. http://pyrorobotics.org/?page=PyroModuleVisionSystem From dperlman at wisc.edu Tue Sep 11 15:15:49 2007 From: dperlman at wisc.edu (David Perlman) Date: Tue, 11 Sep 2007 08:15:49 -0500 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <46E68C49.30205@gmail.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> <46E61C94.8000701@brunson.com> <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> <46E68C49.30205@gmail.com> Message-ID: Also keep in mind that if you want your code to work, your grammar and punctuation in code has to be absolutely flawless. Writing English well is excellent practice for writing code well; writing English poorly is excellent practice for writing code poorly. You get what you pay for. If you put in the effort, you will reap the reward. If you don't put in the effort, you will reap the reward of that instead, which is "teh suck"... :) On Sep 11, 2007, at 7:38 AM, Luke Paireepinart wrote: > max baseman wrote: >> lol sorry i was born with bad grammar and hand writing (although it's >> the bit after being born that matters) >> > Just imagine you're talking instead of writing. Everywhere you'd > put a > pause, put a comma. If it seems like the end of a sentence, put a > period. In most cases, even bad punctuation will be better than no > punctuation. People's inner monologues will just take on a > Christopher > Walken accent as they read over your e-mails, but this is arguably > not a > bad thing. > Grammar is something you can learn, not something inborn. Now is as > good > a time as any to start learning it. > -Luke > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- -dave---------------------------------------------------------------- All I ask is that the kind of unsolvable that it turns out to be has respectable precedents. -Jerry Fodor From timmichelsen at gmx-topmail.de Tue Sep 11 16:22:25 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 11 Sep 2007 16:22:25 +0200 Subject: [Tutor] input file encoding In-Reply-To: <46E64C74.9030303@timgolden.me.uk> References: <46E64C74.9030303@timgolden.me.uk> Message-ID: > Not sure what you mean by "standard encoding" (is this an Ubuntu > thing?) but essentially whenever you're pulling stuff into Python As it was lined out by others I was printing to a linux terminal which had the encoding set to UTF-8. Therefore and for further processing of the data I had to open it with the right encoding. > In this case, assuming you have files in iso-8859-1, something > like this: > > > import codecs > > filenames = ['a.txt', 'b.txt', 'c.txt'] > for filename in filenames: > f = codecs.open (filename, encoding="iso-8859-1") This piece of code did the trick. After a short adaption I had exactly what I wanted to achive. Thanks you for your help. From wormwood_3 at yahoo.com Tue Sep 11 16:42:32 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 11 Sep 2007 07:42:32 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <205832.8269.qm@web32403.mail.mud.yahoo.com> Thanks very much! This may be exactly what I need, and in any case will be a great starting point! -Sam ___________________________ ----- Original Message ---- From: "Carnell, James E" To: tutor at python.org Sent: Tuesday, September 11, 2007 9:45:30 AM Subject: Re: [Tutor] Image Analysis "wormwood_3" wrote > I need some way to analyze an image for color patterns. > > My only lead right now is PIL, and I am not sure if it will meet my > needs. I am using PIL and numpy ##### something hat at least looks sorta like import numpy import PIL myImage = Image.open("C:\\file.bmp") myImage.assarray(stuff) I can't remember the code and am at work, but this will give you a big array to work with. Each pixel for RGB looks kind of like [100,150,250] then each line is in a matrix etc. It's a bit of a pain traversing the matrices, but you can do anything you would do to an array. Pyro Robotics also has a small tutorial about this. http://pyrorobotics.org/?page=PyroModuleVisionSystem _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From silas428 at gmail.com Tue Sep 11 17:39:44 2007 From: silas428 at gmail.com (Ryan) Date: Tue, 11 Sep 2007 08:39:44 -0700 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: References: Message-ID: <46E6B6C0.8050205@gmail.com> Jan Erik Mostr?m wrote: > Ryan 07-09-10 15:35 > >> Once I edit the config files for cgi scripts the browser says I don't >> have permission to access the file. > > You must make sure that the script file has execute/read permissions > for the process/user who runs the apache server. On my ubuntu machine > that is 'www-data' > > jem I found the lines with 'www-data' but I am not sure what exactly I have to do. I have User and Group-www-data. From pacbaby27 at yahoo.com Tue Sep 11 17:36:18 2007 From: pacbaby27 at yahoo.com (Latasha Marks) Date: Tue, 11 Sep 2007 08:36:18 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <303826.19489.qm@web56401.mail.re3.yahoo.com> need help writting a program of pick up sticks. --------------------------------- Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070911/e2fc3fa8/attachment.htm From kent37 at tds.net Tue Sep 11 18:01:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 12:01:26 -0400 Subject: [Tutor] (no subject) In-Reply-To: <303826.19489.qm@web56401.mail.re3.yahoo.com> References: <303826.19489.qm@web56401.mail.re3.yahoo.com> Message-ID: <46E6BBD6.30707@tds.net> Latasha Marks wrote: > need help writting a program of pick up sticks. That is pretty vague. What help do you need? What do you want the program to do? Kent From noufal at airtelbroadband.in Tue Sep 11 18:16:40 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Tue, 11 Sep 2007 21:46:40 +0530 Subject: [Tutor] Running other files In-Reply-To: References: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> Message-ID: <46E6BF68.9050303@airtelbroadband.in> Rikard Bosnjakovic wrote: > On 10/09/2007, Lawrence Barrott wrote: > >> is it possible to run other non-python files using python such as .exe or >> other files. > > Have a look at os.system(). > Or more generally, the subprocess module. -- ~noufal From sacharook at hotmail.co.uk Tue Sep 11 18:18:18 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Tue, 11 Sep 2007 17:18:18 +0100 Subject: [Tutor] extract hosts from html write to file Message-ID: Hi I wonder if anyone can help with the following I am trying to read a html page extract only fully qualified hostnames from the page and output these hostnames to a file on disk to be used later as input to another program. I have this so far import urllib2f=open("c:/tmp/newfile.txt", "w")for line in urllib2.urlopen("http://www.somedomain.uk"): if "href" in line and "http://" in line: print line f.write(line)f.close()fu=open("c:/tmp/newfile.txt", "r") for line in fu.readlines(): print line so i have opened a file to write to, got a page of html, printed and written those to file that contain href & http:// references. closed file opened file read all the lines from file and printed out Can someone point me in right direction please on the flow of this program, the best way to just extract the hostnames and print these to file on disk? As you can see I am newish to this Thanks in advance for any help given! s _________________________________________________________________ Feel like a local wherever you go. http://www.backofmyhand.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070911/ebd60715/attachment.htm From srikanth007m at gmail.com Tue Sep 11 18:54:37 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 11 Sep 2007 22:24:37 +0530 Subject: [Tutor] automate daily tasks Message-ID: Hi all, I am working on MAC OS x my project is updating all ready installed products.I have to automate this in python.so,can any one will give some suggestions and some examples how to automate.some basic things of my project is ... i think u all know that there will be a plist file for each product in mac.i have to degrade the version of plist automatically through my script and it has to edit the plist file and degrade it to least version and as to check for updates by itself.like this there are 15 products under this now each time i can't go and degrade the version and save it and run updates manually..so,that can any one plz..tell me how to start from first step... -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070911/75c73c5e/attachment.htm From tktucker at gmail.com Tue Sep 11 19:03:54 2007 From: tktucker at gmail.com (Tom Tucker) Date: Tue, 11 Sep 2007 13:03:54 -0400 Subject: [Tutor] automate daily tasks In-Reply-To: References: Message-ID: <2a278ffe0709111003v5d89101fvebdcde704fc9a5b7@mail.gmail.com> Are you looking for a method to automate the execution of your Python program? Is that the question? If yes, have you tried using cron or at jobs (man cron or man at). Tom On 9/11/07, chinni wrote: > > Hi all, > > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give some > suggestions and some examples how to automate.some basic things of my > project is ... i think u all know that there will be a plist file for each > product in mac.i have to degrade the version of plist automatically > through my script and it has to edit the plist file and degrade it to least > version and as to check for updates by itself.like this there are 15 > products under this now each time i can't go and degrade the version and > save it and run updates manually..so,that can any one plz..tell me how to > start from first step... > > -- > Best Regards, > M.Srikanth Kumar, > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070911/ea45fd19/attachment.htm From alan.gauld at btinternet.com Tue Sep 11 19:37:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 18:37:33 +0100 Subject: [Tutor] automate daily tasks References: Message-ID: "chinni" wrote > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give > some sounds fair. > project is ... i think u all know that there will be a plist file > for each > product in mac. I wouldn't assume too much knowledge of how MacOS works, despite Apple's recent successes its still very much a minority OS! I own an iBook and use the Terminal for unix type stuff but I rarely delve inside the MacOs specifics. > i have to degrade the version of plist automatically through > my script and it has to edit the plist file and degrade it to least > version > and as to check for updates by itself.like this there are 15 > products under > this now each time i can't go and degrade the version and save it > and run > updates manually..so,that can any one plz..tell me how to start from > first > step... Nope, sorry. You lost me on that one. Can you give some example data formats. And maybe show us what you are trying to do with them? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brunson at brunson.com Tue Sep 11 19:46:00 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 11:46:00 -0600 Subject: [Tutor] extract hosts from html write to file In-Reply-To: References: Message-ID: <46E6D458.6020303@brunson.com> sacha rook wrote: > Hi I wonder if anyone can help with the following > > I am trying to read a html page extract only fully qualified hostnames > from the page and output these hostnames to a file on disk to be used > later as input to another program. > > I have this so far > > import urllib2 > f=open("c:/tmp/newfile.txt", "w") > for line in urllib2.urlopen("_http://www.somedomain.uk_ > "): > if "href" in line and "http://" in line: > print line > f.write(line) > f.close() > fu=open("c:/tmp/newfile.txt", "r") > > for line in fu.readlines(): > print line > > so i have opened a file to write to, got a page of html, printed and > written those to file that contain href & http:// references. > closed file opened file read all the lines from file and printed out > > Can someone point me in right direction please on the flow of this > program, the best way to just extract the hostnames and print these to > file on disk? I would start with a Regular Expression to match the text of the URL, it will match exactly the text of the URL and you can extract that. You can probably even find one in a web search. Read up on regular expressions to start with, they're extremely powerful, but a little bit of a learning curve to start with. Google "regular expression tutorial" or search the list archive for a reference. > > As you can see I am newish to this > > Thanks in advance for any help given! > > s > > ------------------------------------------------------------------------ > Do you know a place like the back of your hand? Share local knowledge > with BackOfMyHand.com > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From eric at ericwalstad.com Tue Sep 11 19:51:36 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 11 Sep 2007 10:51:36 -0700 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: <46E6B6C0.8050205@gmail.com> References: <46E6B6C0.8050205@gmail.com> Message-ID: <46E6D5A8.3050907@ericwalstad.com> Ryan wrote: > Jan Erik Mostr?m wrote: >> Ryan 07-09-10 15:35 >> >>> Once I edit the config files for cgi scripts the browser says I don't >>> have permission to access the file. >> You must make sure that the script file has execute/read permissions >> for the process/user who runs the apache server. On my ubuntu machine >> that is 'www-data' >> >> jem > I found the lines with 'www-data' but I am not sure what exactly I have > to do. I have User and Group-www-data. Hi Ryan, Have you RTFM? Googled for something like "apache file permission", etc? http://httpd.apache.org/docs/2.0/ http://httpd.apache.org/docs/2.0/howto/cgi.html http://www.google.com/search?q=apache+cgi+file+permission http://catb.org/~esr/faqs/smart-questions.html#before Eric. From dperlman at wisc.edu Wed Sep 12 00:20:03 2007 From: dperlman at wisc.edu (David Perlman) Date: Tue, 11 Sep 2007 17:20:03 -0500 Subject: [Tutor] automate daily tasks In-Reply-To: References: Message-ID: <22780F5F-E3CA-41E4-8E1F-DB8EAF2045EF@wisc.edu> As far as making something run automatically at various times, if you're certain that you want to do it in a Mac-only way, Apple's recommended method for timing jobs is described here: http://developer.apple.com/macosx/launchd.html "Getting started with launchd" otherwise use cron or at, as Tom said. On Sep 11, 2007, at 11:54 AM, chinni wrote: > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give > some suggestions and some examples how to automate.some basic > things of my project is ... i think u all know that there will be a > plist file for each product in mac.i have to degrade the version of > plist automatically through my script and it has to edit the plist > file and degrade it to least version and as to check for updates by > itself.like this there are 15 products under this now each time i > can't go and degrade the version and save it and run updates > manually..so,that can any one plz..tell me how to start from first > step... -- -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 kent37 at tds.net Wed Sep 12 00:29:43 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 18:29:43 -0400 Subject: [Tutor] extract hosts from html write to file In-Reply-To: References: Message-ID: <46E716D7.1010500@tds.net> sacha rook wrote: > Hi I wonder if anyone can help with the following > > I am trying to read a html page extract only fully qualified hostnames > from the page and output these hostnames to a file on disk to be used > later as input to another program. I would use BeautifulSoup to parse out the hrefs and urlparse.urlparse() to split the hostname out of the href. http://www.crummy.com/software/BeautifulSoup/documentation.html Kent From eike.welk at gmx.net Wed Sep 12 01:57:35 2007 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 12 Sep 2007 01:57:35 +0200 Subject: [Tutor] Image Analysis In-Reply-To: <15059.1222.qm@web32403.mail.mud.yahoo.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> Message-ID: <200709120157.35935.eike.welk@gmx.net> Hello Sam; if you seriously want to do image analysis, you should use Numpy, Scipy, and Matplotlib. Scipy has a sub-project named 'ndimage' which implements many common image analysis algorithms. You should also subscribe to the mailinglists of these projects. Numpy and Scipy: http://www.scipy.org/ Matplotlib: http://matplotlib.sourceforge.net/ A nice Python enhancement is Ipython: http://ipython.scipy.org/moin/ You should also bookmark this page: http://www.scipy.org/Numpy_Example_List I have written a little program, to illustrate how it works. The program tries to recognize red blood cells in a microscopic image (from Wikipedia). It also counts the cells and measures their diameter. (The program does not work very well, although I've spent way too much time on it.) I have attached the program, the input image, and the output image. Usage: Start Ipython with: ipython --pylab Then type: run "image.py" The program should run with regular Python as well. Kind regards, Eike. -------------- next part -------------- A non-text attachment was scrubbed... Name: image.py Type: application/x-python Size: 4144 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070912/aa19e71e/attachment-0001.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: Blood_smear.png Type: image/png Size: 391016 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070912/aa19e71e/attachment-0002.png -------------- next part -------------- A non-text attachment was scrubbed... Name: Blood-final-image.png Type: image/png Size: 392002 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070912/aa19e71e/attachment-0003.png From dkuhlman at rexx.com Wed Sep 12 05:09:36 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 11 Sep 2007 20:09:36 -0700 Subject: [Tutor] Image Analysis In-Reply-To: <200709120157.35935.eike.welk@gmx.net> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> Message-ID: <20070912030936.GA45033@cutter.rexx.com> On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > I have attached the program, the input image, and the output image. > Please do not stuff 1 MB emails in my mailbox. Either (1) post the images on the Web and provide a link or (2) ask before emailing large attachments. Thank you. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From ghashsnaga at gmail.com Wed Sep 12 05:12:59 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Tue, 11 Sep 2007 21:12:59 -0600 Subject: [Tutor] calling class instances in functions Message-ID: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Thank you for your help on classes. I am working on an old program I started in 2005. This time around I am trying to model cell behavior using a PD model. I have the main program and then a file called yeast_cell.py that contains the classes I want to instance. In the main program at the function def add_yeast(world): I want to instance the class GoodYeast and have the global variable @ change to G on the world. I tried just creating an instance but that did not go over so well. I was wondering what is the proper and pythonic way to create an instance that the user will be selecting in a function. I eventually want to add a bunch of different cell classes. Thank you for your help. Ara Kooser Main Program ######################################################################## #Yeast Cooperation Model #by Ara Kooser #Version 1.0 no PD, 070906 # #This code contain just the world setup and not the actually PD code #for copperation behavior. This is better left to classes not functions # #TO DO LIST: Add error handling, dump to text file, data gathering, #different classes of yeast # #Many thanks to: Danny Yoo, Lee Haar, Max Noel, Kent Johnson ######################################################################## import random import copy import textwrap import yeast_cell ######################################################################### #This section of the code sets up and prints out the starting conditions #of the world and the yeast ######################################################################## YEAST, EMPTY, GROUP = '@', '.', 'Q' def percolation(perc): #Sets up a percolation threshold value randval = random.random() if randval > perc: return EMPTY else: return YEAST def random_world(M, N): #Constructs random world of size MxN world = {} for j in range(N): for i in range(M): world[i, j] = percolation(perc) world['dimensions'] = (M, N) return world def print_world(world): #Prints out a string representation of a world. M, N = world['dimensions'] for j in range(N): for i in range(M): print world[i, j], print def add_yeast(world): #Allows the user to add a yeast cell at point m,n M,N = world['dimensions'] new_world = copy.copy(world) counta = 0 yy = raw_input("How many yeast cells do you wish to add?") yy = int(yy) while counta References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: <5e58f2e40709112103r7e246238l9d65caf2222380e4@mail.gmail.com> I'm not sure I understnad your quesiton.. You can put classes into lists, dictionaries, et cetera. For example: ## class Foo(object): pass class Bar(object): pass class Baz(object): pass my_classes = { 'foo':Foo, 'bar':Bar, 'baz':Baz } thing = my_classes['bar']() ## It seems quite strange to me, though, to have the instantiation of a class change a global variable. Maybe you could do something like this: ## class GoodYeast(object): pass # etc class BadYeast(object): pass # etc class World(object): yeasts = { 'good':GoodYeast, 'bad':'BadYeast } def init(self): self.yeast = None def setYeast(self, yeast): self.yeast = self.yeasts[yeast]() w = World() w.setYeast('good') ## But I confess that I have not read or run your code, so I'm not sure if this is the best way forward for you.. -- John. From brunson at brunson.com Wed Sep 12 07:10:27 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 23:10:27 -0600 Subject: [Tutor] Image Analysis In-Reply-To: <20070912030936.GA45033@cutter.rexx.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> Message-ID: <46E774C3.4090405@brunson.com> Just my opinion, but I didn't mind the attachments, I felt they added quite a bit to the discussion and I certainly appreciated the input on the application of the libraries. My opinion on your tone, I'll keep to myself. Dave Kuhlman wrote: > On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > > >> I have attached the program, the input image, and the output image. >> >> > > Please do not stuff 1 MB emails in my mailbox. Either (1) post the > images on the Web and provide a link or (2) ask before emailing > large attachments. > > Thank you. > > Dave > > > From bill at celestial.net Wed Sep 12 07:40:11 2007 From: bill at celestial.net (Bill Campbell) Date: Tue, 11 Sep 2007 22:40:11 -0700 Subject: [Tutor] Image Analysis In-Reply-To: <46E774C3.4090405@brunson.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> <46E774C3.4090405@brunson.com> Message-ID: <20070912054011.GA5480@ayn.mi.celestial.com> On Tue, Sep 11, 2007, Eric Brunson wrote: > >Just my opinion, but I didn't mind the attachments, I felt they added >quite a bit to the discussion and I certainly appreciated the input on >the application of the libraries. > >My opinion on your tone, I'll keep to myself. Figure out the total size sending a megabyte+ mail message to hundreds of list recipients. Most mailing lists limit the size of messages to 40k or less. While large messages aren't much of an issue on broadband connections, they can be a problem for those on dialup or with tight disk quotas. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 We'll show the world we are prosperous, even if we have to go broke to do it. Will Rogers From alan.gauld at btinternet.com Wed Sep 12 09:59:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 08:59:00 +0100 Subject: [Tutor] calling class instances in functions References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: "Ara Kooser" wrote > In the main program at the function def add_yeast(world): I want to > instance the class GoodYeast and have the global variable @ change > to > G on the world. I tried just creating an instance but that did not > go > over so well. "did no go over so well" is not very useful to us. Can you be a bit more specific? How did you create the instance? What happened? Did you get an error message? If so what? Can you show us the specific code where you create the instance? I don't see it in the code you posted? But theres rather a lot. Can you show us a shorter example of what you are trying to do? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Sep 12 13:24:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 07:24:12 -0400 Subject: [Tutor] Image Analysis In-Reply-To: <20070912054011.GA5480@ayn.mi.celestial.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> <46E774C3.4090405@brunson.com> <20070912054011.GA5480@ayn.mi.celestial.com> Message-ID: <46E7CC5C.5090204@tds.net> Bill Campbell wrote: > Most mailing lists limit the size > of messages to 40k or less. On this list large messages go to moderation. I think I was so captivated with the images that I forgot about the size. A better way to present this would be to put the images on a web site and reference them from email. Sorry about that... Kent From kent37 at tds.net Wed Sep 12 13:33:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 07:33:20 -0400 Subject: [Tutor] calling class instances in functions In-Reply-To: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: <46E7CE80.2000608@tds.net> Ara Kooser wrote: Your question is not very clear but I made some guesses below. > zz = raw_iput("What kind of yeast cell do you want to add? > Options:GoodYeast") > #Here I want to call this instace of GoodYeast from yeast_cell.py So you want the user to input the name of a class and you create an instance of the class? Try cls = getattr(yeast_cell, zz) instance = cls() > class GoodYeast: > #Cooperates all the time > YEAST = 'G' > #Should change generic variable @ in the world to G??? This is just assigning a class variable. The assignment is made at the time the class is defined, not when an instance is created, so that is not what you want either. > def __init__(self,name): > self.name = name > currency = 0 > location = [] I agree with John that changing a global variable in another module when a class instance is created doesn't seem like a great design, but you can do it here with import main # or whatever the main module is called main.YEAST = 'G' In general it is good to avoid circular dependencies like this, they lead to a variety of complications. Maybe YEAST could be a variable in the yeast_cell module? Kent From janos.juhasz at VELUX.com Wed Sep 12 14:00:30 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 12 Sep 2007 14:00:30 +0200 Subject: [Tutor] Unicode question In-Reply-To: <46E69CE4.9000803@tds.net> Message-ID: Dear Kent, thanks for your respond. It is clear now. > As a mnemonic I think of Unicode as pure unencoded data. (This is *not* > accurate, it is a memory aid!) Then it's easy to remember that decode() > removes encoding == convert to Unicode, encode() adds encoding == > convert from Unicode. So I had to convert cp852 ascii file into unicode, that can be made with page.decode('cp852') There was another problem also about, o with double acute and O with double acute, as they were missed from the font files. It works well now. from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import pagesizes from reportlab.lib.units import cm PAGE_HEIGHT=defaultPageSize[1] import copy styles = getSampleStyleSheet() InvStyle = copy.deepcopy(styles["Normal"]) InvStyle.fontSize = 8 InvStyle.leading = 9 InvStyle.fontName = 'Courier' InvLineNum = 92 im = Image("bimbambumm.bmp", width=100, height=35) im.hAlign = 'RIGHT' def MakePdfInvoice(InvoiceNum, pages): PdfInv = [] for page in pages: PdfInv.append(im) PdfInv.append(Preformatted(page, InvStyle)) PdfInv.append(PageBreak()) PdfInv = PdfInv[:-1] doc = SimpleDocTemplate(InvoiceNum) doc.topMargin = 1*cm doc.bottomMargin = 0 doc.leftMargin = 0 doc.rightMArgin = 0 doc.build(PdfInv) def BreakIntoPages(content): while len(content) > InvLineNum: page = content[:InvLineNum] content = content[InvLineNum:] yield page else: yield content if __name__ == '__main__': content = open('invoice01_0707.txt').readlines() content = [line.replace('\x8a','\x99').replace('\x8b','\x94') for line in content] pages = [] for page in BreakIntoPages(content): page = ''.join(page) pages.append(page.decode('cp852')) MakePdfInvoice('test.pdf', pages) Kent Johnson wrote on 2007.09.11 15:49:24: > J?nos Juh?sz wrote: > > Dear All, > > > > I would like to convert my DOS txt file into pdf with reportlab. > > The file can be seen correctly in Central European (DOS) encoding in > > Explorer. > > > > My winxp uses cp852 as default codepage. > > > > When I open the txt file in notepad and set OEM/DOS script for terminal > > fonts, it shows the file correctly. > > > > I tried to convert the file with the next way: > > > Use decode() here, not encode(). > decode() goes towards Unicode > encode() goes away from Unicode > As a mnemonic I think of Unicode as pure unencoded data. (This is *not* > accurate, it is a memory aid!) Then it's easy to remember that decode() > removes encoding == convert to Unicode, encode() adds encoding == > convert from Unicode. > > MakePdfInvoice('test.pdf', page) > > > > But it raised exception: > > ordinal not in range(128) > When you call encode on a string (instead of a unicode object) the > string is first decoded to Unicode using ascii encoding. This usually fails. > Kent From wormwood_3 at yahoo.com Wed Sep 12 15:21:28 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 12 Sep 2007 06:21:28 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <443787.8228.qm@web32405.mail.mud.yahoo.com> Very strange. This is the second time that I know of in the last month that I have not received some emails from the list. I did not get the message Eike Welk sent out. Checking archives... ----- Original Message ---- From: Dave Kuhlman To: tutor at python.org Sent: Tuesday, September 11, 2007 11:09:36 PM Subject: Re: [Tutor] Image Analysis On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > I have attached the program, the input image, and the output image. > Please do not stuff 1 MB emails in my mailbox. Either (1) post the images on the Web and provide a link or (2) ask before emailing large attachments. Thank you. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From mlangford.cs03 at gtalumni.org Wed Sep 12 15:38:18 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 12 Sep 2007 09:38:18 -0400 Subject: [Tutor] calling class instances in functions In-Reply-To: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: <82b4f5810709120638v17f89247i40fd6331c511e8b8@mail.gmail.com> I too am a little confused what exactly you're going for, but here is a shot at the two things I think you could be asking for: If you're trying to create a world where you have it populated with several different types of cells at different coordinates, and you'd like to make it so the user can select one of the already created cells, I suggest making a class for the world, and having its str method create a text list something like so you can use it for printing out to the user if they need to interact with the individual cells. 1. Yeast(0,4) 2. Malaria(5,6) 3. Gondrii(5,8) 4. Yeast(5,9) ... Etc. World would use getattr to get the name of the class of each cell on it, and would append the position. I'd make a function that will be able to get cells based on the number that the user selected. Also, a dictionary keyed off a positions tuple will probably work just fine for your world and will also be a lot easier and faster to access and enumerate, especially if you make the field very very large. ie, You could populate the world like this non interactively: world_data = {} word_data[(0,4)] = Yeast() word_data[(5,6)] = Malaria() word_data[(5,8)] = Gondrii() word_data[(5,9)] = Yeast() ================ Now if I've misunderstood, and you're talking about making NEW cells of various types and the user dynamically tells you what places to put what cells, here is how you do that. In your main, I would collect a list of all the types of microbes you can create and cycle through them to get their names, and use the users choices to make them and use the users choice of position to insert them in the world: myWorld = World() theMicrobes = [Yeast,Malaria,Gondrii] print "Please type the name of the microbe you wish to create:" for each in theMicrobes: cls = getattr(each,"__class__") print cls.__name__ microbeToCreateRaw= raw_input() # #do some stuff here to cleanup the input # for each in theMicrobes: cls = getattr(each,"__class__") if microbeToCreate == cls.__name__: newMicrobe = cls() #Now you find where they wish to drop it in the world print "Where do you want it in the world?" rawCoords = raw_input() #parse out the x and y # # Left to the reader to parse out # myWorld.insertAt(newMicrobe,x,y) #assuming you made a class for the world --Michael On 9/11/07, Ara Kooser wrote: > > Thank you for your help on classes. I am working on an old program I > started in 2005. This time around I am trying to model cell behavior > using a PD model. I have the main program and then a file called > yeast_cell.py that contains the classes I want to instance. > > In the main program at the function def add_yeast(world): I want to > instance the class GoodYeast and have the global variable @ change to > G on the world. I tried just creating an instance but that did not go > over so well. I was wondering what is the proper and pythonic way to > create an instance that the user will be selecting in a function. I > eventually want to add a bunch of different cell classes. > > Thank you for your help. > > Ara Kooser > > > Main Program > ######################################################################## > #Yeast Cooperation Model > #by Ara Kooser > #Version 1.0 no PD, 070906 > # > #This code contain just the world setup and not the actually PD code > #for copperation behavior. This is better left to classes not functions > # > #TO DO LIST: Add error handling, dump to text file, data gathering, > #different classes of yeast > # > #Many thanks to: Danny Yoo, Lee Haar, Max Noel, Kent Johnson > ######################################################################## > > import random > import copy > import textwrap > import yeast_cell > > > ######################################################################### > #This section of the code sets up and prints out the starting conditions > #of the world and the yeast > ######################################################################## > > > YEAST, EMPTY, GROUP = '@', '.', 'Q' > > > def percolation(perc): > #Sets up a percolation threshold value > randval = random.random() > if randval > perc: > return EMPTY > else: > return YEAST > > def random_world(M, N): > #Constructs random world of size MxN > world = {} > for j in range(N): > for i in range(M): > world[i, j] = percolation(perc) > world['dimensions'] = (M, N) > return world > > def print_world(world): > #Prints out a string representation of a world. > M, N = world['dimensions'] > for j in range(N): > for i in range(M): > print world[i, j], > print > > > def add_yeast(world): > #Allows the user to add a yeast cell at point m,n > M,N = world['dimensions'] > new_world = copy.copy(world) > > counta = 0 > > yy = raw_input("How many yeast cells do you wish to add?") > yy = int(yy) > > while counta zz = raw_iput("What kind of yeast cell do you want to add? > Options:GoodYeast") > #Here I want to call this instace of GoodYeast from yeast_cell.py > > > print "Please place this yeast cell using an m,n point" > print "The upper left hand corner is (0,0)" > i = int(raw_input("Please enter a m value for the yeast cell.")) > j = int(raw_input("Please enter a n value for the yeast cell.")) > > new_world[i,j] = YEAST > for j in range(N): > for i in range(M): > world[i,j]=new_world[i,j] > > counta = counta+1 > > print_world(small_world) > > > ################################## > #The following code gets the state of the world and determines > #what is next to each cell, sensing > ################################# > > def get_state(world,i,j): > #Returns the state of the cell at position (i,j) > return world.get((i,j), EMPTY) > > def count_neighbors(world,i,j): > #Returns the number of cells next to this one > live_count = 0 > for i_delta in [-1,0,1]: > for j_delta in [-1,0,1]: > if(i_delta,j_delta)==(0,0): > continue > if get_state(world, i+i_delta, j+j_delta)==YEAST: > live_count+=1 > return live_count > > def is_grouped(world,i,j): > #Returns a true value if the cell at (i,j) is connected by 1-8 others > return(get_state(world,i,j)==YEAST and > (1 <=count_neighbors(world,i,j)<=8)) > > def next_world(world): > #Shows which yeast are in a group using Q > M,N = world['dimensions'] > new_world=copy.copy(world) > for j in range(N): > for i in range(M): > if is_grouped(world,i,j): > new_world[i,j] = GROUP > for j in range(N): > for i in range(M): > world[i,j]=new_world[i,j] > > def AddYeast(): > print "If you selected 0 for your percolation you may now add > yeast to the world." > print "The upper left hand corner is point (0,0)." > zz = raw_input("Do you want to add a yeast cell? y or n") > if zz == "y": > add_yeast(small_world) > > elif zz == "n": > print_world(small_world) > > raw_input("Please press return to group your yeast cells.") > > ##################################################### > #This is where the PD portion of the program starts > ##################################################### > > def PD_yeast(): > print textwrap.fill ("The PD will added later in the OOP version") > print"REFERENCES" > print textwrap.fill ("Learning to program. By Alan Gauld") > print textwrap.fill ("How to Think Like a Computer Scientist. By > Downey, Elkner, and Meyers") > print textwrap.fill("Cooperation amoung Microorganisms. Wingreen > and Levin.") > print textwrap.fill ("Synthetic cooperation in engineered yeast > populations. Shou, Ram, and Vilar") > print textwrap.fill ("Evolution in group-structured populations > can resolve the tragedy of the commons. Killingback, Bieri, and > Flatt") > > > ############################################################################### > #Start of program > > ############################################################################### > > > > raw_input("Please press return to start the program.") > > perc = raw_input("Please enter a thresold between 0-1 for the > population.") > perc = float(perc) > > > n = int(raw_input("Please enter a n dimension. ")) > m = int(raw_input("Please enter a m dimension. ")) > > > small_world = random_world(m,n) > > print_world(small_world) > > AddYeast() > > next_world(small_world) > print_world(small_world) > > print "Q indictates that the yeast cells found a group." > print > print > print "Please press return to start the PD program." > print > print > > > PD_yeast() > > > yeast_cell.py > ############################################################### > #yeast_cell.py > #Contains the different types of yeast behavior > #By Ara Kooser > ############################################################### > > > #0 = cooperate > #1 = defect > > > class GoodYeast: > #Cooperates all the time > YEAST = 'G' > #Should change generic variable @ in the world to G??? > def __init__(self,name): > self.name = name > currency = 0 > location = [] > > def response(self): > return 0 > > def location(world,i,j): > return world.get(i,j) > #I believe this allows the cell to know it's coordinates > > > -- > Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis > an sub cardine glacialis ursae. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/744c4289/attachment-0001.htm From wormwood_3 at yahoo.com Wed Sep 12 15:43:35 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 12 Sep 2007 06:43:35 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <75672.43946.qm@web32413.mail.mud.yahoo.com> Could not find it. The searchable interface at ActiveState's site does not have it, and I don't know of any way to search the zipped archives... Eike, if you would be able to send me your post, even just to my address and not the tutor list, I would greatly appreciate it! Seems it had some neat things in it. -Sam ----- Original Message ---- From: wormwood_3 To: Python Tutorlist Sent: Wednesday, September 12, 2007 9:21:28 AM Subject: Re: [Tutor] Image Analysis Very strange. This is the second time that I know of in the last month that I have not received some emails from the list. I did not get the message Eike Welk sent out. Checking archives... ----- Original Message ---- From: Dave Kuhlman To: tutor at python.org Sent: Tuesday, September 11, 2007 11:09:36 PM Subject: Re: [Tutor] Image Analysis On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > I have attached the program, the input image, and the output image. > Please do not stuff 1 MB emails in my mailbox. Either (1) post the images on the Web and provide a link or (2) ask before emailing large attachments. Thank you. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From python at mrfab.info Wed Sep 12 15:58:46 2007 From: python at mrfab.info (Michael) Date: Wed, 12 Sep 2007 21:58:46 +0800 Subject: [Tutor] interpreted or compiled? Message-ID: <46E7F096.8050408@mrfab.info> Hi As a new Python user I was curious if you can run Python without the environment, ie make it an executable? Thanks Michael From kent37 at tds.net Wed Sep 12 16:14:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 10:14:20 -0400 Subject: [Tutor] Image Analysis In-Reply-To: <75672.43946.qm@web32413.mail.mud.yahoo.com> References: <75672.43946.qm@web32413.mail.mud.yahoo.com> Message-ID: <46E7F43C.3060604@tds.net> wormwood_3 wrote: > Could not find it. The searchable interface at ActiveState's site does not have it, and I don't know of any way to search the zipped archives... There is a plaintext archive at http://mail.python.org/pipermail/tutor/ Here is the post you want though without the attachments: http://mail.python.org/pipermail/tutor/2007-September/057012.html Kent From wormwood_3 at yahoo.com Wed Sep 12 16:19:28 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 12 Sep 2007 07:19:28 -0700 (PDT) Subject: [Tutor] interpreted or compiled? Message-ID: <836611.73027.qm@web32403.mail.mud.yahoo.com> Michael, The most common method I know of to do this is py2exe: http://www.py2exe.org/ This lets you turn scripts into executable Windows programs. A different, and perhaps better, method is PyInstaller: http://pyinstaller.python-hosting.com/ This creates executables for Windows and Linux. If you just meant run a script without calling Python, you can add the she-bang line (#!/usr/bin/python as the first line. Change to wherever Python lives on your system), and make the file executable (this is all assuming you are on Linux, sorry). Then you can just do "./mycoolscript.py" and run it. Hope these help! -Sam ----- Original Message ---- From: Michael To: tutor at python.org Sent: Wednesday, September 12, 2007 9:58:46 AM Subject: [Tutor] interpreted or compiled? Hi As a new Python user I was curious if you can run Python without the environment, ie make it an executable? Thanks Michael _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From python at mrfab.info Wed Sep 12 16:27:27 2007 From: python at mrfab.info (Michael) Date: Wed, 12 Sep 2007 22:27:27 +0800 Subject: [Tutor] interpreted or compiled? In-Reply-To: <836611.73027.qm@web32403.mail.mud.yahoo.com> References: <836611.73027.qm@web32403.mail.mud.yahoo.com> Message-ID: <46E7F74F.5050405@mrfab.info> wormwood_3 wrote: > Michael, > > The most common method I know of to do this is py2exe: http://www.py2exe.org/ This lets you turn scripts into executable Windows programs. > > A different, and perhaps better, method is PyInstaller: http://pyinstaller.python-hosting.com/ This creates executables for Windows and Linux. > > If you just meant run a script without calling Python, you can add the she-bang line (#!/usr/bin/python as the first line. Change to wherever Python lives on your system), and make the file executable (this is all assuming you are on Linux, sorry). Then you can just do "./mycoolscript.py" and run it. > > Hope these help! > > -Sam > > ----- Original Message ---- > From: Michael > To: tutor at python.org > Sent: Wednesday, September 12, 2007 9:58:46 AM > Subject: [Tutor] interpreted or compiled? > > Hi > > As a new Python user I was curious if you can run Python without the > environment, ie make it an executable? > > Thanks > > Michael > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Thanks guys. Amazingly quick response. From srikanth007m at gmail.com Wed Sep 12 16:39:12 2007 From: srikanth007m at gmail.com (chinni) Date: Wed, 12 Sep 2007 20:09:12 +0530 Subject: [Tutor] Tutor Digest, Vol 43, Issue 36 In-Reply-To: References: Message-ID: Hi, Thanx for Responding for the Query. The actual Output what i want is my python script has to change the version number(degrade) in plist file.and automatically change the time to 25 hrs more from present time cause my product will check for updates for every 25hrs. But u all told that cronjob and at inbuilt features of UNIX but every time ihave to manually go and change the version.i can't so that's why i want to write a script for this 1.open the app 2.degrade the version automatically to least version 3.change the time to 25hrs more 4.check for updates(1.force Update and silent update) 5.the whole procedure is for admin and non-admin users can i implement this by using both python and shell scripting.if possible give the reference book for quick learn. > > > Message: 2 > Date: Tue, 11 Sep 2007 22:24:37 +0530 > From: chinni > Subject: [Tutor] automate daily tasks > To: tutor at python.org > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Hi all, > > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give some > suggestions and some examples how to automate.some basic things of my > project is ... i think u all know that there will be a plist file for each > product in mac.i have to degrade the version of plist automatically > through > my script and it has to edit the plist file and degrade it to least > version > and as to check for updates by itself.like this there are 15 products > under > this now each time i can't go and degrade the version and save it and run > updates manually..so,that can any one plz..tell me how to start from first > step... > > -- > Best Regards, > M.Srikanth Kumar, > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20070911/75c73c5e/attachment-0001.htm > > ------------------------------ > > Message: 3 > Date: Tue, 11 Sep 2007 13:03:54 -0400 > From: "Tom Tucker" > Subject: Re: [Tutor] automate daily tasks > To: srikanthkumar007m at rediffmail.com > Cc: tutor at python.org > Message-ID: > <2a278ffe0709111003v5d89101fvebdcde704fc9a5b7 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Are you looking for a method to automate the execution of your Python > program? Is that the question? > If yes, have you tried using cron or at jobs (man cron or man at). > > Tom > > On 9/11/07, chinni wrote: > > > > Hi all, > > > > I am working on MAC OS x my project is updating all ready installed > > products.I have to automate this in python.so,can any one will give some > > suggestions and some examples how to automate.some basic things of my > > project is ... i think u all know that there will be a plist file for > each > > product in mac.i have to degrade the version of plist automatically > > through my script and it has to edit the plist file and degrade it to > least > > version and as to check for updates by itself.like this there are 15 > > products under this now each time i can't go and degrade the version and > > save it and run updates manually..so,that can any one plz..tell me how > to > > start from first step... > > > > -- > > Best Regards, > > M.Srikanth Kumar, > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20070911/ea45fd19/attachment-0001.htm > > ------------------------------ > > Message: 4 > Date: Tue, 11 Sep 2007 18:37:33 +0100 > From: "Alan Gauld" > Subject: Re: [Tutor] automate daily tasks > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "chinni" wrote > > > I am working on MAC OS x my project is updating all ready installed > > products.I have to automate this in python.so,can any one will give > > some > > sounds fair. > > > project is ... i think u all know that there will be a plist file > > for each > > product in mac. > > I wouldn't assume too much knowledge of how MacOS works, > despite Apple's recent successes its still very much a > minority OS! I own an iBook and use the Terminal for unix > type stuff but I rarely delve inside the MacOs specifics. > > > i have to degrade the version of plist automatically through > > my script and it has to edit the plist file and degrade it to least > > version > > and as to check for updates by itself.like this there are 15 > > products under > > this now each time i can't go and degrade the version and save it > > and run > > updates manually..so,that can any one plz..tell me how to start from > > first > > step... > > Nope, sorry. You lost me on that one. > Can you give some example data formats. > And maybe show us what you are trying to do with them? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/3966890a/attachment.htm From eike.welk at gmx.net Wed Sep 12 16:40:52 2007 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 12 Sep 2007 16:40:52 +0200 Subject: [Tutor] Image Analysis In-Reply-To: <75672.43946.qm@web32413.mail.mud.yahoo.com> References: <75672.43946.qm@web32413.mail.mud.yahoo.com> Message-ID: <200709121640.53212.eike.welk@gmx.net> On Wednesday 12 September 2007 15:43, wormwood_3 wrote: > Eike, if you would be able to send me your post, even just to my > address and not the tutor list, I would greatly appreciate it! > Seems it had some neat things in it. I've sent it to your e-mail address (wormwood_3 at yahoo.com). From eike.welk at gmx.net Wed Sep 12 17:05:01 2007 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 12 Sep 2007 17:05:01 +0200 Subject: [Tutor] Image Analysis In-Reply-To: <20070912030936.GA45033@cutter.rexx.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> Message-ID: <200709121705.02818.eike.welk@gmx.net> On Wednesday 12 September 2007 05:09, Dave Kuhlman wrote: > Please do not stuff 1 MB emails in my mailbox. Either (1) post the > images on the Web and provide a link or (2) ask before emailing > large attachments. Sorry! I guess I'm spoiled by my ADSL connection. I did not know that the limit is so low (40 KB). I did really consider to put the images on a web server, but the Berlios ftp server was down last night. (It's the only one where I have bookmarked the upload directory.) It was also late and I wanted to send the message before it would become pointless; so I sent it with the images attached. To the moderators: Thank you for posting my big message. Kind regards, Eike. From tktucker at gmail.com Wed Sep 12 17:06:28 2007 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 12 Sep 2007 11:06:28 -0400 Subject: [Tutor] Tutor Digest, Vol 43, Issue 36 In-Reply-To: References: Message-ID: <2a278ffe0709120806i7f86a62avc3caef70e2a5440a@mail.gmail.com> Comments below. On 9/12/07, chinni wrote: > > Hi, > Thanx for Responding for the Query. > The actual Output what i want is my python script has to change the > version number(degrade) in plist file.and automatically change the time to > 25 hrs more from present time cause my product will check for updates for > every 25hrs. > But u all told that cronjob and at inbuilt features of UNIX but every time > ihave to manually go and change the version.i can't so that's why i want > to write a script for this > > 1.open the app > 2.degrade the version automatically to least version What is the manual process for this task? More info is need here. Is plist a text file? 3.change the time to 25hrs more Are we changing the system time 25 hours ahead, changing a time variable in the script, or flag/timestamp in the plist file? 4.check for updates(1.force Update and silent update) This is achievable with a system call. 5.the whole procedure is for admin and non-admin users We change the unix file permission to restrict which user and groups are allowed access to the file. can i implement this by using both python and shell scripting.if possible > give the reference book for quick learn. >From what we know so far, yes. Please share what you have coded so far. Message: 2 > > Date: Tue, 11 Sep 2007 22:24:37 +0530 > > From: chinni > > Subject: [Tutor] automate daily tasks > > To: tutor at python.org > > Message-ID: > > > > Content-Type: text/plain; charset="iso-8859-1" > > > > Hi all, > > > > I am working on MAC OS x my project is updating all ready installed > > products.I have to automate this in python.so,can any one will give some > > suggestions and some examples how to automate.some basic things of my > > project is ... i think u all know that there will be a plist file for > > each > > product in mac.i have to degrade the version of plist automatically > > through > > my script and it has to edit the plist file and degrade it to least > > version > > and as to check for updates by itself.like this there are 15 products > > under > > this now each time i can't go and degrade the version and save it and > > run > > updates manually..so,that can any one plz..tell me how to start from > > first > > step... > > > > -- > > Best Regards, > > M.Srikanth Kumar, > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > http://mail.python.org/pipermail/tutor/attachments/20070911/75c73c5e/attachment-0001.htm > > > > ------------------------------ > > > > Message: 3 > > Date: Tue, 11 Sep 2007 13:03:54 -0400 > > From: "Tom Tucker" < tktucker at gmail.com> > > Subject: Re: [Tutor] automate daily tasks > > To: srikanthkumar007m at rediffmail.com > > Cc: tutor at python.org > > Message-ID: > > <2a278ffe0709111003v5d89101fvebdcde704fc9a5b7 at mail.gmail.com> > > Content-Type: text/plain; charset="iso-8859-1" > > > > Are you looking for a method to automate the execution of your Python > > program? Is that the question? > > If yes, have you tried using cron or at jobs (man cron or man at). > > > > Tom > > > > On 9/11/07, chinni < srikanth007m at gmail.com> wrote: > > > > > > Hi all, > > > > > > I am working on MAC OS x my project is updating all ready installed > > > products.I have to automate this in python.so,can any one will give > > some > > > suggestions and some examples how to automate.some basic things of my > > > project is ... i think u all know that there will be a plist file for > > each > > > product in mac.i have to degrade the version of plist automatically > > > through my script and it has to edit the plist file and degrade it to > > least > > > version and as to check for updates by itself.like this there are 15 > > > products under this now each time i can't go and degrade the version > > and > > > save it and run updates manually..so,that can any one plz..tell me how > > to > > > start from first step... > > > > > > -- > > > Best Regards, > > > M.Srikanth Kumar, > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: http://mail.python.org/pipermail/tutor/attachments/20070911/ea45fd19/attachment-0001.htm > > > > > > ------------------------------ > > > > Message: 4 > > Date: Tue, 11 Sep 2007 18:37:33 +0100 > > From: "Alan Gauld" > > Subject: Re: [Tutor] automate daily tasks > > To: tutor at python.org > > Message-ID: > > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > > reply-type=original > > > > > > "chinni" wrote > > > > > I am working on MAC OS x my project is updating all ready installed > > > products.I have to automate this in python.so,can any one will give > > > some > > > > sounds fair. > > > > > project is ... i think u all know that there will be a plist file > > > for each > > > product in mac. > > > > I wouldn't assume too much knowledge of how MacOS works, > > despite Apple's recent successes its still very much a > > minority OS! I own an iBook and use the Terminal for unix > > type stuff but I rarely delve inside the MacOs specifics. > > > > > i have to degrade the version of plist automatically through > > > my script and it has to edit the plist file and degrade it to least > > > version > > > and as to check for updates by itself.like this there are 15 > > > products under > > > this now each time i can't go and degrade the version and save it > > > and run > > > updates manually..so,that can any one plz..tell me how to start from > > > first > > > step... > > > > Nope, sorry. You lost me on that one. > > Can you give some example data formats. > > And maybe show us what you are trying to do with them? > > > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > > > > > > > > > -- > Best Regards, > M.Srikanth Kumar, > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/2c1c4a01/attachment.htm From abooth at stanford.edu Wed Sep 12 17:35:48 2007 From: abooth at stanford.edu (Ashley Booth) Date: Wed, 12 Sep 2007 08:35:48 -0700 Subject: [Tutor] Making a python script to feed files into another pythonscript In-Reply-To: References: Message-ID: Unfortunately I was confused by both responses I received. I have only been working with Python for a week, so everything is new. Thanks for your patience. John- I was not sure what you meant by "command line". I took what you said quite literally and created this: indir = raw_input('input directory path ') # asks for input directory script1 = raw_input('python script path ') # asks for path to desired script for j in os.listdir(indir): input = os.path.join(indir,j) output = os.path.join(indir,j.split('rovctd')[0]+'.txt') os.system('python %s %s %s' % (script1, input, output) which does not run and I was confused by all the % symbols. I think I completely misinterpreted your comment. Alan-I am confused about how to used the communicate() module. Could you please give me an example? the format should be(?): communicate(input=None) where input is the file path I want to give my child process (script1) (what if I have two files paths I need to give it?- one for the input file path and one for the output? and I want to put PIPE and not None so that it will deliver that input? What I was trying to say before at the end of my post: > I would at least be happy with how to tack on the list > directory stuff to THE END of the script1- it would not be a > stand alone script but at least it would work. In other words, instead of having a stand alone script that feeds files into script1 (the program I want the files to be fed into-it reformats files so it requires a file path input and output), could I have script1 ask me for a directory instead of a specific input and output file path as it does now. Then it would theoretically go through and reformat each file in that directory, rename them and put the formatted files back in that directory. I hope that is clearer. Thanks again! From agunnerson at gmail.com Wed Sep 12 17:45:48 2007 From: agunnerson at gmail.com (Andy) Date: Wed, 12 Sep 2007 09:45:48 -0600 Subject: [Tutor] Would an emulator be possible in Python? Message-ID: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> Ok, I'm pretty sure the answer is no but I'm hoping that someone will prove me wrong. I have decided that I would like to try and write an emulator, I'm going to start out with a couple of simpler systems like the Chip 8 and maybe a well documented arcade game but I would like to do an NES emulator eventually. Is Python anywhere near fast enough to do this and have it be playable? I hope so because I really don't like C/C++. -- -Andy "I have a great faith in fools; self-confidence my friends call it." ? Edgar Allen Poe From kent37 at tds.net Wed Sep 12 19:31:40 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 13:31:40 -0400 Subject: [Tutor] Would an emulator be possible in Python? In-Reply-To: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> References: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> Message-ID: <46E8227C.7000702@tds.net> Andy wrote: > Ok, I'm pretty sure the answer is no but I'm hoping that someone will > prove me wrong. I have decided that I would like to try and write an > emulator, I'm going to start out with a couple of simpler systems like > the Chip 8 and maybe a well documented arcade game but I would like to > do an NES emulator eventually. Is Python anywhere near fast enough to > do this and have it be playable? I hope so because I really don't > like C/C++. GIYF... Chip8 emulator, they claim it is *too* fast! http://www.pygame.org/projects/20/190/ Apparently Java was fast enough in 2003: http://www.peterbe.com/plog/blogitem-20031211-1300 Kent From alan.gauld at btinternet.com Wed Sep 12 19:51:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 18:51:03 +0100 Subject: [Tutor] Making a python script to feed files into anotherpythonscript References: Message-ID: "Ashley Booth" wrote > John- I was not sure what you meant by "command line". I took what > you > said quite literally and created this: > > indir = raw_input('input directory path ') # asks for input > directory > script1 = raw_input('python script path ') # asks for path to > desired script > > for j in os.listdir(indir): > input = os.path.join(indir,j) > output = os.path.join(indir,j.split('rovctd')[0]+'.txt') > os.system('python %s %s %s' % (script1, input, output) Count the parens, you are one short... > which does not run and I was confused by all the % symbols. I think > I > completely misinterpreted your comment. This uises a "format string2 which is a Python feature enabling you to insert values into a string. In this case the string takes three values, all themselves strings - thats what %s means. The bit after the % on its own is the tuple of values to be inserted, in this case the values of script1, input and output. See the simple sequences topic in my tutorial for more info. > Alan-I am confused about how to used the communicate() module. Could > you please give me an example? > > the format should be(?): > > communicate(input=None) Look at the subprocess module for lots of examples of how to use the Popen class. It has a method called communicate which allows you to communicate with the running process and access its output. This is explained fuerther in the Using the OS topic in my tutorial... about three quarters down under the heading Running an External Program > What I was trying to say before at the end of my post: > >> I would at least be happy with how to tack on the list >> directory stuff to THE END of the script1- it would not be a >> stand alone script but at least it would work. > > In other words, instead of having a stand alone script that feeds > files into script1 (the program I want the files to be fed into-it > reformats files so it requires a file path input and output), This is the bit that confuses me. You want the initial program to reformat the files (which files?) so that it requires a path instead of a filename? > have script1 ask me for a directory instead of a specific input and > output file path as it does now. Sure, but it doesn't win you much if any advantage. > Then it would theoretically go > through and reformat each file in that directory, rename them and > put > the formatted files back in that directory. Why not just do that in the tiop level script? Or do you want a top level script that will do something like run any given script/command on any given file pattern? In other words a Python version of the unix find -exec command? Can you give us a sample user session to sjhow what this would look like if you got it working? Regards, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Sep 12 19:54:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 18:54:01 +0100 Subject: [Tutor] Image Analysis References: <75672.43946.qm@web32413.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > Could not find it. The searchable interface at ActiveState's site > does not have it, > and I don't know of any way to search the zipped archives... I use the gmane news inteface, I dunno about Eike, but its possible the problem lies in gmane's interface to the mailing list! > Very strange. This is the second time that I know of in the last > month > that I have not received some emails from the list. I did not get > the > message Eike Welk sent out. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Sep 12 20:01:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 19:01:41 +0100 Subject: [Tutor] interpreted or compiled? References: <46E7F096.8050408@mrfab.info> Message-ID: "Michael" wrote > As a new Python user I was curious if you can run Python without the > environment, ie make it an executable? There are two separate issues here. First: Can you make executable Python scripts? Yes, see Sam's response re py2exe etc Second: Can you run Python without the environment? No. py2exe and the other installers simply bundle up the interpreter and other modules you need into a single executable file. The environment is still present. This is somewhat analagous to a C/C++ program which is compiled. You can either link the libraries it needs statically or dynamically. If you do it statically you don't need those DLLs on the host PC but the file is much bigger, but if you do it dynamically the libraries need to be installed as well as the basic exe. Same with py2exe, the basic text files might only be a few kilobytes but the combined exe will be 5-10 Megabytes typically. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Sep 12 20:07:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 19:07:42 +0100 Subject: [Tutor] Tutor Digest, Vol 43, Issue 36 References: Message-ID: "chinni" wrote > But u all told that cronjob and at inbuilt features of UNIX but > every time > ihave to manually go and change the version.i can't The first question to answer is why not? If you can't do it manually you probably can't get a script to do it either! Assuming its a text file youb should be able to use sed to edit the file from a shell script using cron. > 1.open the app > 2.degrade the version automatically to least version > 3.change the time to 25hrs more Down to here, nomproblem and pyhon can do it all so far. > 4.check for updates(1.force Update and silent update) Not sure what this means. I suspect its Pythonable... > 5.the whole procedure is for admin and non-admin users A Unix issue mainly. > can i implement this by using both python and shell scripting. Yes I think so. In fact you can probably do it in shell only or python only or a mix of both. > if possible give the reference book for quick learn. Thee are lots of free tutorials on the Python web site under the beginners section. You could try my tutorial, just do the first "The Basics" section and take a look at the later "Using the OS" topic too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Sep 12 21:26:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 20:26:46 +0100 Subject: [Tutor] Would an emulator be possible in Python? References: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> Message-ID: "Andy" wrote > prove me wrong. I have decided that I would like to try and write > an > emulator, I'm going to start out with a couple of simpler systems > like > the Chip 8 and maybe a well documented arcade game but I would like > to > do an NES emulator eventually. That's pretty challenging but not that difficult techically for the CPU. The hardest bit is simulating the I/O subsystem and all the quirks of the monitor/OS. > Is Python anywhere near fast enough to do this and have > it be playable? Probably. Modern PCs are arpund 4000 times faster than the older machines and you can do a lot of emulation in 4000 instructions! And because you are doing it in a high level language a single machine instruction should only translate to a few Python commands which hopefully translate to a few hundred CPU commands. > I hope so because I really don't like C/C++. C is simple enough and quite good for this kind of thing because its so close to the hardware. C++ doesn't add much for this kind of job in my experience. Its basically a big jump table (aka dictionary) with a whole lot of very small functions. But python makes it easier to experiment because the jump table is almost fgree and the functions should be only a handful of lines each. The most technically challenging bit is likely to be reading the programs from the other machine - extracting and decoding the binary data format. If you have that documented then its a fairly straightforward if tedious job! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bill at celestial.net Thu Sep 13 01:01:05 2007 From: bill at celestial.net (Bill Campbell) Date: Wed, 12 Sep 2007 16:01:05 -0700 Subject: [Tutor] Image Analysis In-Reply-To: <46E7CC5C.5090204@tds.net> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> <46E774C3.4090405@brunson.com> <20070912054011.GA5480@ayn.mi.celestial.com> <46E7CC5C.5090204@tds.net> Message-ID: <20070912230105.GA1851@ayn.mi.celestial.com> On Wed, Sep 12, 2007, Kent Johnson wrote: >Bill Campbell wrote: >> Most mailing lists limit the size >> of messages to 40k or less. > >On this list large messages go to moderation. I think I was so >captivated with the images that I forgot about the size. A better way to >present this would be to put the images on a web site and reference them >from email. > >Sorry about that... I've done the same thing on occassion on lists I manage :-). One of the things I really like about the IMP webmail package is that it makes it easy for people to provide links to attachments rather than sending the files. It automatically copies the files to the web server, adding the links to the bottom of the message. I don't generally like web e-mail interfaces, but do use IMP when dealing with large attachment. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 I don't make jokes, I just watch the Government and report the facts... Will Rogers From ghashsnaga at gmail.com Thu Sep 13 03:45:48 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Wed, 12 Sep 2007 19:45:48 -0600 Subject: [Tutor] Classes: global name not defined Message-ID: <2107481c0709121845o7610a67aucebe485538dabe50@mail.gmail.com> So taking the advice given my John, Kent, and Michael I reworked the program and created a class for world. I was able to solve the first several errors that came up as a I moved functions into class methods but this one stumps me. The error I am getting is: Traceback (most recent call last): File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 87, in first_instance.print_world() File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 40, in print_world m, n = world['dimensions'] NameError: global name 'world' is not defined I understand that the error refers to the method print_world(). In the instance before first_instance.print_world() I define what world is but that is not being carried over to the print_world method. In the print world method do I need to refer back to the random_world method so it knows what world is? Thank you. CODE STARTS HERE: import random import copy YEAST = '@' EMPTY = '.' GROUP = 'Q' class World: #What makes this a world def __init__(self,name): self.name = name #Add other things later #Methods def percolation(self,perc): #Sets up a percolation threshold value perc = float(perc) randval = random.random() if randval > perc: return EMPTY else: return YEAST def random_world(self): #Constructs random world of size MxN world = {} for j in range(n): for i in range(m): world[i, j] = self.percolation(perc) world['dimensions'] = (m, n) return world def print_world(self): #Prints out a string representation of a world. m, n = world['dimensions'] for j in range(n): for i in range(m): print world[i, j], print def add_yeast(self): #Allows the user to add a yeast cell at point m,n m,n = world['dimensions'] new_world = copy.copy(world) counta = 0 print "The upper left corner is the point (0,0)" yy = raw_input("How many yeast cells do you wish to add?") yy = int(yy) while counta I created a script that opens an existing text file, allows the user to write over the original contents, and then save the file. The original contents are then saved in a separate file. Here is the script: #!/usr/bin/python 'editTextFile.py -- write over contents of existing text file' import os, string # get filename while True: fname = raw_input('Enter file name: ') if not (os.path.exists(fname)): print"*** ERROR: '%s' doesn't exist" % fname else: break # get file content (text) lines all = [] print "\nEnter lines ('.' by itself to quit).\n" # loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry) # write lines to file with NEWLINE line terminator print "1) Replace file's contents" print "Any other key quits function without replacing file's contents" choice = raw_input("Make a choice: ") if choice == '1': fobj = open(fname, 'r') fobj_lines = fobj.readlines() fobj.close() fobj = open(fname, 'w') fname_orig = fname + '_orig' fobj_orig = open(fname_orig, 'w') stripped_lines = [] for line in fobj_lines: string.strip(line) stripped_lines.append(line) fobj_orig.write('\n'.join(stripped_lines)) fobj_orig.close() fobj.write('\n'.join(all)) fobj.close() print 'DONE!' else: print 'Bye!' I took a file called myfile. The original contents of myfile were: Hi! This is my file. It really rocks! I then ran my script: Enter file name: myfile Enter lines ('.' by itself to quit). > test > test > test > . 1) Replace file's contents Any other key quits function without replacing file's contents Make a choice: 1 DONE! Now the contents of myfile are: test test test The original contents were saved in myfile_orig. The contents of myfile_orig are: Hi! This is my file. It really rocks! Extra newlines were added. This won't do. I think the problem lies with fobj_orig.write('\n'.join(stripped_lines)) However, when I rewrite this line code as fobj_orig.write(string.join(stripped_lines)) I get Hi! This is my file. It really rocks! That doesn't work either. Any suggestions? From alan.gauld at btinternet.com Thu Sep 13 05:56:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2007 04:56:58 +0100 Subject: [Tutor] Classes: global name not defined References: <2107481c0709121845o7610a67aucebe485538dabe50@mail.gmail.com> Message-ID: "Ara Kooser" wrote > File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 87, in > > first_instance.print_world() > File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 40, in > print_world > m, n = world['dimensions'] > NameError: global name 'world' is not defined > > I understand that the error refers to the method print_world(). In > the > instance before first_instance.print_world() I define what world is > but that is not being carried over to the print_world method. In the > print world method You need to work on your terminology. You are not defining world anywhere in any instance. You are calling methods of the instance. But the real problem lies inside the definition of the class methods. > class World: > #What makes this a world > > def __init__(self,name): > self.name = name > #Add other things later You should probably define world here self.world = ???? whatever > def percolation(self,perc): > perc = float(perc) This is forgotten as soon as the method ends. And you don;t use it anywhere else in the method. Are you sure you don't mean self.perc = float(perc) > randval = random.random() > if randval > perc: > return EMPTY > else: > return YEAST > def random_world(self): > #Constructs random world of size MxN > world = {} And again this is lost as soon as the methjod ends. It should be self.world = {} except that since its initialisatoon it would be better in the __init__ method. Thats what its for! > for j in range(n): > for i in range(m): > world[i, j] = self.percolation(perc) > world['dimensions'] = (m, n) > return world In this case you return world but you don't store it in your main code, so it is still lost. > def print_world(self): > #Prints out a string representation of a world. > m, n = world['dimensions'] And because world ghas never been set anywhee outside the random_world() method this fails. You should be accessing self.world. here. > for j in range(n): > for i in range(m): > print world[i, j], and here... > print > > def add_yeast(self): > #Allows the user to add a yeast cell at point m,n > m,n = world['dimensions'] and here > new_world = copy.copy(world) > > counta = 0 > print "The upper left corner is the point (0,0)" > yy = raw_input("How many yeast cells do you wish to add?") > yy = int(yy) > > while counta i = int(raw_input("Please enter a m value for the yeast > cell.")) > j = int(raw_input("Please enter a n value for the yeast > cell.")) > > new_world[i,j] = YEAST > for j in range(n): > for i in range(m): You just got i.j from the user but now you are throwing away their input and overwriting it with the values from the for loop. I assume thats an error? > world[i,j]=new_world[i,j] and here... > > counta = counta+1 > > def debug(self): > print self.name > > > ########################################################## > #Start of prgram > ########################################################## > > first_instance = World("small_world") > #first_instance.debug() > > raw_input("Please press return to start the program.") > > perc = raw_input("Please enter a thresold between 0-1 for the > population.") > first_instance.percolation(perc) > > n = int(raw_input("Please enter a n dimension. ")) > m = int(raw_input("Please enter a m dimension. ")) These global variables are accessed from the class, it woyld be safer and more readable to put them into the init method and make them attributes which can then be accessed with self.m, self.n Its slightly more typing but makes the code more readable and more reliable. > first_instance.random_world() > first_instance.print_world() > > first_instance.add_yeast() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Thu Sep 13 05:59:03 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 12 Sep 2007 22:59:03 -0500 Subject: [Tutor] editTextFile.py In-Reply-To: <846024.78106.qm@web51612.mail.re2.yahoo.com> References: <846024.78106.qm@web51612.mail.re2.yahoo.com> Message-ID: <46E8B587.6030103@gmail.com> Christopher Spears wrote: > I created a script that opens an existing text file, > allows the user to write over the original contents, > and then save the file. The original contents are > then saved in a separate file. Here is the script: > > #!/usr/bin/python > > 'editTextFile.py -- write over contents of existing > text file' > > import os, string > > # get filename > while True: > fname = raw_input('Enter file name: ') > if not (os.path.exists(fname)): > print"*** ERROR: '%s' doesn't exist" % fname > else: > break > > # get file content (text) lines > all = [] > print "\nEnter lines ('.' by itself to quit).\n" > > # loop until user terminates input > while True: > entry = raw_input('> ') > if entry == '.': > break > else: > all.append(entry) > > # write lines to file with NEWLINE line terminator > print "1) Replace file's contents" > print "Any other key quits function without replacing > file's contents" > choice = raw_input("Make a choice: ") > > if choice == '1': > fobj = open(fname, 'r') > fobj_lines = fobj.readlines() > fobj.close() > fobj = open(fname, 'w') > > fname_orig = fname + '_orig' > fobj_orig = open(fname_orig, 'w') > stripped_lines = [] > for line in fobj_lines: > string.strip(line) > stripped_lines.append(line) > fobj_orig.write('\n'.join(stripped_lines)) > fobj_orig.close() > > fobj.write('\n'.join(all)) > fobj.close() > print 'DONE!' > else: > print 'Bye!' > > I took a file called myfile. The original contents of > myfile were: > Hi! > This is my file. > It really rocks! > > I then ran my script: > Enter file name: myfile > > Enter lines ('.' by itself to quit). > > >> test >> test >> test >> . >> > 1) Replace file's contents > Any other key quits function without replacing file's > contents > Make a choice: 1 > DONE! > > Now the contents of myfile are: > test > test > test > > The original contents were saved in myfile_orig. The > contents of myfile_orig are: > Hi! > > This is my file. > > It really rocks! > > Extra newlines were added. This won't do. I think > the problem lies with > > fobj_orig.write('\n'.join(stripped_lines)) > > However, when I rewrite this line code as > > fobj_orig.write(string.join(stripped_lines)) > > I get > > Hi! > This is my file. > It really rocks! > > That doesn't work either. Any suggestions? > Before you write to the file, just use one of the os module functions to rename the original file to the new filename. Then when you go to open the original file, it'll just create a new one. The way you're currently doing it now, there's a period where both file's data is stored in memory, after you've opened both files for writing. This means that if the program were to crash at some point in here, you'll lose your original data. This is a pretty big problem for a text editor :) As per your original question, we can use reasoning to figure out what the problem is. There are extra spaces on every line except the first. However, there are still newlines. This means that your original strings must have had newlines. The spaces are explained by the string.join method. (Methods of string are deprecated anyway.) We can deduce that by default string.join uses space as the separation character. But by leiu of the example "\n".join() we know we can say "somestring".join(strings_to_join) and it will join the strings with that character in between each string. " ".join(stripped_lines) would have the same effect as string.join(stripped_lines). So what do you do if you don't want any characters at all separating your strings? Simple: use an empty string: "".join(stripped_lines) As I mentioned above, there are multiple ways to approach this problem. One other thing you could do if you wanted the program to be functionally equivalent is just use writelines() instead of write() and then you don't have to join the strings. -Luke From varsha.purohit at gmail.com Thu Sep 13 08:09:30 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Wed, 12 Sep 2007 23:09:30 -0700 Subject: [Tutor] printing value returning from a Class Message-ID: Hello friends,, I have a problem in displaying data which i have invoked from class. City is the name of the class which i havent displayed here. There is another script using that class. It has a function name setCities which takes a text file as argument. Text file contains name of the city, x and y location. there are 4 datas in 4 different lines. Code is as follows. import City def setCities(inFile): # puts city.txt content into City class objects # the field order of input file is: name x y x, y are integers. data are in newlines. f = open(inFile, 'r') body = f.readlines() f.close() cities = [] # list of cities for row in body: cityData = row.strip().split() cityName = cityData[0] cityX = cityData[1] cityY = cityData[2] newCity = City(cityName, cityX, cityY) # city class is invoked cities.append(newCity) return cities abc = setCities("C:\MS\sem5\Lab2_scripts\cities.txt") # setCities function will return the array with values read from the file. print abc I am getting output like [, , < city.City instance at 0x023E8350>, ] I want the data and not the instance... what should i do ?? -- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/9e162ea3/attachment.htm From washakie at gmail.com Thu Sep 13 08:45:42 2007 From: washakie at gmail.com (John) Date: Wed, 12 Sep 2007 23:45:42 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int Message-ID: I've written a program which calculates areas of grid cells distributed over the globe. It works fine with Python 2.5, however, when I run it with 2.4(the Enthon edition) I get the following error: OverflowError: long int too large to convert to int It occurs on this line: for ix in range(nx): area[ix,iy]=gridarea I have no idea which int it's referring to? The values of ix/nx will not exceed 360, iy will not exceed 180. Any suggestions on what to change for the backward compatability? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/e25811a7/attachment.htm From kent37 at tds.net Thu Sep 13 13:01:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 07:01:07 -0400 Subject: [Tutor] editTextFile.py In-Reply-To: <846024.78106.qm@web51612.mail.re2.yahoo.com> References: <846024.78106.qm@web51612.mail.re2.yahoo.com> Message-ID: <46E91873.8080007@tds.net> Christopher Spears wrote: > I created a script that opens an existing text file, > allows the user to write over the original contents, > and then save the file. The original contents are > then saved in a separate file. Here is the script: > > #!/usr/bin/python > > 'editTextFile.py -- write over contents of existing > text file' > > import os, string > > # get filename > while True: > fname = raw_input('Enter file name: ') > if not (os.path.exists(fname)): > print"*** ERROR: '%s' doesn't exist" % fname > else: > break > > # get file content (text) lines > all = [] > print "\nEnter lines ('.' by itself to quit).\n" > > # loop until user terminates input > while True: > entry = raw_input('> ') > if entry == '.': > break > else: > all.append(entry) > > # write lines to file with NEWLINE line terminator > print "1) Replace file's contents" > print "Any other key quits function without replacing > file's contents" > choice = raw_input("Make a choice: ") > > if choice == '1': > fobj = open(fname, 'r') > fobj_lines = fobj.readlines() > fobj.close() > fobj = open(fname, 'w') It would be safer to write the '_orig' file before opening the original file for writing (which erases its contents) > > fname_orig = fname + '_orig' > fobj_orig = open(fname_orig, 'w') > stripped_lines = [] > for line in fobj_lines: > string.strip(line) This doesn't change line. You need to assign the result back to line: line = string.strip(line) or, better, line = line.strip() Note that this will also strip leading and trailing whitespace from the lines so the copy will not be a duplicate of the original. A simpler way to copy a file is to read the entire contents using fobj.read() and write them as a single string. Even easier is to use shutil.copyfile() which does this for you. Kent From kent37 at tds.net Thu Sep 13 14:08:50 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 08:08:50 -0400 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: References: Message-ID: <46E92852.90602@tds.net> John wrote: > I've written a program which calculates areas of grid cells distributed > over the globe. It works fine with Python 2.5, however, when I run it > with 2.4 (the Enthon edition) I get the following error: > > OverflowError: long int too large to convert to int > > It occurs on this line: > > for ix in range(nx): area[ix,iy]=gridarea > > I have no idea which int it's referring to? The values of ix/nx will not > exceed 360, iy will not exceed 180. Any suggestions on what to change > for the backward compatability? Are you sure nx is not large? The argument to range() must be an int. I would split the line in two so you know which part of it is generating the error, then insert a print statement to give you some more data. Kent From kalle.svensson at gmail.com Thu Sep 13 15:11:44 2007 From: kalle.svensson at gmail.com (Kalle Svensson) Date: Thu, 13 Sep 2007 15:11:44 +0200 Subject: [Tutor] printing value returning from a Class In-Reply-To: References: Message-ID: <9584033b0709130611g59e9661atf617a0fe0591b8cd@mail.gmail.com> Hello! On 9/13/07, Varsha Purohit wrote: > Hello friends,, > I have a problem in displaying data which i have invoked from > class. City is the name of the class which i havent displayed here. There is > another script using that class. It has a function name setCities which > takes a text file as argument. Text file contains name of the city, x and y > location. there are 4 datas in 4 different lines. Code is as follows. > > import City > > def setCities(inFile): > # puts city.txt content into City class objects > # the field order of input file is: name x y x, y are integers. data > are in newlines. > f = open(inFile, 'r') > body = f.readlines() > f.close() > cities = [] # list of cities > for row in body: > cityData = row.strip().split() > cityName = cityData[0] > cityX = cityData[1] > cityY = cityData[2] > newCity = City(cityName, cityX, cityY) # city class is invoked > cities.append(newCity) > return cities > > > abc = setCities("C:\MS\sem5\Lab2_scripts\cities.txt") # > setCities function will return the array with values read from the file. > print abc > > I am getting output like > [, , > , ] > > I want the data and not the instance... what should i do ?? Well, that depends on the City class. When you print a list, it just calls repr() on each item in the list and prints that. Now, suppose there is a method printCity() in the City class for printing the city data. In that case you should probably just loop over the list of instances and call the method, like this: >>> abc = setCities("city file") >>> for city in abc: ... city.printCity() If there is no such method, maybe you can extract the data from the class and write your own printing function, or modify the class to add one. HTH, Kalle From sacharook at hotmail.co.uk Thu Sep 13 17:33:43 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Thu, 13 Sep 2007 16:33:43 +0100 Subject: [Tutor] is this a vista issue In-Reply-To: <46E563DA.4090106@umn.edu> References: <46E563DA.4090106@umn.edu> Message-ID: Hi when I run this code on a winxp box I get a nice list of url's when I run this code on a win VISTA box I get this print urlparse.urlparse(href)[1]TypeError: 'module' object is not callable can a. someone tell me why & b. how do i get rid of this condition before I throw vista away :) Many thanks in advance S [CODE] from BeautifulSoup import BeautifulSoupdoc = ['Page title', '

This is paragraph one.', '

This is paragraph two.', '', '', '', '', '']soup = BeautifulSoup(''.join(doc))blist = soup.findAll('a')print blist import urlparsefor a in blist: href = a['href'] print urlparse.urlparse(href)[1] [/CODE] _________________________________________________________________ Get free emoticon packs and customisation from Windows Live. http://www.pimpmylive.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/33e94f54/attachment.htm From kent37 at tds.net Thu Sep 13 17:55:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 11:55:58 -0400 Subject: [Tutor] is this a vista issue In-Reply-To: References: <46E563DA.4090106@umn.edu> Message-ID: <46E95D8E.7070801@tds.net> sacha rook wrote: > Hi > > when I run this code on a winxp box I get a nice list of url's > when I run this code on a win VISTA box I get this > > > print urlparse.urlparse(href)[1] > TypeError: 'module' object is not callable Please show the whole traceback. Kent > > can a. someone tell me why & b. how do i get rid of this condition > before I throw vista away :) > > Many thanks in advance > > S > > > [CODE] > > from BeautifulSoup import BeautifulSoup > doc = ['Page title', > '

This is paragraph > one.', > '

This is paragraph two.', > '' > '>, > '' '>, > '' > '>, > '' > '>, > ''] > soup = BeautifulSoup(''.join(doc)) > blist = soup.findAll('a') > print blist > import urlparse > for a in blist: > href = a['href'] > print urlparse.urlparse(href)[1] > > > [/CODE] > > ------------------------------------------------------------------------ > Are you the Quizmaster? Play BrainBattle with a friend now! > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From washakie at gmail.com Thu Sep 13 21:27:07 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:27:07 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <46E92852.90602@tds.net> References: <46E92852.90602@tds.net> Message-ID: The error occurs here: area[ix,iy]=gridarea The values of nx, ix, iy leading up to the error are: 360 0 0 360 1 0 360 2 0 360 3 0 360 4 0 360 ... ... 360 357 9 360 358 9 360 359 9 360 0 10 OverflowError: long int too large to convert to int I guess then the problem occurs when iy goes from 9 to 10, but why?? It wasn't a problem before and it's not a problem for ix??? Thanks! On 9/13/07, Kent Johnson wrote: > > John wrote: > > I've written a program which calculates areas of grid cells distributed > > over the globe. It works fine with Python 2.5, however, when I run it > > with 2.4 (the Enthon edition) I get the following error: > > > > OverflowError: long int too large to convert to int > > > > It occurs on this line: > > > > for ix in range(nx): area[ix,iy]=gridarea > > > > I have no idea which int it's referring to? The values of ix/nx will not > > exceed 360, iy will not exceed 180. Any suggestions on what to change > > for the backward compatability? > > Are you sure nx is not large? The argument to range() must be an int. I > would split the line in two so you know which part of it is generating > the error, then insert a print statement to give you some more data. > > Kent > -- 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/031a0f60/attachment.htm From kent37 at tds.net Thu Sep 13 21:36:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 15:36:24 -0400 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: References: <46E92852.90602@tds.net> Message-ID: <46E99138.1030002@tds.net> John wrote: > The error occurs here: > area[ix,iy]=gridarea What is area? Is it a dict or something else? What is gridarea? Please show more code and the complete traceback. Kent > > The values of nx, ix, iy leading up to the error are: > 360 0 0 > 360 1 0 > 360 2 0 > 360 3 0 > 360 4 0 > 360 ... ... > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > > I guess then the problem occurs when iy goes from 9 to 10, but why?? It > wasn't a problem before and it's not a problem for ix??? > > Thanks! From washakie at gmail.com Thu Sep 13 21:55:44 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:55:44 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <46E99138.1030002@tds.net> References: <46E92852.90602@tds.net> <46E99138.1030002@tds.net> Message-ID: In all it's glory: I'm just a bit embarrassed because I'm sure it's poor coding: def gridarea(H): """ returns an array of area corresponding to each nx,ny,nz %=========================================== % %------------------------------------------- % input % - H : Header dict object with nx, ny, nz % % output % - Numpy array area corresponding to nx,ny,nz %------------------------------------------- % %------------------------------------------- % last changes: ww, 2007 %=========================================== """ import math import numpy as N pih=math.pi/180. r_earth=6.371e6 cosfunc = lambda y : math.cos(y*pih)*r_earth nz=H['nz'] nx=H['nx'] ny=H['ny'] outlat0=H['outlat0'] dyout=H['dyout'] dxout=H['dxout'] area=N.zeros((nx,ny)) #creates numpy array for iy in range(ny): ylata=outlat0+(float(iy)+0.5)*dyout ylatp=ylata+0.5*dyout ylatm=ylata-0.5*dyout if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih else: cosfact=cosfunc(ylata) cosfactp=cosfunc(ylatp) cosfactm=cosfunc(ylatm) if cosfactp", line 1, in ? File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? H,fail=readheader(pathname,1,0) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in readheader H['area'] = gridarea(H) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea area[ix,iy]=gridarea -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/0d07e64c/attachment-0001.htm From washakie at gmail.com Thu Sep 13 21:55:44 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:55:44 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <46E99138.1030002@tds.net> References: <46E92852.90602@tds.net> <46E99138.1030002@tds.net> Message-ID: In all it's glory: I'm just a bit embarrassed because I'm sure it's poor coding: def gridarea(H): """ returns an array of area corresponding to each nx,ny,nz %=========================================== % %------------------------------------------- % input % - H : Header dict object with nx, ny, nz % % output % - Numpy array area corresponding to nx,ny,nz %------------------------------------------- % %------------------------------------------- % last changes: ww, 2007 %=========================================== """ import math import numpy as N pih=math.pi/180. r_earth=6.371e6 cosfunc = lambda y : math.cos(y*pih)*r_earth nz=H['nz'] nx=H['nx'] ny=H['ny'] outlat0=H['outlat0'] dyout=H['dyout'] dxout=H['dxout'] area=N.zeros((nx,ny)) #creates numpy array for iy in range(ny): ylata=outlat0+(float(iy)+0.5)*dyout ylatp=ylata+0.5*dyout ylatm=ylata-0.5*dyout if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih else: cosfact=cosfunc(ylata) cosfactp=cosfunc(ylatp) cosfactm=cosfunc(ylatm) if cosfactp", line 1, in ? File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? H,fail=readheader(pathname,1,0) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in readheader H['area'] = gridarea(H) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea area[ix,iy]=gridarea -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/0d07e64c/attachment-0002.htm From washakie at gmail.com Thu Sep 13 21:57:26 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:57:26 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: References: <46E92852.90602@tds.net> <46E99138.1030002@tds.net> Message-ID: for the record: nx=360 ny=180 nz=1 On 9/13/07, John wrote: > > > In all it's glory: I'm just a bit embarrassed because I'm sure it's poor > coding: > > > > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > %=========================================== > % > %------------------------------------------- > % input > % - H : Header dict object with nx, ny, nz > % > % output > % - Numpy array area corresponding to nx,ny,nz > %------------------------------------------- > % > %------------------------------------------- > % last changes: ww, 2007 > %=========================================== > """ > import math > import numpy as N > > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp (r_earth**2-cosfactm**2) > else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2) > > > gridarea=2.*math.pi*r_earth*hzone*dxout/360. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea > > return area #returns numpy array of area > > > > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > Traceback: > File "", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea > area[ix,iy]=gridarea > -- 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/02fe19df/attachment.htm From washakie at gmail.com Thu Sep 13 21:57:26 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:57:26 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: References: <46E92852.90602@tds.net> <46E99138.1030002@tds.net> Message-ID: for the record: nx=360 ny=180 nz=1 On 9/13/07, John wrote: > > > In all it's glory: I'm just a bit embarrassed because I'm sure it's poor > coding: > > > > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > %=========================================== > % > %------------------------------------------- > % input > % - H : Header dict object with nx, ny, nz > % > % output > % - Numpy array area corresponding to nx,ny,nz > %------------------------------------------- > % > %------------------------------------------- > % last changes: ww, 2007 > %=========================================== > """ > import math > import numpy as N > > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp (r_earth**2-cosfactm**2) > else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2) > > > gridarea=2.*math.pi*r_earth*hzone*dxout/360. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea > > return area #returns numpy array of area > > > > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > Traceback: > File "", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea > area[ix,iy]=gridarea > -- 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/02fe19df/attachment-0001.htm From pyth0nc0d3r at gmail.com Thu Sep 13 22:03:57 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 13 Sep 2007 15:03:57 -0500 Subject: [Tutor] Class Inheritance Message-ID: Okay class A: def __init__(self,x,y): self.x = x self.y = y def save(self,fn): f = open(fn,"w") f.write(str(self.x)+ '\n') # convert to a string and add newline f.write(str(self.y)+'\n') return f # for child objects to use def restore(self, fn): f = open(fn) self.x = int(f.readline()) # convert back to original type self.y = int(f.readline()) return f class B(A): def __init__(self,x,y,z): A.__init__(self,x,y) self.z = z def save(self,fn): f = A.save(self,fn) # call parent save f.write(str(self.z)+'\n') return f # in case further children exist def restore(self, fn): f = A.restore(self,fn) self.z = int(f.readline()) return f In the class B, I'm not understanding the A.__init(self,x,y) part. So its initializing the class A, and basically you can use the A class like normal? Part im confused about is the self.z, does that belong to the class A or class B? Else I think I'm understanding it correctly. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/2102617a/attachment.htm From kent37 at tds.net Thu Sep 13 22:27:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 16:27:12 -0400 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: References: <46E92852.90602@tds.net> <46E99138.1030002@tds.net> Message-ID: <46E99D20.4000904@tds.net> I have no clue; anyone else? Maybe you should try the numpy list. Kent John wrote: > for the record: > nx=360 > ny=180 > nz=1 > > > On 9/13/07, *John* > wrote: > > > In all it's glory: I'm just a bit embarrassed because I'm sure it's > poor coding: > > > > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > %=========================================== > % > %------------------------------------------- > % input > % - H : Header dict object with nx, ny, nz > % > % output > % - Numpy array area corresponding to nx,ny,nz > %------------------------------------------- > % > %------------------------------------------- > % last changes: ww, 2007 > %=========================================== > """ > import math > import numpy as N > > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt(r_earth**2-cosfactm**2) > else: > hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2) > > > gridarea=2.*math.pi*r_earth*hzone*dxout/360. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea > > return area #returns numpy array of area > > > > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > Traceback: > File "", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in > gridarea > area[ix,iy]=gridarea > > > > > -- > 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 From brunson at brunson.com Thu Sep 13 23:32:34 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 13 Sep 2007 15:32:34 -0600 Subject: [Tutor] Class Inheritance In-Reply-To: References: Message-ID: <46E9AC72.1030308@brunson.com> Lamonte Harris wrote: > Okay > > class A: > def __init__(self,x,y): > self.x = x > self.y = y > > def save(self,fn): > f = open(fn,"w") > f.write(str(self.x)+ '\n') > # convert to a string and add newline > f.write(str(self.y)+'\n') > return f # for child objects to use > > def restore(self, fn): > f = open(fn) > > self.x = int(f.readline()) # convert back to original type > self.y = int(f.readline()) > return f > > class B(A): > def __init__(self,x,y,z): > A.__init__(self,x,y) > > self.z = z > > def save(self,fn): > f = A.save(self,fn) # call parent save > f.write(str(self.z)+'\n') > return f # in case further children exist > > > def restore(self, fn): > f = A.restore(self,fn) > self.z = int(f.readline()) > return f > In the class B, I'm not understanding the A.__init(self,x,y) part. > So its initializing the class A, and basically you can use the A class > like normal? Essentially, yes, but the way you've worded it is imprecise. Any instance of B is a subclass of A, essentially an A: Every boy is a male, but not all males are boys. When you override a method in a subclass you have essentially turned off all behavior in the parent method, including "magic" methods like the constructor. You have to call the parent constructor explicitly to get its benefits. A method of an instance can be called like this: instance.method() and python makes sure that a pointer to the instance is passed in as the first argument, generally "self". But a method of a class can be called without instantiating the class, but you have to supply "self" on you own. The method you are using is valid, yet depricated. Using "new style classes" (which aren't actually that new) you'd write your code like this: class A(object): def __init__(self, a): self.aye = a class B(A): def __init__(self, a, b): self.bee = b super( B, self ).__init__( a ) Notice that you don't have to supply self. You can use any method of A in an instance of B that you haven't overridden in B without having to use super(). > Part im confused about is the self.z, does that belong to the class A > or class B? z is an attribute B only. Hope that helps, e. > Else I think I'm understanding it correctly. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From orest.kozyar at gmail.com Thu Sep 13 23:43:08 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Thu, 13 Sep 2007 17:43:08 -0400 Subject: [Tutor] evaluating AND Message-ID: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Given a variable x that can either be None or a tuple of two floats [i.e. (0.32, 4.2)], which syntax is considered most appropriate under Python coding standards? if x and x[0] > 0: pass =====OR===== if x: if x[0] > 0: pass In the first, I'm obviously making the assumption that if the first condition evaluates to false, then the second condition won't be evaluated. But, is this a good/valid assumption to make? Is there a more appropriate design pattern in Python? Thanks! Orest From brunson at brunson.com Fri Sep 14 00:02:24 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 13 Sep 2007 16:02:24 -0600 Subject: [Tutor] evaluating AND In-Reply-To: <000e01c7f64f$1406aea0$bd32000a@issphoenix> References: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: <46E9B370.5010001@brunson.com> The first is how I would code it. Python guarantees that compound boolean statements are processed from left to right and also that the AND operator will "short circuit" the rest of the evaluation, since the rest of the line cannot change the falseness of the entire statement. Orest Kozyar wrote: > Given a variable x that can either be None or a tuple of two floats [i.e. > (0.32, 4.2)], which syntax is considered most appropriate under Python > coding standards? > > if x and x[0] > 0: > pass > > =====OR===== > > if x: > if x[0] > 0: > pass > > > In the first, I'm obviously making the assumption that if the first > condition evaluates to false, then the second condition won't be evaluated. > But, is this a good/valid assumption to make? Is there a more appropriate > design pattern in Python? > > Thanks! > Orest > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ghashsnaga at gmail.com Fri Sep 14 00:03:56 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Thu, 13 Sep 2007 16:03:56 -0600 Subject: [Tutor] Killing an instance Message-ID: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> I have two instances called and running. They interact with each other and I would like one of the instances to cease to exist in the second round based on a given condition. How do you kill an instance? The code is below. I have Red and Yellow as my instances and I want them to die when life = 0 and not show up in the preceding rounds of the game. Thank you. Ara CODE HERE: ########################################################################## #Red and Yellow yeast model # #Both yeast start out cooperating. #If the yeast detect that there is no ade or lys present they will defect #but die. ########################################################################## import time chemicals = [] #0 cooperates #1 defects class RedYeast: #Needs adenine to grow, releases lysine def __init__(self,name,group): self.name = name self.group = group self.life = 1 self.hate_tolerance = 0 self.choice = 0 #METHODS def lys_re(self,stuffa): #release of lys in the environment if self.choice == 0: print self.name, "-- Releasing lys" chemicals.append(stuffa) elif self.choice == 1: print self.name, "-- Withholds lys" def ade_need(self,stuffb): if stuffb != chemicals: print self.name,"is taking ade" self.life = self.life+1 chemicals.remove(stuffb) print chemicals print "Life", self.life else: print "No ade presents" self.life = self.life-1 self.choice = 1 class YellowYeast: #Needs lysine to grow, releases adenine def __init__(self,name,group): self.name = name self.group = group self.life = 1 self.hate_tolerance = 0 self.choice = 0 #METHODS def ade_re(self,stuffa): #release of lys in the environment if self.choice == 0: print self.name, "-- Releasing ade" chemicals.append(stuffa) elif self.choice == 1: print self.name, "-- Withholds ade" def lys_need(self,stuffb): if stuffb != chemicals: print self.name," is taking ade" self.life = self.life+1 chemicals.remove(stuffb) print chemicals print "Life",self.life print else: print "No ade presents" self.life = self.life-1 self.choice = 1 def death(self): ############################################################## #Start of program ############################################################## rounds = raw_input("How many rounds to you wish to play through?") print "Starting environment", chemicals rounds =int(rounds) count = 0 #Creates the instances for RedYeast and YellowYeast one = RedYeast("Red","alpha") two = YellowYeast("Yellow","alpha") #Game logic while count < rounds: print "##################################################" print one.lys_re("lys") two.ade_re("ade") print print "Chemicals in the environment",chemicals print time.sleep(1) one.ade_need("ade") two.lys_need("lys") print "##################################################" print count = count+1 print "Ending environment", chemicals -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From carroll at tjc.com Fri Sep 14 00:04:02 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 13 Sep 2007 15:04:02 -0700 (PDT) Subject: [Tutor] evaluating AND In-Reply-To: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: On Thu, 13 Sep 2007, Orest Kozyar wrote: > Given a variable x that can either be None or a tuple of two floats [i.e. > (0.32, 4.2)], which syntax is considered most appropriate under Python > coding standards? > > if x and x[0] > 0: > pass > > =====OR===== > > if x: > if x[0] > 0: > pass I would like either one if instead of "if x" you used "if x is not None"; that seems a lot easier to me to read. It's a bit jarring to see the same variable used in one expression as both a boolean and a list/tuple. Besides, suppose somehow x got set to zero. It would pass without error, something you wouldn't want to have happen. Even if you've set things up so that it couldn't happen, it's not obvious from looking at this code that it couldn't happen. If you really want to test for x being non-None, test for x being non-None. From kent37 at tds.net Fri Sep 14 00:05:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 18:05:38 -0400 Subject: [Tutor] evaluating AND In-Reply-To: <000e01c7f64f$1406aea0$bd32000a@issphoenix> References: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: <46E9B432.3090007@tds.net> Orest Kozyar wrote: > Given a variable x that can either be None or a tuple of two floats [i.e. > (0.32, 4.2)], which syntax is considered most appropriate under Python > coding standards? > > if x and x[0] > 0: > pass > > =====OR===== > > if x: > if x[0] > 0: > pass The first is fine. > In the first, I'm obviously making the assumption that if the first > condition evaluates to false, then the second condition won't be evaluated. > But, is this a good/valid assumption to make? Yes, this is guaranteed by the language. http://docs.python.org/ref/Booleans.html Kent From mlangford.cs03 at gtalumni.org Fri Sep 14 00:12:45 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 13 Sep 2007 18:12:45 -0400 Subject: [Tutor] Killing an instance In-Reply-To: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> References: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> Message-ID: <82b4f5810709131512xb706d62i99e4b5b4370b800@mail.gmail.com> This is a little more complicated. The more object oriented way: Make each cell know its location and have a reference to the world its in. You can have the world set the object the coordinates the item is at when it adds it to itself. When the life==0, you can have the yeast cell call a remove( self.x, self.y) method on the world. This is useful if you're doing a lot of things that involve the cell knowing its position. Your life simulation could probably get this complicated. The less object oriented way...that's a lot simpler: Make a "reap()" method in the world class that removes all the tokens that are life==0. I'd make a method in the cell like isDead(). The reap function for the world will remove all cells that isDead()==True. This is a better approach when your cells don't do very much more than they already do. --Michael On 9/13/07, Ara Kooser wrote: > > I have two instances called and running. They interact with each > other and I would like one of the instances to cease to exist in the > second round based on a given condition. How do you kill an instance? > > The code is below. I have Red and Yellow as my instances and I want > them to die when life = 0 and not show up in the preceding rounds of > the game. > > Thank you. > Ara > > > > > CODE HERE: > ########################################################################## > #Red and Yellow yeast model > # > #Both yeast start out cooperating. > #If the yeast detect that there is no ade or lys present they will defect > #but die. > ########################################################################## > > import time > > chemicals = [] > > #0 cooperates > #1 defects > > class RedYeast: > #Needs adenine to grow, releases lysine > def __init__(self,name,group): > self.name = name > self.group = group > self.life = 1 > self.hate_tolerance = 0 > self.choice = 0 > > #METHODS > def lys_re(self,stuffa): > #release of lys in the environment > if self.choice == 0: > print self.name, "-- Releasing lys" > chemicals.append(stuffa) > elif self.choice == 1: > print self.name, "-- Withholds lys" > > def ade_need(self,stuffb): > > if stuffb != chemicals: > print self.name,"is taking ade" > self.life = self.life+1 > chemicals.remove(stuffb) > print chemicals > print "Life", self.life > else: > print "No ade presents" > self.life = self.life-1 > self.choice = 1 > > > > class YellowYeast: > #Needs lysine to grow, releases adenine > def __init__(self,name,group): > self.name = name > self.group = group > self.life = 1 > self.hate_tolerance = 0 > self.choice = 0 > > #METHODS > def ade_re(self,stuffa): > #release of lys in the environment > if self.choice == 0: > print self.name, "-- Releasing ade" > chemicals.append(stuffa) > elif self.choice == 1: > print self.name, "-- Withholds ade" > > def lys_need(self,stuffb): > > if stuffb != chemicals: > print self.name," is taking ade" > self.life = self.life+1 > chemicals.remove(stuffb) > print chemicals > > print "Life",self.life > print > else: > print "No ade presents" > self.life = self.life-1 > self.choice = 1 > > > def death(self): > > > > ############################################################## > #Start of program > ############################################################## > > rounds = raw_input("How many rounds to you wish to play through?") > print "Starting environment", chemicals > rounds =int(rounds) > count = 0 > > #Creates the instances for RedYeast and YellowYeast > one = RedYeast("Red","alpha") > two = YellowYeast("Yellow","alpha") > > #Game logic > > while count < rounds: > print "##################################################" > print > > one.lys_re("lys") > two.ade_re("ade") > > print > print "Chemicals in the environment",chemicals > print > > time.sleep(1) > > one.ade_need("ade") > two.lys_need("lys") > > print "##################################################" > print > > > count = count+1 > > print "Ending environment", chemicals > > -- > Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis > an sub cardine glacialis ursae. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/39417767/attachment-0001.htm From adam.jtm30 at gmail.com Fri Sep 14 00:15:50 2007 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 13 Sep 2007 23:15:50 +0100 Subject: [Tutor] evaluating AND In-Reply-To: References: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: On 13/09/2007, Terry Carroll wrote: > > On Thu, 13 Sep 2007, Orest Kozyar wrote: > > > Given a variable x that can either be None or a tuple of two floats [i.e > . > > (0.32, 4.2)], which syntax is considered most appropriate under Python > > coding standards? > > > > if x and x[0] > 0: > > pass > > > > =====OR===== > > > > if x: > > if x[0] > 0: > > pass > > I would like either one if instead of "if x" you used "if x is not None"; > that seems a lot easier to me to read. It's a bit jarring to see the same > variable used in one expression as both a boolean and a list/tuple. > > Besides, suppose somehow x got set to zero. It would pass without error, > something you wouldn't want to have happen. Even if you've set things up > so that it couldn't happen, it's not obvious from looking at this code > that it couldn't happen. > > If you really want to test for x being non-None, test for x being > non-None. The problem is what if it's an empty list or tuple? It would pass but have not value whereas if x would work fine. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/2cffd709/attachment.htm From carroll at tjc.com Fri Sep 14 00:34:10 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 13 Sep 2007 15:34:10 -0700 (PDT) Subject: [Tutor] evaluating AND In-Reply-To: Message-ID: On Thu, 13 Sep 2007, Adam Bark wrote: > The problem is what if it's an empty list or tuple? It would pass but have > not value > whereas if x would work fine. Exactly. The poster stated that x is supposed to be either None or a tuple of two floats. Just to put a bit of meat on the example, let's create a function whose job is to return x[1]/x[0], but only if x[0] > 0. Otherwise, it just falls off, i.e., returning None. Here are two versions, one using "if x" is None; the other using just "if x" >>> def test01(x): ... if x is not None: ... if x[0]>0: ... return x[1]/x[0] ... >>> def test02(x): ... if x: ... if x[0]>0: ... return x[1]/x[0] When x is None, both work: >>> x = None >>> print test01(x) None >>> print test02(x) None When x is, in fact, a tuple of two floats, both work: >>> x = (2.0, 5.0) >>> print test01(x) 2.5 >>> print test02(x) 2.5 Now... if x is an empty tuple: >>> x = tuple() >>> print test01(x) Traceback (most recent call last): File "", line 1, in File "", line 3, in test01 IndexError: tuple index out of range >>> print test02(x) None >>> The first one, which checks "if x is None" fails. This is a good thing. The second one, which just checks "if x" and is satisfied with any false value, including an empty tuple, does not raise the error condition, even though the data is bad. This is a bad thing. From alan.gauld at btinternet.com Fri Sep 14 00:50:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2007 23:50:56 +0100 Subject: [Tutor] Suggested books for Agile Programming & Testing References: Message-ID: "Shannon -jj Behrens" wrote >> Also, can anyone comment on the limits or caveats of agile >> development? I posted a longish response on this but it seems not to have made to gmane! Here it is again: =================================== "Stephen McInerney" wrote > Can anyone recommend me the best single must-read book for Agile > Programming? One of the most widely cited is Robert Martin's Agile Software Development. Personally I didn't like it much for agile but it is quite good on OOD. The original XP book by Kent Beck is good too, along with its sequel. > Also Agile Testing. Sorry I can't comment on any specific testing books. > (If they compare Agile in general to the other methodologies, > that would be great) The best comparison book I can recommend is Balancing Agility & Discipline by Barry Boehm. > Also, can anyone comment on the limits or caveats of agile > development? I'm sure lots of people can but Agile is such a nebulous concept that its difficult to get anything objective or useful. My own personal experieces follow for what they are wrth: Agile works well if: 1) You have very close contact with end users/requirement owners 2) Small, co-located teams - small = 20 or less people 3) The requirements are not clearly understood (even by the users). 4) You have an experienced, talented team You need *all* of those to make it work significantly better than traditional methods. If even one if missing you will be no better off. You might not be any worse off, but you will be no better. If you have only one of those items then traditional methods (NOT waterfall!) will be better. Dangers of agile: 1) Not good for building scaleable, resilient, long term flexible structures 2) Very expensive due to the large proportion of time spent in rework (aka refactoring) 3) Tendency to drift over budget as new featiures get thought up and added to the original scope. 4) Not good for long term maintenance, the documentation often being inadeqate for anyone outside of the original project team Note, All of these things can be addressed but it takes specific, directed action to do so. Some general comments: 1) Its easy for management to "embrace agile" by adopting some bits that they like. Requirements become User Stories, Progress meetings become Stand-Ups, Phased releases become iterations. in fact its just a renaming exercise not real Agile. Re-naming doesn't work, agile does (with the caveats above) 2) Agile is very open to hype. Exaggerated claims and comparisons with the waterfall method are common, even though the waterfall method has not been widely used for years and methods like RUP are more appropriate comparisons. If you compare a motorcycle to a penny farthing cycle you will get an exaggerated idea of "progress" 3) Agile badly done is just as bad as traditional badly done. 4) finally, do you need to hire an architect to build a garden shed? Agile is in some ways addressing an artificial problem. Software engineeering was invented in the late 70's to deal with very large projects. Most methodologies still tackle that problem. Many software houses now work on much smaller problems that only need small teams and can be completed in a few weeks. If you apply traditional methodologies to those problems they will be overkill. So Agile comes along. But on these very small projects, usually all that's needed is some common sense and experience - like building a garden shed! My personal career jhas been based on large projects. On most large projects there is a tools team who churn out little programs used by the main development/test teams. The tools team does not typically apply the main project methodology for each tool written, they "just get on with it". The tools team will typically be 4-10 people. A tool will typically take 1-20 days to write. In other words the small end of Agile, but they don't use Agile, they don't use anything but common sense and their experiece... That's way more than I intended writing! I'm sure others will have different views. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Sep 14 01:28:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 00:28:29 +0100 Subject: [Tutor] 2.5 to 2.4 problem with Int References: <46E92852.90602@tds.net><46E99138.1030002@tds.net> Message-ID: "John" wrote > In all it's glory: I'm just a bit embarrassed because I'm sure it's > poor > coding: > Thats what we're here for... The first thing to note is that gridarea is here a function object. So are you assigning the function object to area[x,y]. Is that what you intend? > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > % input > % - H : Header dict object with nx, ny, nz > % output > % - Numpy array area corresponding to nx,ny,nz > """ > import math > import numpy as N It's traditional to put the imports outside the function, especially if they will always be called. > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth You could use the more conventional def cosfunc(y): return math.cos(y*pih)*r_earth lambda is fine by me but some folks find them harder to read. > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp < cosfactm: > hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt > (r_earth**2-cosfactm**2) > else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt > (r_earth**2-cosfactp**2) > More whitespace will help readability and avoid errors! please... > gridarea=2.*math.pi*r_earth*hzone*dxout/360. This is a bit iffy since you are creating a variable gridarea inside a function gridarea. That effectively removes the possibility of using recursion, although otherwise I don't *think* it should cause a problem in itself. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea And here looks like we have the dodgy line because you are assigning the internal variable not the function after all. So gridarea is actually the result of that big calculation. That is a float value and potentially big, I don't know. Did you try printing the value of gridarea in your debug trace? But that shouldn't cause the error since you aren't trying to convert it to an int. Very odd. iy is set in the loop up to ny. But how does it compare to the original ny parameter you passed to N.zeros at the top? Is this a numpy index error we are actually seeing? I don't know how numpy's zeros function works... I'm clutching at straws here... > return area #returns numpy array of area > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 So this is where we loop all the way back to the outer loop and then start the second loop again.. Can you add gridarea and ny to the debug data? > OverflowError: long int too large to convert to int > Traceback: > File "", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in > gridarea > area[ix,iy]=gridarea Personally I'd change gridarea() to take the individiual parameters rather than the dictionary. There is a shortcut way of doing that using **kwords which means you canb pass the dictionary but the unpacking will be done for you by Python... But most of my comments are stylistic, I have no real idea whats going wrong here. Sorry. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Sep 14 01:33:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 00:33:54 +0100 Subject: [Tutor] Killing an instance References: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> Message-ID: "Ara Kooser" wrote > The code is below. I have Red and Yellow as my instances and I > want > them to die when life = 0 and not show up in the preceding rounds of > the game. I'm not sure I understand this last bit. Won't they already have shown up in the preceding bits of the game. Setting to zero won't affect the preceding rounds unless you only display all of the rounds at the end and keep the records in memory. In which case you could go back and retrospectively change the earlier displays. It sounds a bit odd tho' can you elaborate? Alan G. From alan.gauld at btinternet.com Fri Sep 14 01:30:47 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 00:30:47 +0100 Subject: [Tutor] Killing an instance References: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> Message-ID: "Ara Kooser" wrote > I have two instances called and running. They interact with each > other and I would like one of the instances to cease to exist in the > second round based on a given condition. How do you kill an > instance? Either set the variable to something else or explicitly with del() class C: pass c = C() # create a C instance c = 42 # the C instance gets garbage collected or c -= C() # another instance del(c) # delete it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bhaaluu at gmail.com Fri Sep 14 03:58:43 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 13 Sep 2007 21:58:43 -0400 Subject: [Tutor] deleting one line in multiple files Message-ID: Greetings, I'm running Python 2.4.3 on a GNU/Linux box. This question is about using 'fileinput.' I have a directory of files, and I've created a file list of the files I want to work on: $ ls > file.list Each file in file.list needs to have a line removed, leaving the rest of the file intact. I found this snippet on the Net, and it works fine for one file: # the lines with '

Testing Summary  
Tested by:  Machine Name:
   
   
TestIDSpecificationResultBuildID