From kent37 at tds.net Fri Feb 1 04:22:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 Jan 2008 22:22:19 -0500 Subject: [Tutor] creating a nested dictionary In-Reply-To: <4799E36C.4090404@bigfoot.com> References: <68AB53D3-6D4E-4326-8791-FFA6FCADFD24@newcastle.edu.au> <7ae3ca10801240146g2eeac1e9i36cade3e1b926c6e@mail.gmail.com> <479893CE.1000901@tds.net> <4799E36C.4090404@bigfoot.com> Message-ID: <47A2906B.1000502@tds.net> Ricardo Ar?oz wrote: > These solutions sometimes may have unexpected behavior. > class recursivedefaultdict(defaultdict): > def __init__(self): > self.default_factory = type(self) > d = recursivedefaultdict() > d['pepe']['jose']['juan'] = 25 > d['pepe']['jose'] = 25 Presumably you mean d['pepe']['martin'] = 25 > [i for i in d['pepe']] > it prints : ['jose', 'pedro', 'martin'] > expected : [defaultdict(, {'jose': > defaultdict(, {'juan': 25}), 'pedro': 25, > 'martin': 33})] I think your expectations are off. Iterating a dict gives the keys: In [14]: d=dict(juan=25, pedro=25, martin=33) In [15]: d Out[15]: {'juan': 25, 'martin': 33, 'pedro': 25} In [16]: [ i for i in d] Out[16]: ['juan', 'pedro', 'martin'] Kent From varsha.purohit at gmail.com Fri Feb 1 07:37:33 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Thu, 31 Jan 2008 22:37:33 -0800 Subject: [Tutor] [tutor] Scrollbars around the image Message-ID: Hi All, I have made a simple panel where i am loading an image from the folder. I have a button named zoomin. When i press this button a pair of horizontal and vertical scrollbars should appear on the image panel nearby image. so that we can see the zoomed image properly. I am trying to use wx.Scrollbarbut i am not able to fix the scrollbars properly around the image. I have not added the scrollbar portion to the button handler in the code below.. i have just commented out as its not actually working. import wx class ComboBox(wx.Dialog): def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size=(450, 470)) panel = wx.Panel(self, -1, (75, 20), (100, 127), style= wx.SUNKEN_BORDER) self.picture = wx.StaticBitmap(panel) self.picture.SetBitmap(wx.Bitmap('srk.jpg')) panel.SetBackgroundColour(wx.WHITE) wx.Button(self, 1, 'Close', (80, 220)) wx.Button(self, 2, 'Zoomin', (80, 280)) self.Bind(wx.EVT_BUTTON, self.OnClose, id=1) self.Bind(wx.EVT_BUTTON, self.OnZoom, id=2) self.Centre() self.ShowModal() self.Destroy() def OnClose(self, event): self.Close() def OnZoom(self, event): ## sw = wx.ScrolledWindow(panel) ## sw.SetScrollbars(20, 20, 155, 40) ## sw.Scroll(50,10) self.Close() app = wx.App() ComboBox(None, -1, 'picture box') app.MainLoop() But can please anybody suggest me how should i go ahead and solve this problem ?? -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080131/e8d5d84a/attachment-0001.htm From dineshbvadhia at hotmail.com Fri Feb 1 23:13:00 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 1 Feb 2008 14:13:00 -0800 Subject: [Tutor] matrix-vector multiplication errors Message-ID: I've posted this on the Scipy forum but maybe there are answers on Tutor too. I'm performing a standard Scipy matrix* vector multiplication, b=Ax , (but not using the sparse module) with different sizes of A as follows: Assuming 8 bytes per float, then: 1. matrix A with M=10,000 and N=15,000 is of approximate size: 1.2Gb 2. matrix A with M=10,000 and N=5,000 is of approximate size: 390Mb 3. matrix A with M=10,000 and N=1,000 is of approximate size: 78Mb The Python/Scipy matrix initialization statements are: > A = scipy.asmatrix(scipy.empty((I,J), dtype=int)) > x = scipy.asmatrix(scipy.empty((J,1), dtype=float)) > b = scipy.asmatrix(scipy.empty((I,1), dtype=float)) I'm using a Windows XP SP2 PC with 2Gb RAM. Both matrices 1. and 2. fail with INDeterminate values in b. Matrix 3. works perfectly. As I have 2Gb of RAM why are matrices 1. and 2. failing? The odd thing is that Python doesn't return any error messages with 1. and 2. but we know the results are garbage (literally!) Cheers! Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080201/5c3abb34/attachment.htm From williamakilmartin at yahoo.com Sat Feb 2 05:52:39 2008 From: williamakilmartin at yahoo.com (William Kilmartin) Date: Fri, 01 Feb 2008 20:52:39 -0800 Subject: [Tutor] Where to start? Message-ID: <47A3F717.90708@yahoo.com> Here's what I'm trying to accomplish; I track statistics at work. E.g. calls out, $ collected etc.. The graph has a rough guess of highest possible at the top and the lowest number in the past 3 months at the bottom. It's a simple line graph, week after week. I need to be able to add names of various statistics. I.e. calls out, money collected, proposals sent etc.. It then needs to create the graph, store the names, be able to take the week's numbers and store them along with being able to print. The highest and lowest points also need to also be inputed and changed if needed. Ideally this would be a GUI driven app for the sake of simplicity. What I'm looking for is advice on where to start, a middle ground and an end. I'm new to Python and programming and took this as the 1st thing I'd to create. I've been studying for a bit now and knowing where I'm going would be very helpful. -- "Microsoft isn't evil, they just make really crappy operating systems." -Linus Torvalds From alan.gauld at btinternet.com Sat Feb 2 08:25:53 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 2 Feb 2008 07:25:53 -0000 Subject: [Tutor] Where to start? References: <47A3F717.90708@yahoo.com> Message-ID: "William Kilmartin" wrote > It then needs to create the graph, store the names, be able to take > the > week's numbers and store them along with being able to print. The > highest and lowest points also need to also be inputed and changed > if > needed. > > Ideally this would be a GUI driven app for the sake of simplicity. > > What I'm looking for is advice on where to start, a middle ground > and an > end. I'm new to Python and programming and took this as the 1st > thing > I'd to create. I'd start off with a non gui version to check that the logic and math work. The simplest non GUI approach will be a week by week horizontal bar chart: wk5 ***************** $5K wk4 ******** $2K wk3 ************ $3K wk2 ************** $4K wk1 ***** $7K Calls 10 20 30 Total This is fairly easy to do using string formatting and print statements. Then work on saving the data to a file - a simple text file would do, or you could use pickle or even shelve. Shelve would be my bet since it will allow you to add the ability to easily retrieve data over a limited period or from archive etc Finally convert the text form of the graph to a GUI version using your favourite toolkit. This wouldn't be hard to do from scratch using a bare Canvas widget but there are plotting libraries available that make it easier still. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Feb 2 13:54:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 02 Feb 2008 07:54:26 -0500 Subject: [Tutor] [Fwd: PyWeek 6 is coming!] Message-ID: <47A46802.3000200@tds.net> For all of the budding game authors on the list...maybe there is interest in a python-tutor team? (No, I am not volunteering to lead it though of course the list is available for help.) Kent -------- Original Message -------- Subject: PyWeek 6 is coming! Date: Fri, 1 Feb 2008 08:11:34 +1100 From: richard at pyweek.org Reply-To: python-list at python.org To: pygame-users at seul.org CC: python-announce-list at python.org, pyglet-users at googlegroups.com, python-list at python.org PyWeek 6 will run from 00:00 UTC on March 30th through to 00:00 UTC on April 6th. Registration is NOT OPEN YET. It will open on Friday 2008/02/29. If you're new (or even coming back again) please have a look at the rules and help pages at http://www.pyweek.org/ The PyWeek challenge: 1. Invites entrants to write a game in one week from scratch either as an individual or in a team, 2. Is intended to be challenging and fun, 3. Will hopefully increase the public body of game tools, code and expertise, 4. Will let a lot of people actually finish a game, and 5. May inspire new projects (with ready made teams!) Entries must be developed in Python during the challenge, and must incorporate some theme decided at the start of the challenge. -- Visit the PyWeek website: http://www.pyweek.org/ From seon.kang at gmail.com Sat Feb 2 05:41:45 2008 From: seon.kang at gmail.com (Seon Kang) Date: Fri, 1 Feb 2008 23:41:45 -0500 Subject: [Tutor] Livewires Message-ID: Python will not recognize the keyboard class of livewires. what is my problem? (i have imported the modules and everything) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080201/90e7048b/attachment.htm From seon.kang at gmail.com Sat Feb 2 05:59:09 2008 From: seon.kang at gmail.com (Seon Kang) Date: Fri, 1 Feb 2008 23:59:09 -0500 Subject: [Tutor] Background Message-ID: How does set the background to change on the press of a chosen key? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080201/8ce4d388/attachment.htm From kent37 at tds.net Sat Feb 2 14:37:39 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 02 Feb 2008 08:37:39 -0500 Subject: [Tutor] Background In-Reply-To: References: Message-ID: <47A47223.9070401@tds.net> Seon Kang wrote: > How does set the background to change on the press of a chosen key? The background of what? The desktop? An application? What platform? Are you using a GUI toolkit? Kent From bhaaluu at gmail.com Sat Feb 2 16:48:18 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 2 Feb 2008 10:48:18 -0500 Subject: [Tutor] [Fwd: PyWeek 6 is coming!] In-Reply-To: <47A46802.3000200@tds.net> References: <47A46802.3000200@tds.net> Message-ID: Would you consider a python-Tutor team member who: 1. Is new to Python? 2. Never worked with a programming team before? 3. Doesn't have much gaming experience? 4. Doesn't have a recent version of MS-Windows (has Mac OS X or GNU/Linux)? 5. May not be running the latest and greatest version of Python? 6. Is willing to learn! If so, in what ways could such a team member contribute to the challenge? (Hoping to start a discussion here!) Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] On Feb 2, 2008 7:54 AM, Kent Johnson wrote: > For all of the budding game authors on the list...maybe there is > interest in a python-tutor team? (No, I am not volunteering to lead it > though of course the list is available for help.) > > Kent > > -------- Original Message -------- > Subject: PyWeek 6 is coming! > Date: Fri, 1 Feb 2008 08:11:34 +1100 > From: richard at pyweek.org > Reply-To: python-list at python.org > To: pygame-users at seul.org > CC: python-announce-list at python.org, pyglet-users at googlegroups.com, > python-list at python.org > > PyWeek 6 will run from 00:00 UTC on March 30th through to 00:00 UTC on > April > 6th. > > Registration is NOT OPEN YET. It will open on Friday 2008/02/29. > > If you're new (or even coming back again) please have a look at the > rules and > help pages at http://www.pyweek.org/ > > The PyWeek challenge: > > 1. Invites entrants to write a game in one week from scratch either > as an > individual or in a team, > 2. Is intended to be challenging and fun, > 3. Will hopefully increase the public body of game tools, code and > expertise, > 4. Will let a lot of people actually finish a game, and > 5. May inspire new projects (with ready made teams!) > > Entries must be developed in Python during the challenge, and must > incorporate > some theme decided at the start of the challenge. > > > -- > Visit the PyWeek website: > http://www.pyweek.org/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bhaaluu at gmail.com Sat Feb 2 16:50:46 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 2 Feb 2008 10:50:46 -0500 Subject: [Tutor] Livewires In-Reply-To: References: Message-ID: On Feb 1, 2008 11:41 PM, Seon Kang wrote: > Python will not recognize the keyboard class of livewires. what is my > problem? (i have imported the modules and everything) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Can you show us the error? Which platform are you running? Python/PyGame versions? Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From eike.welk at gmx.net Sat Feb 2 16:59:02 2008 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 02 Feb 2008 16:59:02 +0100 Subject: [Tutor] matrix-vector multiplication errors In-Reply-To: References: Message-ID: <200802021659.02554.eike.welk@gmx.net> On Friday 01 February 2008 23:13, Dinesh B Vadhia wrote: > I've posted this on the Scipy forum but maybe there are answers on > Tutor too. I'm performing a standard Scipy matrix* vector > multiplication, b=Ax , (but not using the sparse module) with > different sizes of A as follows: > > > Assuming 8 bytes per float, then: > 1. matrix A with M=10,000 and N=15,000 is of approximate size: > 1.2Gb 2. matrix A with M=10,000 and N=5,000 is of approximate size: > 390Mb 3. matrix A with M=10,000 and N=1,000 is of approximate size: > 78Mb > > The Python/Scipy matrix initialization statements are: > > A = scipy.asmatrix(scipy.empty((I,J), dtype=int)) > > x = scipy.asmatrix(scipy.empty((J,1), dtype=float)) > > b = scipy.asmatrix(scipy.empty((I,1), dtype=float)) > > I'm using a Windows XP SP2 PC with 2Gb RAM. > > Both matrices 1. and 2. fail with INDeterminate values in b. > Matrix 3. works perfectly. As I have 2Gb of RAM why are matrices > 1. and 2. failing? > > The odd thing is that Python doesn't return any error messages with > 1. and 2. but we know the results are garbage (literally!) > > Cheers! > > Dinesh I suspect that you have some uninitialized elements accidentally left in A or x; similarly to what Matthieu said in the Scipy list. You could try to initialize all elements to zero, and see if the errors still happen. It'll take some additional time but it's not too bad: In [1]:import numpy In [2]:M=10000 In [3]:N=15000 In [4]:time A = numpy.matrix(numpy.zeros((M,N), dtype=int)) CPU times: user 1.14 s, sys: 3.01 s, total: 4.15 s Wall time: 44.37 In [5]:time A = numpy.matrix(numpy.empty((M,N), dtype=int)) CPU times: user 0.65 s, sys: 1.12 s, total: 1.76 s Wall time: 6.11 Regards, Eike. From eike.welk at post.rwth-aachen.de Sat Feb 2 16:57:08 2008 From: eike.welk at post.rwth-aachen.de (Eike Welk) Date: Sat, 02 Feb 2008 16:57:08 +0100 Subject: [Tutor] matrix-vector multiplication errors In-Reply-To: References: Message-ID: <200802021657.12070.eike.welk@post.rwth-aachen.de> On Friday 01 February 2008 23:13, Dinesh B Vadhia wrote: > I've posted this on the Scipy forum but maybe there are answers on > Tutor too. I'm performing a standard Scipy matrix* vector > multiplication, b=Ax , (but not using the sparse module) with > different sizes of A as follows: > > > Assuming 8 bytes per float, then: > 1. matrix A with M=10,000 and N=15,000 is of approximate size: > 1.2Gb 2. matrix A with M=10,000 and N=5,000 is of approximate size: > 390Mb 3. matrix A with M=10,000 and N=1,000 is of approximate size: > 78Mb > > The Python/Scipy matrix initialization statements are: > > A = scipy.asmatrix(scipy.empty((I,J), dtype=int)) > > x = scipy.asmatrix(scipy.empty((J,1), dtype=float)) > > b = scipy.asmatrix(scipy.empty((I,1), dtype=float)) > > I'm using a Windows XP SP2 PC with 2Gb RAM. > > Both matrices 1. and 2. fail with INDeterminate values in b. > Matrix 3. works perfectly. As I have 2Gb of RAM why are matrices > 1. and 2. failing? > > The odd thing is that Python doesn't return any error messages with > 1. and 2. but we know the results are garbage (literally!) > > Cheers! > > Dinesh I suspect that you have some uninitialized elements accidentally left in A or x; similarly to what Matthieu said in the Scipy list. You could try to initialize all elements to zero, and see if the errors still happen. It'll take some additional time but it's not too bad: In [1]:import numpy In [2]:M=10000 In [3]:N=15000 In [4]:time A = numpy.matrix(numpy.zeros((M,N), dtype=int)) CPU times: user 1.14 s, sys: 3.01 s, total: 4.15 s Wall time: 44.37 In [5]:time A = numpy.matrix(numpy.empty((M,N), dtype=int)) CPU times: user 0.65 s, sys: 1.12 s, total: 1.76 s Wall time: 6.11 Regards, Eike. From rdm at rcblue.com Sat Feb 2 18:44:39 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Feb 2008 09:44:39 -0800 Subject: [Tutor] How to run this script? Message-ID: <20080202174536.E9A941E4018@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080202/6dcc41f0/attachment.htm From kent37 at tds.net Sat Feb 2 18:56:13 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 02 Feb 2008 12:56:13 -0500 Subject: [Tutor] How to run this script? In-Reply-To: <20080202174536.E9A941E4018@bag.python.org> References: <20080202174536.E9A941E4018@bag.python.org> Message-ID: <47A4AEBD.3020901@tds.net> Dick Moores wrote: > I found I couldn't figure out how to run it. Run as is, all it does is > print "usage: numbers.py NUMBER[s]" It's telling you to put the numbers on the command line, e.g. python numbers.py 12341234123412341234123412341234 Kent From rdm at rcblue.com Sat Feb 2 19:46:53 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 02 Feb 2008 10:46:53 -0800 Subject: [Tutor] How to run this script? In-Reply-To: <47A4AEBD.3020901@tds.net> References: <20080202174536.E9A941E4018@bag.python.org> <47A4AEBD.3020901@tds.net> Message-ID: <20080202184922.510201E4405@bag.python.org> At 09:56 AM 2/2/2008, Kent Johnson wrote: >Dick Moores wrote: > >>I found I couldn't figure out how to run it. Run as is, all it does >>is print "usage: numbers.py NUMBER[s]" > >It's telling you to put the numbers on the command line, e.g. >python numbers.py 12341234123412341234123412341234 Oh sure. Should have realized that. Thanks, Kent. Also, about the copy and pasting problem. I just heard from the author. Told me to use Firefox. I was using IE7. Dick From williamakilmartin at yahoo.com Sat Feb 2 22:07:47 2008 From: williamakilmartin at yahoo.com (William Kilmartin) Date: Sat, 02 Feb 2008 13:07:47 -0800 Subject: [Tutor] Tutor Digest, Vol 48, Issue 2 In-Reply-To: References: Message-ID: <47A4DBA3.10508@yahoo.com> Thanks! I'll get to work! "Microsoft isn't evil, they just make really crappy operating systems." -Linus Torvalds tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. matrix-vector multiplication errors (Dinesh B Vadhia) > 2. Where to start? (William Kilmartin) > 3. Re: Where to start? (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 1 Feb 2008 14:13:00 -0800 > From: "Dinesh B Vadhia" > Subject: [Tutor] matrix-vector multiplication errors > To: > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > I've posted this on the Scipy forum but maybe there are answers on Tutor too. I'm performing a standard Scipy matrix* vector multiplication, b=Ax , (but not using the sparse module) with different sizes of A as follows: > > > Assuming 8 bytes per float, then: > 1. matrix A with M=10,000 and N=15,000 is of approximate size: 1.2Gb > 2. matrix A with M=10,000 and N=5,000 is of approximate size: 390Mb > 3. matrix A with M=10,000 and N=1,000 is of approximate size: 78Mb > > The Python/Scipy matrix initialization statements are: > >> A = scipy.asmatrix(scipy.empty((I,J), dtype=int)) >> x = scipy.asmatrix(scipy.empty((J,1), dtype=float)) >> b = scipy.asmatrix(scipy.empty((I,1), dtype=float)) >> > > I'm using a Windows XP SP2 PC with 2Gb RAM. > > Both matrices 1. and 2. fail with INDeterminate values in b. Matrix 3. works perfectly. As I have 2Gb of RAM why are matrices 1. and 2. failing? > > The odd thing is that Python doesn't return any error messages with 1. and 2. but we know the results are garbage (literally!) > > Cheers! > > Dinesh > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: http://mail.python.org/pipermail/tutor/attachments/20080201/5c3abb34/attachment-0001.htm > > ------------------------------ > > Message: 2 > Date: Fri, 01 Feb 2008 20:52:39 -0800 > From: William Kilmartin > Subject: [Tutor] Where to start? > To: tutor at python.org > Message-ID: <47A3F717.90708 at yahoo.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Here's what I'm trying to accomplish; > > I track statistics at work. E.g. calls out, $ collected etc.. > > The graph has a rough guess of highest possible at the top and the > lowest number in the past 3 months at the bottom. > > It's a simple line graph, week after week. > > I need to be able to add names of various statistics. I.e. calls out, > money collected, proposals sent etc.. > > It then needs to create the graph, store the names, be able to take the > week's numbers and store them along with being able to print. The > highest and lowest points also need to also be inputed and changed if > needed. > > Ideally this would be a GUI driven app for the sake of simplicity. > > What I'm looking for is advice on where to start, a middle ground and an > end. I'm new to Python and programming and took this as the 1st thing > I'd to create. > > I've been studying for a bit now and knowing where I'm going would be > very helpful. > > > From varsha.purohit at gmail.com Sun Feb 3 03:45:08 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sat, 2 Feb 2008 18:45:08 -0800 Subject: [Tutor] [tutor]Imagechop error Message-ID: Hello everyone, I am tryin to use the imagechop module but i am not able to implement it successfully. I want to compare two images and give the resultant of the image using difference module. i am tryin to save the resultant image. But i am getting some wierd error. It gives error in the line where i have used imagechop.difference and the error is AttributeError: 'str' object has no attribute 'load' I am unable to understand what is the problem. Can any one help me understand this imagechop module ?? import Image import ImageChops file1 = "Nearest.jpg" file2 = "Bilinear.jpg" diff = ImageChops.difference(file1, file2) ext = ".jpg" diff.save("diff" + ext, "JPEG", quality =100) -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080202/50f9435e/attachment.htm From keridee at jayco.net Sun Feb 3 06:04:40 2008 From: keridee at jayco.net (Tiger12506) Date: Sun, 3 Feb 2008 00:04:40 -0500 Subject: [Tutor] [tutor]Imagechop error References: Message-ID: <001501c86622$4c0f9530$12fce004@jslaptop> > Hello everyone, > I am tryin to use the imagechop module but i am not able to > implement it successfully. I want to compare two images and give the > resultant of the image using difference module. i am tryin to save the > resultant image. But i am getting some wierd error. It gives error in the > line where i have used imagechop.difference and the error is > > AttributeError: 'str' object has no attribute 'load' I am unable to > understand what is the problem. Can any one help me understand this > imagechop module ?? I am 80% sure that this means it wants you to load the jpg files first, and then pass in those jpg objects into the difference function. > > import Image > import ImageChops > > file1 = "Nearest.jpg" > file2 = "Bilinear.jpg" > > diff = ImageChops.difference(file1, file2) > > ext = ".jpg" > diff.save("diff" + ext, "JPEG", quality =100) > > -- > Varsha Purohit, > Graduate Student > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tomdiz at yahoo.com Sun Feb 3 06:00:21 2008 From: tomdiz at yahoo.com (Thomas DiZoglio) Date: Sat, 2 Feb 2008 21:00:21 -0800 (PST) Subject: [Tutor] Windows Python 2.5.1 IPV6 problems Message-ID: <182998.40643.qm@web53505.mail.re2.yahoo.com> Hi, I'm trying to get some IPV6 python code running under Windows. I have installed Python 2.5.1 for Windows using the binaries from python.org. I'm a newbie to Python programming as well. The code works fine under Debian and MacOSX (both using Python 2.5) I have rebuilt the python binaries from source and set ENABLE_IPV6. This didn't help. I have also read about not being able to bind to a IPV4 and IPV6 socket. I tried setting the setsockopt() call using IPV6_V6ONLY, but this is not recognized by the python interpreter. Thanks for any help I can get. I'm stuck on this and searching the NET for help. I get the following error: C:\test_py>python ipv6.py Traceback (most recent call last): File "ipv6.py", line 119, in main() File "ipv6.py", line 113, in main p = listenTCP6(6666, TrivialServerFactory()) File "ipv6.py", line 95, in listenTCP6 return reactor.listenWith(Port, port, factory, backlog, interface) File "C:\python251\lib\site-packages\twisted\internet\posixbase.py", line 499, in listenWith p.startListening() File "C:\python251\lib\site-packages\twisted\internet\tcp.py", line 730, in st artListening skt = self.createInternetSocket() File "C:\python251\lib\site-packages\twisted\internet\tcp.py", line 718, in cr eateInternetSocket s = base.BasePort.createInternetSocket(self) File "C:\python251\lib\site-packages\twisted\internet\base.py", line 724, in c reateInternetSocket s = socket.socket(self.addressFamily, self.socketType) File "C:\Python251\lib\socket.py", line 154, in __init__ _sock = _realsocket(family, type, proto) TypeError: an integer is required Thanks. ------------------------- t0md I run with the following command: python ipv6.py ------------------------------------------------ HERE IS THE CODE for ipv6.py: ------------------------------------------------ #this is copied verbatim from http://twistedmatrix.com/trac/browser/sandbox/exarkun/ipv6.py #I'm unclear on the license that applies import socket from twisted.internet import tcp from twisted.internet import protocol from twisted.internet import reactor class IPv6Address(object): def __init__(self, type, host, port, flowInfo, scope): self.type = type self.host = host self.port = port self.flowInfo = flowInfo self.scope = scope def __eq__(self, other): if isinstance(other, IPv6Address): a = (self.type, self.host, self.port, self.flowInfo, self.scope) b = (other.type, other.host, other.port, other.flowInfo, other.scope) return a == b return False def __str__(self): return 'IPv6Address(%s, %r, %d, %d, %d)' % ( self.type, self.host, self.port, self.flowInfo, self.scope) def isIPv6Address(ip): try: socket.inet_pton(socket.AF_INET6, ip) except: return 0 return 1 class Client(tcp.Client): addressFamily = socket.AF_INET6 def resolveAddress(self): if isIPv6Address(self.addr[0]): self._setRealAddress(self.addr[0]) else: reactor.resolve(self.addr[0]).addCallbacks( self._setRealAddress, self.failIfNotConnected ) def getHost(self): return IPv6Address('TCP', *self.socket.getsockname()) def getPeer(self): return IPv6Address('TCP', *self.socket.getpeername()) class Connector(tcp.Connector): def _makeTransport(self): return Client(self.host, self.port, self.bindAddress, self, self.reactor) def getDestination(self): return IPv6Address('TCP', self.host, self.port, 0, 0) class Server(tcp.Server): def getHost(self): return IPv6Address('TCP', *self.socket.getsockname()) def getPeer(self): return IPv6Address('TCP', *self.client) class Port(tcp.Port): addressFamily = socket.AF_INET6 transport = Server def _buildAddr(self, address): return IPv6Address('TCP', *address) def getHost(self): return IPv6Address('TCP', *self.socket.getsockname()) def getPeer(self): return IPv6Address('TCP', *self.socket.getpeername()) def connectTCP6(host, port, factory, timeout=30, bindAddress=None, reactor=None): if reactor is None: from twisted.internet import reactor return reactor.connectWith( Connector, host, port, factory, timeout, bindAddress ) def listenTCP6(port, factory, backlog=5, interface='::', reactor=None): if reactor is None: from twisted.internet import reactor #IPV6_V6ONLY = 27, IPV6_BINDV6ONLY #IPPROTO_IPV6 = 41 #_socket.socket.setsockopt(_socket.IPPROTO_IPV6, _socket.IPV6_V6ONLY, 0) return reactor.listenWith(Port, port, factory, backlog, interface) def main(): from twisted.internet import reactor class TrivialProtocol(protocol.Protocol): def connectionMade(self): print 'I (', self.transport.getHost(), ') am connected! (to ', self.transport.getPeer(), ')' self.transport.write('Hello, world!\n') def dataReceived(self, data): print 'Received: ' + repr(data) class TrivialServerFactory(protocol.ServerFactory): protocol = TrivialProtocol class TrivialClientFactory(protocol.ClientFactory): protocol = TrivialProtocol p = listenTCP6(6666, TrivialServerFactory()) c = connectTCP6('::1', 6666, TrivialClientFactory()) reactor.run() if __name__ == '__main__': main() CONFIDENTIALITY NOTICE: Proprietary/Confidential Information belonging to Virgil Software, Inc. may be contained in this message. If you are not a recipient indicated or intended in this message (or responsible for delivery of this message to such person), or you think for any reason that this message may have been addressed to you in error, you may not use or copy or deliver this message (and all attachments) to anyone else. In such case, you should destroy this message (and all attached documents) and are asked to notify the sender by reply email. ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping From alan.gauld at btinternet.com Sun Feb 3 09:04:45 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Feb 2008 08:04:45 -0000 Subject: [Tutor] [tutor]Imagechop error References: Message-ID: "Varsha Purohit" wrote > AttributeError: 'str' object has no attribute 'load' I am unable > to > understand what is the problem. Can any one help me understand this > imagechop module ?? When posting errors don't just post the last line. Post the whole error message since the stacv trace often contains the most useful data. > file1 = "Nearest.jpg" > file2 = "Bilinear.jpg" > > diff = ImageChops.difference(file1, file2) You are passing file names not files so it may be that you need to pass file objects? But I don't know because I've bnever used ImageChops Alan G. From dotancohen at gmail.com Sun Feb 3 17:36:50 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 3 Feb 2008 18:36:50 +0200 Subject: [Tutor] Bad time to get into Python? Message-ID: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> The little programming that I need I have been able to get away with silly php and bash scripts. However, my needs are getting bigger and I see Python as an ideal language for my console apps, and the occasional GUI that I might write for the wife. However, with the coming of Python3 and the new syntax, is this a bad time to start learning Python? I don't want to learn 2.x if 3.x will replace it, and not be compatible, in one year. I know that I can continue using 2.x, but maybe I should wait until 3.x is released to start learning? What does the community think? That asked, I've heard that 2.6 can be configured to warn when using code that will not run in 3.x. Is this correct? How is this done? I'd like to do it on a per-file basis, so that I will only need to run one version of python on this machine. I want my own apps to throw errors, but not other python apps on this system. Is there some error-level code that I can run? Thanks in advance. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From alan.gauld at btinternet.com Sun Feb 3 18:33:11 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Feb 2008 17:33:11 -0000 Subject: [Tutor] Bad time to get into Python? References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> Message-ID: "Dotan Cohen" wrote > coming of Python3 and the new syntax, is this a bad time to start > learning Python? I don't want to learn 2.x if 3.x will replace it, 3.x won't be the end of changes in Python, amy more than other languages change. While the changes for 3.x will be bigger than for previous languages my understanding is that they ae not huge and certainly not as big as the jump from VB6 to VB.NET for example. A coming version change is never a good reason not to learn a language IMHO. More important is to ask why learn that language in the first place? What will it offer that your current skills don;t already provide? If you can answer that question positively then the version change will likely make no significant change to the cost/benefit equation. > That asked, I've heard that 2.6 can be configured > to warn when using code that will not run in 3.x. > Is this correct? How is this done? I beliebe you re right but don;t know the mechanism. But I should think it equally likely that there will be tools available either with the release or very soon after thart will, at the very least, identify the areas needing change - if not actually making most of the changes for you. This nearly always happens with significant language upgrades. > version of python on this machine. I want my own apps to throw > errors, > but not other python apps on this system. Is there some error-level > code that I can run? I'm not clear what you mean by that bit. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dave6502 at googlemail.com Sun Feb 3 18:54:39 2008 From: dave6502 at googlemail.com (dave selby) Date: Sun, 3 Feb 2008 17:54:39 +0000 Subject: [Tutor] os.system() problem Message-ID: Hi all, I am not sure if this is a Python or bash issue :). In bash if I execute 'motion' with the following ... dave at dev-machine:~/.kde/share/apps/kmotion$ motion &> /dev/null & [1] 10734 dave at dev-machine:~/.kde/share/apps/kmotion$ I get what I expect, a background job, however if I execute it from Python with an os.system ... os.system('motion &> /dev/null &') I get tons of output to the BASH shell ... [0] Processing thread 0 - config file /etc/motion/motion.conf [0] Processing config file /etc/motion/motion.1.conf [0] Processing config file /etc/motion/motion.2.conf [1] Thread is from /etc/motion/motion.1.conf [2] Thread is from /etc/motion/motion.2.conf [1] Thread started [2] Thread started [1] File of type 2 saved to: /var/lib/motion/20080203/01/tmp/175253.jpg ...etc ... I just can't work out why this is happening & how to stop it ?. Any ideas ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From dotancohen at gmail.com Sun Feb 3 18:57:24 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 3 Feb 2008 19:57:24 +0200 Subject: [Tutor] Bad time to get into Python? In-Reply-To: References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> Message-ID: <880dece00802030957m41e82470h3bf57e6b2c1d16f6@mail.gmail.com> On 03/02/2008, Alan Gauld wrote: > > "Dotan Cohen" wrote > > > coming of Python3 and the new syntax, is this a bad time to start > > learning Python? I don't want to learn 2.x if 3.x will replace it, > > 3.x won't be the end of changes in Python, amy more than > other languages change. While the changes for 3.x will be > bigger than for previous languages my understanding is > that they ae not huge and certainly not as big as the > jump from VB6 to VB.NET for example. > > A coming version change is never a good reason not > to learn a language IMHO. More important is to ask > why learn that language in the first place? What will > it offer that your current skills don;t already provide? > If you can answer that question positively then the > version change will likely make no significant change > to the cost/benefit equation. I currently use php on the webserver, and bash on desktop. I'm good at neither, and I've been leaning towards using php more and more on the desktop for scripting (the php -q flag supresses http header output for console usage). Python seems like a real language that can replace both. It is also flexible enough to let me do a GUI app in Qt if need be, or even a windows app should I ever need. I'm already convinced that I need to learn Python. But I don't want to learn it twice, and I'm in no rush. > > That asked, I've heard that 2.6 can be configured > > to warn when using code that will not run in 3.x. > > Is this correct? How is this done? > > I beliebe you re right but don;t know the mechanism. > But I should think it equally likely that there will be > tools available either with the release or very soon > after thart will, at the very least, identify the areas > needing change - if not actually making most of > the changes for you. This nearly always happens > with significant language upgrades. > > > version of python on this machine. I want my own apps to throw > > errors, > > but not other python apps on this system. Is there some error-level > > code that I can run? > > I'm not clear what you mean by that bit. In php error reporting can be changed on the fly, in the script file itself. So I can have one script that logs errors to a text file, and another that prints errors to the browser/CLI. I was hoping for something similar in Python. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From mlangford.cs03 at gtalumni.org Sun Feb 3 19:17:52 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 3 Feb 2008 13:17:52 -0500 Subject: [Tutor] os.system() problem In-Reply-To: References: Message-ID: <82b4f5810802031017u54fb7652rb19c6e931f5a7316@mail.gmail.com> Popen may be a better call for what you're trying to do. Some of the higher numbered popens will give you the stderr stream. The lowered numbered ones are probably all you need. http://docs.python.org/lib/node529.html --Michael On Feb 3, 2008 12:54 PM, dave selby wrote: > Hi all, > > I am not sure if this is a Python or bash issue :). > > In bash if I execute 'motion' with the following ... > > dave at dev-machine:~/.kde/share/apps/kmotion$ motion &> /dev/null & > [1] 10734 > dave at dev-machine:~/.kde/share/apps/kmotion$ > > I get what I expect, a background job, however if I execute it from > Python with an os.system ... > > os.system('motion &> /dev/null &') > > I get tons of output to the BASH shell ... > > [0] Processing thread 0 - config file /etc/motion/motion.conf > [0] Processing config file /etc/motion/motion.1.conf > [0] Processing config file /etc/motion/motion.2.conf > [1] Thread is from /etc/motion/motion.1.conf > [2] Thread is from /etc/motion/motion.2.conf > [1] Thread started > [2] Thread started > [1] File of type 2 saved to: /var/lib/motion/20080203/01/tmp/175253.jpg > ...etc ... > > I just can't work out why this is happening & how to stop it ?. Any ideas ? > > Cheers > > Dave > > > > -- > > Please avoid sending me Word or PowerPoint attachments. > See http://www.gnu.org/philosophy/no-word-attachments.html > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From thomas.pani at gmail.com Sun Feb 3 19:56:10 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Sun, 03 Feb 2008 19:56:10 +0100 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> Message-ID: <47A60E4A.1010902@gmail.com> Dotan Cohen wrote: > However, with the coming of Python3 and the new syntax, is this a bad time to start learning Python? Not at all, I'd say. Changes will be fairly small, with the main changes being: - print is replaced by a print() function - / will become the float division operator - changes towards iterators (e.g. range() doesn't return a list) - string filetype changes There are lots of other changes, but most of them include removing already deprecated idioms. [1] has a list of Python 3k changes. There's also the 2to3 conversion tool which allows you to run lots of conversion automated. > That asked, I've heard that 2.6 can be configured to warn when using > code that will not run in 3.x. Is this correct? Yes, 2.6 will support a "Py3k warnings mode". It should also have many of 3k's features already implemented, allowing to run both side-by-side or via __future__. PEP 3000 ([2]) has more info on this. > How is this done? I'd like to do it on a per-file basis, so that I will > only need to run one version of python on this machine. Don't know. But if your only using it for some home-coding, you would just once do the conversion and then update to 3k. > I want my own apps to throw errors, > but not other python apps on this system. Is there some error-level > code that I can run? Not sure what you mean by that. Are you refering to exception-handling? I'd say it's not a bad time to learn Python. There will be some major changes in 3k, but as long as you don't have to maintain 2.6 and 3.0 in parallel, conversion should be easy enough. Cheers, thomas pani [1] http://docs.python.org/dev/3.0/whatsnew/3.0.html [2] http://www.python.org/dev/peps/pep-3000/ From kent37 at tds.net Sun Feb 3 20:01:41 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 14:01:41 -0500 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> Message-ID: <47A60F95.7000704@tds.net> Dotan Cohen wrote: > The little programming that I need I have been able to get away with > silly php and bash scripts. However, my needs are getting bigger and I > see Python as an ideal language for my console apps, and the > occasional GUI that I might write for the wife. However, with the > coming of Python3 and the new syntax, is this a bad time to start > learning Python? I don't want to learn 2.x if 3.x will replace it, and > not be compatible, in one year. I know that I can continue using 2.x, > but maybe I should wait until 3.x is released to start learning? What > does the community think? Don't wait. Python 2.5 is very useful today. Python 2.x will be viable for years. Python 2.6 is not even scheduled for release until this summer and it will be maintained long after that. PEP 3000 says, "I expect that there will be parallel Python 2.x and 3.x releases for some time; the Python 2.x releases will continue for a longer time than the traditional 2.x.y bugfix releases. Typically, we stop releasing bugfix versions for 2.x once version 2.(x+1) has been released. But I expect there to be at least one or two new 2.x releases even after 3.0 (final) has been released, probably well into 3.1 or 3.2. This will to some extent depend on community demand for continued 2.x support, acceptance and stability of 3.0, and volunteer stamina." http://www.python.org/dev/peps/pep-3000/ > That asked, I've heard that 2.6 can be configured to warn when using > code that will not run in 3.x. Is this correct? How is this done? I'd > like to do it on a per-file basis, so that I will only need to run one > version of python on this machine. I want my own apps to throw errors, > but not other python apps on this system. Is there some error-level > code that I can run? There is a command-line switch in 2.6, -3, which will enables warnings about features that will be removed in Python 3.0, and some features of Python 3.0 are being back-ported to Python 2.6: http://docs.python.org/dev/whatsnew/2.6.html#python-3-0 There is also a tool being developed (2to3) to convert Python 2.x code to 3.0 semi-automatically: http://svn.python.org/view/sandbox/trunk/2to3/README?rev=57919&view=markup However, the goal of these efforts, IIUC, is *not* to allow a single script to run in both 2.6 and 3.0, it is to enable easy porting from 2.6 to 3.0. In particular, my understanding is that the -3 warnings will warn of constructs that cannot be correctly converted by 2to3. More details here: http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition So I would say the outlook for 2.6 is better than you think but the outlook for compatibility is worse. Kent From dotancohen at gmail.com Sun Feb 3 20:08:42 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 3 Feb 2008 21:08:42 +0200 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <47A60F95.7000704@tds.net> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> <47A60F95.7000704@tds.net> Message-ID: <880dece00802031108va543f6eqa30317b0f3a651c4@mail.gmail.com> On 03/02/2008, Kent Johnson wrote: > Dotan Cohen wrote: > > The little programming that I need I have been able to get away with > > silly php and bash scripts. However, my needs are getting bigger and I > > see Python as an ideal language for my console apps, and the > > occasional GUI that I might write for the wife. However, with the > > coming of Python3 and the new syntax, is this a bad time to start > > learning Python? I don't want to learn 2.x if 3.x will replace it, and > > not be compatible, in one year. I know that I can continue using 2.x, > > but maybe I should wait until 3.x is released to start learning? What > > does the community think? > > > Don't wait. Python 2.5 is very useful today. Python 2.x will be viable > for years. Python 2.6 is not even scheduled for release until this > summer and it will be maintained long after that. PEP 3000 says, > > "I expect that there will be parallel Python 2.x and 3.x releases for > some time; the Python 2.x releases will continue for a longer time than > the traditional 2.x.y bugfix releases. Typically, we stop releasing > bugfix versions for 2.x once version 2.(x+1) has been released. But I > expect there to be at least one or two new 2.x releases even after 3.0 > (final) has been released, probably well into 3.1 or 3.2. This will to > some extent depend on community demand for continued 2.x support, > acceptance and stability of 3.0, and volunteer stamina." > > > http://www.python.org/dev/peps/pep-3000/ > > > > > That asked, I've heard that 2.6 can be configured to warn when using > > code that will not run in 3.x. Is this correct? How is this done? I'd > > like to do it on a per-file basis, so that I will only need to run one > > version of python on this machine. I want my own apps to throw errors, > > but not other python apps on this system. Is there some error-level > > code that I can run? > > > There is a command-line switch in 2.6, -3, which will enables warnings > about features that will be removed in Python 3.0, and some features of > Python 3.0 are being back-ported to Python 2.6: > http://docs.python.org/dev/whatsnew/2.6.html#python-3-0 > > There is also a tool being developed (2to3) to convert Python 2.x code > to 3.0 semi-automatically: > http://svn.python.org/view/sandbox/trunk/2to3/README?rev=57919&view=markup > > However, the goal of these efforts, IIUC, is *not* to allow a single > script to run in both 2.6 and 3.0, it is to enable easy porting from 2.6 > to 3.0. In particular, my understanding is that the -3 warnings will > warn of constructs that cannot be correctly converted by 2to3. More > details here: > http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition > > So I would say the outlook for 2.6 is better than you think but the > outlook for compatibility is worse. > > > Kent > Thanks. My concern is not that the code won't run on Python3, rather, that the effort that I put into learning 2.x will be wasted when 3.x will be current. Now I'm a bit more confident, however. I'll get to work learning right away. Thanks. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From kent37 at tds.net Sun Feb 3 20:19:58 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 14:19:58 -0500 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <880dece00802031108va543f6eqa30317b0f3a651c4@mail.gmail.com> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> <47A60F95.7000704@tds.net> <880dece00802031108va543f6eqa30317b0f3a651c4@mail.gmail.com> Message-ID: <47A613DE.5020008@tds.net> Dotan Cohen wrote: > Thanks. My concern is not that the code won't run on Python3, rather, > that the effort that I put into learning 2.x will be wasted when 3.x > will be current. No, it will not be wasted. 3.0 is not a new language, it is a major tuneup of the existing language. > Now I'm a bit more confident, however. I'll get to > work learning right away. Thanks. Great! Come back when you have more questions! Kent From python-list at puzzled.xs4all.nl Sun Feb 3 21:15:59 2008 From: python-list at puzzled.xs4all.nl (Patrick) Date: Sun, 03 Feb 2008 21:15:59 +0100 Subject: [Tutor] Hello and newbie question about "self" Message-ID: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> Hi guru's, New to the list. I bought O'Reilly's Learning Python (3rd edition for 2.5) a while back. Slowly making my way through it and was pleasantly surprised that Python seems easier than C. Until...I bumped into the "self" thingy. Can anyone please point me to a document that explains "self" in layman's terms. Or lacking such a doc throw in a much appreciated layman's explanation what "self" is and when/where to use it? In the book (so far) I've seen "self" pop up in these examples (on pages 457 and 458): class C1(C2, C3): def setname(self, who) self.name = who class C1(C2, C3): def __init__(self, who) self.name = who Thanks for any pointers! Regards, Patrick From seon.kang at gmail.com Sun Feb 3 20:30:38 2008 From: seon.kang at gmail.com (Seon Kang) Date: Sun, 3 Feb 2008 14:30:38 -0500 Subject: [Tutor] TypeError Message-ID: When i tried to run my program, i was given this message (this is the message in part) file "C:Python25\lib\site-packages\livewires\games.py", line 503, in_tick self.position = ((self._x + self._dx), (self._y + self._dy)) TypeError: unsopported opernad type(s) for +: 'int' and type' What is the nature of my problem? But more specifically, what is the 'type' it's referring to? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080203/ad3b99b1/attachment.htm From tyler.smith at mail.mcgill.ca Sun Feb 3 21:30:49 2008 From: tyler.smith at mail.mcgill.ca (Tyler Smith) Date: Sun, 3 Feb 2008 20:30:49 +0000 (UTC) Subject: [Tutor] newbie code review please! Message-ID: Hi, I'm a middling amateur coder in C and elisp, trying to wrap my head around python syntax. I've implemented the code for the markov chain random text generator from Kernighan and Pike's "The practice of programming", and I'd appreciate any tips on how to make it more pythonic. The code appears to work as intended. It reads a file, breaks the text into a list of individual words. It then builds a hash table in the form of: (prefix-word-1, prefix-word-2):[list-of-possible-following-words] It finishes by using the hash table to generate a nonsensical, and occasionally amusing bit of text based on the input. Any comments welcome! Thanks, Tyler #! /usr/bin/python import sys, random word_max = 1000 # Read in file infile = open(sys.argv[1], 'r') ifstring = infile.read() # break file into words iflist = ifstring.replace('\n', ' ').split() # build hash of form (prefix1, prefix2): [word] word_hash = {} for i in range(len(iflist) - 2): pr1 = iflist[i] pr2 = iflist[i+1] tv = iflist[i+2] tk = (pr1, pr2) if word_hash.has_key(tk) and tv not in word_hash[tk]: word_hash[tk].append(tv) else: word_hash[tk] = [tv] if word_hash.has_key((iflist[-2], iflist[-1])): word_hash[(iflist[-2], iflist[-1])].append('\n') else: word_hash[(iflist[-2], iflist[-1])] = ['\n'] # output first two words w1, w2 = iflist[0:2] print w1, w2, # generate new words from hash word_num = 0 while w2 <> '\n' and word_num < word_max: w1, w2 = w2, random.choice(word_hash[(w1, w2)]) print w2, word_num += 1 From mlangford.cs03 at gtalumni.org Sun Feb 3 22:15:45 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 3 Feb 2008 16:15:45 -0500 Subject: [Tutor] Hello and newbie question about "self" In-Reply-To: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> Message-ID: <82b4f5810802031315j4ee9a72do1ff37674c7e82664@mail.gmail.com> In C, you may have "objectorientedesque" code like the following; struct net { int foo; int bar; int baz; }; void populate_net( struct net* mynet, int fooval, int barval) { mynet->foo = fooval; mynet->bar = barval; mynet ->baz = fooval * 5; } int connect_to_net(struct net* mynet) { return open_internet_connection(mynet->foo); } int main (void) { struct net inet; populate_net(&inet,2,2); int returncode = connect_to_net(&inet); printf("%d\n",returncode); } In that batch of C code, you manipulate the struct without fiddling with its fields in the user code. You let the functions change its values so that they are done correctly. In python, you are doing something similar. However, they make some syntactic sugar to make it so you don't have to pass the object in explicily. That is what self is. So the analgous python code is: class net(object): def __init__(self,fooval,barbal): self.foo = fooval self.bar = barval self.baz = fooval*5 def connect_to(self): return open_internet_connection(self.foo) inet = net(2,2) returncode = inet.connect_to() print returncode See how you don't have to pass in the inet object in? Instead you call it with the inet.connect_to() function, and the object itself is passed in explicitly as self? That's all it is. Btw, make sure to always include "self". Otherwise you'll be writing a class method and it doesn't work the same way. --Michael On Feb 3, 2008 3:15 PM, Patrick wrote: > Hi guru's, > > New to the list. I bought O'Reilly's Learning Python (3rd edition for > 2.5) a while back. Slowly making my way through it and was pleasantly > surprised that Python seems easier than C. Until...I bumped into the > "self" thingy. > > Can anyone please point me to a document that explains "self" in > layman's terms. Or lacking such a doc throw in a much appreciated > layman's explanation what "self" is and when/where to use it? > > In the book (so far) I've seen "self" pop up in these examples (on pages > 457 and 458): > > class C1(C2, C3): > def setname(self, who) > self.name = who > > class C1(C2, C3): > def __init__(self, who) > self.name = who > > Thanks for any pointers! > > Regards, > Patrick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From kent37 at tds.net Sun Feb 3 22:16:43 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 16:16:43 -0500 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <47A60F95.7000704@tds.net> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> <47A60F95.7000704@tds.net> Message-ID: <47A62F3B.9060106@tds.net> I did a little research on the question of running the same script unmodified in Python 2.6 and 3.0. It seems that there is no consensus opinion and it may depend on your personal tolerance for compatibility cruft. Here is a c.l.py thread of interest: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4e0a71d86e80d0f9/8e7fb527e32d3064?hl=en& Kent From kent37 at tds.net Sun Feb 3 22:21:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 16:21:27 -0500 Subject: [Tutor] TypeError In-Reply-To: References: Message-ID: <47A63057.5030908@tds.net> Seon Kang wrote: > When i tried to run my program, i was given this message > (this is the message in part) > > file "C:Python25\lib\site-packages\livewires\games.py", line 503, in_tick > self.position = ((self._x + self._dx), (self._y + self._dy)) > TypeError: unsopported opernad type(s) for +: 'int' and type' > > What is the nature of my problem? It seems that either self._dx or self._dy is not an integer. > But more specifically, what is the 'type' it's referring to? A type is the class of a value. For example, int, str and float are all types. If you show us the full traceback and some of your code we can be more helpful. Kent From kent37 at tds.net Sun Feb 3 22:26:05 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 16:26:05 -0500 Subject: [Tutor] Hello and newbie question about "self" In-Reply-To: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> Message-ID: <47A6316D.2080605@tds.net> Patrick wrote: > Hi guru's, > > New to the list. I bought O'Reilly's Learning Python (3rd edition for > 2.5) a while back. Slowly making my way through it and was pleasantly > surprised that Python seems easier than C. Until...I bumped into the > "self" thingy. This should be covered by any tutorial. 2nd edition of Learning Python has a section called Methods that introduces self. Also see http://www.ibiblio.org/swaroopch/byteofpython/read/self.html http://hetland.org/writing/instant-hacking.html Kent From kent37 at tds.net Sun Feb 3 22:35:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 16:35:08 -0500 Subject: [Tutor] newbie code review please! In-Reply-To: References: Message-ID: <47A6338C.40708@tds.net> Tyler Smith wrote: > iflist = ifstring.replace('\n', ' ').split() The replace is not needed, split() splits on any whitespace including newlines. > # build hash of form (prefix1, prefix2): [word] > word_hash = {} > for i in range(len(iflist) - 2): > pr1 = iflist[i] > pr2 = iflist[i+1] > tv = iflist[i+2] > tk = (pr1, pr2) or, tk = tuple(iflist[i:i+2]) > if word_hash.has_key(tk) and tv not in word_hash[tk]: > word_hash[tk].append(tv) > else: > word_hash[tk] = [tv] This could be done much more cleanly with a defaultdict that maps a pair to a set: from collections import defaultdict wordhash = defaultdict(set) ...then just wordhash[tk].add(tv) > if word_hash.has_key((iflist[-2], iflist[-1])): > word_hash[(iflist[-2], iflist[-1])].append('\n') > else: > word_hash[(iflist[-2], iflist[-1])] = ['\n'] word_hash[(iflist[-2], iflist[-1])].add('\n') > # generate new words from hash > word_num = 0 > while w2 <> '\n' and word_num < word_max: > w1, w2 = w2, random.choice(word_hash[(w1, w2)]) > print w2, > word_num += 1 or, for word_num in range(word_max): w1, w2 = w2, random.choice(word_hash[(w1, w2)]) print w2, if w2 == '\n': break Kent From kent37 at tds.net Sun Feb 3 22:43:43 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 16:43:43 -0500 Subject: [Tutor] TypeError In-Reply-To: References: <47A63057.5030908@tds.net> Message-ID: <47A6358F.4030508@tds.net> Seon Kang wrote: > Why does it not specify the type? Actually, it is specifying the type of the bad argument, which is itself 'type'. Confusing, I know. Try this: >>> 1+int ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : unsupported operand type(s) for +: 'int' and 'type' The type of 1 is 'int' and the type of int is 'type'. It is telling you that you are trying to add an integer to a type object. > here is the entire section of the module that i imported that's giving > me the trouble. Why is it giving the TypeError? It would really help to see *your* code and the *complete* traceback. Can you figure out where _dx and _dy are coming from? They don't seem to be assigned in the code you show here. Also please use Reply All to reply to the list. Kent > > > > class Sprite(object): > def __init__(self, image, angle=0, > x=0, y=0, > top=None, bottom=None, left=None, right=None, > dx=0, dy=0, > interval=1, is_collideable=True): > > if not Screen.initialized: > raise GamesError, "Screen object must be intialized before > any Sprite object" > > self._surface = image > self._orig_surface = image # Surface before any rotation > self._rect = self._surface.get_rect() > > self.position = (x, y) > > if top != None: > self.top = top > if bottom != None: > self.bottom = bottom > if left != None: > self.left = left > if right != None: > self.right = right > > self.velocity = (dx, dy) > > self._angle = angle % 360 > if self._angle != 0: > self._rotate() > > self.is_collideable = is_collideable > > self._interval = interval > self._tickable = 1 > self._next = 0 > > self._gone = 0 > > def __del__(self): > if screen and not self._gone: > self.destroy() > > def _draw(self): > """ > Draw object on screen by blitting the image onto the screen. > """ > screen.blit_and_dirty(self._surface, self._rect) > > def _erase(self): > """ > Erase object from screen by blitting the background over where > it was. > """ > screen.blit_background(self._rect) > > def _replace(self, new_surface): > x, y = self.position > self._surface = new_surface > self._rect = self._surface.get_rect() > self.position = (x, y) > > def _rotate(self): > self._replace(pygame.transform.rotate(self._orig_surface, > -self._angle)) > > def _tick(self): > self._next = self._next + 1 > if self._next >= self._interval: > self._next = 0 > self.tick() > if self._dx or self._dy: > self.position = ( (self._x + self._dx), (self._y + self._dy) ) > self.update() > > def start (self): > self._tickable = 1 > self._next = 0 > > def stop (self): > self._tickable = 0 > > def update(self): > pass > > def tick(self): > pass > > def overlaps(self, other): > if not self.is_collideable or not other.is_collideable: > return False > else: > return self._rect.colliderect(other._rect) > > def elevate(self, above=None): > """ > Elevate an object to the top of the stack, or above the specified > object. > """ > screen._elevate(self, above) > > def lower(self, below=None): > """ > Lower an object to the bottom of the stack, or below the specified > object. > """ > screen._lower(self, below) > > def destroy(self): > """ > Erase object from screen and remove it from the list of objects > maintained by games module. > """ > self._erase() > screen.remove(self) > self._gone = 1 > > > > > On 2/3/08, *Kent Johnson* > wrote: > > Seon Kang wrote: > > When i tried to run my program, i was given this message > > (this is the message in part) > > > > file "C:Python25\lib\site-packages\livewires\games.py", line 503, > in_tick > > self.position = ((self._x + self._dx), (self._y + self._dy)) > > TypeError: unsopported opernad type(s) for +: 'int' and type' > > > > What is the nature of my problem? > > It seems that either self._dx or self._dy is not an integer. > > > But more specifically, what is the 'type' it's referring to? > > A type is the class of a value. For example, int, str and float are all > types. > > If you show us the full traceback and some of your code we can be more > helpful. > > Kent > > From gslindstrom at gmail.com Sun Feb 3 23:06:36 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sun, 3 Feb 2008 16:06:36 -0600 Subject: [Tutor] PyCon 2008 Tutorial Sessions Message-ID: Registration for PyCon 2008 is now open. Held in Chicago March 14-16 with "Tutorial Thursday" on March 13 and sprints afterwards, it is expected that nearly 800 Python enthusiasts will attend at least part of the conference. It is totally run by volunteers and is affordable for just about anyone. I would like to point out the tutorial sessions being offered; all the way from "Python for the Absolute Beginner", to advanced courses on optimizing Python programs (with 27 more classes in between). Click on over to http://us.pycon.org/2008/about/ for information about the conference. Here is a list of the classes being offered along with the instructors scheduled to present the classes (click to get more information on a session). It's a great way to learn more Python. *Morning Session* (9:00am-12:20pm) - Eggs and Buildout Deployment in Python(Jeff Rush) - Python 101 for Programmers(Steve Holden) - Introduction to SQLAlchemy(Jonathan Ellis and Michael Bayer) - Python plotting with matplotlib and pylab(John Hunter) - SWIG Master Class (David Beazley) - Secrets of the Framework Creators(Feihong Hsu and Kumar McMillan) - Introduction to NumPy(Travis Oliphant and Eric Jones) - Making Small Software for Small People, Sugar/OLPC Coding by Example(Mike C. Fletcher) - Hands-on Python for the Absolute Beginner I(Dr. Andrew Harrington) *Afternoon Session* (1:20pm-4:40pm) - Python 101 (Stuart Williams) - Getting Started with Pylons/TurboGears2 & WSGI: Modern Python Web Development (Mark Ramm and Ben Bangert) - Advanced SQLAlchemy(Jonathan Ellis and Michael Bayer) - Django Tutorial (Jacob Kaplan-Moss) - wxPython I: Intro to GUI Programming with wxPython and MVC(David Goodger) - Faster Python Programs through Optimization and Extensions I(Mike M?ller) - Tools for Scientific Computing in Python(Travis Oliphant and Eric Jones) - Generator Tricks for Systems Programmers(David Beazley) - Basic Python for Java Programmers(Alex Martelli and Anna Ravenscroft) - Hands-on Python for the Absolute Beginner II(Dr. Andrew Harrington) *Evening Session* (6:10pm-9:30pm) - Python 102 (Stuart Williams) - Mastering Pylons and TurboGears 2: Moving Beyond the Basics.(Mark Ramm, Ben Bangert) - Practical Applications of Agile (Web) Testing Tools(C. Titus Brown and Grig Gheorghiu) - Django Code Lab (Jacob Kaplan-Moss, Adrian Holovaty and James Bennett) - wxPython II: Advanced GUI Programming with wxPython and MVC(David Goodger) - Faster Python Programs through Optimization and Extensions II(Mike M?ller) - Automating Windows Applications with win32com(Roy H. Han) - Internet Programming with Python(Wesley J. Chun) - Tail Wags Fangs: What Python Developers Should Know About Plone(Rob Lineberger) - Pygame: Modern game development(Noah Kantrowitz and Marc Destefano) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080203/ab2c771b/attachment.htm From gtxy20 at gmail.com Mon Feb 4 00:35:08 2008 From: gtxy20 at gmail.com (GTXY20) Date: Sun, 3 Feb 2008 18:35:08 -0500 Subject: [Tutor] PHP & Python suggestions.... Message-ID: <39cb7e5d0802031535ja1ce7desdc8d4462cd984f39@mail.gmail.com> Hi all, First off let me say how helpful and informative this mailing list is. It is very much appreciated. Anyway, I am looking for some suggestions for reading up on how to call Python from PHP scripts, specifically calling from a PHP web application - PHP will call python script with some arguments and python will run on the server and return the results within another PHP page. Once again thanks. GTXY20. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080203/2f9aeaa6/attachment.htm From alan.gauld at btinternet.com Mon Feb 4 00:50:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 3 Feb 2008 23:50:49 -0000 Subject: [Tutor] Hello and newbie question about "self" References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> Message-ID: "Patrick" wrote > Can anyone please point me to a document that explains "self" in > layman's terms. Try the OOP topic inmy tutorial... > Or lacking such a doc throw in a much appreciated > layman's explanation what "self" is and when/where to use it? Others have given code samples but a conceptuial explanation is that a) self is only used in OO programming within metjhods of a class. b) self refers to the actual instance of the object receiving the message with caused the method to be invoked. Thus if we have a class C with a method m and 3 instances a,b and z then when we invoke a.m() self will refer to a and when we invoke b.m() self will refer to b. This means that the innards of the method can use self to access the instance specific data for that invocation. If you have used C++ at all you might recognise it as the same as 'this' in C++ except that in Python you must explicitly specify it whereas C++ creates 'this' magically behind the scenes. See my tutorial for more on this under the heading "Using classes". If you haven't started writing classes yet, you can safely ignore it for now! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From python-list at puzzled.xs4all.nl Mon Feb 4 01:33:02 2008 From: python-list at puzzled.xs4all.nl (Patrick) Date: Mon, 04 Feb 2008 01:33:02 +0100 Subject: [Tutor] Hello and newbie question about "self" In-Reply-To: <47A6316D.2080605@tds.net> References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> <47A6316D.2080605@tds.net> Message-ID: <47A65D3E.3000005@puzzled.xs4all.nl> Hi Kent, Kent Johnson wrote: > Patrick wrote: >> Hi guru's, >> >> New to the list. I bought O'Reilly's Learning Python (3rd edition for >> 2.5) a while back. Slowly making my way through it and was pleasantly >> surprised that Python seems easier than C. Until...I bumped into the >> "self" thingy. > > This should be covered by any tutorial. 2nd edition of Learning Python > has a section called Methods that introduces self. Also see Yes it does but all was not clear after I finished the first part (chapter 22 in my 3rd edition). Just read chapter 23 and things are clearer now. Luckily the start of chapter 24 mentions that it's no big deal if I didn't understand everything because they will dive deeper into it explaining more. > http://www.ibiblio.org/swaroopch/byteofpython/read/self.html > http://hetland.org/writing/instant-hacking.html Thanks for the links. Will read them when I have some spare cycles. Regards, Patrick From python-list at puzzled.xs4all.nl Mon Feb 4 01:34:05 2008 From: python-list at puzzled.xs4all.nl (Patrick) Date: Mon, 04 Feb 2008 01:34:05 +0100 Subject: [Tutor] Hello and newbie question about "self" In-Reply-To: <82b4f5810802031315j4ee9a72do1ff37674c7e82664@mail.gmail.com> References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> <82b4f5810802031315j4ee9a72do1ff37674c7e82664@mail.gmail.com> Message-ID: <47A65D7D.5020508@puzzled.xs4all.nl> Hi Michael, Michael Langford wrote: > In C, you may have "objectorientedesque" code like the following; > > struct net { > int foo; > int bar; > int baz; > }; > > > void populate_net( struct net* mynet, int fooval, int barval) > { > mynet->foo = fooval; > mynet->bar = barval; > mynet ->baz = fooval * 5; > } > > int connect_to_net(struct net* mynet) > { > return open_internet_connection(mynet->foo); > } > > int main (void) > { > struct net inet; > populate_net(&inet,2,2); > > int returncode = connect_to_net(&inet); > printf("%d\n",returncode); > } Heh I had to grab my C book and browse up on structs and pointers to get an idea what this was all about :) > In that batch of C code, you manipulate the struct without fiddling > with its fields in the user code. You let the functions change its > values so that they are done correctly. Ok that makes sense. > In python, you are doing something similar. However, they make some > syntactic sugar to make it so you don't have to pass the object in > explicily. That is what self is. Got it. > So the analgous python code is: > > > class net(object): > def __init__(self,fooval,barbal): > self.foo = fooval > self.bar = barval > self.baz = fooval*5 > > def connect_to(self): > return open_internet_connection(self.foo) > > > inet = net(2,2) > returncode = inet.connect_to() > print returncode > > See how you don't have to pass in the inet object in? Instead you call > it with the inet.connect_to() function, and the object itself is > passed in explicitly as self? Aaah starting to understand now. > That's all it is. > > Btw, make sure to always include "self". Otherwise you'll be writing a > class method and it doesn't work the same way. Thanks for the elaborate explanation! Regards, Patrick From python-list at puzzled.xs4all.nl Mon Feb 4 01:38:52 2008 From: python-list at puzzled.xs4all.nl (Patrick) Date: Mon, 04 Feb 2008 01:38:52 +0100 Subject: [Tutor] Hello and newbie question about "self" In-Reply-To: References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> Message-ID: <47A65E9C.1040405@puzzled.xs4all.nl> Hi Alan, Alan Gauld wrote: > "Patrick" wrote > >> Can anyone please point me to a document that explains "self" in >> layman's terms. > > Try the OOP topic inmy tutorial... Thanks will have a look. >> Or lacking such a doc throw in a much appreciated >> layman's explanation what "self" is and when/where to use it? > > Others have given code samples but a conceptuial explanation > is that > a) self is only used in OO programming within metjhods of a class. Now that really helps. I was wondering about that and this answers it. > b) self refers to the actual instance of the object receiving the > message with caused the method to be invoked. This and reading chapter 23 in the book makes things much clearer now. Thanks! > Thus if we have a class C with a method m and 3 instances > a,b and z then when we invoke a.m() self will refer to a and > when we invoke b.m() self will refer to b. This means that the > innards of the method can use self to access the instance > specific data for that invocation. Even more clear now :) > If you have used C++ at all you might recognise it as the > same as 'this' in C++ except that in Python you must explicitly > specify it whereas C++ creates 'this' magically behind the scenes. Last time I used C++ was (iirc) in 1987 with a Borland product. I recall "this" and remember I got stuck on it then too. > See my tutorial for more on this under the heading > "Using classes". Will do. Thanks for the pointer. > If you haven't started writing classes yet, you can safely ignore > it for now! I probably won't need to start writing classes but I really want to finish the book before I start coding something. I have a small script I did in (horrible) bash and look forward to try to implement it in (less horrible) Python. Thanks for your help. Regards, Patrick From patrick-lists at puzzled.xs4all.nl Mon Feb 4 01:35:39 2008 From: patrick-lists at puzzled.xs4all.nl (Patrick Lists) Date: Mon, 04 Feb 2008 01:35:39 +0100 Subject: [Tutor] Hello and newbie question about "self" In-Reply-To: References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> Message-ID: <47A65DDB.1030901@puzzled.xs4all.nl> Hi Alan, Alan Gauld wrote: > "Patrick" wrote > >> Can anyone please point me to a document that explains "self" in >> layman's terms. > > Try the OOP topic inmy tutorial... Thanks will have a look. >> Or lacking such a doc throw in a much appreciated >> layman's explanation what "self" is and when/where to use it? > > Others have given code samples but a conceptuial explanation > is that > a) self is only used in OO programming within metjhods of a class. Now that really helps. I was wondering about that and this answers it. > b) self refers to the actual instance of the object receiving the > message with caused the method to be invoked. This and reading chapter 23 in the book makes things much clearer now. Thanks! > Thus if we have a class C with a method m and 3 instances > a,b and z then when we invoke a.m() self will refer to a and > when we invoke b.m() self will refer to b. This means that the > innards of the method can use self to access the instance > specific data for that invocation. Even more clear now :) > If you have used C++ at all you might recognise it as the > same as 'this' in C++ except that in Python you must explicitly > specify it whereas C++ creates 'this' magically behind the scenes. Last time I used C++ was (iirc) in 1987 with a Borland product. I recall "this" and remember I got stuck on it then too. > See my tutorial for more on this under the heading > "Using classes". Will do. Thanks for the pointer. > If you haven't started writing classes yet, you can safely ignore > it for now! I probably won't need to start writing classes but I really want to finish the book before I start coding something. I have a small script I did in (horrible) bash and look forward to try to implement it in (less horrible) Python. Thanks for your help. Regards, Patrick From kent37 at tds.net Mon Feb 4 02:26:34 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 20:26:34 -0500 Subject: [Tutor] TypeError In-Reply-To: References: <47A63057.5030908@tds.net> <47A6358F.4030508@tds.net> Message-ID: <47A669CA.5080807@tds.net> Seon Kang wrote: > class EnemyPokemon(games.Sprite): > > image = games.load_image("bulbasaur.bmp") > > def __init__(self, speed = 2, odds_change = 200, y = 240): > """ Initialize the Chef object. """ > super(EnemyPokemon, self).__init__(image = EnemyPokemon.image, y > = 240, > x = 580, > dy = speed) > > self.odds_change = odds_change > self.time_til_shoot = 0 > enemy_pokemon = EnemyPokemon(games.Sprite) Here is the problem. The EnemyPokemon.__init__() method takes a speed parameter, an int. You are passing it games.Sprite, a type. The speed parameter becomes dy for the sprite and causes the error. Kent From cappy2112 at gmail.com Mon Feb 4 03:44:17 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sun, 3 Feb 2008 18:44:17 -0800 Subject: [Tutor] Hello and newbie question about "self" Message-ID: <8249c4ac0802031844x1a70068cqffe6fcb05ff7a542@mail.gmail.com> >>http://www.ibiblio.org/swaroopch/byteofpython/read/self.html Is there a typo in the contents of this web page? Should this statement Note for C++/Java/C# Programmers The self in Python is equivalent to the "self" pointer in C++ and the this reference in Java and C#. Actually be Note for C++/Java/C# Programmers The self in Python is equivalent to the "this" pointer in C++ and the this reference in Java and C#. (I substituted "this" for "self") From kent37 at tds.net Mon Feb 4 03:49:26 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 03 Feb 2008 21:49:26 -0500 Subject: [Tutor] Hello and newbie question about "self" In-Reply-To: <8249c4ac0802031844x1a70068cqffe6fcb05ff7a542@mail.gmail.com> References: <8249c4ac0802031844x1a70068cqffe6fcb05ff7a542@mail.gmail.com> Message-ID: <47A67D36.4020601@tds.net> Tony Cappellini wrote: >>> http://www.ibiblio.org/swaroopch/byteofpython/read/self.html > Is there a typo in the contents of this web page? Yes, you are right, C++ uses 'this'. Kent > > Should this statement > > Note for C++/Java/C# Programmers > > The self in Python is equivalent to the "self" pointer in C++ and the > this reference in Java and C#. > > > Actually be > > Note for C++/Java/C# Programmers > > The self in Python is equivalent to the "this" pointer in C++ and the > this reference in Java and C#. > > > (I substituted "this" for "self") > From alan.gauld at btinternet.com Mon Feb 4 06:17:48 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Feb 2008 05:17:48 -0000 Subject: [Tutor] Hello and newbie question about "self" References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl> <47A65DDB.1030901@puzzled.xs4all.nl> Message-ID: "Patrick Lists" wrote > I probably won't need to start writing classes but I really want to > finish the book before I start coding something. Such things are personal but I would personally recommend writing as much code as you can as soon as you can. Do the examples in the book but treat them as starting points. Try modifying them and guess what will happen. See if you are right. If so you understand it! If not go back and dig until you see why your expectation was wrong and why the code did what it dd. This is one of the great things about Python's >>> interactive prompt, you can learn so much by just doodling with code. Alan G. From alan.gauld at btinternet.com Mon Feb 4 06:23:28 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 4 Feb 2008 05:23:28 -0000 Subject: [Tutor] PHP & Python suggestions.... References: <39cb7e5d0802031535ja1ce7desdc8d4462cd984f39@mail.gmail.com> Message-ID: "GTXY20" wrote > Anyway, I am looking for some suggestions for reading up on how to > call > Python from PHP scripts, specifically calling from a PHP web > application - > PHP will call python script with some arguments and python will run > on the > server and return the results within another PHP page. Since PHP is also running on the server then the equivalent of os.system in Python should work. The equivalent of os.popen would p[robably be even better, although tyou could use an output file to exchange data. My (very old) PHP book says: passthru can be used to put the outoput on the web page or using back ticks you can capture the output in a variable. So $myvar = `python myscript.py` would store the output of the Python command as a string in $myvar HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dotancohen at gmail.com Mon Feb 4 16:01:39 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Mon, 4 Feb 2008 17:01:39 +0200 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <47A62F3B.9060106@tds.net> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> <47A60F95.7000704@tds.net> <47A62F3B.9060106@tds.net> Message-ID: <880dece00802040701r1aea5671m62e7d3343ac1847b@mail.gmail.com> On 03/02/2008, Kent Johnson wrote: > I did a little research on the question of running the same script > unmodified in Python 2.6 and 3.0. It seems that there is no consensus > opinion and it may depend on your personal tolerance for compatibility > cruft. Here is a c.l.py thread of interest: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/4e0a71d86e80d0f9/8e7fb527e32d3064?hl=en& > > > Kent > Like I mentioned earlier, I'm more interested in my learning being 3.x compatible, not my scripts. If all I need to do is learn to print("") instead of print"" then that's fine. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From tyler.smith at mail.mcgill.ca Mon Feb 4 17:43:45 2008 From: tyler.smith at mail.mcgill.ca (Tyler Smith) Date: Mon, 4 Feb 2008 16:43:45 +0000 (UTC) Subject: [Tutor] newbie code review please! References: <47A6338C.40708@tds.net> Message-ID: On Sun, Feb 03, 2008 at 04:35:08PM -0500, Kent Johnson made several helpful suggestions: Thanks! That cleaned up a lot. However, I couldn't figure out a way to do random.choice(word_hash[(w1, w2)]) on a dict with set-type values. The closest I could get was word_hash[(w1, w2)].pop(), but then I need to add a few lines to put the value back into the set afterwards. Is there a way to randomly lookup a value in a set without removing it from the set? I had better success with collections.defaultdict(list), as pasted below. Cheers, Tyler #! /usr/bin/python2.5 import sys, random, collections word_max = 1000 # Read in file infile = open(sys.argv[1], 'r') ifstring = infile.read() # break file into words iflist = ifstring.split() # build hash of form (prefix1, prefix2): [word] word_hash = collections.defaultdict(list) for i in range(len(iflist) - 2): tk = tuple(iflist[i:i+2]) tv = iflist[i+2] if tv not in word_hash[tk]: word_hash[tk].append(tv) word_hash[(iflist[-2], iflist[-1])].append('\n') # output first two words w1, w2 = iflist[0:2] print w1, w2, # generate new words from hash for word_num in range(word_max): w1, w2 = w2, random.choice(word_hash[(w1, w2)]) print w2, if w2 == '\n': break From tyler.smith at mail.mcgill.ca Mon Feb 4 14:12:29 2008 From: tyler.smith at mail.mcgill.ca (tyler) Date: Mon, 04 Feb 2008 09:12:29 -0400 Subject: [Tutor] newbie code review please! In-Reply-To: <47A6338C.40708@tds.net> References: <47A6338C.40708@tds.net> Message-ID: <20080204131229.GA32729@sedgenet> On Sun, Feb 03, 2008 at 04:35:08PM -0500, Kent Johnson made several helpful suggestions: Thanks! That cleaned up a lot. However, I couldn't figure out a way to do random.choice(word_hash[(w1, w2)]) on a dict with set-type values. The closest I could get was word_hash[(w1, w2)].pop(), but then I need to add a few lines to put the value back into the set afterwards. Is there a way to randomly lookup a value in a set without removing it from the set? I had better success with collections.defaultdict(list), as pasted below. Cheers, Tyler #! /usr/bin/python2.5 import sys, random, collections word_max = 1000 # Read in file infile = open(sys.argv[1], 'r') ifstring = infile.read() # break file into words iflist = ifstring.split() # build hash of form (prefix1, prefix2): [word] word_hash = collections.defaultdict(list) for i in range(len(iflist) - 2): tk = tuple(iflist[i:i+2]) tv = iflist[i+2] if tv not in word_hash[tk]: word_hash[tk].append(tv) word_hash[(iflist[-2], iflist[-1])].append('\n') # output first two words w1, w2 = iflist[0:2] print w1, w2, # generate new words from hash for word_num in range(word_max): w1, w2 = w2, random.choice(word_hash[(w1, w2)]) print w2, if w2 == '\n': break From kent37 at tds.net Mon Feb 4 17:56:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 04 Feb 2008 11:56:17 -0500 Subject: [Tutor] newbie code review please! In-Reply-To: References: <47A6338C.40708@tds.net> Message-ID: <47A743B1.2040207@tds.net> Tyler Smith wrote: > That cleaned up a lot. However, I couldn't figure out a way to do > random.choice(word_hash[(w1, w2)]) on a dict with set-type values. Ah, sorry; random.choice() needs an indexable sequence. Try w1, w2 = w2, random.sample(word_hash[(w1, w2)], 1)[0] random.sample() works with any iterable, not just sequences. It returns a list, hence the indexing [0]. Kent From brunson at brunson.com Mon Feb 4 18:12:25 2008 From: brunson at brunson.com (Eric Brunson) Date: Mon, 04 Feb 2008 10:12:25 -0700 Subject: [Tutor] os.system() problem In-Reply-To: References: Message-ID: <47A74779.7080708@brunson.com> dave selby wrote: > Hi all, > > I am not sure if this is a Python or bash issue :). > > In bash if I execute 'motion' with the following ... > > dave at dev-machine:~/.kde/share/apps/kmotion$ motion &> /dev/null & > [1] 10734 > dave at dev-machine:~/.kde/share/apps/kmotion$ > > I get what I expect, a background job, however if I execute it from > Python with an os.system ... > > os.system('motion &> /dev/null &') > This happens because &> and & are shell constructs, they are bash specific shell syntax for "redirect stderr and stdout" and "put this job in the background". But os.system simply calls the OS's "system(3)" call, which under linux calls "/bin/sh". If you read the docs for bash, calling it as "sh" results in POSIX compliance mode and falls back to Bourne shell's less rich syntax, so it doesn't understand the "&>" construct. If I had to guess at the parsing, I imagine it runs the "motion &" as one process in the background, then "> /dev/null &" as a second. Long story short, look at this page: http://docs.python.org/lib/node537.html > I get tons of output to the BASH shell ... > > [0] Processing thread 0 - config file /etc/motion/motion.conf > [0] Processing config file /etc/motion/motion.1.conf > [0] Processing config file /etc/motion/motion.2.conf > [1] Thread is from /etc/motion/motion.1.conf > [2] Thread is from /etc/motion/motion.2.conf > [1] Thread started > [2] Thread started > [1] File of type 2 saved to: /var/lib/motion/20080203/01/tmp/175253.jpg > ...etc ... > > I just can't work out why this is happening & how to stop it ?. Any ideas ? > > Cheers > > Dave > > > > From brunson at brunson.com Mon Feb 4 18:26:04 2008 From: brunson at brunson.com (Eric Brunson) Date: Mon, 04 Feb 2008 10:26:04 -0700 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <880dece00802040701r1aea5671m62e7d3343ac1847b@mail.gmail.com> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> <47A60F95.7000704@tds.net> <47A62F3B.9060106@tds.net> <880dece00802040701r1aea5671m62e7d3343ac1847b@mail.gmail.com> Message-ID: <47A74AAC.6010203@brunson.com> Dotan Cohen wrote: > On 03/02/2008, Kent Johnson wrote: > >> I did a little research on the question of running the same script >> unmodified in Python 2.6 and 3.0. It seems that there is no consensus >> opinion and it may depend on your personal tolerance for compatibility >> cruft. Here is a c.l.py thread of interest: >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/4e0a71d86e80d0f9/8e7fb527e32d3064?hl=en& >> >> >> Kent >> >> > > Like I mentioned earlier, I'm more interested in my learning being 3.x > compatible, not my scripts. If all I need to do is learn to print("") > instead of print"" then that's fine. > Basically, if you follow a few simple rules you'll avoid 99% of 3.0 incompatibilities: 1) Always use: print( "like it was a function" ) rather than: print "like it was a statement" 2) Always use: class NewStyle( object ): rather than: class OldStyle(): 3) Never try to be clever with side effects of internal implementations of language Pretty much everything else you learn in 2.5 will be applicable in 3.0. (Others on the list, please feel free to extend my rules with things that you feel will be important) > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? > _______________________________________________ > 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/20080204/8d630ad4/attachment.htm From andre.roberge at gmail.com Mon Feb 4 20:35:03 2008 From: andre.roberge at gmail.com (Andre Roberge) Date: Mon, 4 Feb 2008 15:35:03 -0400 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <47A74AAC.6010203@brunson.com> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> <47A60F95.7000704@tds.net> <47A62F3B.9060106@tds.net> <880dece00802040701r1aea5671m62e7d3343ac1847b@mail.gmail.com> <47A74AAC.6010203@brunson.com> Message-ID: <7528bcdd0802041135y1e288336ic1a0f234470e9015@mail.gmail.com> On Feb 4, 2008 1:26 PM, Eric Brunson wrote: > > Dotan Cohen wrote: > > Like I mentioned earlier, I'm more interested in my learning being 3.x > compatible, not my scripts. If all I need to do is learn to print("") > instead of print"" then that's fine. > > > Basically, if you follow a few simple rules you'll avoid 99% of 3.0 > incompatibilities: > > 1) Always use: > > print( "like it was a function" ) > rather than: > print "like it was a statement" > 2) Always use: > > class NewStyle( object ): > rather than: > class OldStyle(): > 3) Never try to be clever with side effects of internal implementations of > language > > > Pretty much everything else you learn in 2.5 will be applicable in 3.0. > > (Others on the list, please feel free to extend my rules with things that > you feel will be important) > No, this seems about right. For the record, I have attempted an experiment to see if I could make my program (Crunchy) run under 2.4, 2.5, 3.0a1 and 3.0a2 simulatenously. This is a program with about 40 different modules, using a number of other modules from the standard library. I managed to get everything working almost perfectly using 3.0a1 and about 95% under 3.0a2 - I am convinced that, with a bit more effort, I could have gotten everything working under all 4 Python versions. I have complete unit tests for about 20 of the modules I wrote and it was very easy to make them work (with no errors) under all 4 Python versions. There are only a small number of places where the transition from 2.x to 3.0 is going to be tricky - and most of these are related to dealings with strings and unicode characters, something not everyone has to deal with. So, based on actual experience, I am confident in telling anyone interested that they should not fear learning Python 2.x (thinking it might become obsolete) as 99% of your code (excluding print statements) is probably going to work unchanged. Andr? From dotancohen at gmail.com Mon Feb 4 23:04:49 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 5 Feb 2008 00:04:49 +0200 Subject: [Tutor] Bad time to get into Python? In-Reply-To: <7528bcdd0802041135y1e288336ic1a0f234470e9015@mail.gmail.com> References: <880dece00802030836i4a985cb8pd75e55fcd518533@mail.gmail.com> <47A60F95.7000704@tds.net> <47A62F3B.9060106@tds.net> <880dece00802040701r1aea5671m62e7d3343ac1847b@mail.gmail.com> <47A74AAC.6010203@brunson.com> <7528bcdd0802041135y1e288336ic1a0f234470e9015@mail.gmail.com> Message-ID: <880dece00802041404x19b6b38eh79e7ffbfd519c77e@mail.gmail.com> On 04/02/2008, Andre Roberge wrote: > I have complete unit tests for about 20 of the modules I wrote and it > was very easy to make them work (with no errors) under all 4 Python > versions. There are only a small number of places where the > transition from 2.x to 3.0 is going to be tricky - and most of these > are related to dealings with strings and unicode characters, something > not everyone has to deal with. > Since my language is Hebrew, I will be dealing with unicode characters a lot. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From tyler.smith at mail.mcgill.ca Tue Feb 5 00:54:44 2008 From: tyler.smith at mail.mcgill.ca (tyler) Date: Mon, 4 Feb 2008 19:54:44 -0400 Subject: [Tutor] good reference book recommendations In-Reply-To: <20080204194257.GC21772@sedgenet> References: <20080204194257.GC21772@sedgenet> Message-ID: <20080204235444.GB24242@sedgenet> Hi, At the risk of beating a well-dead horse, I'm looking for book suggestions. I've already got Core Python Programming, but I find it doesn't quite suit my needs. I'd like a comprehensive and *concise* reference to the core language and standard libraries. It looks like Beazely's Essential Reference and the Martelli's Nutshell book are both aimed to fill this role - any reason to choose one over the other? The free library reference would almost do for me, except that I want a hardcopy and it's a big document to print out. Thanks! Tyler -- I never loan my books, for people never return them. The only books remaining in my library are those I?ve borrowed from others. --unknown From tyler.smith at mail.mcgill.ca Tue Feb 5 00:53:38 2008 From: tyler.smith at mail.mcgill.ca (tyler) Date: Mon, 4 Feb 2008 19:53:38 -0400 Subject: [Tutor] newbie code review please! In-Reply-To: <20080204192735.GB21772@sedgenet> References: <47A6338C.40708@tds.net> <47A743B1.2040207@tds.net> <20080204192735.GB21772@sedgenet> Message-ID: <20080204235338.GA24242@sedgenet> On Mon, Feb 04, 2008 at 03:27:35PM -0400, tyler wrote: > On Mon, Feb 04, 2008 at 11:56:17AM -0500, Kent Johnson wrote: > > Tyler Smith wrote: > > > >> That cleaned up a lot. However, I couldn't figure out a way to do > >> random.choice(word_hash[(w1, w2)]) on a dict with set-type values. > > > > Ah, sorry; random.choice() needs an indexable sequence. Try > > w1, w2 = w2, random.sample(word_hash[(w1, w2)], 1)[0] > > > > random.sample() works with any iterable, not just sequences. It returns > > a list, hence the indexing [0]. > > Excellent, thanks! Tyler From bhaaluu at gmail.com Tue Feb 5 02:41:45 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 4 Feb 2008 20:41:45 -0500 Subject: [Tutor] good reference book recommendations In-Reply-To: <20080204235444.GB24242@sedgenet> References: <20080204194257.GC21772@sedgenet> <20080204235444.GB24242@sedgenet> Message-ID: Being a book snob, I'd go for the O'Reilly Nutshell book over the SAMS Essential Reference. I've always had good luck with books published by O'Reilly. I have neither of the books you asked about, because I use online docs. I don't need no steenkin' dead tree Python reference. 8^P Actually, I've heard several recommendations for the Nutshell book, but never heard of the Beaszely book. Sprinkle with salt. Go to Borders or B&N and check them out (if they're on the shelf). It shouldn't take more than a few minutes for you to see which one fits you! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] On Feb 4, 2008 6:54 PM, tyler wrote: > Hi, > > At the risk of beating a well-dead horse, I'm looking for book > suggestions. I've already got Core Python Programming, but I find it > doesn't quite suit my needs. I'd like a comprehensive and *concise* > reference to the core language and standard libraries. It looks like > Beazely's Essential Reference and the Martelli's Nutshell book are > both aimed to fill this role - any reason to choose one over the > other? The free library reference would almost do for me, except that > I want a hardcopy and it's a big document to print out. > > Thanks! > > Tyler > From cfuller084 at thinkingplanet.net Mon Feb 4 16:43:02 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 4 Feb 2008 09:43:02 -0600 Subject: [Tutor] PHP & Python suggestions.... In-Reply-To: <39cb7e5d0802031535ja1ce7desdc8d4462cd984f39@mail.gmail.com> References: <39cb7e5d0802031535ja1ce7desdc8d4462cd984f39@mail.gmail.com> Message-ID: <200802040943.02496.cfuller084@thinkingplanet.net> On Sunday 03 February 2008 17:35, GTXY20 wrote: > Hi all, > > First off let me say how helpful and informative this mailing list is. It > is very much appreciated. > > Anyway, I am looking for some suggestions for reading up on how to call > Python from PHP scripts, specifically calling from a PHP web application - > PHP will call python script with some arguments and python will run on the > server and return the results within another PHP page. > > Once again thanks. > > GTXY20. You can also use python in server-side scripting, at least with apache and mod_python. You can use it the same way as PHP. This might not be suitable for what you need to do, but if you could do it this way, it would probably be faster. Cheers Chris Fuller From mlangford.cs03 at gtalumni.org Tue Feb 5 03:38:31 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 4 Feb 2008 21:38:31 -0500 Subject: [Tutor] PHP & Python suggestions.... In-Reply-To: <200802040943.02496.cfuller084@thinkingplanet.net> References: <39cb7e5d0802031535ja1ce7desdc8d4462cd984f39@mail.gmail.com> <200802040943.02496.cfuller084@thinkingplanet.net> Message-ID: <82b4f5810802041838w6c19861k8f4fcb98008ffde2@mail.gmail.com> OT Aside: Anyone ever used PSP pages? Seems like a good substitute for PHPish tasks, but I've not seen many users. As to the actual question, PHP can call python through a variety of means. One such one I'm familiar with is XMLRPC. PHP: http://phpxmlrpc.sourceforge.net/ Python: http://www.ibm.com/developerworks/library/ws-pyth10.html (servers at the bottom). XMLRPC can be slooooooooooooow. Make sure its fast enough for what you're doing by running a benchmark. But if it is fast enough, the python libraries at least are quite magically simple as far as cross language programming can be. --Michael On Feb 4, 2008 10:43 AM, Chris Fuller wrote: > > On Sunday 03 February 2008 17:35, GTXY20 wrote: > > Hi all, > > > > First off let me say how helpful and informative this mailing list is. It > > is very much appreciated. > > > > Anyway, I am looking for some suggestions for reading up on how to call > > Python from PHP scripts, specifically calling from a PHP web application - > > PHP will call python script with some arguments and python will run on the > > server and return the results within another PHP page. > > > > Once again thanks. > > > > GTXY20. > > You can also use python in server-side scripting, at least with apache and > mod_python. You can use it the same way as PHP. This might not be suitable > for what you need to do, but if you could do it this way, it would probably > be faster. > > Cheers > Chris Fuller > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From brunson at brunson.com Tue Feb 5 03:42:25 2008 From: brunson at brunson.com (Eric Brunson) Date: Mon, 04 Feb 2008 19:42:25 -0700 Subject: [Tutor] PHP & Python suggestions.... In-Reply-To: <82b4f5810802041838w6c19861k8f4fcb98008ffde2@mail.gmail.com> References: <39cb7e5d0802031535ja1ce7desdc8d4462cd984f39@mail.gmail.com> <200802040943.02496.cfuller084@thinkingplanet.net> <82b4f5810802041838w6c19861k8f4fcb98008ffde2@mail.gmail.com> Message-ID: <47A7CD11.2020707@brunson.com> Michael Langford wrote: > OT Aside: > Anyone ever used PSP pages? Seems like a good substitute for PHPish > tasks, but I've not seen many users. > I have, but I find generating my HTML with classes I wrote to be more to my tastes. I did PHP for years and I'm just not a fan of the way it mixes code and HTML. I think that model works better when you have someone doing the layout and someone else doing the server side code. > As to the actual question, PHP can call python through a variety of > means. One such one I'm familiar with is XMLRPC. > > PHP: > http://phpxmlrpc.sourceforge.net/ > > Python: > http://www.ibm.com/developerworks/library/ws-pyth10.html (servers at > the bottom). > > XMLRPC can be slooooooooooooow. Make sure its fast enough for what > you're doing by running a benchmark. But if it is fast enough, the > python libraries at least are quite magically simple as far as cross > language programming can be. > > --Michael > > On Feb 4, 2008 10:43 AM, Chris Fuller wrote: > >> On Sunday 03 February 2008 17:35, GTXY20 wrote: >> >>> Hi all, >>> >>> First off let me say how helpful and informative this mailing list is. It >>> is very much appreciated. >>> >>> Anyway, I am looking for some suggestions for reading up on how to call >>> Python from PHP scripts, specifically calling from a PHP web application - >>> PHP will call python script with some arguments and python will run on the >>> server and return the results within another PHP page. >>> >>> Once again thanks. >>> >>> GTXY20. >>> >> You can also use python in server-side scripting, at least with apache and >> mod_python. You can use it the same way as PHP. This might not be suitable >> for what you need to do, but if you could do it this way, it would probably >> be faster. >> >> Cheers >> Chris Fuller >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > From aaron at aaron-m.co.nz Tue Feb 5 10:55:31 2008 From: aaron at aaron-m.co.nz (aaron meredith) Date: Tue, 5 Feb 2008 01:55:31 -0800 Subject: [Tutor] hiya Message-ID: <8c41a1620802050155tf137afatceef969530b1fc94@mail.gmail.com> i have tried to do this so many different ways but im not sure how to do it, i have a file with say multiple lines in it, it has a word in each line i want to keep but i also need the kept word in every first and second line joined together with some text in the middle this is what file looks like ------------------------------------- line test 6 tree /keptpart/1_1/ word test line test 6 tree /keptpart/2_2/ test word line test 6 tree /keptpart/3_1/ word test line test 6 tree /keptpart/4_2/ test word line test 6 tree /keptpart/5_1/ word test line test 6 tree /keptpart/6_2/ test word line test 6 tree /keptpart/7_1/ word test line test 6 tree /keptpart/8_2/ test word -------------------------------------- i need to have the above file printed as below "/keptpart/1_1/ joined to /keptpart/2_2/" "/keptpart/3_1/ joined to /keptpart/4_2/" "/keptpart/5_1/ joined to /keptpart/6_2/" "/keptpart/7_1/ joined to /keptpart/8_2/" i dont really have any script to show u what i have done cause i have tried so many different things please help -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080205/98915771/attachment.htm From cmniyas at gmail.com Tue Feb 5 13:00:34 2008 From: cmniyas at gmail.com (muhamed niyas) Date: Tue, 5 Feb 2008 17:30:34 +0530 Subject: [Tutor] Import error in UNO In-Reply-To: References: Message-ID: Dear All, I have a problem while importing UNO module in my windows vista. Openoffice and its uno module is installed in D:\ drive and my application is running in C:\ drive. i can import uno in interactive mode while moving to 'D:\Program Files\OpenOffice 2.0\program' location. I am getting an error 'No module named uno' while running my application. In my application i am moving to the location through os.chdir os.chdir("C:\Program Files\OpenOffice.org 2.0\program") import uno import unohelper Also i set 'C:\Program Files\OpenOffice.org 2.0\program' in PATH evvironment variable. Thanks in advance. -- Thanks & Best Regards, Muhamed Niyas C (GM, Core Solutions India) Mobile: +91 9447 468825 URL: www.coresolutionsindia.com Email: niyas at coresolutionsindia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080205/a0735d59/attachment.htm From kent37 at tds.net Tue Feb 5 14:43:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Feb 2008 08:43:04 -0500 Subject: [Tutor] hiya In-Reply-To: <8c41a1620802050155tf137afatceef969530b1fc94@mail.gmail.com> References: <8c41a1620802050155tf137afatceef969530b1fc94@mail.gmail.com> Message-ID: <47A867E8.4000609@tds.net> aaron meredith wrote: > i have tried to do this so many different ways but im not sure how to do > it, i have a file with say multiple lines in it, it has a word in each > line i want to keep but i also need the kept word in every first and > second line joined together with some text in the middle I would do this with an explicit iterator and a loop which processes a group of lines each time through the loop: f = '''line test 6 tree /keptpart/1_1/ word test line test 6 tree /keptpart/2_2/ test word line test 6 tree /keptpart/3_1/ word test line test 6 tree /keptpart/4_2/ test word line test 6 tree /keptpart/5_1/ word test line test 6 tree /keptpart/6_2/ test word line test 6 tree /keptpart/7_1/ word test line test 6 tree /keptpart/8_2/ test word'''.splitlines() # You would use # f = open('myfile.txt') # Get an explicit iterator for access to next() it = iter(f) try: for line in it: kept1 = line.split()[4] it.next() line = it.next() kept2 = line.split()[4] print kept1, 'joined to', kept2 it.next() except StopIteration: pass Kent From bhaaluu at gmail.com Tue Feb 5 14:46:21 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 5 Feb 2008 08:46:21 -0500 Subject: [Tutor] designing POOP Message-ID: Greetings, POOP: Python Object Oriented Programming/Programmer/Program(s).... I have finished the procedural Python version of the Text Adventure Game. See attached uuencoded zip file which contains tag10.py, data.py and actions.py. [uudecode tag.uue; unzip tag.zip; python tag10.zip] Now I am interested in learning how to DESIGN an object-oriented version of the game in Python. All my Python tutorials show me the mechanics of how to MAKE classes. What I'm interested in is the thought processes and/or guidelines that Tutors employ when they sit down to design a POOP. Can I use the procedural program as a specification? I'd like the input/output and gameplay to be the same. However, I'd like to design the program so it can be expanded in the future. If I'm not mistaken, 'reuse' is a design criteria? My main tutorial is: Programming Python for the Absolute Beginner 2E. Michael Dawson. Boston, MA: Thomson Course Technology, 2006. ISBN-13 978-1-59863-112-8 I also have access to online tutorials. Most of the tutorials I've seen are mainly about how to MAKE a class, ie. the mechanics of POOP. Give a person a fish, feed them for a day. Teach them to fish, and they'll be gone fishing all day. I already have examples of how to make classes. Can you explain how to DESIGN classes. (I see a difference here.) How do you design POOP? What are the guidelines you keep in mind to design "good" POOP? Can an absolute beginner learn to design POOP? 8^D -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] -------------- next part -------------- A non-text attachment was scrubbed... Name: tag.uue Type: application/octet-stream Size: 8293 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080205/3e8c7c7d/attachment.obj From kent37 at tds.net Tue Feb 5 14:49:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Feb 2008 08:49:17 -0500 Subject: [Tutor] Import error in UNO In-Reply-To: References: Message-ID: <47A8695D.6060700@tds.net> muhamed niyas wrote: > Also i set 'C:\Program Files\OpenOffice.org 2.0\program' in PATH evvironment > variable. PYTHONPATH is the environment variable you need, it is one way to tell the interpreter where to look for imports. Kent From gslindstrom at gmail.com Tue Feb 5 17:00:53 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 5 Feb 2008 10:00:53 -0600 Subject: [Tutor] cx_Oracle help Message-ID: Hello, I'm trying to help out a friend and am stumped. Can you help me out? Thanks, --greg - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - I will briefly explain the problem I am facing. I am using Oracle 9.2, Python 2.5 and I installed cx_Oracle- 4.3.1-win32-9i-py25 in Python. From python I tried following : >>> import cx_Oracle >>> myDsn = cx_Oracle.makedsn('ISCN47',1521,'AUBDBS01') >>> CONN = cx_Oracle.connect(myusr, mypwd, myDsn) Traceback (most recent call last): File "", line 1, in conn = cx_Oracle.Connection('scott','tiger',myDsn) RuntimeError: Unable to acquire Oracle environment handle I have set the below environment variables too NLS_LANG: .WE8MSWIN1252 ORACLE_HOME: D:\Tools\oracle\ora92 ORACLE_SID: AUBDBS01 PYTHON_HOME: d:\Utility\Python25 PYTHONPATH: %PYTHON_HOME%\lib;%PYTHON_HOME%\DLLs;%PYTHON_HOME%\Lib\site-packages;%ORACLE_HOME%\bin LD_LIBRARY_PATH: %LD_LIBRARY_PATH%;D:\Tools\oracle\ora92\lib Not getting any idea where I am wrong? Regards, Kishore -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080205/a910d398/attachment-0001.htm From aditya.n.lal at gmail.com Tue Feb 5 17:00:56 2008 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Tue, 05 Feb 2008 21:30:56 +0530 Subject: [Tutor] os.system() problem In-Reply-To: <47A74779.7080708@brunson.com> Message-ID: On 04/02/08 10:42 PM, "Eric Brunson" wrote: > dave selby wrote: >> Hi all, >> >> I am not sure if this is a Python or bash issue :). >> >> In bash if I execute 'motion' with the following ... >> >> dave at dev-machine:~/.kde/share/apps/kmotion$ motion &> /dev/null & >> [1] 10734 >> dave at dev-machine:~/.kde/share/apps/kmotion$ >> >> I get what I expect, a background job, however if I execute it from >> Python with an os.system ... >> >> os.system('motion &> /dev/null &') >> > > This happens because &> and & are shell constructs, they are bash > specific shell syntax for "redirect stderr and stdout" and "put this job > in the background". But os.system simply calls the OS's "system(3)" > call, which under linux calls "/bin/sh". If you read the docs for bash, > calling it as "sh" results in POSIX compliance mode and falls back to > Bourne shell's less rich syntax, so it doesn't understand the "&>" > construct. If I had to guess at the parsing, I imagine it runs the > "motion &" as one process in the background, then "> /dev/null &" as a > second. > > Long story short, look at this page: > http://docs.python.org/lib/node537.html > >> I get tons of output to the BASH shell ... >> >> [0] Processing thread 0 - config file /etc/motion/motion.conf >> [0] Processing config file /etc/motion/motion.1.conf >> [0] Processing config file /etc/motion/motion.2.conf >> [1] Thread is from /etc/motion/motion.1.conf >> [2] Thread is from /etc/motion/motion.2.conf >> [1] Thread started >> [2] Thread started >> [1] File of type 2 saved to: /var/lib/motion/20080203/01/tmp/175253.jpg >> ...etc ... >> >> I just can't work out why this is happening & how to stop it ?. Any ideas ? >> >> Cheers >> >> Dave >> >> Try os.system('bash motion &> /dev/null &') From brunson at brunson.com Tue Feb 5 17:07:51 2008 From: brunson at brunson.com (Eric Brunson) Date: Tue, 05 Feb 2008 09:07:51 -0700 Subject: [Tutor] cx_Oracle help In-Reply-To: References: Message-ID: <47A889D7.9040209@brunson.com> Greg Lindstrom wrote: > Hello, > > I'm trying to help out a friend and am stumped. Can you help me out? > Thanks, > --greg > Hi Greg, I fought with this for a long, long time when I was trying to get cx_Oracle to work with the latest Oracle Instant Client (which I like to call "Oracle Instant Crap") on Solaris 10. It was a while ago and it I tried a lot of things, but I think it ended up getting fixed when I properly set my $TNS_ADMIN variable so it could find my tnsnames.ora file, since it's in a non-standard location wrt $ORACLE_HOME in the Instant Crap. If that doesn't do it, I afraid I don't know what else to suggest. My pertinent oracle environment settings look like this: LD_LIBRARY_PATH=/usr/local/lib:/usr/sfw/lib:/opt/sfw/lib:/lib:/usr/lib:/usr/local/oracle:/usr/local/ssl/lib:/usr/local/mysql/lib/mysql:/wb/lib/oracle ORACLE_HOME=/usr/lib/oracle ORACLE_SID=PROD_ORA01 TNS_ADMIN=/usr/lib/oracle Note: tnsnames.ora lives in /usr/lib/oracle on my system, TNS_ADMIN just refers to the directory. Hope that helps, e. > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > I will briefly explain the problem I am facing. > I am using Oracle 9.2, Python 2.5 and I installed > cx_Oracle-4.3.1-win32-9i-py25 in Python. > > From python I tried following : > >>> import cx_Oracle > >>> myDsn = cx_Oracle.makedsn('ISCN47',1521,'AUBDBS01') > >>> CONN = cx_Oracle.connect(myusr, mypwd, myDsn) > Traceback (most recent call last): > File "", line 1, in > conn = cx_Oracle.Connection('scott','tiger',myDsn) > RuntimeError: Unable to acquire Oracle environment > handle > > I have set the below environment variables too > NLS_LANG: .WE8MSWIN1252 > ORACLE_HOME: D:\Tools\oracle\ora92 > ORACLE_SID: AUBDBS01 > PYTHON_HOME: d:\Utility\Python25 > PYTHONPATH: > %PYTHON_HOME%\lib;%PYTHON_HOME%\DLLs;%PYTHON_HOME%\Lib\site-packages;%ORACLE_HOME%\bin > LD_LIBRARY_PATH: %LD_LIBRARY_PATH%;D:\Tools\oracle\ora92\lib > > Not getting any idea where I am wrong? > > Regards, > > Kishore > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Tue Feb 5 17:11:38 2008 From: brunson at brunson.com (Eric Brunson) Date: Tue, 05 Feb 2008 09:11:38 -0700 Subject: [Tutor] os.system() problem In-Reply-To: References: Message-ID: <47A88ABA.8050702@brunson.com> Aditya Lal wrote: > On 04/02/08 10:42 PM, "Eric Brunson" wrote: > > >> dave selby wrote: >> >>> Hi all, >>> >>> I am not sure if this is a Python or bash issue :). >>> >>> In bash if I execute 'motion' with the following ... >>> >>> dave at dev-machine:~/.kde/share/apps/kmotion$ motion &> /dev/null & >>> [1] 10734 >>> dave at dev-machine:~/.kde/share/apps/kmotion$ >>> >>> I get what I expect, a background job, however if I execute it from >>> Python with an os.system ... >>> >>> os.system('motion &> /dev/null &') >>> >>> >> This happens because &> and & are shell constructs, they are bash >> specific shell syntax for "redirect stderr and stdout" and "put this job >> in the background". But os.system simply calls the OS's "system(3)" >> call, which under linux calls "/bin/sh". If you read the docs for bash, >> calling it as "sh" results in POSIX compliance mode and falls back to >> Bourne shell's less rich syntax, so it doesn't understand the "&>" >> construct. If I had to guess at the parsing, I imagine it runs the >> "motion &" as one process in the background, then "> /dev/null &" as a >> second. >> >> Long story short, look at this page: >> http://docs.python.org/lib/node537.html >> >> >>> I get tons of output to the BASH shell ... >>> >>> [0] Processing thread 0 - config file /etc/motion/motion.conf >>> [0] Processing config file /etc/motion/motion.1.conf >>> [0] Processing config file /etc/motion/motion.2.conf >>> [1] Thread is from /etc/motion/motion.1.conf >>> [2] Thread is from /etc/motion/motion.2.conf >>> [1] Thread started >>> [2] Thread started >>> [1] File of type 2 saved to: /var/lib/motion/20080203/01/tmp/175253.jpg >>> ...etc ... >>> >>> I just can't work out why this is happening & how to stop it ?. Any ideas ? >>> >>> Cheers >>> >>> Dave >>> >>> >>> > > Try os.system('bash motion &> /dev/null &') > I doubt that would work. The command line would still be parsed by /bin/sh, so it would execute "bash motion &", then "> /dev/null &". Maybe if you did something like: os.system( 'bash -c "motion &> /dev/null &" ' ) Or you could just use Popen, which is the more appropriate solution. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From marc.tompkins at gmail.com Tue Feb 5 19:13:02 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 5 Feb 2008 10:13:02 -0800 Subject: [Tutor] designing POOP In-Reply-To: <40af687b0802051012u20eaeb3dr94729c7c536e7124@mail.gmail.com> References: <40af687b0802051012u20eaeb3dr94729c7c536e7124@mail.gmail.com> Message-ID: <40af687b0802051013r3729b1acsbe746161ceedbba7@mail.gmail.com> On Feb 5, 2008 5:46 AM, bhaaluu wrote: > What I'm interested in is the thought processes and/or > guidelines that Tutors employ when they sit down to design a POOP. Whenever I have a few free minutes and a desire to contemplate the infinite (Hah!), I surf over to the C2 wiki. I don't know the official name of the thing, I don't even know which page (if any) is supposed to be the "home" page. Rather, I surf around it the same way I did the dictionary when I was a kid - just let one link lead to another. Officially it's about refactoring - which basically means tuning-up a suboptimal design, with the implicit assumption that all designs are suboptimal and could be improved. But it's also a great place to see a bunch of very smart programmers opine on exactly what a good design is in the first place. The principles of OnceAndOnlyOnce and Don'tRepeatYourself, for instance, speak directly to the questions you're asking. I must say that I find the visual design, and the editing style, incredibly infuriating. Not every contributor signs his/her submission, so it's not always clear where one ends and another begins. Did I mention it's ugly? But it's fascinating stuff, and I feel it's made me a better programmer. Most of the programming examples are in Java {ick!}, some are in Smalltalk; I think I've seen some Lisp; I have yet to see an example in Python. But the code is all pretty readable (which is, after all, one of the principles they're trying to get across.) The Code Smells page is as good a starting place as any: http://c2.com/xp/CodeSmell.html Enjoy! (And by the way - if you find any paragraphs particularly hard to follow {I certainly have!}, don't kill yourself. Read on a bit further down the page. Generally another contributor will have restated the same argument in more accessible terms - remember that great programmers are not necessarily great essayists, and vice versa.) -- www.fsrtechnologies.com -- www.fsrtechnologies.com From dave-lists-tutor at weller-fahy.com Tue Feb 5 19:43:17 2008 From: dave-lists-tutor at weller-fahy.com (David J. Weller-Fahy) Date: Tue, 5 Feb 2008 12:43:17 -0600 (CST) Subject: [Tutor] Question regarding list editing (in place) Message-ID: Let me know if this should be on the general python list. I'm playing with some python to iterate over a directory structure. Part of the directory structure should be ignored, and will have a period (.) as the first character of the directory name. My solution was to use the following code. #v+ for root, dirs, files in os.walk(data_dir()): for n in xrange(len(dirs) - 1, -1, -1): if dirs[n].startswith(u'.'): del dirs[n] #v- This works. But I'm wondering whether there is a simpler solution (rather than walking the index backwards through the list) to removing items from a list without replacing the list? Specifically, I'm looking for something that would be similar to the concept, "Remove every list item that starts with X." Regards, -- David J. Weller-Fahy (please don't CC me) From bgailer at alum.rpi.edu Tue Feb 5 20:15:40 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 05 Feb 2008 14:15:40 -0500 Subject: [Tutor] Question regarding list editing (in place) In-Reply-To: References: Message-ID: <47A8B5DC.6090700@alum.rpi.edu> David J. Weller-Fahy wrote: > Let me know if this should be on the general python list. > > I'm playing with some python to iterate over a directory structure. Part > of the directory structure should be ignored, and will have a period (.) > as the first character of the directory name. > > My solution was to use the following code. > #v+ > for root, dirs, files in os.walk(data_dir()): > for n in xrange(len(dirs) - 1, -1, -1): > if dirs[n].startswith(u'.'): > del dirs[n] > #v- > > This works. But I'm wondering whether there is a simpler solution (rather > than walking the index backwards through the list) to removing items from > a list without replacing the list? Specifically, I'm looking for > something that would be similar to the concept, "Remove every list item > that starts with X." > dirs = [dir for dir in dirs if not dir.startswith(u'.')] -- Bob Gailer 919-636-4239 Chapel Hill, NC From bhaaluu at gmail.com Tue Feb 5 20:19:30 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 5 Feb 2008 14:19:30 -0500 Subject: [Tutor] designing POOP In-Reply-To: <40af687b0802051013r3729b1acsbe746161ceedbba7@mail.gmail.com> References: <40af687b0802051012u20eaeb3dr94729c7c536e7124@mail.gmail.com> <40af687b0802051013r3729b1acsbe746161ceedbba7@mail.gmail.com> Message-ID: On Feb 5, 2008 1:13 PM, Marc Tompkins wrote: > > On Feb 5, 2008 5:46 AM, bhaaluu wrote: > > What I'm interested in is the thought processes and/or > > guidelines that Tutors employ when they sit down to design a POOP. > > > The Code Smells page is as good a starting place as any: > http://c2.com/xp/CodeSmell.html > > -- > www.fsrtechnologies.com This page looks good: http://c2.com/cgi/wiki?PrinciplesOfObjectOrientedDesign 8^D -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Tue Feb 5 20:41:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Feb 2008 14:41:32 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: <47A8BBEC.400@tds.net> bhaaluu wrote: > POOP: Python Object Oriented Programming/Programmer/Program(s).... POOP = borderline offensive and definitely annoying. Maybe you don't know that poop is a synonym for excrement? Is that what you are trying to learn? > Now I am interested in learning how to DESIGN an object-oriented version > of the game in Python. All my Python tutorials show me the mechanics of > how to MAKE classes. What I'm interested in is the thought processes and/or > guidelines that Tutors employ when they sit down to design a POOP. From the archives: http://thread.gmane.org/gmane.comp.python.tutor/29876 http://thread.gmane.org/gmane.comp.python.tutor/39443/focus=39489 http://thread.gmane.org/gmane.comp.python.org.baypiggies/2857/focus=43197 Also: http://personalpages.tds.net/~kent37/stories/00014.html Kent From alan.gauld at btinternet.com Tue Feb 5 20:41:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Feb 2008 19:41:40 -0000 Subject: [Tutor] good reference book recommendations References: <20080204194257.GC21772@sedgenet> <20080204235444.GB24242@sedgenet> Message-ID: "tyler" wrote > reference to the core language and standard libraries. It looks like > Beazely's Essential Reference and the Martelli's Nutshell book are > both aimed to fill this role - any reason to choose one over the > other? I have earlier editions of both books, and in fact have owned two versions of Beazley's book. Both books cover very similar ground and do it well. As a matter of taste I prefer the Nutshell one, but that's mainly because Beazley's one is in very small font. OTOH Beazleys is the more up to date, covering Python 2.5 and, I believe, references to 3.0 as well. But they have been leapfrogging each other for years - Beazley got in first then Nutshell, then Beazley's 2nd ed etc... Neither says significantly more than the online docs, for that you need bigger more specific references. HTH, Alan G. From kent37 at tds.net Tue Feb 5 20:43:51 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Feb 2008 14:43:51 -0500 Subject: [Tutor] Question regarding list editing (in place) In-Reply-To: <47A8B5DC.6090700@alum.rpi.edu> References: <47A8B5DC.6090700@alum.rpi.edu> Message-ID: <47A8BC77.5080300@tds.net> bob gailer wrote: > dirs = [dir for dir in dirs if not dir.startswith(u'.')] Except to filter the directory list for os.walk() you have to modify the list in place. Use this: dirs[:] = [dir for dir in dirs if not dir.startswith(u'.')] Kent From alan.gauld at btinternet.com Tue Feb 5 20:44:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Feb 2008 19:44:16 -0000 Subject: [Tutor] Import error in UNO References: Message-ID: "muhamed niyas" wrote > Also i set 'C:\Program Files\OpenOffice.org 2.0\program' in PATH > evvironment > variable. Close but not quite. You need to set the module folder in your PYTHONPATH environment variable. PATH is where the python interpreter lives PYTHONPATH is where your modules live -- 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 Feb 5 21:02:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 5 Feb 2008 20:02:19 -0000 Subject: [Tutor] designing POOP References: Message-ID: "bhaaluu" wrote > Now I am interested in learning how to DESIGN an object-oriented > version A useful distinction. You need to understand what classes are before you can use them but the art of desiogn is indeed different to the skills of construction > Can I use the procedural program as a specification? Yes, it defines input and required output. > However, I'd like to design the program so > it can be expanded in the future. > If I'm not mistaken, 'reuse' is a design criteria? Reuse is different to expansion of the existing design. But both are valid design criteria, and both are quite hard to do until you have some experience. Initially focus on just getting a set of objects that collaborate to give the right results. Then you can rework (or refactor to use the technical jargon) for reuse etc. One of the earliest ways of doing this has now fallen sonewhat out of favour but in practie I find it works quite well for beginners is: Describe the problem in plain English text(or whatever you language is!). Underline the nouns and separate into proper and common nouns. Common nouns are likely classes (although be careful to check for synonyms - the same class described by different nouns) while proper nouns are likely to be instances of classes (which classes may or may not be in your list of common nouns) Identify the common noun (class) that applies and add to your list. Now go through and identify the verbs and adjectives in the text. Assign each to a noun. Verns are potential methods of the classes and adjectives are potential attributes. The end result is a candidate set of classes with potential methods and attributes. Now try linking them together to identify relationships. Don't be surprised if not all classes are related to others - you will usuially identify more classes than you need and some classes will be "demoted" to attributes of other more significant classes. And a few attributes may get promoted to classes in their own right. Once you have your candidate classes pick a few that look like they will be core to the problem and try to work through some scenarios focussing on the interactions between the objects. At this point its often good to think of the objects in physical terms - as if you were building a mechanical model of the problem rather than a software version. What kinds of signals or messagews would you send to each object and how would each object interact with those around it Don't at this stage worry too much about inheritance. Focus on function. If you find that several classes have the same or similar methods then consider if they are sub types of an abstract superclass. Do NOT use data attributes for this, always base inheritance heirarchies on behaviour. Worth a try. It will miss many OOP tricks but as a starter methodology it is how millions of OOP programmers began. As you gain experience you will identify common abstract patterns. Once that starts then go and read the design patterns book by Gamma et al. Thats how I'd do it, I'm sure others will suggest other approaches. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Feb 5 22:51:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 05 Feb 2008 16:51:21 -0500 Subject: [Tutor] hiya In-Reply-To: <8c41a1620802051336w7e74f979h9aed04435706417@mail.gmail.com> References: <8c41a1620802050155tf137afatceef969530b1fc94@mail.gmail.com> <47A867E8.4000609@tds.net> <8c41a1620802051336w7e74f979h9aed04435706417@mail.gmail.com> Message-ID: <47A8DA59.9070502@tds.net> aaron meredith wrote: > heya kent say if i want to select which line to specificlly join the > kept parts from so like to join /keptpart/1_1/ with /keptpart/6_2/ I don't understand. How would you select the line? Kent PS Please use Reply All to stay on list. From keridee at jayco.net Tue Feb 5 23:24:04 2008 From: keridee at jayco.net (Tiger12506) Date: Tue, 5 Feb 2008 17:24:04 -0500 Subject: [Tutor] Import error in UNO References: Message-ID: <00ac01c86845$d5031400$71fce004@jslaptop> > "muhamed niyas" wrote > >> Also i set 'C:\Program Files\OpenOffice.org 2.0\program' in PATH >> evvironment >> variable. > > Close but not quite. > You need to set the module folder in your PYTHONPATH environment > variable. > > PATH is where the python interpreter lives > PYTHONPATH is where your modules live For a less intrusive approach you can import sys sys.path.append("path of containing folder here") From mobiledreamers at gmail.com Wed Feb 6 00:10:13 2008 From: mobiledreamers at gmail.com (Mark) Date: Tue, 05 Feb 2008 15:10:13 -0800 Subject: [Tutor] Traversing python datatypes via http Message-ID: <47A8ECD5.7010205@gmail.com> Is it possible to traverse say python lists via http:// say there is a list in the memory can we traverse the list using list/next list/prev list/first list/last is there a pythonic library to do that? thanks From tiagosaboga at terra.com.br Wed Feb 6 01:43:34 2008 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Tue, 5 Feb 2008 22:43:34 -0200 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: <20080206004334.GC1267@localdomain> On Tue, Feb 05, 2008 at 08:02:19PM -0000, Alan Gauld wrote: > "bhaaluu" wrote > > > Now I am interested in learning how to DESIGN an object-oriented > > version The question was very interesting, and so where the answers. > Don't at this stage worry too much about inheritance. > Focus on function. If you find that several classes have > the same or similar methods then consider if they are > sub types of an abstract superclass. Do NOT use data > attributes for this, always base inheritance heirarchies > on behaviour. Could you please elaborate on this last sentence? I don't understand what you mean, and I feel I may be on this track. Thanks, Tiago Saboga. From keridee at jayco.net Wed Feb 6 02:03:02 2008 From: keridee at jayco.net (Tiger12506) Date: Tue, 5 Feb 2008 20:03:02 -0500 Subject: [Tutor] Traversing python datatypes via http References: <47A8ECD5.7010205@gmail.com> Message-ID: <002d01c8685c$099c5760$71fce004@jslaptop> > Is it possible to traverse say python lists via http:// > > say there is a list in the memory > > can we traverse the list using list/next list/prev list/first list/last > > is there a pythonic library to do that? > > thanks That's a very unlikely request. There are a few ways to interpret this question I will cover the obvious (to me) ones. Q1) Can I use the http protocol in such a way to make requests of a remote computer to send me elements of a list that is stored in memory on the remote computer? A1) Yes, but an http server is required that knows how to respond to these requests, and knows how to send the correct information. There are standard modules to make programming servers easier. Q2) Can I use other protocols (not specifically http)? A1) Yes, it would make more sense to use something other than http because http is meant to follow strict guidlines that really aren't applicable to the problem as I have interpreted it. In this case, there are modules that can help in communication using sockets. Q3) I want to know how to find the answer to the linked list problem in the Python Challenges. Can I do this using http:// and python? A3) Of course. The module urllib is specifically meant for downloading web pages and can be used for the linked list challenge. Q4) Excellent. Can I use it to give me the last element in the list, thus skipping all the guesswork in between and giving me the solution right away? A4) No. By its very nature, a linked list (not python specific btw) has to be traversed element by element. That means using urllib and opening each page as it is presented to your program. Q5) No you're totally off-base. I meant, can I download a list of web pages, where all of the addresses are stored in a python list? A5) Of course. urllib Q6) No this doesn't cover anything that I am asking. A6) Please structure your question in a more precise manner. Thank you. Have a nice day. ;-) From keridee at jayco.net Wed Feb 6 02:15:36 2008 From: keridee at jayco.net (Tiger12506) Date: Tue, 5 Feb 2008 20:15:36 -0500 Subject: [Tutor] Hello and newbie question about "self" References: <1202069759.17271.13.camel@zeus.puzzled.xs4all.nl><47A65DDB.1030901@puzzled.xs4all.nl> Message-ID: <005201c8685d$cb63ed30$71fce004@jslaptop> >> I probably won't need to start writing classes but I really want to >> finish the book before I start coding something. One of the greatest mistakes of my life was to completely finish a programming book before I started coding something. It is why I cannot write a Visual Basic program to this day, even though I read through an absolutely excellent book. I even said to myself, "This will totally help me write Visual Basic programs as easily as I write Python programs". So instead, I learned C. Always, always write code as you read a book. If it is a good book/programming language, you should be able to write working programs with increasing complexity as you continue in the book. Also, it is a good idea to periodically go back and observe code that you have written in the past and revise it to better reflect the skills you garner later. From cmniyas at gmail.com Wed Feb 6 05:45:38 2008 From: cmniyas at gmail.com (muhamed niyas) Date: Wed, 6 Feb 2008 10:15:38 +0530 Subject: [Tutor] Import error in UNO In-Reply-To: <00ac01c86845$d5031400$71fce004@jslaptop> References: <00ac01c86845$d5031400$71fce004@jslaptop> Message-ID: Thanks for your kind response. I tried to include the path 'C:\Program Files\OpenOffice.org 2.0\program' in PYTHONPATH. but now i didnt get any error message but its hanging while importing. Pls advice me to correct this. On Feb 6, 2008 3:54 AM, Tiger12506 wrote: > > "muhamed niyas" wrote > > > >> Also i set 'C:\Program Files\OpenOffice.org 2.0\program' in PATH > >> evvironment > >> variable. > > > > Close but not quite. > > You need to set the module folder in your PYTHONPATH environment > > variable. > > > > PATH is where the python interpreter lives > > PYTHONPATH is where your modules live > > For a less intrusive approach you can > import sys > sys.path.append("path of containing folder here") > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Thanks & Best Regards, Muhamed Niyas C (GM, Core Solutions India) Mobile: +91 9447 468825 URL: www.coresolutionsindia.com Email: niyas at coresolutionsindia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080206/1f129f4b/attachment-0001.htm From alan.gauld at btinternet.com Wed Feb 6 09:58:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Feb 2008 08:58:09 -0000 Subject: [Tutor] designing POOP References: <20080206004334.GC1267@localdomain> Message-ID: "Tiago Saboga" wrote >> sub types of an abstract superclass. Do NOT use data >> attributes for this, always base inheritance heirarchies >> on behaviour. > > Could you please elaborate on this last sentence? I don't understand > what you mean, and I feel I may be on this track. Inheritance heirarchies are the basis of polymorphism in OOP. Polymorphism is all about methods not data. Therefore to create useful inheritance heirarchies the key is to find groups of objects that share the same behaviour (ie method set) even if the internal data (the attributres) are different. The classic example of polymorphism is shapes. Now if you look at the data attributres of a set of shapes: square, circle, triangle etc they look quite different. (radius v lenxbreadth, height, angles etc) So from a data perspective they are not good inheritance candidates. But idf you look at their behaviours - draw, calculate area, move, intersect etc they are all shared, thus we can create an abstract superclass with those behaviours. Each subclass can provide its own internal data and implementt the methods using that data but the external interface of all shapes is identical and therefore polymorphiasm can be used. By contrast if you take some objects that have the same data but different methods and try to create a superclass you will simply wind up with a very big class that aggregates all the methods of all the objects but cannot be used in a polymorphic way because only a subaset of the methods actually apply to any given instance. Thus always base inheriotance on common mbehaviour not on common data. I hope that makes it clearer. -- 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 Feb 6 09:59:59 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Feb 2008 08:59:59 -0000 Subject: [Tutor] Import error in UNO References: <00ac01c86845$d5031400$71fce004@jslaptop> Message-ID: "muhamed niyas" wrote > Thanks for your kind response. I tried to include the path > 'C:\Program > Files\OpenOffice.org 2.0\program' in PYTHONPATH. but now i didnt get > any error message but its hanging while importing. Pls advice me to > correct > this. > What happens if you start an interactive Python sesssion and try 'import uno' at the >>> prompt. Does that work? Alan G. From cmniyas at gmail.com Wed Feb 6 10:33:43 2008 From: cmniyas at gmail.com (muhamed niyas) Date: Wed, 6 Feb 2008 15:03:43 +0530 Subject: [Tutor] Import error in UNO In-Reply-To: References: <00ac01c86845$d5031400$71fce004@jslaptop> Message-ID: When i import >>>import uno I am not getting the promt >>> after importing that. On Feb 6, 2008 2:29 PM, Alan Gauld wrote: > > "muhamed niyas" wrote > > > Thanks for your kind response. I tried to include the path > > 'C:\Program > > Files\OpenOffice.org 2.0\program' in PYTHONPATH. but now i didnt get > > any error message but its hanging while importing. Pls advice me to > > correct > > this. > > > > What happens if you start an interactive Python sesssion and > try 'import uno' at the >>> prompt. Does that work? > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Thanks & Best Regards, Muhamed Niyas C (GM, Core Solutions India) Mobile: +91 9447 468825 URL: www.coresolutionsindia.com Email: niyas at coresolutionsindia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080206/5b5e97ed/attachment.htm From alan.gauld at btinternet.com Wed Feb 6 11:12:31 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Feb 2008 10:12:31 -0000 Subject: [Tutor] Import error in UNO References: <00ac01c86845$d5031400$71fce004@jslaptop> Message-ID: "muhamed niyas" wrote >>>>import uno > > I am not getting the promt >>> after importing that. OK, That suggests a problem in the uno module itself. Yet ISTR you said you could import if you changed to the directory and ran Python there? Can you try that again just to confirm CD to the OOo folder that contains uno and startt python and try the import again. Alan G. From cmniyas at gmail.com Wed Feb 6 11:23:22 2008 From: cmniyas at gmail.com (muhamed niyas) Date: Wed, 6 Feb 2008 15:53:22 +0530 Subject: [Tutor] Import error in UNO In-Reply-To: References: <00ac01c86845$d5031400$71fce004@jslaptop> Message-ID: I can import when i moved to the uno location. pls see the messages in the terminal. C:\>cd "Program Files\OpenOffice.org 2.0\program"\ C:\Program Files\OpenOffice.org 2.0\program>python Python 2.3.4 (#53, Feb 2 2006, 01:06:22) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import uno >>> On Feb 6, 2008 3:42 PM, Alan Gauld wrote: > "muhamed niyas" wrote > > >>>>import uno > > > > I am not getting the promt >>> after importing that. > > OK, That suggests a problem in the uno module itself. > > Yet ISTR you said you could import if you changed to > the directory and ran Python there? > > Can you try that again just to confirm > > CD to the OOo folder that contains uno and startt python > and try the import again. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Thanks & Best Regards, Muhamed Niyas C (GM, Core Solutions India) Mobile: +91 9447 468825 URL: www.coresolutionsindia.com Email: niyas at coresolutionsindia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080206/a96cfe97/attachment.htm From bhaaluu at gmail.com Wed Feb 6 11:24:22 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 6 Feb 2008 05:24:22 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: On Feb 5, 2008 3:02 PM, Alan Gauld wrote: > > One of the earliest ways of doing this has now fallen sonewhat > out of favour but in practie I find it works quite well for beginners > is: > > Describe the problem in plain English text(or whatever you > language is!). Underline the nouns and separate into proper > and common nouns. Common nouns are likely classes (although > be careful to check for synonyms - the same class described > by different nouns) while proper nouns are likely to be instances > of classes (which classes may or may not be in your list of > common nouns) Identify the common noun (class) that applies > and add to your list. This sounds like a good suggestion! I've already started, and have a rough draft. I still need to knock the rough edges off the description. How detailed do you make your description? Do you write an overview that isn't very detailed, or do you describe every detail you can think of? (My rough draft is quite detailed because I have just finished writing the procedural program, and have all the details in my head.) Actually, writing a description of the problem in Plain English is part of designing any computer program (according to some old programming texts I have). This is why beginning computer programmers should stay awake in English class, and pay attention to grammar! > Now go through and identify the verbs and adjectives in the text. > Assign each to a noun. Verns are potential methods of the classes > and adjectives are potential attributes. Noted: "potential" > > The end result is a candidate set of classes with potential > methods and attributes. Now try linking them together to identify > relationships. Don't be surprised if not all classes are related to > others - you will usuially identify more classes than you need > and some classes will be "demoted" to attributes of other more > significant classes. And a few attributes may get promoted to > classes in their own right. I had a 'testing' directory when I wrote the procedural version of the program. I tested snippets of code to see if they would work, before putting them in the main program. I can see that a similar 'testing' directory will be well used when designing this POOP version. 8^D > Once you have your candidate classes pick a few that look > like they will be core to the problem and try to work through > some scenarios focussing on the interactions between the > objects. At this point its often good to think of the objects > in physical terms - as if you were building a mechanical > model of the problem rather than a software version. What > kinds of signals or messagews would you send to each > object and how would each object interact with those > around it This is why I chose the Text Adventure Game as a learning program. It is full of objects that can be thought of in physical terms! I'm not quite clear how they will message each other (yet), but that will probably become clearer as I work through this. > Don't at this stage worry too much about inheritance. > Focus on function. If you find that several classes have > the same or similar methods then consider if they are > sub types of an abstract superclass. Do NOT use data > attributes for this, always base inheritance heirarchies > on behaviour. Noted. > Worth a try. It will miss many OOP tricks but as a starter > methodology it is how millions of OOP programmers began. > As you gain experience you will identify common abstract > patterns. Once that starts then go and read the design > patterns book by Gamma et al. This is exactly the kind of thing I was looking for.... I'm sure I'll have more questions as I go along. > Thats how I'd do it, I'm sure others will suggest other > approaches. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld Thank you Alan! Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From seon.kang at gmail.com Wed Feb 6 04:57:30 2008 From: seon.kang at gmail.com (Seon Kang) Date: Tue, 5 Feb 2008 22:57:30 -0500 Subject: [Tutor] Games Message-ID: When I run some of my games on python, I notice they seem to lag and take up a large portion of my CPU when the game itself is actually pretty simple. why does this happen? I run a window XP and my computer should have no problems with this simple of a game. Is the problem in my programming? Are there any things to look out for in a program that would get rid of this lag problem? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080205/bf50af1f/attachment.htm From imonthejazz at googlemail.com Wed Feb 6 16:23:46 2008 From: imonthejazz at googlemail.com (Damian Archer) Date: Wed, 6 Feb 2008 15:23:46 +0000 Subject: [Tutor] Ending a script Message-ID: When I am running a script in cmd the script runs but the cmd windows closes immediately after the script has finished. Is there anyway I can freeze the cmd window until a user actually closers it?? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080206/48686f6f/attachment.htm From tiagosaboga at terra.com.br Wed Feb 6 16:35:08 2008 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Wed, 6 Feb 2008 13:35:08 -0200 Subject: [Tutor] designing POOP In-Reply-To: References: <20080206004334.GC1267@localdomain> Message-ID: <20080206153508.GB28002@localdomain> On Wed, Feb 06, 2008 at 08:58:09AM -0000, Alan Gauld wrote: > Thus always base inheriotance on common mbehaviour not on > common data. > > I hope that makes it clearer. Thanks Alan, it's clear now. And now I know that this is not one of the mistakes I am making ;) Tiago Saboga. From kent37 at tds.net Wed Feb 6 16:36:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Feb 2008 10:36:29 -0500 Subject: [Tutor] Ending a script In-Reply-To: References: Message-ID: <47A9D3FD.7050302@tds.net> Damian Archer wrote: > When I am running a script in cmd the script runs but the cmd windows > closes immediately after the script has finished. > > Is there anyway I can freeze the cmd window until a user actually > closers it?? End your script with something like raw_input('Press any key to exit') Kent From bhaaluu at gmail.com Wed Feb 6 16:40:38 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 6 Feb 2008 10:40:38 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: On Feb 5, 2008 3:02 PM, Alan Gauld wrote: > > Describe the problem in plain English text(or whatever you > language is!). > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > Here is my description, in plain English. Text Adventure Game Requirements: 1. The Explorer enters her name at a prompt. 2. Other things are initialized at this point. 3. The layout of the Castle is defined. 4. Treasure is placed in rooms in the Castle. A. Treasure is distributed randomly to four rooms. B. Treasure is placed in two specific rooms. 5. Four Monsters are randomly distributed to four rooms in the Castle. A. No monsters should be placed at Entrance or Exit. B. Each monster has a name. C. Each monster has a Ferocity Factor / Danger Level. 6. She has 100 strength and $75 wealth to start with. A. Strength is decremented 5 for each prompt entry. 1. If strength equals zero: a. She dies. b. Final score displayed. c. Game over. B. Strength can be incremented by consuming food. C. Wealth can be used to buy things in QuarterMaster's Store. D. Wealth can be incremented by finding and picking-up treasure. 7. She does not have food, weapons, armor, magic, or light. 8. She starts at the Entrance to the Castle (Room 6). 9. She cannot see anything without a light. 10. She enters commands at the prompt in order to: A. Move in six directions [N,S,E,W,U,D]: 1. Move in indicated direction. 2. Informed she cannot move in indicated direction. 3. Her strength is decremented 5 each move. 4. The tally of moves is incremented 1 each move. B. Access the Provisions & Inventory menu [I]: 1. She must have some wealth to access the P&I menu. 2. She can purchase items from the menu: a. Light is 0 or 1. b. Weapons: Axe / Sword is 0 or 1. c. Food units. 1. She is told how many units of food she has. 2. She is asked how many units of food she wants to buy. d. Magic amulet. e. Armor. 3. Wealth is decremented after each purchase. a. She is informed when she has no money, and exited from the store. b. She loses everything except strength and food, if she tries to spend more wealth than she has. C. She can pick-up treasure [P]. 1. She cannot pick-up treasure if she cannot see it (she needs light). 2. The treasure will remain in the room if not picked-up. D. She can run from a monster [R]. 1. She may be asked where she wants to flee to (direction). 2. She may be told she must stand and fight (random decision). E. She can fight a monster. 1. Wearing armor increases her chance of success. 2. If she has a weapon, she must fight with it. 3. If she has two weapons, she is asked which one she wants to use. 4. If she has no weapon(s), she must fight bare-handed. a. The Explorer or the monster may attack first (random decision). b. The Explorer or the monster may wound the other (random decision). c. The Explorer or the monster may defeat the other. 1. Strength is decremented from the Explorer during the fight. 2. Ferocity Factor is decremented from the monster during the fight. 11. She can consume food [C]. A. She must have food to consume 1. She is told how many units of food she has. 2. She is asked how many units of food she wants to eat. 12. She can use the Magic Amulet [M]. A. She must have the Magic Amulet in her possession. B. The Magic Amulet will move her to a random room in the Castle. 1. It should not move her to the Entrance or Exit. 13. The game ends when she exits the Castle (finds Room 11). A. Exit message is displayed. B. Final Score is displayed. 1. Final score depends on several factors: a. Strength, wealth, tally, food, number of monsters killed. Now the hard part: grammar. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From alan.gauld at btinternet.com Wed Feb 6 18:06:09 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Feb 2008 17:06:09 -0000 Subject: [Tutor] designing POOP References: Message-ID: "bhaaluu" wrote > Here is my description, in plain English. > > Text Adventure Game Requirements: > 1. The Explorer enters her name at a prompt. > 2. Other things are initialized at this point. > 3. The layout of the Castle is defined. > 4. Treasure is placed in rooms in the Castle. Actually thats not really plain English its a very structured English. In fact it approaches procedural pseudo code! Its possibly a little too detailed too. I'd go for a more free-form paragraph or two(at most) something like: ------------------ I want to build a text adventure game based around an explorer moving around a castle with multiple rooms,. In each rooms there could be various items of treasure or monsters. To win the game the explorer has to collect as much treasure as possible and defeat as many monsters as possible. Treasure is worth points and the expolorer starts off with a given amount of strength and points. ...... Because its a text game the interface will consist of a series of input prompts with responses and printed status messages. The game is over when..... ----------------------- That should be shorter and less likely to predispose your thinking to a particular approach - such as when the initialisation takes place, or how many rooms or premature consideration of the command structures etc. These things should emerge as you create the object definitions and interactions. The initial aim is only to find the half dozen to a dozen key classes top get started. Other classes will emerge as you progress, and some of the original candidates may merge into others or be discarded. And don't forget that there could well be a game class/object to control the overall flow of the game and coordinate the actions of the other objects. For example the prompt/response/display mechanism might be part of the game class (and they might be classes too!). This would maximise reuse of the compnent objects within a different game framework ( a GUI fort instance) later. 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 Feb 6 18:07:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Feb 2008 17:07:47 -0000 Subject: [Tutor] Games References: Message-ID: "Seon Kang" wrote > When I run some of my games on python, I notice they seem to lag > and take > up a large portion of my CPU when the game itself is actually pretty > simple. > why does this happen? I run a window XP and my computer should have > no > problems with this simple of a game. Is the problem in my > programming? Are > there any things to look out for in a program that would get rid of > this lag > problem? Its hard to guess without examples. But classic things to be aware of are infinite loops while waiting for input. These will keep the computer busy even while its not really doing anything... Alan G From alan.gauld at btinternet.com Wed Feb 6 18:10:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Feb 2008 17:10:40 -0000 Subject: [Tutor] Ending a script References: Message-ID: "Damian Archer" wrote > When I am running a script in cmd the script runs but the cmd > windows closes > immediately after the script has finished. > > Is there anyway I can freeze the cmd window until a user actually > closers > it?? I discuss various ways to address this in my tutorial in the topic entitled Talking to the User, under the heading Saving your programs and in the sidebar/box Note for Windows Users. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cfuller084 at thinkingplanet.net Wed Feb 6 18:14:16 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 6 Feb 2008 11:14:16 -0600 Subject: [Tutor] Ending a script In-Reply-To: References: Message-ID: <200802061114.16710.cfuller084@thinkingplanet.net> On Wednesday 06 February 2008 09:23, Damian Archer wrote: > When I am running a script in cmd the script runs but the cmd windows > closes immediately after the script has finished. > > Is there anyway I can freeze the cmd window until a user actually closers > it?? There are numerous ways to do this, the simplest (and least interesting) being to use raw_input() to prompt the user to hit ENTER. A more elegant way would be to redirect the text somewhere else, perhaps a GUI textbox, or even out a network socket to an independent logging process. This is simple to do in python. All you need is a class with a write() method. Asign sys.stdout and sys.stderr to an instance of such a class. You can use the same instance, or treat them seperately. When the interpreter prints some output, or an exception is raised, the output will be passed to the write() methods of these objects, and your code can perform any arbitrary manipulations upon the output that is desired. Handling exceptions is actually a bit trickier, of course, since the default action is to terminate the program (although not always if it occurs in a GUI callback), but there are other uses for sys.stderr. A lot of modules will display error or warning messages on it, for instance. There is a bigger caveat: these do not correspond to the stdout and stderr used by the OS and the underlying C inside the interpreter. Many python modules wrap C libraries (pygtk, for instance), and the messages displayed at runtime will not be handled with any python-awareness. You can still redirect these, but you have to make low-level operating system calls, and the details differ ever so slightly from standard POSIX systems if you are suffering under the yoke of Redmond. The attached program demostrates these concepts, except the nasty lowlevel OS dependent bit. Cheers -------------- next part -------------- A non-text attachment was scrubbed... Name: redirtk.py Type: application/x-python Size: 1398 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20080206/52548809/attachment-0001.bin From alan.gauld at btinternet.com Wed Feb 6 18:15:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 6 Feb 2008 17:15:39 -0000 Subject: [Tutor] Import error in UNO References: <00ac01c86845$d5031400$71fce004@jslaptop> Message-ID: "muhamed niyas" wrote >I can import when i moved to the uno location. > pls see the messages in the terminal. > > > C:\>cd "Program Files\OpenOffice.org 2.0\program"\ > C:\Program Files\OpenOffice.org 2.0\program>python > Python 2.3.4 (#53, Feb 2 2006, 01:06:22) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more > information. >>>> import uno >>>> Ok, Odd. Lets just check its finding the PYTHONPATH setting OK. Exit Python, start a new cmd window and restart python. Now import sys and print sys.path Does your PYTHONPATH folder show up in the list? If so the only other things I can think of are 1) Create a simple Python module in the same folder as uno and try importing that to see if you definitely can find it and prove the folder permissions aren't the issue. 2) Check that there are no modules called uno in any other of the sys.path folders that are masking the OOo one. After that I'm kind of stumped. Alan G From cbc at unc.edu Wed Feb 6 18:40:28 2008 From: cbc at unc.edu (Chris Calloway) Date: Wed, 6 Feb 2008 12:40:28 -0500 Subject: [Tutor] Import error in UNO In-Reply-To: References: <00ac01c86845$d5031400$71fce004@jslaptop> Message-ID: On Feb 6, 2008, at 5:23 AM, muhamed niyas wrote: > I can import when i moved to the uno location. > pls see the messages in the terminal. > > > C:\>cd "Program Files\OpenOffice.org 2.0\program"\ > C:\Program Files\OpenOffice.org 2.0\program>python > Python 2.3.4 (#53, Feb 2 2006, 01:06:22) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import uno > >>> Given this and the behavior before where the import uno did not return to the prompt, it sounds like the dependencies the uno module has on the OpenOffice libraries. When OpenOffice is in the current path, uno seems to be able to find them. If you look at the windows documentation for uno: http://udk.openoffice.org/python/python-bridge.html even the hello world examples have you switch to the Open Office program directory. Later on in the documentation, it explains this (pay close attention the third paragraph below): "Unlike the Java or C++ UNO binding, the python UNO binding is not self contained. It requires the C++ UNO binding and additional scripting components. These additional components currently live in the shared libraries typeconverter.uno, invocation.uno, corereflection.uno, introspection.uno, invocadapt.uno, proxyfac.uno, pythonloader.uno (on windows typeconverter.uno.dll,...; unix typeconverter.uno.so,...). Often, the components for setting up an interprocess connection are also required. These are uuresolver.uno, connector.uno, remotebridge.uno, bridgefac.uno shared libraries. The path environment variables ( LD_LIBRARY_PATH on Unix, PATH on Windows) must point to a directory, where the core UNO libraries, the above listed components and the pyuno shared library is located. (On Unix, there exists two files: libpyuno.so containing the code and a pyuno.so which is needed for importing a native python module). Additionally, the python module uno.py, unohelper.py and pythonloader.py must be located in a directory, which is listed in the PYTHONPATH environment variable. " -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall cell: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080206/e61e1c8d/attachment.htm From bhaaluu at gmail.com Wed Feb 6 19:01:33 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 6 Feb 2008 13:01:33 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: Thank you Alan. This helps tremendously! I had gone to your OOP tutorial and read it over (again) and the closest thing I could find on that page was the Bank Account example that had a list of things a bank account might be expected to do. So away I went, making a list. The problems with that approach surfaced as soon as I started trying to identify the nouns (potential classes and instances), adjectives (potential attributes) and verbs (potential methods). I'm making mistakes, but at least that shows that I'm trying. If nothing else, I now know what doesn't work. 8^D Actually, I'm not expecting to get this done today. It may take awhile. From my past experience, that is how the design process goes. But if I can learn how to do this, I'm pretty sure it will save a lot of time when I work on future projects. Back to the drawing board! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] On Feb 6, 2008 12:06 PM, Alan Gauld wrote: > "bhaaluu" wrote > > > Here is my description, in plain English. > > > > Text Adventure Game Requirements: > > 1. The Explorer enters her name at a prompt. > > 2. Other things are initialized at this point. > > 3. The layout of the Castle is defined. > > 4. Treasure is placed in rooms in the Castle. > > Actually thats not really plain English its a very structured > English. In fact it approaches procedural pseudo code! > > Its possibly a little too detailed too. > > I'd go for a more free-form paragraph or two(at most) something > like: > ------------------ > I want to build a text adventure game based around > an explorer moving around a castle with multiple rooms,. In > each rooms there could be various items of treasure or monsters. > To win the game the explorer has to collect as much treasure > as possible and defeat as many monsters as possible. Treasure > is worth points and the expolorer starts off with a given amount > of strength and points. ...... > > Because its a text game the interface will consist of a series > of input prompts with responses and printed status messages. > The game is over when..... > ----------------------- > > That should be shorter and less likely to predispose your thinking > to a particular approach - such as when the initialisation takes > place, or how many rooms or premature consideration of the > command structures etc. These things should emerge as you > create the object definitions and interactions. The initial aim is > only to find the half dozen to a dozen key classes top get started. > Other classes will emerge as you progress, and some of the > original candidates may merge into others or be discarded. > > And don't forget that there could well be a game class/object to > control the overall flow of the game and coordinate the actions > of the other objects. For example the prompt/response/display > mechanism might be part of the game class (and they might > be classes too!). This would maximise reuse of the compnent > objects within a different game framework ( a GUI fort instance) > later. > > 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 > From bhaaluu at gmail.com Wed Feb 6 21:02:39 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 6 Feb 2008 15:02:39 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: On Feb 6, 2008 12:06 PM, Alan Gauld wrote: > "bhaaluu" wrote > > > Here is my description, in plain English. > > > > Text Adventure Game Requirements: > > 1. The Explorer enters her name at a prompt. > > 2. Other things are initialized at this point. > > 3. The layout of the Castle is defined. > > 4. Treasure is placed in rooms in the Castle. > > Actually thats not really plain English its a very structured > English. In fact it approaches procedural pseudo code! > > Its possibly a little too detailed too. My first try didn't work. I'm going to try again. I'm intrigued with the idea that the nouns, verbs, and adjectives can indicate possible classes, instances, methods, and attributes. While I'm familiar with the objects in this TAG example, I'd like to have a way to approach something that I'm not as familiar with. I like the idea of this technique. It seems like it should work with just about anything that can be modelled as an object. I have a tendancy to think about things as actual objects (but probably not OOP objects -- more like real objects, like a vase). I also like techniques. I know this much: Explorer: has strength & wealth, can carry weapons & food, can wear armor, can pick-up treasure, can fight monsters, can wound monsters, can defeat monsters, can move from room to room. Monster: can be anywhere, has Ferocity Factor / Danger Level, can fight Explorer, can wound Explorer, can defeat Explorer. Treasure: can be picked-up, can be in any room in Castle (except entrance and exit). Castle: contains interconnected rooms, has three levels. Rooms: room has door(s), door(s) connect to other rooms, room has description, can contain treasure, can contain monster. The trick is to take all that stuff, and figure out what the classes are, the instances, the methods, and the attributes. So it seems I need to write something descriptive about exploring the above. Subject, verb, adjective object. I must start somewhere! 8^D The above is much smaller than my previous "pseudocode" attempt. > > I'd go for a more free-form paragraph or two(at most) something > like: > ------------------ > I want to build a text adventure game based around > an explorer moving around a castle with multiple rooms,. In > each rooms there could be various items of treasure or monsters. > To win the game the explorer has to collect as much treasure > as possible and defeat as many monsters as possible. Treasure > is worth points and the expolorer starts off with a given amount > of strength and points. ...... > > Because its a text game the interface will consist of a series > of input prompts with responses and printed status messages. > The game is over when..... > ----------------------- > > That should be shorter and less likely to predispose your thinking > to a particular approach - such as when the initialisation takes > place, or how many rooms or premature consideration of the > command structures etc. These things should emerge as you > create the object definitions and interactions. The initial aim is > only to find the half dozen to a dozen key classes top get started. > Other classes will emerge as you progress, and some of the > original candidates may merge into others or be discarded. > > And don't forget that there could well be a game class/object to > control the overall flow of the game and coordinate the actions > of the other objects. For example the prompt/response/display > mechanism might be part of the game class (and they might > be classes too!). This would maximise reuse of the compnent > objects within a different game framework ( a GUI fort instance) > later. > > 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 > Happy Happy Joy Joy -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From alan.gauld at btinternet.com Thu Feb 7 01:01:13 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Feb 2008 00:01:13 -0000 Subject: [Tutor] designing POOP References: Message-ID: "bhaaluu" wrote Let me preface this message by saying that I've never written a TAG before - either procedurally nor using OOP. so I don't know if the following approach is a good way to go or not. However it's where I feel things moving... > I have a tendancy to think about > things as actual objects (but probably not OOP > objects -- more like real objects, like a vase). But thats the right way to go. The whole point of OOP is that you are trying to simulate the real world objects. Thats why people who haven't been trained in "classical" programming techniqiues usually find OOP much easier to pick up than experienced programmers do. Its logically more sensible to say "move a table" in a direction for a distance than to change the x,y coordinates explicitly! > Explorer: has strength & wealth, can carry weapons & food, > can wear armor, can pick-up treasure, can fight monsters, > can wound monsters, can defeat monsters, can move from > room to room. A good start so Explorer looks like a class with two scalar attributes: strength and wealth. Also a number of lists of objects - weapons, food, treasure and maybe armor. Looks like we might have a set of methods to pickUp(object) and to wear(armor) and maybe some test methods hasWeapon(weapon), isWearing(armor) etc. Also we have some methods around fighting, BUT... We are interested in what we can do TO the objerect not what it does to other objects (at least at this point). So rather than fighting a monster maybe the monster can be fought - ie the fight method is a method of monster? Except.... > Monster: can be anywhere, has Ferocity Factor / Danger Level, > can fight Explorer, can wound Explorer, can defeat Explorer. It looks like the same applies to monsters and Explorers. So maybe both Monster and Explorer are subclasses of a Fighter because they share the same methods. Now we can have a battle between two fighter objects - and this could allow the game to be extended to allow monsters to fight monsters and explorers to fight explorers, almost for free! class Fighter(object): def fight(self, fighter) def attack(self, weapon) def repulse(self, weapon) def isKilled(self) def currentStrength(self) Notice that one of the things that seems to come out of this is that maybe the strength attribute and the list of weapons belongs in the fighter class? Or maybe not if monsters don't have weapons - a design decision... Now we can make a stab at how the fight metjod might work: def fight(self, fighter): weapon = self chooseWeapon() fighter.attack(weapon) if fighter.isKilled(): self.strength += fighter.value And from this we could maybe do the attack method too: def attack(self,weapon): if self.canRepulse(weapon): self.repulse(weapon) else: self.strength -= weapon.value if self.strength < 0: self.die() And this reveals some new attributes and methods we can add, and also probably some ideas for how to write the repulse method too... And by constantly repeating this cycle of invent a bit, write a bit, test a lot we gradually build up the individual classes. Remember the >>> prompt is your friend for testing these things. Create a few instances of fighters and weapons and get them to fight each other using the prompt. When you stop being sure of where to go, go back to your text description and look for more clues about other objects that might help. As I say, I don't actually know if the above aproach will really work for a TAG but it looks worth a try. But one of the beauties of OOP is that each object is a mini program that can be played with and experimented with at the >>> prompt so you find out what works and what doesn't very quickly. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Feb 7 02:15:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 06 Feb 2008 20:15:33 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: <47AA5BB5.1020500@tds.net> bhaaluu wrote: > How do you design POOP? What are the guidelines you keep in mind > to design "good" POOP? Can an absolute beginner learn to design POOP? I have mostly stayed out of this thread for lack of time and because Alan is doing a great job, but I think I will chime in a bit because this is an area where Alan and I have very different styles. Let me say that I don't mean any disrespect for Alan or his approach, I just have a different point of view. Also I will say that converting a procedural program to OO 'just because' is not necessarily a good idea. Not every program is improved by OOP. In your case, it probably will be though. I tend to work from small pieces to larger ones and let the design grow from the needs of the code, rather than from considerations of nouns and verbs in the spec. I think for me the primary drivers are data structure and functionality. For example, maybe I need a way to represent a room. I might start with a simple list or tuple and write some code that works with rooms. Soon I get tired of having to use subscripts all the time so I make a simple container class Room to hold the data. Then I will find bits of functionality - functions - that work with the room data; they become methods of the Room class. One piece at a time the code grows. Each new piece of functionality imposes new requirements on the design and the design may change to accommodate it. Design a little, code a little, repeat... http://personalpages.tds.net/~kent37/stories/00003.html Once and Only Once - aka Don't Repeat Yourself - is one of the best principles of design. Whenever you are tempted to copy/paste code or data, ask yourself how you could change the design to avoid the copying. You can discover many useful design techniques by applying DRY. More here: http://personalpages.tds.net/~kent37/stories/00012.html Sensitivity to code smells is another good way to discover when your design needs to change. Martin Fowler's book Refactoring popularized this term. It has a chapter that explains the code smells and points out ways to fix them. An abbreviated version is available here: http://wiki.java.net/bin/view/People/SmellsToRefactorings The writings of Robert C Martin have taught me a lot about good design and agile development. They don't all apply to Python - many design patterns that make sense in C++ or Java are not needed in Python - but the principles still hold. A lot of his work is available on-line: http://objectmentor.com/resources/publishedArticles.html http://objectmentor.com/resources/articles/Principles_and_Patterns.pdf might be a good starting point. http://objectmentor.com/resources/articles/xpepisode.htm attempts to give the flavor of agile, test-driven development. I don't use the command-line interpreter much, I do a lot more work in unit tests. In test-driven development (TDD), if you decide you want a Room class, the first thing you do is create a unit test for the class. The test will fail, because the class doesn't exist, so you next write the class and make the test pass. Then add another (failing) test for the next bit of functionality, then implement it and make the test pass. Continue as needed. I have written a little more about this here: http://personalpages.tds.net/~kent37/stories/00007.html HTH, Kent From trs5678 at hotmail.com Thu Feb 7 05:26:56 2008 From: trs5678 at hotmail.com (Timothy Sikes) Date: Wed, 6 Feb 2008 22:26:56 -0600 Subject: [Tutor] Pixelize ubuntu python script acting odd. Message-ID: so I recently installed ubuntu and started messing around with some of the programs. Pixelize takes a picture, then using a database of other pictures, makes a picture out of the database. The only way I know of to add pictures to the database is through the command 'make_db ' It doesn't seem to accept folders, only files. So I made this script in order to get a large number of files into it without having to type them all manually. def runThrough(): walk = os.walk("/media/sda1/Documents/Pictures/2007") #location of the pics I want to use count = 0 for root, dirs, files in walk: try: for x in files: if x.lower().find(".jpg")> -1: #If it's a .jpg... count = count + 1 operation = 'make_db ' + root + '/' + x os.system(operation) # Call the command line with the operation above print root + '/' + x #This is optional, I did this for debugging print str(count) + " files done" except OSError: print root + "/" + x + " was not included in the list" #This was run to get rid of all the obnoxious spaces in the file names #try: # for x in files: # loc = root + '/' + x # pic = loc.replace(' ', "_") # os.rename(loc, pic) # count = count + 1 # print str(count) + "files done" #except OSError: # print root + '/' + x + " was not included" But here's the problem... My computer has randomly restarted (or logged me off possibly) every I have run the program, about thirty seconds into the program. os.system('make_db ' + ) manually works in python, I tried it. Note: the same thing with double quotes does not work. I have changed some stuff since I last ran this, but I haven't run it again, because my computer randomly logging me off kinda bothers me. I am using Gusty Gibbons Ubuntu. Thanks. _________________________________________________________________ Shed those extra pounds with MSN and The Biggest Loser! http://biggestloser.msn.com/ From trs5678 at hotmail.com Thu Feb 7 05:38:05 2008 From: trs5678 at hotmail.com (Timothy Sikes) Date: Wed, 6 Feb 2008 22:38:05 -0600 Subject: [Tutor] Thought of some other things. Message-ID: First off, I was running my script from my flash drive-That could have caused something. Next, I have possible found something.... IN the location where I ran the script, I found a pic_db.bat with stuff in it... It still doesn't explain why the program crashed, but it does explain why I didn't think it was doing anything. Thanks again _________________________________________________________________ Shed those extra pounds with MSN and The Biggest Loser! http://biggestloser.msn.com/ From orsenthil at gmail.com Thu Feb 7 06:05:54 2008 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 7 Feb 2008 00:05:54 -0500 Subject: [Tutor] Thought of some other things. In-Reply-To: References: Message-ID: <7c42eba10802062105m385a8a93qcc0d40ddaa14df83@mail.gmail.com> On Feb 6, 2008 11:38 PM, Timothy Sikes wrote: > > First off, I was running my script from my flash drive-That could have caused something. Next, I have possible found something.... IN the location where I ran the script, I found a pic_db.bat with stuff in it... It still doesn't explain why the program crashed, but it does explain why I didn't think it was doing anything. Your question is unclear, Timothy. Running from the flash drive is not going to cause your program to crash. The interpreter is in the PATH of your computer and you can run your program from flash drive, cd or from the floppy drive. pic_db.bat could be anything. Google for it and verify if it is not a virus. Paste the error message you received for more specific response. Thanks, -- -- O.R.Senthil Kumaran http://phoe6.livejournal.com From alan.gauld at btinternet.com Thu Feb 7 10:15:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Feb 2008 09:15:12 -0000 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net> Message-ID: "Kent Johnson" wrote > Let me say that I don't mean any disrespect for Alan or his > approach, I > just have a different point of view. Heh, heh! I was waiting for someone to post a message like this. I'll respond by saying the noun/verb thing is not actually the method I would normally use (although when all else fails I do drop back to it as a starter technique). However I have found it to be a techhnique that woerks well for beginners who don't know how to get started. Partly because it is fairly mechanistic. But noun/verb does have some problems and often produces designs that have too many classes and that do not make best use of OOP idioms like polymorphism or abstraction. But for beginners and in small problems it is a good starter. > Also I will say that converting a procedural program to OO 'just > because' is not necessarily a good idea. Not every program is > improved > by OOP. In your case, it probably will be though. This is absolutely true. Too many people approach OOP as if it were some kind of holy grail that is inherently better than other styles - it isn't, its just another tool in the toolkit. > I tend to work from small pieces to larger ones and let the design > grow > from the needs of the code, rather than from considerations of nouns > and > verbs in the spec. I agree at the micro level and in fact my discussion of explorers and monsters merging into a figher superclass hopefully illustrates how that micro level design/code cycle can generate new features of a design including new classes/objects. Many OO Design gurus have commented on the way that OO design tends to cycle between top down design - identifying core classes - and bottom up design - writing the lowest building blocks and using that to discover more about the higher level needs. OO design is a very organic process compared to procedural design which tends to bemuch more top down and heirarchical in nature. In my experience at least. > accommodate it. Design a little, code a little, repeat... > http://personalpages.tds.net/~kent37/stories/00003.html Exactly so. > The writings of Robert C Martin have taught me a lot about good > design > and agile development. They don't all apply to Python Martin is very good on Agile, I'm less impressed with his OO writing, largely because he does tend to see the world through the eyes of C++ and Java, both of which have a very singular view of OO which does not always work in other more dynamic OOP languages (Lisp, Smalltalk, Python, JavaScript etc) > I don't use the command-line interpreter much, I do a lot more work > in > unit tests. In test-driven development (TDD), if you decide you want > a > Room class, the first thing you do is create a unit test for the > class. For production programming I wholly endorse that approach, for exploring and inventing code structures (which is mainly what I use Python for, the results get converted to Java where we use TDD) I find the interpreter is very useful. To use TDD effectively you first need to know what you are trying to do. An example of bad use of TDD can be found in one of Robert Martins books where he tries to give an example of pair programming of a bowling game scorer. Unfortunately because of the haphazard design approach they wind up with code that is both bloated (it repeats an algorithm twice) and faulty (one of the algorithm implementations is broken). Unfortunately they don't detect the fault because the test data they used missed out all of the cases where the defect is exhibited... Note it wasn't the test that was broken it was the limited data set used. And that is one of the big limitations of TDD, it is only as effective as the test data. It is important to realize that there is no single way to design OOP programs. The noun/verb thing is a good way to get started and often effective when nothing else seems to be working. But there are plenty of other approaches out there and books by authors like Booch, Rumbaugh, Jacobsen, Schaer/Mellor, Coad/Yourdon, Wirfs-Brock and yes, Robert Martin are all worh reading to see the different approaches available. The Coad/Nicola OOP book is especially interesting because it contrasts the same problems in C++ and Smalltalk (which is conceptually close to python) and shows how the choice of language can have a big impact on detailed OOP design decisions. Once you get experienced in OPP you will not use the noun/verb te4chnique very often because your brain will start to think in terms of objects without need of intermediate tools. In fact when I went back to COBOL for the Y2K bug I found it hard initially to think procedurally because I'd been using OOP for so long by then. Nowadays I don;t write so much code I find I switch between both modes of design without really thinking too much about it. On small scale stuff I tend to go procedural but on big problems I tend to go OOP. Alan G. From bhaaluu at gmail.com Thu Feb 7 10:39:36 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 7 Feb 2008 04:39:36 -0500 Subject: [Tutor] designing POOP In-Reply-To: <47AA5BB5.1020500@tds.net> References: <47AA5BB5.1020500@tds.net> Message-ID: On Feb 6, 2008 8:15 PM, Kent Johnson wrote: > .... > Design a little, code a little, repeat... > http://personalpages.tds.net/~kent37/stories/00003.html > > .... > You can discover many useful design techniques by applying DRY. More here: > http://personalpages.tds.net/~kent37/stories/00012.html > > .... > It has a chapter that explains the code smells and points out > ways to fix them. An abbreviated version is available here: > http://wiki.java.net/bin/view/People/SmellsToRefactorings > > The writings of Robert C Martin have taught me a lot about good design > and agile development. .... A lot of his work is available on-line: > http://objectmentor.com/resources/publishedArticles.html > > http://objectmentor.com/resources/articles/Principles_and_Patterns.pdf > might be a good starting point. > http://objectmentor.com/resources/articles/xpepisode.htm attempts to > give the flavor of agile, test-driven development. > > I don't use the command-line interpreter much, I do a lot more work in > unit tests. .... I have written a little more about this here: > http://personalpages.tds.net/~kent37/stories/00007.html > > HTH, > Kent Thank you Kent! I am open to all suggestions as to where to get started learning how to design with the Python Object-Oriented Paradigm. I'm doing a lot of reading, some coding (in my 'testing' directory), and a lot of thinking about what I'm trying to do. This is a learning situation. Since I'm a Hobbyist programmer, I don't have a 'class' deadline to meet (and believe me, I'm happy about that!). I do feel that learning how to do this will enhance the enjoyment of my Hobby for years to come. I do know that it will open a lot of doors for me that are currently closed, especially when it comes to creating games with Python/PyGame, and so forth. Plus, it is quite possible that this discussion will benefit others who are also just beginning. Happy Happy Joy Joy. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From michael at arpsorensen.dk Thu Feb 7 11:37:21 2008 From: michael at arpsorensen.dk (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=) Date: Thu, 7 Feb 2008 11:37:21 +0100 Subject: [Tutor] A bit about python culture Message-ID: <1618520802070237x49d821aex6bf1f65c49ea007b@mail.gmail.com> Greetings Masters. I was wondering if there's a well know word for python programmers, that is usable as a domain name. Unfortunately, "pug.dk", as in "python user group, Denmark", is unavailable here in Denmark. I hope to acquire a national domain name and let future local user groups choose their own third level domain name. Any ideas are welcome. -- Kind regards Michael B. Arp S?rensen Programmer / BOFH I am /root and if you see me laughing you better have a backup. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080207/10de4d4e/attachment.htm From murderbystealth at gmail.com Thu Feb 7 11:44:00 2008 From: murderbystealth at gmail.com (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=) Date: Thu, 7 Feb 2008 11:44:00 +0100 Subject: [Tutor] A bit about python culture Message-ID: <1618520802070244u1849f1f9u9c421cf5136e35e@mail.gmail.com> Greetings Masters. I was wondering if there's a well know word for python programmers, that is usable as a domain name. Unfortunately, "pug.dk", as in "python user group, Denmark", is unavailable here in Denmark. I hope to acquire a national domain name and let future local user groups choose their own third level domain name. Any ideas are welcome. -- Kind regards Michael B. Arp S?rensen Programmer / BOFH I am /root and if you see me laughing you better have a backup. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080207/1c6a9afe/attachment-0001.htm From kent37 at tds.net Thu Feb 7 13:08:47 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Feb 2008 07:08:47 -0500 Subject: [Tutor] A bit about python culture In-Reply-To: <1618520802070237x49d821aex6bf1f65c49ea007b@mail.gmail.com> References: <1618520802070237x49d821aex6bf1f65c49ea007b@mail.gmail.com> Message-ID: <47AAF4CF.5070701@tds.net> Michael Bernhard Arp S?rensen wrote: > Greetings Masters. > > I was wondering if there's a well know word for python programmers, that > is usable as a domain name. Pythonista is one. pythonista.dk seems to be available. Kent From kent37 at tds.net Thu Feb 7 13:25:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Feb 2008 07:25:06 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> Message-ID: <47AAF8A2.7030502@tds.net> Alan Gauld wrote: > "Kent Johnson" wrote >> The writings of Robert C Martin have taught me a lot about good >> design >> and agile development. They don't all apply to Python > > Martin is very good on Agile, I'm less impressed with his OO writing, > largely because he does tend to see the world through the eyes > of C++ and Java, both of which have a very singular view of OO > which does not always work in other more dynamic OOP > languages (Lisp, Smalltalk, Python, JavaScript etc) I found his writing on principles of OO design very helpful when I was a C++ programmer. I admit I have not revisited them from the point-of-view of a Python programmer. I'm sure some of the techniques are not needed - the pervasive use of interfaces, in particular - but the underlying principles should still apply. Taking a closer look, I think these still have something to offer: The Liskov Substitution Principle http://objectmentor.com/resources/articles/lsp.pdf Inheritance vs. Delegation (Template Method and Strategy patterns) http://objectmentor.com/resources/articles/inheritanceVsDelegation.pdf The Craftsman series might be of interest. One thing to keep in mind is that when C++ and Java use interfaces, Python uses duck typing. C++ and Java use classes to encapsulate functions (e.g. in Strategy) but Python can use functions directly. Kent From dotancohen at gmail.com Thu Feb 7 13:31:14 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Thu, 7 Feb 2008 14:31:14 +0200 Subject: [Tutor] A bit about python culture In-Reply-To: <1618520802070244u1849f1f9u9c421cf5136e35e@mail.gmail.com> References: <1618520802070244u1849f1f9u9c421cf5136e35e@mail.gmail.com> Message-ID: <880dece00802070431t6159f10cwc495c7d0d4fd11c9@mail.gmail.com> On 07/02/2008, Michael Bernhard Arp S?rensen wrote: > Greetings Masters. > > I was wondering if there's a well know word for python programmers, that is > usable as a domain name. Unfortunately, "pug.dk", as in "python user group, > Denmark", is unavailable here in Denmark. > > I hope to acquire a national domain name and let future local user groups > choose their own third level domain name. > > Any ideas are welcome. > feisty at feisty-laptop:~$ whois python.dk # Any use of this material to target advertising or similar activities # are explicitly forbidden and will be prosecuted. DK Hostmaster A/S # requests to be notified of any such activities or suspicions thereof. Domain: python.dk DNS: python.dk Registered: 1999-09-14 Expires: 2008-09-30 Registration period: 1 year VID: no Status: Active Nameservers Hostname: ns1.rackserverz.biz Hostname: ns2.rackserverz.biz feisty at feisty-laptop:~$ whois pyden.dk # Any use of this material to target advertising or similar activities # are explicitly forbidden and will be prosecuted. DK Hostmaster A/S # requests to be notified of any such activities or suspicions thereof. No entries found for the selected source. feisty at feisty-laptop:~$ pyden.dk doesn't sound too bad. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From imonthejazz at googlemail.com Thu Feb 7 13:42:13 2008 From: imonthejazz at googlemail.com (Damian Archer) Date: Thu, 7 Feb 2008 12:42:13 +0000 Subject: [Tutor] Anyone fancy giving me some tips and an expert opinion?? Message-ID: I have written what i see as a pretty decent script to resolve this question: Write an improved version of the Chaos program from Chapter 1 that allows a user to input two initial values and the number of iterations and then prints a nicely formatted table showing how the values change over time. For example, if the starting values were .25 and .26 with 10 iterations, the table might look like this: index 0.25 0.26 ---------------------------- 1 0.731250 0.750360 2 0.766441 0.730547 3 0.698135 0.767707 4 0.821896 0.695499 5 0.570894 0.825942 6 0.955399 0.560671 7 0.166187 0.960644 8 0.540418 0.147447 9 0.968629 0.490255 10 0.118509 0.974630 Although it works I am sure I could have gone about this a better way, it probably doesn't fit all the rules of best practice either. Was wondering if anyone would mind having a look and offering a few tips?? # chaos.py # A program to mimic the chaos theory def main(): print "Example of Chaos" # User inputs numbers to compare, z is for the index counter x = input("Enter a number between 1 and 0: ") y = input("Enter a second number between 1 and 0: ") z = 0 # Prints the table borders and titles print '%10s %20s %20s' % ("Index", x, y) print "----------------------------------------------------------" tempx = x tempy = y # Loops calculates 'chaotic behaviour for input numbers for i in range(10): tempx = 3.9 * tempx * (1 - tempx) tempy = 3.9 * tempy * (1 - tempy) z = z + 1 # Print chaotice results into table print '%10s %20s %20s' % (z, tempx, tempy) raw_input("Press any key to exit") main() Thanks!!! And thanks for all the help you've all supplied me with so far, you guys certainly are an extremely valuable resource!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080207/9bda1706/attachment.htm From thomas at lizacom.com Thu Feb 7 12:40:53 2008 From: thomas at lizacom.com (Thomas B.D=?UTF-8?Q?=C3=B8derlein?=) Date: Thu, 7 Feb 2008 13:40:53 +0200 Subject: [Tutor] A bit about python culture Message-ID: <20080207124035.BF17D28A5D@osl01mta02.no.ventelo.net> >Michael Bernhard Arp S?rensen wrote: >> Greetings Masters. >> >> I was wondering if there's a well know word for python programmers, that >> is usable as a domain name. > >Pythonista is one. pythonista.dk seems to be available. > >Kent Other available .dk domains pyproject.dk pyprojects.dk python-project.dk pythonprogram.dk These might be used for project subdomains, then the programmers might add their name in E-mail adresses. Doing this you will also marked Python projects + making people aware of Python as a programming language. Just a thought :) BR Thomas >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From bhaaluu at gmail.com Thu Feb 7 14:59:53 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 7 Feb 2008 08:59:53 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> Message-ID: Greetings, I've read both Kent's and Alan's approaches to designing a POOP, and am intrigued with the possibilities of the noun/verb/adjective technique, but am also sympathetic to the TDD method as well because it is how I've always programmed. I have noted Alan's comments on the limitations of TDD, as well as the limitations of the noun/verb/adjective method of design. The TDD method is the method used in my tutorial: Python Programming for the Absolute Beginner 2E. Michael Dawson. 2006. Dawson uses a very simple Tamagotchi example called Critter Caretaker to introduce the mechanics of POOP. However, perhaps he is using the TDD method of "design"? I'm still experimenting with the noun/verb/adjective design technique, but I was also itching to get started on something as well, so here is a first little testing snippet from the testing directory, using the TDD method. I'm confident that if I am using the terminology incorrectly, someone will point out the error of my ways. The Tutors are always saying they really can't help unless they see some code, so this is a simple adventure game that involves switching a light on and off. The gameplay isn't all that great, but it is a start. 8^D #!/user/bin/python """ >From the testing laboratory of: b h a a l u u at g m a i l dot c o m 2008-02-07 """ import time CS = "\n"*50 class TestClass1(object): """ please give me a better name""" def __init__(self): """please document me""" self.name = "" self.answer = "" self.strength = 20 self.wealth = 45 self.light = 0 self.tally = 0 def main(): tc1 = TestClass1() # instance tc1.__init__() # invoke method print CS N1 = tc1.name N1 = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") # main game loop while True: print CS print (" %s, YOUR STRENGTH IS %d") % (N1, tc1.strength) print (" YOU HAVE $%d") % tc1.wealth if tc1.light == 0: print (" IT IS TOO DARK TO SEE ANYTHING") else: print (" THE LIGHT'S ON, BUT NO ONE'S HOME") print print A = tc1.answer A = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") # main game prompt if A.upper() == "Q": break if A.upper() == "L": light = raw_input(" LIGHT? [0|1]: ") # turn the light on and off if light == 0 and tc1.light == 0: print (" THE LIGHT IS OFF") time.sleep(2) if tc1.wealth <= 0: print print (" YOU HAVE NO MONEY") time.sleep(2) else: tc1.light = int(light) tc1.wealth -= 15 else: print (" INVALID CHOICE") time.sleep(2) tc1.tally += 1 tc1.strength -= 5 if tc1.strength <= 0: print (" YOU DIED....") time.sleep(2) break print print (" Final Score:") print (" Tally: %d") % tc1.tally print (" Wealth: $%d") % tc1.wealth print (" Strength: %d") % tc1.strength if __name__ == "__main__": main() On Feb 7, 2008 4:15 AM, Alan Gauld wrote: > "Kent Johnson" wrote > > > Let me say that I don't mean any disrespect for Alan or his > > approach, I > > just have a different point of view. > > Heh, heh! I was waiting for someone to post a message like this. > I'll respond by saying the noun/verb thing is not actually the > method I would normally use (although when all else fails I > do drop back to it as a starter technique). However I have found > it to be a techhnique that woerks well for beginners who don't > know how to get started. Partly because it is fairly mechanistic. > > But noun/verb does have some problems and often produces > designs that have too many classes and that do not make > best use of OOP idioms like polymorphism or abstraction. > But for beginners and in small problems it is a good starter. > > > Also I will say that converting a procedural program to OO 'just > > because' is not necessarily a good idea. Not every program is > > improved > > by OOP. In your case, it probably will be though. > > This is absolutely true. Too many people approach OOP as > if it were some kind of holy grail that is inherently better > than other styles - it isn't, its just another tool in the toolkit. > > > I tend to work from small pieces to larger ones and let the design > > grow > > from the needs of the code, rather than from considerations of nouns > > and > > verbs in the spec. > > I agree at the micro level and in fact my discussion of > explorers and monsters merging into a figher superclass > hopefully illustrates how that micro level design/code cycle > can generate new features of a design including new > classes/objects. Many OO Design gurus have commented > on the way that OO design tends to cycle between top down > design - identifying core classes - and bottom up design - writing > the lowest building blocks and using that to discover more > about the higher level needs. > > OO design is a very organic process compared to procedural > design which tends to bemuch more top down and heirarchical > in nature. In my experience at least. > > > accommodate it. Design a little, code a little, repeat... > > http://personalpages.tds.net/~kent37/stories/00003.html > > Exactly so. > > > The writings of Robert C Martin have taught me a lot about good > > design > > and agile development. They don't all apply to Python > > Martin is very good on Agile, I'm less impressed with his OO writing, > largely because he does tend to see the world through the eyes > of C++ and Java, both of which have a very singular view of OO > which does not always work in other more dynamic OOP > languages (Lisp, Smalltalk, Python, JavaScript etc) > > > I don't use the command-line interpreter much, I do a lot more work > > in > > unit tests. In test-driven development (TDD), if you decide you want > > a > > Room class, the first thing you do is create a unit test for the > > class. > > For production programming I wholly endorse that approach, > for exploring and inventing code structures (which is mainly > what I use Python for, the results get converted to Java > where we use TDD) I find the interpreter is very useful. > > To use TDD effectively you first need to know what you are > trying to do. An example of bad use of TDD can be found in > one of Robert Martins books where he tries to give an example > of pair programming of a bowling game scorer. Unfortunately > because of the haphazard design approach they wind up > with code that is both bloated (it repeats an algorithm twice) > and faulty (one of the algorithm implementations is broken). > Unfortunately they don't detect the fault because the test data > they used missed out all of the cases where the defect is > exhibited... Note it wasn't the test that was broken it was > the limited data set used. And that is one of the big limitations > of TDD, it is only as effective as the test data. > > It is important to realize that there is no single way to design > OOP programs. The noun/verb thing is a good way to get > started and often effective when nothing else seems to > be working. But there are plenty of other approaches out > there and books by authors like Booch, Rumbaugh, Jacobsen, > Schaer/Mellor, Coad/Yourdon, Wirfs-Brock and yes, Robert Martin > are all worh reading to see the different approaches available. > The Coad/Nicola OOP book is especially interesting because > it contrasts the same problems in C++ and Smalltalk (which > is conceptually close to python) and shows how the choice > of language can have a big impact on detailed OOP design > decisions. > > Once you get experienced in OPP you will not > use the noun/verb te4chnique very often because your brain > will start to think in terms of objects without need of intermediate > tools. In fact when I went back to COBOL for the Y2K bug I > found it hard initially to think procedurally because I'd been > using OOP for so long by then. Nowadays I don;t write so > much code I find I switch between both modes of design > without really thinking too much about it. On small scale > stuff I tend to go procedural but on big problems I tend to > go OOP. > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From bhaaluu at gmail.com Thu Feb 7 15:12:13 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 7 Feb 2008 09:12:13 -0500 Subject: [Tutor] A bit about python culture In-Reply-To: <1618520802070244u1849f1f9u9c421cf5136e35e@mail.gmail.com> References: <1618520802070244u1849f1f9u9c421cf5136e35e@mail.gmail.com> Message-ID: On Feb 7, 2008 5:44 AM, Michael Bernhard Arp S?rensen wrote: > Greetings Masters. > > I was wondering if there's a well know word for python programmers, that is > usable as a domain name. Unfortunately, "pug.dk", as in "python user group, > Denmark", is unavailable here in Denmark. > > I hope to acquire a national domain name and let future local user groups > choose their own third level domain name. > > Any ideas are welcome. > > -- > Kind regards > > Michael B. Arp S?rensen > Programmer / BOFH > > I am /root and if you see me laughing you better have a backup. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Your best bet might be to look at the old comedy sketches of Monty Python's Flying Circus. I've found several of their skits on YouTube. A couple of the more well known sketches are the Cheese Shop and the Dead Parrot, but there are others that may also be a source of ideas for names of a Python Programming domain. Even though the logo for many Python Programming sites is a python snake, the Python Programming language was named after the British comedy troupe. Happy Happy Joy Joy. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From bhaaluu at gmail.com Thu Feb 7 20:52:53 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 7 Feb 2008 14:52:53 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> Message-ID: I was asked: Here's a situation I often encounter, and I was wondering what the "best practice" is. I've generally initialized my classes' attributes this same way: > class TestClass1(object): > """ please give me a better name""" > def __init__(self): > """please document me""" > self.name = "" > self.answer = "" > self.strength = 20 > self.wealth = 45 > self.light = 0 > self.tally = 0 but it could also be done like so: > class TestClass1(object): > """ please give me a better name""" > name = "" > answer = "" > strength = 20 > wealth = 45 > light = 0 > tally = 0 > def __init__(self,name="Zed"): > """please document me""" > self.name = name > ...etc. I realize that the two are NOT equivalent if you're using the class as a static class, rather than instantiating it (e.g. using a static class called Global while weaning oneself from global variables...) However, I'm asking about this present case: the class under discussion will always be instantiated. It seems to me that declaring the attributes in the class body makes the class more amenable to introspection, but are there downsides I'm not seeing? What's the best practice? I've tried both ways and can't see any difference between the two as far as input/output is concerned. Best practice? -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Thu Feb 7 21:10:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Feb 2008 15:10:21 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> Message-ID: <47AB65AD.4030106@tds.net> bhaaluu wrote: > Best practice? Use class attributes when you actually want a shared attribute, for example for constants with class scope, or as defaults when instance attributes may not be assigned. Class attributes can be redefined by subclasses which makes them useful as a way to configure a class. Don't use them strictly as documentation. Write a docstring instead. My $.02 Kent From marc.tompkins at gmail.com Thu Feb 7 21:37:02 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 7 Feb 2008 12:37:02 -0800 Subject: [Tutor] designing POOP In-Reply-To: <40af687b0802071236s601abf35qff9bf0d58a33dcc7@mail.gmail.com> References: <47AA5BB5.1020500@tds.net> <40af687b0802071048w2aa02131xf28ee334dd6641fc@mail.gmail.com> <40af687b0802071236s601abf35qff9bf0d58a33dcc7@mail.gmail.com> Message-ID: <40af687b0802071237q2f52f3f1u6ae2606e3c0a431a@mail.gmail.com> > Sorry, my bad - this was my me, but I forgot to hit "Reply All". My me? I think I meant to type "my message". -- www.fsrtechnologies.com From marc.tompkins at gmail.com Thu Feb 7 21:36:18 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 7 Feb 2008 12:36:18 -0800 Subject: [Tutor] Fwd: designing POOP In-Reply-To: <40af687b0802071048w2aa02131xf28ee334dd6641fc@mail.gmail.com> References: <47AA5BB5.1020500@tds.net> <40af687b0802071048w2aa02131xf28ee334dd6641fc@mail.gmail.com> Message-ID: <40af687b0802071236s601abf35qff9bf0d58a33dcc7@mail.gmail.com> Sorry, my bad - this was my me, but I forgot to hit "Reply All". Here's a situation I often encounter, and I was wondering what the "best practice" is. I've generally initialized my classes' attributes this same way: > class TestClass1(object): > """ please give me a better name""" > def __init__(self): > """please document me""" > self.name = "" > self.answer = "" > self.strength = 20 > self.wealth = 45 > self.light = 0 > self.tally = 0 but it could also be done like so: > class TestClass1(object): > """ please give me a better name""" > name = "" > answer = "" > strength = 20 > wealth = 45 > light = 0 > tally = 0 > def __init__(self,name="Zed"): > """please document me""" > self.name = name > ...etc. I realize that the two are NOT equivalent if you're using the class as a static class, rather than instantiating it (e.g. using a static class called Global while weaning oneself from global variables...) However, I'm asking about this present case: the class under discussion will always be instantiated. It seems to me that declaring the attributes in the class body makes the class more amenable to introspection, but are there downsides I'm not seeing? What's the best practice? Standing by to get flamed... -- www.fsrtechnologies.com From trs5678 at hotmail.com Thu Feb 7 21:50:48 2008 From: trs5678 at hotmail.com (Timothy Sikes) Date: Thu, 7 Feb 2008 14:50:48 -0600 Subject: [Tutor] Thought of some other things. Message-ID: > Date: Thu, 7 Feb 2008 00:05:54 -0500> From: orsenthil at gmail.com> To: trs5678 at hotmail.com; Tutor at python.org> Subject: Re: [Tutor] Thought of some other things.> > On Feb 6, 2008 11:38 PM, Timothy Sikes wrote:> >> > First off, I was running my script from my flash drive-That could have caused something. Next, I have possible found something.... IN the location where I ran the script, I found a pic_db.bat with stuff in it... It still doesn't explain why the program crashed, but it does explain why I didn't think it was doing anything.> > Your question is unclear, Timothy.> Running from the flash drive is not going to cause your program to> crash. The interpreter is in the PATH of your computer and you can run> your program from flash drive, cd or from the floppy drive.> > pic_db.bat could be anything. Google for it and verify if it is not a virus.> > Paste the error message you received for more specific response.> > Thanks,> > Well, the problem was I wasn't getting an error message. My computer would just stop and log me off. Sorry I didn't specify before, but the pic_db.bat is the result of the 'make_db' command. So it basically started to work, then crashed my computer. I meant to ask whether or not anyone could see anything that would cause my system to restart, but it's not necissary now. For some reason, when I ran this script the second time, only this time saving the list of files to a list, and then using the 'make_db' command on each and every file in the list seemed to work. If anyone can tell me why my computer restarted off the top of thier head, great, but otherwise I"m not going to worry about it now.... Thanks though! > > -- > -- > O.R.Senthil Kumaran> http://phoe6.livejournal.com> _______________________________________________> Tutor maillist - Tutor at python.org> http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Climb to the top of the charts!?Play the word scramble challenge with star power. http://club.live.com/star_shuffle.aspx?icid=starshuffle_wlmailtextlink_jan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080207/41848223/attachment.htm From bgailer at alum.rpi.edu Thu Feb 7 21:55:50 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Thu, 07 Feb 2008 15:55:50 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> Message-ID: <47AB7056.1020207@alum.rpi.edu> Also beware the difference between reassigning and extending: class F: a = 3 b = [] def __init__(self, a, b): self.a = a self.b.append(b) def show(self): print self.a, self.b f1=F(1,2) f2=F(3,4) f1.show() # 1 [2, 4] f2.show() # 3 [2, 4] -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Thu Feb 7 22:07:02 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Feb 2008 16:07:02 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> Message-ID: <47AB72F6.6020201@tds.net> bhaaluu wrote: > The TDD method is the method used in my tutorial: > Python Programming for the Absolute Beginner 2E. Michael Dawson. 2006. > Dawson uses a very simple Tamagotchi example called Critter Caretaker > to introduce the mechanics of POOP. However, perhaps he is using > the TDD method of "design"? I don't think Dawson uses TDD. AFAIK he doesn't talk about unit-testing at all, which is the fundamental practice of TDD. For an example of unit tests in Python, see http://docs.python.org/lib/minimal-example.html > here is > a first little testing snippet from the testing directory, using the TDD > method. I'm confident that if I am using the terminology incorrectly, > someone will point out the error of my ways. I think you are using the terminology incorrectly. I would call this an example of experimental programming, maybe. A classic example of TDD in Java is here: http://junit.sourceforge.net/doc/testinfected/testing.htm > class TestClass1(object): > """ please give me a better name""" > def __init__(self): > """please document me""" > self.name = "" > self.answer = "" > self.strength = 20 > self.wealth = 45 > self.light = 0 > self.tally = 0 This is a good example of a data class - a class that is just a container for data. That is a code smell. It seems to contain unrelated values - name and strength are attributes of the player, light is an attribute of the environment. So it should probably be more than one class, or, since the entire program is in one loop, these could just be local variables of main(). > def main(): > tc1 = TestClass1() # instance > tc1.__init__() # invoke method The __init__() method is called implicitly by calling TestClass1(). Generally the only time you explicitly call __init__() is when calling the method of a base class. Kent From bhaaluu at gmail.com Thu Feb 7 22:42:15 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 7 Feb 2008 16:42:15 -0500 Subject: [Tutor] designing POOP In-Reply-To: <47AB72F6.6020201@tds.net> References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> Message-ID: On Feb 7, 2008 4:07 PM, Kent Johnson wrote: > bhaaluu wrote: > > > The TDD method is the method used in my tutorial: > > Python Programming for the Absolute Beginner 2E. Michael Dawson. 2006. > > Dawson uses a very simple Tamagotchi example called Critter Caretaker > > to introduce the mechanics of POOP. However, perhaps he is using > > the TDD method of "design"? > > I don't think Dawson uses TDD. AFAIK he doesn't talk about unit-testing > at all, which is the fundamental practice of TDD. For an example of unit > tests in Python, see > http://docs.python.org/lib/minimal-example.html > > > here is > > a first little testing snippet from the testing directory, using the TDD > > method. I'm confident that if I am using the terminology incorrectly, > > someone will point out the error of my ways. > > I think you are using the terminology incorrectly. I would call this an > example of experimental programming, maybe. A classic example of TDD in > Java is here: > http://junit.sourceforge.net/doc/testinfected/testing.htm What is the equivalent of JUnit in Python? The article says that JUnit is used for unit tests, or you can write your own. Since I don't have a clue, writing my own is probably out the question. Also I'm not familiar with Java, and am just learning Python OOP, so I'm not getting much out of that one. Sorry. Absolute Beginner here. > > > class TestClass1(object): > > """ please give me a better name""" > > def __init__(self): > > """please document me""" > > self.name = "" > > self.answer = "" > > self.strength = 20 > > self.wealth = 45 > > self.light = 0 > > self.tally = 0 > > This is a good example of a data class - a class that is just a > container for data. That is a code smell. It seems to contain unrelated > values - name and strength are attributes of the player, light is an > attribute of the environment. So it should probably be more than one > class, or, since the entire program is in one loop, these could just be > local variables of main(). Well, most of these were local variables in main() in the procedural version of this program. So DataClass() is what I should name such a class. I was wondering about that. These variables were all initialized in the procedural program before the loop started. Also, the Castle was setup as part of the initialization, but I'm not dealing with that here. I'm just trying to learn how to design here. I figured I'd put the Castle setup in it's own class because it is an object (using the "model as a real-world object" method). I don't think I can worry about whether the CodeSmells at this point. I'm thinking I need to design something that works, then be able to "refactor" it to eliminate as many CodeSmells as I can. But! Noted: a DataClass is a CodeSmell. > > > def main(): > > tc1 = TestClass1() # instance > > tc1.__init__() # invoke method > > The __init__() method is called implicitly by calling TestClass1(). > Generally the only time you explicitly call __init__() is when calling > the method of a base class. I can fix that right now! Back to the laboratory! 8^D > > Kent > Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From brunson at brunson.com Thu Feb 7 22:58:34 2008 From: brunson at brunson.com (Eric Brunson) Date: Thu, 07 Feb 2008 14:58:34 -0700 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> Message-ID: <47AB7F0A.60303@brunson.com> bhaaluu wrote: > What is the equivalent of JUnit in Python? The article says that JUnit is > used for unit tests, or you can write your own. Since I don't have a clue, > writing my own is probably out the question. Also I'm not familiar with > Java, and am just learning Python OOP, so I'm not getting much out > of that one. Sorry. Absolute Beginner here. > http://www.google.com/search?q=python+unit+test Cleverly called "unittest", though sometimes referred to by its original project name "PyUnit". :-) From alan.gauld at btinternet.com Thu Feb 7 23:17:02 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Feb 2008 22:17:02 -0000 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> Message-ID: "bhaaluu" wrote > What is the equivalent of JUnit in Python? I think the nearest equivalent is > writing my own is probably out the question. Also I'm not familiar > with > Java, and am just learning Python OOP, so I'm not getting much out > of that one. Sorry. Absolute Beginner here. Note that Unit testing is orthogonal to OOP. You can use TDD and unit tests(and should!) when doing procedural programming just as well. > Well, most of these were local variables in main() in the procedural > version of this program. So DataClass() is what I should name such > a class. I was wondering about that. While you can use classes that way it leads to a style of programming called object based rather than object oriented. It uses objects but the underlying design is still procedural. Thats why its better to focus on the behaviour of the objects and add the data attributes needed to support that behaviour. Remember we communicate with objects by sending them messages asking them to *do* stuff not to get data out of them, or at least we should do. "Objects do it to themselves": The Law of demeter. Ask What does this object do? What data does it need to achieve that? > Castle setup in it's own class because it is an object (using the > "model as a real-world object" method). Yes, each object should initialise its own data. (Albeit maybe based on values passed into the constructor.) HTH, Alan G. From kent37 at tds.net Thu Feb 7 23:20:17 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Feb 2008 17:20:17 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> Message-ID: <47AB8421.80805@tds.net> bhaaluu wrote: > What is the equivalent of JUnit in Python? The unittest module is based on JUnit. http://docs.python.org/lib/module-unittest.html Here is a simple introduction to the capabilities of unittest. It doesn't do much to motivate the examples though: http://www.oreillynet.com/onlamp/blog/2007/09/pymotw_unittest.html A longer intro: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html An alternative to unittest is doctest. They both get the job done, which one to use is mostly a matter of preference and the complexity of the tests. http://docs.python.org/lib/module-doctest.html Wikipedia has a short introduction to doctest and a link to Tim Peter's c.l.py posting introducing the module: http://en.wikipedia.org/wiki/Doctest http://groups.google.com/group/comp.lang.python/msg/1c57cfb7b3772763 Another intro: http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-2-doctest.html There are many other testing tools that are not in the standard library. Nose and py.test are popular alternatives to unittest and doctest. http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-3-pytest-tool.html Here is a good list of testing articles: http://www.pycheesecake.org/wiki/AgileTestingArticlesAndTutorials Here is a pretty comprehensive list of tools: http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy Kent From bhaaluu at gmail.com Thu Feb 7 23:31:19 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 7 Feb 2008 17:31:19 -0500 Subject: [Tutor] designing POOP In-Reply-To: <47AB7F0A.60303@brunson.com> References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> <47AB7F0A.60303@brunson.com> Message-ID: On Feb 7, 2008 4:58 PM, Eric Brunson wrote: > bhaaluu wrote: > > What is the equivalent of JUnit in Python? The article says that JUnit is > > used for unit tests, or you can write your own. Since I don't have a clue, > > writing my own is probably out the question. Also I'm not familiar with > > Java, and am just learning Python OOP, so I'm not getting much out > > of that one. Sorry. Absolute Beginner here. > > > > http://www.google.com/search?q=python+unit+test > > Cleverly called "unittest", though sometimes referred to by its original > project name "PyUnit". > > :-) > Cool! http://docs.python.org/lib/module-unittest.html The Python unit testing framework, sometimes referred to as ``PyUnit,'' is a Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in turn, a Java version of Kent's Smalltalk testing framework. Each is the de facto standard unit testing framework for its respective language. Who would have thunk it? I'll Google and see if I can find a nice PyUnit tutorial. So, is my first try dong a "unit test" a total bit-bucket case? No way to make a "test case" out of it? That would be a good example (for me). 8^D -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From alan.gauld at btinternet.com Fri Feb 8 00:47:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 7 Feb 2008 23:47:30 -0000 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net><47AB72F6.6020201@tds.net> Message-ID: "Alan Gauld" wrote >> What is the equivalent of JUnit in Python? > > I think the nearest equivalent is > Oops, I was going top say PyUnit then remembered the name had changed but forgot to check out the latest incarnation. Fortyunately others have done the work for me. Personally I like the Nose framework that comes with TurboGears but even hand written unit tests are no big deal in Python - just use asserts and other invariant checks and tests etc liberally.... Alan G. From bhaaluu at gmail.com Fri Feb 8 01:52:00 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 7 Feb 2008 19:52:00 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> Message-ID: On Feb 7, 2008 6:47 PM, Alan Gauld wrote: > > "Alan Gauld" wrote > > >> What is the equivalent of JUnit in Python? > > > > I think the nearest equivalent is > > > > Oops, I was going top say PyUnit then remembered the name > had changed but forgot to check out the latest incarnation. > Fortyunately others have done the work for me. > > Personally I like the Nose framework that comes with > TurboGears but even hand written unit tests are no big > deal in Python - just use asserts and other invariant > checks and tests etc liberally.... > > > Alan G. PyUnit: It really doesn't seem to be an "absolute beginner" technique. The noun/verb/adjective technique seems to be geared more towards beginners. I like the idea of that technique. Perhaps the "unit test" approach is more for "Intermediate" learners, or learners who already have a background in OOP of some form or another (like Java). I'm just starting out, so I'm looking at everything that is thrown at me, but quite frankly, it is really easy for me to see something that is over my head at this point. If it's over my head, I'll just stall, like I have in the past, and then I'll have to start this thread over again later. 8^D I guess you can tell it's been a long day for me. I've done some reading, some coding, some experimenting... all in a day's play for a Hobbyist Programmer. 8^D I'll take another look at PyUnit tomorrow morning when I'm fresh. One thing I'm encouraged by: in Alan's tutorial, he says that I don't have to "see the light" to use POOP. But if I can learn some basic "design POOP" techniques from all this, then I'll be happy. After all, I'm a beginner... you can't get any more basic than that! Happy Happy Joy Joy. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From keridee at jayco.net Fri Feb 8 02:11:36 2008 From: keridee at jayco.net (Tiger12506) Date: Thu, 7 Feb 2008 20:11:36 -0500 Subject: [Tutor] Pixelize ubuntu python script acting odd. References: Message-ID: <007c01c869ef$b3da5670$e3fce004@jslaptop> Some suggestions throughout > def runThrough(): > walk = os.walk("/media/sda1/Documents/Pictures/2007") #location of the > pics I want to use > count = 0 > for root, dirs, files in walk: > try: > for x in files: > if x.lower().find(".jpg")> -1: #If it's a .jpg... This could be if x.lower().endswith(".jpg"): > count = count + 1 > operation = 'make_db ' + root + '/' + x This could be also operation = "make_db %s/%s" % (root,x) > os.system(operation) # Call the command line with the > operation above > print root + '/' + x #This is optional, I did this for > debugging print "%s/%s" % (root,x) > print str(count) + " files done" print "%s files done" % count > except OSError: > print root + "/" + x + " was not included in the list" > #This was run to get rid of all the obnoxious spaces in the file > names > #try: > # for x in files: > # loc = root + '/' + x > # pic = loc.replace(' ', "_") > # os.rename(loc, pic) > # count = count + 1 > # print str(count) + "files done" > #except OSError: > # print root + '/' + x + " was not included" I don't know much about ubuntu, so I can't answer the question. Also you might consider os.path.join And since you are doing this root+'/'+x so many times, perhaps you should just assign it to a variable once and use it instead? Say~ fullpath = root+'/'+x From keridee at jayco.net Fri Feb 8 02:42:17 2008 From: keridee at jayco.net (Tiger12506) Date: Thu, 7 Feb 2008 20:42:17 -0500 Subject: [Tutor] Anyone fancy giving me some tips and an expert opinion?? References: Message-ID: <009201c869f4$0a465fa0$e3fce004@jslaptop> I'll throw in a couple of ideas, but I won't pretend to be an expert. ;-) >I have written what i see as a pretty decent script to resolve this > question: > > Write an improved version of the Chaos program from Chapter 1 that allows > a > user to input two initial > values and the number of iterations and then prints a nicely formatted > table > showing how the values > change over time. For example, if the starting values were .25 and .26 > with > 10 iterations, the table > might look like this: > index 0.25 0.26 > ---------------------------- > 1 0.731250 0.750360 > 2 0.766441 0.730547 > 3 0.698135 0.767707 > 4 0.821896 0.695499 > 5 0.570894 0.825942 > 6 0.955399 0.560671 > 7 0.166187 0.960644 > 8 0.540418 0.147447 > 9 0.968629 0.490255 > 10 0.118509 0.974630 > > Although it works I am sure I could have gone about this a better way, it > probably doesn't fit all the rules of best practice either. Was wondering > if > anyone would mind having a look and offering a few tips?? > > # chaos.py > # A program to mimic the chaos theory > > def main(): > > print "Example of Chaos" > > # User inputs numbers to compare, z is for the index counter > x = input("Enter a number between 1 and 0: ") > y = input("Enter a second number between 1 and 0: ") Generally, additional checks are made to make sure that the values actually are within the proper range, but I wouldn't think that would be necessary in such a specific script. > z = 0 > > # Prints the table borders and titles > print '%10s %20s %20s' % ("Index", x, y) > print "----------------------------------------------------------" Can be print "-" * 58 > tempx = x > tempy = y You never use x and y again. Why are you changing variables to tempx and tempy? > > # Loops calculates 'chaotic behaviour for input numbers > for i in range(10): > tempx = 3.9 * tempx * (1 - tempx) > tempy = 3.9 * tempy * (1 - tempy) > z = z + 1 > # Print chaotice results into table > print '%10s %20s %20s' % (z, tempx, tempy) > > raw_input("Press any key to exit") > > main() This is really so short of a script, I wouldn't change the design, but some general tips to think about follow... My biggest worry is whether or not you will change how you print your results in a larger piece of code. For example. If you notice, when you print out your columns, you have "%10s %20s %20s" in two different places. What if you wanted to change the code so that the first column was padded to fifteen characters instead of just 10? You would have to change it in all of those places and if you missed one~ bam! Bug. The easy way to fix that is to assign the pattern to a variable and then you only have to change it once. pat = "%10s %20s %20s" print pat % (z,x,y) Will still work. ;-) The only other issue I have with this is the issue of the Z counter. In your loop you allow i to be a counter from 0 to 9. Why don't you take advantage of that? Get rid of the z variable entirely and just use 'i'. A nice script though. Keep going. From kent37 at tds.net Fri Feb 8 03:15:50 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 07 Feb 2008 21:15:50 -0500 Subject: [Tutor] Anyone fancy giving me some tips and an expert opinion?? In-Reply-To: References: Message-ID: <47ABBB56.2060404@tds.net> Damian Archer wrote: > # User inputs numbers to compare, z is for the index counter > x = input("Enter a number between 1 and 0: ") > y = input("Enter a second number between 1 and 0: ") We generally discourage the use of input(), it is (arguably) a security hole - http://www.wellho.net/mouth/956_Python-security-trouble-with-input.html and a rather contentious discussion on this very list - http://mail.python.org/pipermail/tutor/2007-August/056328.html - and it doesn't validate the input. A better way to write this would be x = float(raw_input("Enter a number between 1 and 0: ")) y = float(raw_input("Enter a second number between 1 and 0: ")) which is safer and guarantees that x and y are floating point numbers. Kent From keridee at jayco.net Fri Feb 8 03:40:42 2008 From: keridee at jayco.net (Tiger12506) Date: Thu, 7 Feb 2008 21:40:42 -0500 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net> Message-ID: <012101c869fc$25ef1640$e3fce004@jslaptop> There's a couple of errors in here that no one has addressed yet because the question was geared towards programming style... So now I will address them. Or undress them, I suppose. ;-) > #!/user/bin/python > """ >>From the testing laboratory of: > b h a a l u u at g m a i l dot c o m > 2008-02-07 > """ > > import time > > CS = "\n"*50 This is okay, but it is a little more intuitive to make this def clrscr(): print "\n"*50 so that you can say clrscr() because clearing the screen is an action, not a thing that you would normally think of printing. The point of python is to make programming easier for humans. You defeat it's greatest power by not using it in a style that takes advantage of it's ability to mimic the real world. actions usually indicate functions. (This is definitely a style thing. I'm not trying to start an argument) > class TestClass1(object): > """ please give me a better name""" > def __init__(self): > """please document me""" > self.name = "" > self.answer = "" > self.strength = 20 > self.wealth = 45 > self.light = 0 > self.tally = 0 As mentioned before, data in class should be related to one real (or abstract) object, not just a container for random data. > def main(): > tc1 = TestClass1() # instance > tc1.__init__() # invoke method > print CS > N1 = tc1.name > N1 = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") This is pointless. When you assign the value of tc1.name (which is "") you immediately overwrite it when you say N1 = raw_input(...) What you are trying to accomplish without grokking assignment is this. tc1.name = raw_input("What is your name, explorer?") > # main game loop > while True: > print CS > print (" %s, YOUR STRENGTH IS %d") % (N1, tc1.strength) Earlier you set N1, but not tc1.name. Either use one or the other. > print (" YOU HAVE $%d") % tc1.wealth > if tc1.light == 0: Can be if tc1.light: print("The light's on, but no one's home") else: print("It is too dark to see anything") > print (" IT IS TOO DARK TO SEE ANYTHING") > else: > print (" THE LIGHT'S ON, BUT NO ONE'S HOME") > print > print > A = tc1.answer Again, the same problem with tc1.name. Why are you bothering with A? Please realize that you can assign directly tc1.answer = raw_input(...) and just use the one variable. This is not C, but Python. > A = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") # main game > prompt > if A.upper() == "Q": > break > if A.upper() == "L": > light = raw_input(" LIGHT? [0|1]: ") # turn the light on and > off > if light == 0 and tc1.light == 0: What?!? What is the deal? Do you have two different lights? No... then using two different light variables does not make sense. Also, the variable 'light' will never be == 0 unless you hit enter without entering anything because raw_input returns a string. "0" != 0 > print (" THE LIGHT IS OFF") I see. You have two seperate variables so that you can determine whether the light was off previously. In which case, I suggest you change the variable to a more intuitive name, such as 'chosen' or something. To test whether the light was on before or not, you should have a method of the class islighton() because you are performing an action. Checking to see whether the light is on. If this doesn't make sense to you, consider that often attributes of a class are not directly accessed. There are even special things called properties that define get and set methods of classes... Um, disregard that. Too much info. :-) > time.sleep(2) > if tc1.wealth <= 0: You have put this wealth check after the changing of the light. So it is possible that someone can change the light after they already have no money. > print > print (" YOU HAVE NO MONEY") > time.sleep(2) > else: > tc1.light = int(light) Good. You just didn't think of int() in the if check. btw, you aren't going to tell anyone when they turn the light on? > tc1.wealth -= 15 > else: > print (" INVALID CHOICE") > time.sleep(2) > tc1.tally += 1 > tc1.strength -= 5 > if tc1.strength <= 0: > print (" YOU DIED....") > time.sleep(2) > break > print > print (" Final Score:") > print (" Tally: %d") % tc1.tally > print (" Wealth: $%d") % tc1.wealth > print (" Strength: %d") % tc1.strength > > if __name__ == "__main__": > main() From rdm at rcblue.com Fri Feb 8 08:14:47 2008 From: rdm at rcblue.com (Dick Moores) Date: Thu, 07 Feb 2008 23:14:47 -0800 Subject: [Tutor] Cobra Message-ID: <20080208074156.346881E400B@bag.python.org> Peter Dilley posted these links on the python-list a few hours ago. Cobra looks VERY interesting to me. Comparison to Python: http://cobra-language.com/docs/python/ Main Page: http://cobra-language.com/ Article that first caught my eye regarding Cobra: http://www.computerworld.com.au/index.php/id;342684174;fp;16;fpid;1 Dick Moores From alan.gauld at btinternet.com Fri Feb 8 11:13:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Feb 2008 10:13:22 -0000 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> Message-ID: "bhaaluu" wrote > PyUnit: > It really doesn't seem to be an "absolute beginner" technique. Unit tests and TDD is not a design technique per se. It is definitely not a technique for designing OOP programs its a programming technique that makes code more reliable (whether OOP or not). Where it does help in design is by focussing attention on how a class (or function) should behave from the consumers perspective. This is always a good thing. But TDD in itself will not help you identify classes or their interactions. It will help you build classes that are user friendly and work as expected. > The noun/verb/adjective technique seems to be geared > more towards beginners. I like the idea of that technique. It is completely intended for beginners. It is, in practice, a little too naive for production type use but it is a good starting point when you don't know where to go and don;t have lots of experience in the problem domain. What nouns/verbs does is identify candidate classes and operations. It says nothing about how those operations are to be coded or used. Once you know what classes you want to write TDD can help you build them better, but you have to identify them first! > One thing I'm encouraged by: in Alan's tutorial, he > says that I don't have to "see the light" to use POOP. Absolutely, you have been using string objects and file objects already. You can use classes to bundle data and methods together and use them in an object based approach without fully understanding OOP. But OOP does open up new avenues and possibilities and, particularly in larger programs, offers significant savings in effort and reuse. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Feb 8 13:00:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Feb 2008 07:00:36 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> <47AB72F6.6020201@tds.net> Message-ID: <47AC4464.3010809@tds.net> Alan Gauld wrote: > Unit tests and TDD is not a design technique per se. > It is definitely not a technique for designing OOP programs > its a programming technique that makes code more reliable > (whether OOP or not). > > Where it does help in design is by focussing attention > on how a class (or function) should behave from the consumers > perspective. I agree that TDD is not a design technique, but it does strongly influence design by introducing testability as a design requirement. TDD strongly encourages loose coupling and reusability. - loose coupling because classes and functions that depend on many other classes/functions/modules are harder to test - reusability because of the loose coupling and because any code that has unit tests already has two clients - the production code and the tests. I like to say, no code is reusable until it has been reused. Although a bit of an overstatement, there is a lot of truth in it. It is very hard to anticipate how a bit of code might be reused without actual reuse. TDD provides an artificial second use which promotes reusability. TDD also promotes incremental development where the design evolves to meet current requirements. This is sometimes called Test-Driven Design: http://www.agiledata.org/essays/tdd.html http://www.salientblue.com/blog/?p=10 So TD development can be part of a process that includes design. Kent From clajo04 at mac.com Fri Feb 8 17:09:22 2008 From: clajo04 at mac.com (John Clark) Date: Fri, 8 Feb 2008 11:09:22 -0500 Subject: [Tutor] NYC Python Users Meetup February Meeting Announcement.... Message-ID: <002b01c86a6c$fdc27150$f94753f0$@com> Please pardon the PSA: The New York City Python Users Meetup Group is planning on having our February meeting on February 12th, from 6:30pm - 8:00pm. For more information, please see: http://python.meetup.com/172/calendar/7082384/ Anyone in the NYC area interested in using Python, learning more about Python, or teaching others about Python is welcome to attend. Thanks, -jdc From bhaaluu at gmail.com Fri Feb 8 20:54:45 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 8 Feb 2008 14:54:45 -0500 Subject: [Tutor] designing POOP In-Reply-To: <012101c869fc$25ef1640$e3fce004@jslaptop> References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> Message-ID: On Feb 7, 2008 9:40 PM, Tiger12506 wrote: > There's a couple of errors in here that no one has addressed yet because the > question was geared towards programming style... So now I will address them. > Or undress them, I suppose. ;-) I didn't make much progress until I started thinking about the Explorer and Light classes as actual objects. I've tried to address what you undressed. 8^D Here is another version to undress: #!/user/bin/python import time class Explorer(object): """player""" def __init__(self,name): """initilaization method""" self.__name = name self.strength = 20 self.wealth = 60 def get_name(self): return self.__name class Light(object): """light switch""" def __init__(self,light): self.light = light def state(self): if self.light == 0: print (" IT IS TOO DARK TO SEE ANYTHING") else: print (" THE LIGHTS ARE ON, BUT NO ONE'S HOME") def cs(): print "\n"*50 def main(): tally = 0 switch = Light(0) #instance cs() # clear screen name = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") explr = Explorer(name) while True: cs() # clear screen print (" %s, YOUR STRENGTH IS %d" % (explr.get_name(), explr.strength)) print (" YOU HAVE $%d" % explr.wealth) switch.state() print print answer = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") if answer.upper() == "Q": break if answer.upper() == "L": if switch.light == 1: switch.light = 0 else: switch.light = 1 explr.strength -= 5 explr.wealth -= 15 if explr.wealth <= 0: print print (" YOU HAVE NO MONEY") time.sleep(1) if explr.strength <= 0: print print (" YOU DIED...") time.sleep(1) break else: print (" INVALID CHOICE") tally += 1 print print (" FINAL SCORE:") print (" TALLY: %d" % tally) print (" STRENGTH: %d" % explr.strength) print (" WEALTH: $%d" % explr.wealth) if __name__ == "__main__": main() Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Fri Feb 8 21:24:46 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Feb 2008 15:24:46 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> Message-ID: <47ACBA8E.1020902@tds.net> bhaaluu wrote: > class Explorer(object): > """player""" > def __init__(self,name): > """initilaization method""" > self.__name = name > self.strength = 20 > self.wealth = 60 > > def get_name(self): > return self.__name There is no need for get_name(). Just refer to explr.name, the same as for strength and wealth. > class Light(object): > """light switch""" > > def __init__(self,light): > self.light = light > > def state(self): > if self.light == 0: > print (" IT IS TOO DARK TO SEE ANYTHING") > else: > print (" THE LIGHTS ARE ON, BUT NO ONE'S HOME") show_state() or print_state() might be a better name. If you call this method __str__() and just return the string instead of printing it, it will be called when you print switch > def cs(): > print "\n"*50 > > def main(): > tally = 0 > switch = Light(0) #instance > cs() # clear screen > name = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") > explr = Explorer(name) > while True: > cs() # clear screen > print (" %s, YOUR STRENGTH IS %d" % (explr.get_name(), explr.strength)) > print (" YOU HAVE $%d" % explr.wealth) This could be Explorer.__str__(): def __str__(self): return " %s, YOUR STRENGTH IS %d\n YOU HAVE $%d" % (self.get_name(), self.strength, self.wealth) Then the prints become just print explr > switch.state() > print > print > answer = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") > if answer.upper() == "Q": > break > if answer.upper() == "L": > if switch.light == 1: > switch.light = 0 > else: > switch.light = 1 > explr.strength -= 5 > explr.wealth -= 15 > if explr.wealth <= 0: > print > print (" YOU HAVE NO MONEY") > time.sleep(1) > if explr.strength <= 0: > print > print (" YOU DIED...") > time.sleep(1) > break This could be two Explorer methods: def change_wealth(self, incr): self.wealth += incr if self.wealth <= 0: print print (" YOU HAVE NO MONEY") time.sleep(1) Then call explr.change_wealth(-15) Strength is a little trickier because you need to break out of the loop. You could have def change_strength(self, incr): self.strength += incr if self.strength <= 0: print print (" YOU DIED...") time.sleep(1) self.alive = False Then in Explorer.__init__() set self.alive = True and change the loop from while True: to while explr.alive: This would give you an Explorer class that actually does something useful. Kent > else: > print (" INVALID CHOICE") > tally += 1 > print > print (" FINAL SCORE:") > print (" TALLY: %d" % tally) > print (" STRENGTH: %d" % explr.strength) > print (" WEALTH: $%d" % explr.wealth) > > if __name__ == "__main__": > main() > > Happy Programming! From stuart.the.viking at gmail.com Fri Feb 8 21:55:00 2008 From: stuart.the.viking at gmail.com (Stuart van Zee) Date: Fri, 8 Feb 2008 15:55:00 -0500 Subject: [Tutor] HTTPS file upload Message-ID: <4c95d6f70802081255y43ae80ebl387e92077050ccc@mail.gmail.com> I have a requirement to automate uploading files using https. The https server doesn't give a form or anything they just gave me a URL and said to "push" the files to the URL using HTTPS. Does anyone here have an idea how to do this. I have done some Python programming but nothing like this, and there is a fairly short turn around required on this one. I have done some searching on www and have found a few things that seem like they do something simular, but nothing that looked like the right answer to this. Thanks for any suggestions and/or advice that you can give. s From bhaaluu at gmail.com Fri Feb 8 22:25:27 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 8 Feb 2008 16:25:27 -0500 Subject: [Tutor] designing POOP In-Reply-To: <47ACBA8E.1020902@tds.net> References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> <47ACBA8E.1020902@tds.net> Message-ID: On Feb 8, 2008 3:24 PM, Kent Johnson wrote: > .... > and change the loop from > while True: > to > while explr.alive: > > This would give you an Explorer class that actually does something useful. > > Kent > It also cleaned up main(), and put everything in well defined packages at the top of the program. I can see do difference in "game play". 8^D Here are your changes implemented, and working on my Linux system: #!/user/bin/python import time class Explorer(object): """player""" def __init__(self,name): """initilaization method""" self.name = name self.strength = 20 self.wealth = 60 self.alive = True def __str__(self): return " %s, YOUR STRENGTH IS %d\n YOU HAVE $%d" % (self.name, self.strength, self.wealth) def change_wealth(self, incr): self.wealth += incr if self.wealth <= 0: print print (" YOU HAVE NO MONEY") time.sleep(1) def change_strength(self, incr): self.strength += incr if self.strength <= 0: print ("\n\n YOU DIED...") time.sleep(1) self.alive = False class Light(object): """light switch""" def __init__(self,light): self.light = light def __str__(self): if self.light == 0: return " IT IS TOO DARK TO SEE ANYTHING" else: return " THE LIGHTS ARE ON, BUT NO ONE'S HOME" def cs(): print "\n"*50 def main(): tally = 0 switch = Light(0) #instance cs() # clear screen name = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") explr = Explorer(name) while explr.alive: cs() # clear screen print explr print switch print print answer = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") if answer.upper() == "Q": break if answer.upper() == "L": if switch.light == 1: switch.light = 0 else: switch.light = 1 explr.change_wealth(-15) explr.change_strength(-5) else: print (" INVALID CHOICE") tally += 1 print print (" FINAL SCORE:") print (" TALLY: %d" % tally) print (" STRENGTH: %d" % explr.strength) print (" WEALTH: $%d" % explr.wealth) if __name__ == "__main__": main() Thanks Kent! I like these small incremental changes with explanations. I especially like the way you took blocks of code from main() and made methods out of them. The actual code itself, hardly changed! Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Fri Feb 8 22:46:33 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Feb 2008 16:46:33 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> <47ACBA8E.1020902@tds.net> Message-ID: <47ACCDB9.7000200@tds.net> bhaaluu wrote: > It also cleaned up main(), and put everything in well defined packages > at the top of the program. Yes, good OOD puts things into cohesive, comprehensible packages. > I can see do difference in "game play". 8^D And that's a good thing, right? "Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure." -- Martin Fowler in Refactoring The refactoring you just did is called Extract Method: http://www.refactoring.com/catalog/extractMethod.html Kent From bhaaluu at gmail.com Fri Feb 8 23:27:59 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 8 Feb 2008 17:27:59 -0500 Subject: [Tutor] designing POOP In-Reply-To: <47ACCDB9.7000200@tds.net> References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> <47ACBA8E.1020902@tds.net> <47ACCDB9.7000200@tds.net> Message-ID: On Feb 8, 2008 4:46 PM, Kent Johnson wrote: > bhaaluu wrote: > > > It also cleaned up main(), and put everything in well defined packages > > at the top of the program. > > Yes, good OOD puts things into cohesive, comprehensible packages. > > > I can see do difference in "game play". 8^D > > And that's a good thing, right? > > "Refactoring is the process of changing a software system in such a way > that it does not alter the external behavior of the code yet improves > its internal structure." -- Martin Fowler in Refactoring > > The refactoring you just did is called Extract Method: > http://www.refactoring.com/catalog/extractMethod.html > > Kent > This is something that one can only gain from experience? I really had to struggle to get the Light class to work at all. I have no idea how many times I started over. But I do feel that I am starting to learn some of this stuff. As "simple" as the adventure game is, I can see that it will provide lots of practice for me to design and code it in Python OOP. Thanks Kent! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From nomb85 at comcast.net Fri Feb 8 23:35:26 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Fri, 08 Feb 2008 17:35:26 -0500 Subject: [Tutor] Is it possible? Message-ID: <1202510126.11926.2.camel@localhost.localdomain> Is it possible to write a program that you pipe other programs through and it measures the MBs per second of data moved? Like I could pipe it a cp and find out how fast the cp is working? Thanks, Nate From keridee at jayco.net Fri Feb 8 23:49:08 2008 From: keridee at jayco.net (Tiger12506) Date: Fri, 8 Feb 2008 17:49:08 -0500 Subject: [Tutor] Cobra References: <20080208074156.346881E400B@bag.python.org> Message-ID: <002901c86aa4$fc36a6c0$c7fce004@jslaptop> It's dangerous posting something like this on a python website. ;-) It has definite strengths over python, it seems, and some things I do not like. Particularly interesting is the compilation directly to exe. Damn. I'm am seriously impressed with that. Cobra appears too new to learn and switch to yet but, I think that will/would be the deciding factor for me when it grows a little older. I dislike the method for string interpolation, but I presume that's because I'm used to python and c... I would have to search through the docs of cobra, but my glance did not show me that it has the flexibility of python... The discussion of accuracy is meerly a preference. I personally would like my program to not virtualize every math operation i tell it to do. Sure, accuracy is useful in situations of finance or theoretical mechanics, but someone very wise once told me that significant digits mean more than abtract, unattainable accuracy. (Danny I think) Python's default to use integer arithmetic is supposed to be changed in the new release of 3.0. Also, I wish to mention that my first impression of cobra is that somebody didn't like python and customized it slightly. rip-off, in other words. But the exe compilation directly, using C#... That is different. Powerful. I like it. It has a definite future. > Peter Dilley posted these links on the python-list a few hours ago. > Cobra looks VERY interesting to me. > > Comparison to Python: > http://cobra-language.com/docs/python/ > > Main Page: > http://cobra-language.com/ > > Article that first caught my eye regarding Cobra: > http://www.computerworld.com.au/index.php/id;342684174;fp;16;fpid;1 > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Feb 8 23:51:15 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Feb 2008 17:51:15 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> <47ACBA8E.1020902@tds.net> <47ACCDB9.7000200@tds.net> Message-ID: <47ACDCE3.9090900@tds.net> bhaaluu wrote: > On Feb 8, 2008 4:46 PM, Kent Johnson wrote: >> "Refactoring is the process of changing a software system in such a way >> that it does not alter the external behavior of the code yet improves >> its internal structure." -- Martin Fowler in Refactoring > This is something that one can only gain from experience? Experience and study. I don't think there is much substitute for experience to see *why* OOP and refactoring and clean design are useful. There is nothing like growing a program to the point where you don't know how it works or how to change it to make you appreciate good design :-) Studying gives you good examples to follow and new techniques to try. Kent From kent37 at tds.net Sat Feb 9 00:17:19 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 08 Feb 2008 18:17:19 -0500 Subject: [Tutor] Cobra In-Reply-To: <002901c86aa4$fc36a6c0$c7fce004@jslaptop> References: <20080208074156.346881E400B@bag.python.org> <002901c86aa4$fc36a6c0$c7fce004@jslaptop> Message-ID: <47ACE2FF.4080701@tds.net> Tiger12506 wrote: > It's dangerous posting something like this on a python website. ;-) It is a bit off-topic, especially for this list. c.l.python is a little better but one of the general language forums would be more appropriate. > Particularly interesting is the compilation directly to exe. You might be interested in Boo, which is a language for .NET that is inspired by Python. It seems fairly mature and it can compile to .exe: http://boo.codehaus.org/ http://docs.codehaus.org/display/BOO/How+To+Compile Kent From keridee at jayco.net Sat Feb 9 00:20:00 2008 From: keridee at jayco.net (Tiger12506) Date: Fri, 8 Feb 2008 18:20:00 -0500 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop><47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net> Message-ID: <005001c86aa9$48bd1e30$c7fce004@jslaptop> > This is something that one can only gain from experience? > I really had to struggle to get the Light class to work at all. > I have no idea how many times I started over. But I do feel > that I am starting to learn some of this stuff. This surprises me... I guess it does take experience. What is the most basic thing you can describe about a light? Immediately I answer, "You can turn it on or off". This suggests methods, turn_on(), turn_off(), and something to maintain the state of the light attribute - i.e. whether it is currently on or not. I suggest practice practice practice. You should be able to look at anything in your house and be able to design a basic class for it. Some that come to mind as I look around the room. I've often thought of redesigning my entire house in OOP. ;-) (Granted - these examples aren't entirely useful, but they provide examples of practice with methods and attributes.) class Pen: def __init__(self): self.level = 50 self.on = False def click(self): self.on = (not self.on) def isempty(self): return (self.level > 0) def write(self): if self.isempty: return False if not self.on: return False self.level = self.level - 5 return True class Knob: def __init__(self, locked=False): self.locked = locked def turn(self): if self.locked: return False return True class Door: def __init__(self): self.knob = Knob() def lock(self): self.knob.locked = True def unlock(self): self.knob.locked = False def open(self): return self.knob.turn() Are some simple examples off the top of my head. It's not difficult to model real-life things with classes, but it is much more difficult to model them in such a way that you interact with them normally. (i.e. do you lock the door, or the knob? Does the knob contain a Lock, or does the developer only need to know that it has one and whether it is locked or not?) From keridee at jayco.net Sat Feb 9 00:33:06 2008 From: keridee at jayco.net (Tiger12506) Date: Fri, 8 Feb 2008 18:33:06 -0500 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> <47ACBA8E.1020902@tds.net> <47ACCDB9.7000200@tds.net> <47ACDCE3.9090900@tds.net> Message-ID: <006301c86aab$24f49620$c7fce004@jslaptop> > There is nothing like growing a program to the point where you don't > know how it works or how to change it to make you appreciate good design Amen. I was recently fighting with an example of a multi-client, simple server that I wanted to translate into assembly. Not only was the code unreadable, but they had tried to apply a functional programming technique that failed miserably. Final result: Less # of lines, better readability, and slightly more algorithm efficient. Even with that change of language to something horrendously verbose. Key idea: Choose a design wisely. Understand that if a design does not enhance readability or code reusability, it's a bad design. From alan.gauld at btinternet.com Sat Feb 9 00:41:15 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Feb 2008 23:41:15 -0000 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net> <012101c869fc$25ef1640$e3fce004@jslaptop> Message-ID: "bhaaluu" wrote There have been lots of comments about this already but I'm deliberately jumping in at this level because I want to pick up a few general points... > class Explorer(object): > """player""" > def __init__(self,name): > """initilaization method""" > self.__name = name > self.strength = 20 > self.wealth = 60 > > def get_name(self): > return self.__name Kent already pointed out this is not needed. But as a general rule consider what I said earlier about objects being based on behaviour. And that the data should be there to support the behaviour. So in this case ask: Why do I have a name, strength and wealth? What behaviour do these support? Behaviour is expressed as methods so I am expecting to see methods sof Explorer that use the attributes, otherwise the Explorer is just a data container like a list or dictionary. > class Light(object): > """light switch""" > > def __init__(self,light): > self.light = light > > def state(self): > if self.light == 0: > print (" IT IS TOO DARK TO SEE ANYTHING") > else: > print (" THE LIGHTS ARE ON, BUT NO ONE'S HOME") You have a method here that reports the state but doesn't a light switch usually do something? Like turn the light on or off? Usually by a toggle operation? So maybe a toggle method would be good: def toggle(self): self.light == not self.light # make it a boolean Also remembering the principle that UI and logic should be separated it might be good to pull the printing out of the class and just let the method returmn the string. And as Kent already suggested for Explorer that could be done with an __str__ method so all you need do in the consumer is: print switch > def cs(): > print "\n"*50 > > def main(): > tally = 0 > switch = Light(0) #instance > cs() # clear screen > name = raw_input(" WHAT IS YOUR NAME, EXPLORER? ") > explr = Explorer(name) > while True: > cs() # clear screen > print (" %s, YOUR STRENGTH IS %d" % (explr.get_name(), > explr.strength)) > print (" YOU HAVE $%d" % explr.wealth) Kent has addressed this specifically but as a general rule remember the consumer should not have to get at the data attributes of an object. You should only need to send messages to the Explorer, in this case it's a status report - which we already said can be done via a __str__ method. > switch.state() > print > print > answer = raw_input(" WHAT DO YOU WANT TO DO? [Q|L]: ") > if answer.upper() == "Q": > break > if answer.upper() == "L": > if switch.light == 1: > switch.light = 0 > else: > switch.light = 1 And here is the toggle method, except its in your program rather than in the object. Let the object do it to itself, do not try to mess with the data directly if answer.upper() == "L": switch.toggle() > explr.strength -= 5 > explr.wealth -= 15 Now I'm not quite sure why you decrease these but again the Explorer should be doing it to himself - objects do it to themselves. If the Explorer always loses strengty and wealth after a turn then the method could be called newTurn() or somesuch. But I suspect there might be a more meaningful name we could use. > if explr.wealth <= 0: > print > print (" YOU HAVE NO MONEY") > time.sleep(1) > if explr.strength <= 0: > print > print (" YOU DIED...") > time.sleep(1) > break And all of this could be built into the explorer method above, maybe implemented as an exception? def newTiurn(self): self.wealth -= 15 self.strength -= 5 if self.wealth <= 0: raise ExplorerBroke if self.strength <= 0 raise ExplorerDied You control code then looks something like: if answer.upper() == "L": switch.toggle() try: explr.newTurn() except ExplorerBroke e: print e.message except ExplorerDied e: print e.message Or with a bit more intelligence in the __str__ method if answer.upper() == "L": switch.toggle() try: explr.newTurn() except ExplorerBroke,ExplorerDied: print explr Really the outside control code should be focused around the user interaction and senmding messages to the objects. It should not be pulling out data from inside the objects to do anything with it, that is the job of the objects. Occasionally we can break that rule if its just for printing or maybe to assign directly to another value. For example you could directly access switch.light if you needed to pass that into a method of explorer explr.reactToLight(switch.light) But even there its better to pass the switch to the explorer and let him test the switch state inside the method. 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 Feb 9 00:44:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Feb 2008 23:44:01 -0000 Subject: [Tutor] Cobra References: <20080208074156.346881E400B@bag.python.org> <002901c86aa4$fc36a6c0$c7fce004@jslaptop> Message-ID: "Tiger12506" wrote > It has definite strengths over python, it seems, and some things I > do not > like. My feelings too. My main gripes being that it is based on .NET/Mono and that it only supports OO, no procedural or Functional code. But it has enough positive features that it is definitely one to watch. -- 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 Feb 9 00:50:21 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 8 Feb 2008 23:50:21 -0000 Subject: [Tutor] Is it possible? References: <1202510126.11926.2.camel@localhost.localdomain> Message-ID: "Nathan McBride" wrote > Is it possible to write a program that you pipe other programs > through > and it measures the MBs per second of data moved? Like I could pipe > it > a cp and find out how fast the cp is working? Not in any kind of general sense. Even for cp its not clear what it would report. On some OS cp is often not actually moving any data but just readjusting file pointers within the directory structure. And thats even more true for mv. So would you count the size of the pointers changed or the size of the file being referenced? And what about a mv thats really a rename? And what about ls? It doesn't move any data but you might count the characters in the listing? Or the number of files? Or even the total sizes of the files listed? It would be very difficult to write a general purpose program that could cater for all of those. However you could do one for each specific case... Although in most cases there are already standard Unix tools that will do the job. Alan G. From trs5678 at hotmail.com Sat Feb 9 04:07:17 2008 From: trs5678 at hotmail.com (Timothy Sikes) Date: Fri, 8 Feb 2008 21:07:17 -0600 Subject: [Tutor] Adding network play to an open source game. Message-ID: Hi. First of all, I'm not an amazing programmer. But, I do have large goals, somtimes too large. There is an open source game, konquer, (it's on the ubuntu repos.) that I would like to extend with python to include a network based game. But, I only know how to do simple sockets.... Is this too big a project for first year programmer? (I've been programing for 3, but have taken classes only one year.)The program is like a board game. You move your fleets to different planets, one at a time. The game is written in C++(I think). Just as a preliminary thing, I will go through how I think it will work. One computer in the network will be designated as the 'server' that everyone will send information to. Each turn, four pieces of data will have to be sent to the 'server' that I can think of right now.: 1. how many fleets have left 2. from what planet 3. going to which planet 4.taking how long to get there. From there, the server will then issue those to each player, and tell which player is next, and wait for his reply. I don't really know how to start, so I guess I will start here. I appreciate your reply. _________________________________________________________________ Need to know the score, the latest news, or you need your Hotmail?-get your "fix". http://www.msnmobilefix.com/Default.aspx From keridee at jayco.net Sat Feb 9 04:26:12 2008 From: keridee at jayco.net (Tiger12506) Date: Fri, 8 Feb 2008 22:26:12 -0500 Subject: [Tutor] Adding network play to an open source game. References: Message-ID: <000601c86acb$89121c70$2afce004@jslaptop> I wish to warn you that I've never done anything like this before, but I have a couple of thoughts here. First thought is, network games tend to be slow because sending state information to everyone with enough frames per second to make it decent game play is a lot of information to send... So the least information you have to send the better. Fortunately, now that I read a little more closely... A board game is not going to be bad about this... Second thought is... start with simple sockets, work with the server model and the clients, do not mess with the game at first. Get dummy data to behave properly first before you ever try anything with the game itself. Third thought. C++ is a different language from python. This will further intensify your trouble. In fact, depending on your knowledge of C++, this could greatly intensify your trouble. You could have step two there going just perfectly, but getting python and C++ to talk could throw you in loops. I would say that generally for a programmer of a year, this seems like a very significant goal. Not only do you have to understand quite precisely what the C++ program is doing, (difficult especially in a game, IMO), but you have sockets to deal with, client, server, and just as difficult, C++/Python interaction. Also, given that you didn't write konquer~ someone else's code is harder to read than your own. Trust me. My suggestion is, if you are going to tackle this, very definitely take it in very defined steps. Work on sockets here, then C++/Python here, etc. I don't wish to discourage you, but I wouldn't try this yet. (Of course, I've never taken classes...) ;-) > Hi. First of all, I'm not an amazing programmer. But, I do have large > goals, somtimes too large. There is an open source game, konquer, (it's > on the ubuntu repos.) that I would like to extend with python to include a > network based game. But, I only know how to do simple sockets.... Is > this too big a project for first year programmer? (I've been programing > for 3, but have taken classes only one year.)The program is like a board > game. You move your fleets to different planets, one at a time. The game > is written in C++(I think). > > Just as a preliminary thing, I will go through how I think it will work. > One computer in the network will be designated as the 'server' that > everyone will send information to. Each turn, four pieces of data will > have to be sent to the 'server' that I can think of right now.: 1. how > many fleets have left 2. from what planet 3. going to which planet > 4.taking how long to get there. From there, the server will then issue > those to each player, and tell which player is next, and wait for his > reply. > > I don't really know how to start, so I guess I will start here. > > I appreciate your reply. > _________________________________________________________________ > Need to know the score, the latest news, or you need your Hotmail?-get > your "fix". > http://www.msnmobilefix.com/Default.aspx > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From trs5678 at hotmail.com Sat Feb 9 05:21:00 2008 From: trs5678 at hotmail.com (Timothy Sikes) Date: Fri, 8 Feb 2008 22:21:00 -0600 Subject: [Tutor] Adding network play to an open source game. Message-ID: Thanks for your advice. You're probably right, I do need to figure out sockets first... But it's a goal to work towards... I don't know if I would keep up computer programming if I didn't have a specific goal. A few things: I have the author's email of konquer (it was in the source). I don't think he's actively developing it, but once I get to a nice start, I could try a nice email to him about it. You're also right, I don't know C++, but would like to learn it. Anyone have any advice on good tutorials/books/examples of python network programming? I saw a cherryChat program that I can start to understand, anything else? ---------------------------------------- > From: keridee at jayco.net > To: tutor at python.org > Date: Fri, 8 Feb 2008 22:26:12 -0500 > Subject: Re: [Tutor] Adding network play to an open source game. > > I wish to warn you that I've never done anything like this before, but I > have a couple of thoughts here. First thought is, network games tend to be > slow because sending state information to everyone with enough frames per > second to make it decent game play is a lot of information to send... So the > least information you have to send the better. Fortunately, now that I read > a little more closely... A board game is not going to be bad about this... > > Second thought is... start with simple sockets, work with the server model > and the clients, do not mess with the game at first. Get dummy data to > behave properly first before you ever try anything with the game itself. > > Third thought. C++ is a different language from python. This will further > intensify your trouble. In fact, depending on your knowledge of C++, this > could greatly intensify your trouble. You could have step two there going > just perfectly, but getting python and C++ to talk could throw you in loops. > > I would say that generally for a programmer of a year, this seems like a > very significant goal. Not only do you have to understand quite precisely > what the C++ program is doing, (difficult especially in a game, IMO), but > you have sockets to deal with, client, server, and just as difficult, > C++/Python interaction. Also, given that you didn't write konquer~ someone > else's code is harder to read than your own. Trust me. > > My suggestion is, if you are going to tackle this, very definitely take it > in very defined steps. Work on sockets here, then C++/Python here, etc. I > don't wish to discourage you, but I wouldn't try this yet. (Of course, I've > never taken classes...) ;-) > > >> Hi. First of all, I'm not an amazing programmer. But, I do have large >> goals, somtimes too large. There is an open source game, konquer, (it's >> on the ubuntu repos.) that I would like to extend with python to include a >> network based game. But, I only know how to do simple sockets.... Is >> this too big a project for first year programmer? (I've been programing >> for 3, but have taken classes only one year.)The program is like a board >> game. You move your fleets to different planets, one at a time. The game >> is written in C++(I think). >> >> Just as a preliminary thing, I will go through how I think it will work. >> One computer in the network will be designated as the 'server' that >> everyone will send information to. Each turn, four pieces of data will >> have to be sent to the 'server' that I can think of right now.: 1. how >> many fleets have left 2. from what planet 3. going to which planet >> 4.taking how long to get there. From there, the server will then issue >> those to each player, and tell which player is next, and wait for his >> reply. >> >> I don't really know how to start, so I guess I will start here. >> >> I appreciate your reply. >> _________________________________________________________________ >> Need to know the score, the latest news, or you need your Hotmail?-get >> your "fix". >> http://www.msnmobilefix.com/Default.aspx >> _______________________________________________ >> 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 _________________________________________________________________ Shed those extra pounds with MSN and The Biggest Loser! http://biggestloser.msn.com/ From alan.gauld at btinternet.com Sat Feb 9 10:09:14 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Feb 2008 09:09:14 -0000 Subject: [Tutor] designing POOP References: <47AA5BB5.1020500@tds.net><012101c869fc$25ef1640$e3fce004@jslaptop><47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net> <005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: "Tiger12506" wrote > Are some simple examples off the top of my head. It's not difficult > to model > real-life things with classes, but ... This is a good point, it is excellent practice for thinking about the responsibilities of objects > ...it is much more difficult to model them > in such a way that you interact with them normally. And this is the bit that does require experience and careful thought. But even thinking in the absract about doors, knobs,locks etc helps to get the brain attuned to the kind of decions that need to be made > door, or the knob? Does the knob contain a Lock, or does the > developer only > need to know that it has one and whether it is locked or not?) And its important to remember that the answers will be problem dependant. There is no absolute right or wrong, just what works best for your problem. Of course that's why building reusable objects is so hard. Something apparently reusable will usually only be reusable within a single problem domain. And even then may need to be tweaked for the specific problem. It has been estimated that building reusable objects costs between 3-5 times as much as building a bespoke version (and commercially reusable objects cost up to 10 times as much!) Alan G. From dave6502 at googlemail.com Sat Feb 9 10:21:41 2008 From: dave6502 at googlemail.com (dave selby) Date: Sat, 9 Feb 2008 09:21:41 +0000 Subject: [Tutor] if ... else shorthand form ? Message-ID: Hi all, Returning to python after a brief affair with C++, I have the following code ... if (items.has_keys('snapshot_interval')): self.snap_init[i] = items['snapshot_interval'] else: self.snap_init[i] = 0 I thought Python had a shorthand version of something like .... self.snap_init[i] = (items.has_keys('snapshot_interval'))?items['snapshot_interval']:0 Googled but no luck ... or is it my poor overloaded brain getting confused ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From eric at abrahamsen.com Sat Feb 9 10:26:56 2008 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sat, 9 Feb 2008 17:26:56 +0800 Subject: [Tutor] if ... else shorthand form ? In-Reply-To: References: Message-ID: <60174DC8-D85B-4FA3-868D-326A4E7EEC15@abrahamsen.com> > Hi all, > > Returning to python after a brief affair with C++, I have the > following code ... > > if (items.has_keys('snapshot_interval')): > self.snap_init[i] = items['snapshot_interval'] > else: > self.snap_init[i] = 0 > > I thought Python had a shorthand version of something like .... > > self.snap_init[i] = > (items.has_keys('snapshot_interval'))?items['snapshot_interval']:0 I believe the idiom here is var = value if condition else otherValue So you'd want self.snap_init[i] = items['snapshot_interval'] if items.has_keys('snapshot_interval') else 0 Yours, Eric From bhaaluu at gmail.com Sat Feb 9 11:09:41 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 9 Feb 2008 05:09:41 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <012101c869fc$25ef1640$e3fce004@jslaptop> <47ACBA8E.1020902@tds.net> <47ACCDB9.7000200@tds.net> <005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: On Feb 9, 2008 4:09 AM, Alan Gauld wrote: > > "Tiger12506" wrote > > > Are some simple examples off the top of my head. It's not difficult > > to model > > real-life things with classes, but ... > > This is a good point, it is excellent practice for thinking > about the responsibilities of objects > > > ...it is much more difficult to model them > > in such a way that you interact with them normally. > > And this is the bit that does require experience and careful thought. > But even thinking in the absract about doors, knobs,locks etc helps > to get the brain attuned to the kind of decions that need to be made I'm really getting a lot out of this discussion. In my tutorial (PPftAB2E) the second chapter deals with a Blackjack game. One thing I noticed (and remember, this is a Noob's viewpoint): The classes seemed to be designed from small to large, rather than from large to small. First, a card class was made that had card-object stuff in it (suits and ranks). Then a hand class was made that inherited the card class. Then, a deck class was made, that inherited from the hands class (that already had inherited from the card class). Is this the way you think about designing classes (small to large). I don't know the proper terminolgy for that yet. I'm almost ready to start working on another aspect of the adventure game. I've noticed in my tutorial that several small programs introduce various classes as the chapter proceeds, then at the end, it is all used to make the final program. That's fine for the book: no telling how long, or what he had to do to get it to work that way. But I'm just trying to figure out the design of the adventure game in small increments. If, in the end, I can use parts of these small programs to make the final program, great! But for now, I'm trying to keep it at a manageable size while I'm learning. There is a castle which has several levels and each level has rooms on it. The rooms have doors. The doors connect the rooms to each other. Each room can have either nothing in it, a treasure, or a monster. Each room has a description which describes 1) Is there a treasure in the room? (and if so, what is the amount), 2) Is there a monster in it (and if so, what is the Danger Level), 3) The room description, including where the doors are, (N,S,E,W,U,D). I'd like to try and design this small part so that the Explorer can move around the environment, from room to room, level to level. That's it. The Explorer will be able to see, but not pick-up treasure (keeping in mind that treasure can be picked-up in the final game). The Explorer will be warned about a monster in the room (keeping in mind that the monster can be fought in the final game). Design in small chucks. The Castle needs to be setup. Can the Travel Table from the procedural game be used? Setup requires that the floorplan, or map of the castle be used to define each room on a level, all the doors for the rooms, and treasure/terror. One array is used in the procedural program. Whoops! Sorry. I'm not supposed to think about it like that! If I use the small to large approach: A door is the smallest part of a room. Each room shares doors. Each floor has rooms. All the floors are in the Castle. But in this game, all the doors do is connect the rooms. They don't have knobs or locks. They don't open or close. (Although they MAY have that ability in some future game?). My thought is you can't possibly think of all the future things an object can do or be, but if the class is designed in a very abstract way, then it will be easier to add a new behavior or characteristic in the future, if needed? This is what I'm trying to learn with this adventure game exercise. So, I'm thinking that a door class isn't necessary? The next thing is a room. A room has doors that connect to other rooms, a description, and may contain a monster or treasure. This sounds like a candidate for a class? The castle has levels. Each level has rooms. Everything happens in the castle. The equivalent of the castle in the card game would be the "deck of cards". But the deck of cards holds "hands" (rooms?) which are shuffled and dealt to people. It does something. What does the castle DO? It holds rooms, and monsters and treasure is shuffled and "dealt" to random rooms (for the Explorer to find). Not having much experience doing this, makes it harder than it should be! What is your thought process on this? > > > door, or the knob? Does the knob contain a Lock, or does the > > developer only > > need to know that it has one and whether it is locked or not?) > > And its important to remember that the answers will be problem > dependant. > There is no absolute right or wrong, just what works best for your > problem. > > Of course that's why building reusable objects is so hard. > Something apparently reusable will usually only be reusable > within a single problem domain. And even then may need to > be tweaked for the specific problem. It has been estimated > that building reusable objects costs between 3-5 times as > much as building a bespoke version (and commercially > reusable objects cost up to 10 times as much!) > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From tiagosaboga at terra.com.br Sat Feb 9 12:02:55 2008 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Sat, 9 Feb 2008 09:02:55 -0200 Subject: [Tutor] if ... else shorthand form ? In-Reply-To: References: Message-ID: <20080209110255.GE17065@localdomain> On Sat, Feb 09, 2008 at 09:21:41AM +0000, dave selby wrote: > Hi all, > > Returning to python after a brief affair with C++, I have the following code ... > > if (items.has_keys('snapshot_interval')): > self.snap_init[i] = items['snapshot_interval'] > else: > self.snap_init[i] = 0 > > I thought Python had a shorthand version of something like .... > > self.snap_init[i] = > (items.has_keys('snapshot_interval'))?items['snapshot_interval']:0 self.snap_init[1] = items.get('snapshot_interval', 0) Or, if you also want to set the value on items, ... = items.setdefault('snapshot_interval', 0) []s Tiago. From ricaraoz at gmail.com Sat Feb 9 13:53:13 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 09 Feb 2008 09:53:13 -0300 Subject: [Tutor] Anyone fancy giving me some tips and an expert opinion?? In-Reply-To: References: Message-ID: <47ADA239.509@bigfoot.com> Damian Archer wrote: > I have written what i see as a pretty decent script to resolve this > question: > > Write an improved version of the Chaos program from Chapter 1 that > allows a user to input two initial > values and the number of iterations and then prints a nicely formatted > table showing how the values > change over time. For example, if the starting values were .25 and .26 > with 10 iterations, the table > might look like this: > index 0.25 0.26 > ---------------------------- > 1 0.731250 0.750360 > 2 0.766441 0.730547 > 3 0.698135 0.767707 > 4 0.821896 0.695499 > 5 0.570894 0.825942 > 6 0.955399 0.560671 > 7 0.166187 0.960644 > 8 0.540418 0.147447 > 9 0.968629 0.490255 > 10 0.118509 0.974630 > > Although it works I am sure I could have gone about this a better way, > it probably doesn't fit all the rules of best practice either. Was > wondering if anyone would mind having a look and offering a few tips?? > > # chaos.py > # A program to mimic the chaos theory > > def main(): > > print "Example of Chaos" > > # User inputs numbers to compare, z is for the index counter > x = input("Enter a number between 1 and 0: ") > y = input("Enter a second number between 1 and 0: ") > z = 0 > > # Prints the table borders and titles > print '%10s %20s %20s' % ("Index", x, y) > print "----------------------------- > -----------------------------" > tempx = x > tempy = y > > # Loops calculates 'chaotic behaviour for input numbers > for i in range(10): > tempx = 3.9 * tempx * (1 - tempx) > tempy = 3.9 * tempy * (1 - tempy) > z = z + 1 > # Print chaotice results into table > print '%10s %20s %20s' % (z, tempx, tempy) > > raw_input("Press any key to exit") > > main() > >From a procedural POV, UNTESTED : # chaos.py # A program to mimic the chaos theory def main() : print "Example of Chaos" x, y, iterations = getUserInput() printTitles(x, y) for i in range(1, iterations+1) print '%10s %20s %20s' % (i, chaos(x), chaos(y)) raw_input("Press any key to exit") def printTitles(x, y) : # Prints the table borders and titles print '%10s %20s %20s' % ("Index", x, y) print "----------------------------------------------------------" def getUserInput() : # Should put this inside a try/except block x = float(raw_input("Enter a number between 1 and 0: ")) y = float(raw_input("Enter a second number between 1 and 0: ")) iterations = float(raw_input("Enter a number of iterations: ")) return x, y, iterations def chaos(x) : return (3.9 * x * (1 - x)) if __name__ == '__main__' : main() From alan.gauld at btinternet.com Sat Feb 9 14:46:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Feb 2008 13:46:51 -0000 Subject: [Tutor] designing POOP References: <012101c869fc$25ef1640$e3fce004@jslaptop><47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net><005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: "bhaaluu" wrote > the second chapter deals with a Blackjack game. One thing I noticed > (and remember, this is a Noob's viewpoint): The classes seemed to be > designed from small to large, rather than from large to small. As I mentioned in an earlier mail it tends to oscillate in practice. You start off looking at the problem to identify the basic classes. Then you pick one or two and start designing those in detail and that identifies lower level classes. When you reach the point of being able to write some code you do so. The act of writing code brings up issues that get reflected back up the design - maybe even identifying new classes. Once you've written as much code as you can you go back up to the problem level, using your new found knowledge and design a bit more. Once you know enough to start coding go back into code mode again. This constant iteration between top level class discovery and low level class construction is what Grady Booch refers to in his book as "Round Trip Gestalt Design" and in practice is how most software other than the very biggest projects is built. > I've noticed in my tutorial that several small programs introduce > various > classes as the chapter proceeds, then at the end, it is all used to > make > the final program. That's fine for the book: no telling how long, or > what he > had to do to get it to work that way. One of the problems of tutorials (my own included) is that you tend to focus on the code and never get round to explaining to the student how you worked out which classes to build in the first place! I tried to address that in the Games Framwork case syudy in the paper book version (try your local library) which deliberately sets out to create a class Framework step by step. But its quite hard to explain design techniques at the very early stages of programming. Thats why some of the design books I mentioed earlier are good (especially Booch) because they discuss the process of discovering classes and objects in the first place, and provide some basic heuristics to help. > There is a castle which has several levels and each level has rooms > on it. > The rooms have doors. The doors connect the rooms to each other. > Each > room can have either nothing in it, a treasure, or a monster. Each > room > has a description which describes 1) Is there a treasure in the > room? (and > if so, what is the amount), 2) Is there a monster in it (and if so, > what is the > Danger Level), 3) The room description, including where the doors > are, > (N,S,E,W,U,D). > > I'd like to try and design this small part so that the Explorer can > move > around the environment, from room to room, level to level. That's > it. > The Explorer will be able to see, but not pick-up treasure (keeping > in > mind that treasure can be picked-up in the final game). The Explorer > will be warned about a monster in the room (keeping in mind that the > monster can be fought in the final game). Thats fine so you probably can start with a single room and your Explorer. Get the explorer to ask the room whats in it and then the Explorer can tell the Game what it has found. >>> import room,explorer >>> fred = Explorer('fred') >>> room1 = Room(Dragon(),GoldRing(),Bread() >>> room2 = Room(Serpent(),Bracelet(),Butter() >>> fred.explore(room1) >>> fred.describe() I am in a room with a dragon, a gold ring and a loaf od bread" >>> fred.explore(room2) >>> fred.describe() I am in a room with a serpent, a bracelet and a pack of butter" >>> Once you have that working its a short step to make the castle contain a list of rooms with linkages between - possibly using a variant of your procedural table, but with Room objects rather than the raw data. The Room initialisation could read a data file to get the contents of each room... And the castle initialisation could read the data file to get the layout of the rooms - sounds like a job for the Python config file module maybe? And hppefully from the codec above you can start to think about what the expore method looks like inside? And maybe what method the room might need to support that? > Design in small chucks. The Castle needs to be setup. Can the Travel > Table from the procedural game be used? Setup requires that the > floorplan, or map of the castle be used to define each room on a > level, > all the doors for the rooms, and treasure/terror. One array is used > in > the procedural program. Whoops! Sorry. I'm not supposed to think > about it like that! No, thinking like that is fine when you are thinking about how the methods inside the classes work. So long as the castle stays concerned only with the layout of the rooms (how they are connected to each other) and the rooms look after the content within themselves. The Game class will then control the movement and action of the explorer. So if the user wants the explorer to go Siouth the Game can ask the Castle which room (if any) is Sourth of the current Room - and the explorer knows which room he is currently in so the Game can ask him that, something like: while True: direction = raw_input('What direction to move?[NSEW]").upper() if direction not in 'NSEW': break try: new_room = castle.whichroom(explorer.where(), direction) explorer.explore(new_room) except RoomError: print "Sorry you cannot move ", direction, "please try again" > But in this game, all the doors do is connect the rooms. They don't > have knobs or locks. They don't open or close. (Although they MAY > have that ability in some future game?). If they don;t do anything then leave them out for now. Remember objects have behaviour. No behaviour suggests no object needed! > possibly think of all the future things an object can do or be, but > if the class is designed in a very abstract way, then it will be > easier > to add a new behavior or characteristic in the future, if needed? Thats the hope. And often the additional behaviour is added by subclassing because often you will have found a special category of your more abstract class - a special type of room say, maybe a dungeon with no easy way out... or one that reduces strength and wealth more than usual... And with that we again start to see how OOP allows us to extend the game easily without breaking already working code. > The castle has levels. Each level has rooms. OK, Id start with a single level castle. Add up/down between levels later only if needed. (A simple 3d mesh might be all thats needed) > in the castle. The equivalent of the castle in the card game would > be the "deck of cards". But the deck of cards holds "hands" (rooms?) > which are shuffled and dealt to people. It does something. What does > the castle DO? It determines the validity of movement between rooms. Room 1 and Room 2 may be next door to each other but the catle knows if they are connected (have a doorway?) or whether you need to go via a corridor (another type of room?...) See the example code above for one way to use the castle. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Sat Feb 9 15:16:11 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sat, 9 Feb 2008 09:16:11 -0500 Subject: [Tutor] Adding network play to an open source game. In-Reply-To: References: Message-ID: <82b4f5810802090616p12110a71ha1177139f7d67c06@mail.gmail.com> Your game is perfectly within reach of a novice programmer. Board Games are often used as the final project for early courses at Georgia Tech that many people take who aren't going to be programmers for a living. You're also going to chop up some code you didn't write and make it do something fundamentally different than what it does now if you do this in python. While that is fine, it is not a small task, but it does work well. It may be faster to implement this in C++ as you'd be changing C++ code a lot to do this, but you're going to learn a lot more (in a good way) if you do it in python and attach python to it While you could figure out the generic sockets interface (it's not that hard, but does have some novel concepts in it), you may do better to learn to use a remote procedure call (RPC) mechanism and code your game on top of that. RPC looks like a normal call when you do it. The RPC mechanism I've used a lot in python is XMLRPC. Don't worry, you don't have to know anything about XML to use it, it all happens "magically" under the hood. XMLRPC shines most when few pieces of information are going across. Some references are: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549 and this part of the larger article: http://www.adobe.com/devnet/flex/articles/flex_ui_02.html A lot of games have this pattern of low-level languages for some code plus high-level language for everything else. Civ4 used python for the higher level language. Many games use lua. Most of EA games use an Actionscript front end and a C/C++ backend. There are two ways to do the game. Now there are two methods of combining python with the game: 1. You can turn the modules of the game into python modules, then rewrite the main loop in python. This is essentially putting the game into python. 2. You can embed python into the game in one place. The game will still fundamentally run as it does now, but will have an added scriptable part. This is essentially putting python into the game. By doing approach #1, you may make future additions to the game a lot easier. To do this method, you're going to generate wrappers around the modules. You do that with something called SWIG. That is going to hurt some. But then again, I think it is time the tutor list sees some work with SWIG on here. SWIG is a toolkit that generates wrappers on C/C++ code so languages such as Ruby, Perl and Python can call it. SWIG is not easy. It is difficult in same way that plastering a wall is, lots of little problems, not in the big, complex concepts way that integral calculus is. You will make SWIG do what you want it to if you keep trying. Here is the main page: http://www.swig.org/ Here is the tutorial: http://www.swig.org/papers/PyTutorial98/PyTutorial98.pdf If you go that approach, when/if you get stuck, let us know. I've done SWIG work several times. Someone else here may know of another solution along that line Approach 2 puts a python interpreter into the C/C++ program. It is called embedding. Guido's text on doing so is more than sufficient for most people. http://www.python.org/doc/current/ext/embedding.html While this will be much easier for you to do (especially if you start extremely simply with something that looks like the very simple example), you will fundamentally be leaving the structure of the game a C/C++ game. This will mean if you're going to change other parts of it, you will have to do so in those languages, or you will have to finagle ways to use the embedded python instance more. You're going to learn a lot more doing approach 1 in my opinion. You'll be able to change the game more ways easily, but approach 2 will get what you're trying to do done quickest, and should be the way you do this if you do not intend in changing the game any more than your networking additions. Approach 2 also requires much less rejiggering of the internals of the C/C++ program. --Michael On Feb 8, 2008 11:21 PM, Timothy Sikes wrote: > > > Thanks for your advice. You're probably right, I do need to figure out sockets first... But it's a goal to work towards... I don't know if I would keep up computer programming if I didn't have a specific goal. A few things: > > I have the author's email of konquer (it was in the source). I don't think he's actively developing it, but once I get to a nice start, I could try a nice email to him about it. You're also right, I don't know C++, but would like to learn it. > > Anyone have any advice on good tutorials/books/examples of python network programming? I saw a cherryChat program that I can start to understand, anything else? > > ---------------------------------------- > > From: keridee at jayco.net > > To: tutor at python.org > > Date: Fri, 8 Feb 2008 22:26:12 -0500 > > Subject: Re: [Tutor] Adding network play to an open source game. > > > > > I wish to warn you that I've never done anything like this before, but I > > have a couple of thoughts here. First thought is, network games tend to be > > slow because sending state information to everyone with enough frames per > > second to make it decent game play is a lot of information to send... So the > > least information you have to send the better. Fortunately, now that I read > > a little more closely... A board game is not going to be bad about this... > > > > Second thought is... start with simple sockets, work with the server model > > and the clients, do not mess with the game at first. Get dummy data to > > behave properly first before you ever try anything with the game itself. > > > > Third thought. C++ is a different language from python. This will further > > intensify your trouble. In fact, depending on your knowledge of C++, this > > could greatly intensify your trouble. You could have step two there going > > just perfectly, but getting python and C++ to talk could throw you in loops. > > > > I would say that generally for a programmer of a year, this seems like a > > very significant goal. Not only do you have to understand quite precisely > > what the C++ program is doing, (difficult especially in a game, IMO), but > > you have sockets to deal with, client, server, and just as difficult, > > C++/Python interaction. Also, given that you didn't write konquer~ someone > > else's code is harder to read than your own. Trust me. > > > > My suggestion is, if you are going to tackle this, very definitely take it > > in very defined steps. Work on sockets here, then C++/Python here, etc. I > > don't wish to discourage you, but I wouldn't try this yet. (Of course, I've > > never taken classes...) ;-) > > > > > >> Hi. First of all, I'm not an amazing programmer. But, I do have large > >> goals, somtimes too large. There is an open source game, konquer, (it's > >> on the ubuntu repos.) that I would like to extend with python to include a > >> network based game. But, I only know how to do simple sockets.... Is > >> this too big a project for first year programmer? (I've been programing > >> for 3, but have taken classes only one year.)The program is like a board > >> game. You move your fleets to different planets, one at a time. The game > >> is written in C++(I think). > >> > >> Just as a preliminary thing, I will go through how I think it will work. > >> One computer in the network will be designated as the 'server' that > >> everyone will send information to. Each turn, four pieces of data will > >> have to be sent to the 'server' that I can think of right now.: 1. how > >> many fleets have left 2. from what planet 3. going to which planet > >> 4.taking how long to get there. From there, the server will then issue > >> those to each player, and tell which player is next, and wait for his > >> reply. > >> > >> I don't really know how to start, so I guess I will start here. > >> > >> I appreciate your reply. > >> _________________________________________________________________ > >> Need to know the score, the latest news, or you need your Hotmail(R)-get > >> your "fix". > >> http://www.msnmobilefix.com/Default.aspx > >> _______________________________________________ > >> 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 > > _________________________________________________________________ > Shed those extra pounds with MSN and The Biggest Loser! > http://biggestloser.msn.com/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From kent37 at tds.net Sat Feb 9 15:39:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 09 Feb 2008 09:39:14 -0500 Subject: [Tutor] Adding network play to an open source game. In-Reply-To: References: Message-ID: <47ADBB12.4080901@tds.net> Timothy Sikes wrote: > Anyone have any advice on good tutorials/books/examples of python network programming? The book "Foundations of Python Network Programming" ;-) is pretty good. http://www.apress.com/book/view/9781590593714 Kent From bhaaluu at gmail.com Sat Feb 9 15:49:45 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 9 Feb 2008 09:49:45 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ACBA8E.1020902@tds.net> <47ACCDB9.7000200@tds.net> <005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: On Feb 9, 2008 8:46 AM, Alan Gauld wrote: > "bhaaluu" wrote > Some more thoughts on designing here. You said I can use the procedural program as a program "requirement" because it defines I/O. Even though the OOP program will have the data and functions in classes, I'd like to have the finished program be identical to the procedural program as far as I/O goes. So the first little program's I/O looks like this: WHAT IS YOUR NAME, EXPLORER? _ <- first prompt clrscr() ZORK, YOUR STRENGTH IS 100 YOU HAVE $ 75 IT IS TOO DARK TO SEE ANYTHING WHAT DO YOU WANT TO DO? _ <- second prompt (main game) So I should be able to 'reuse' some of the code from the first little program, in the second little program where the castle is setup, and the player can move around the castle. IT IS TOO DARK TO SEE ANYTHING is replaced with the room description, as far as I/O goes, and I'd like for my second little sample program to follow suit. When you're designing a program, how do you go about dealing with text descriptions, like the descriptions for a room? Here is an example of a room description: THIS IS THE AUDIENCE CHAMBER THERE IS A WINDOW TO THE WEST. BY LOOKING TO THE RIGHT THROUGH IT YOU CAN SEE THE ENTRANCE TO THE CASTLE. DOORS LEAVE THIS ROOM TO THE NORTH, EAST AND SOUTH. In the procedural program, it is a function that prints the description: def room2(): print.... The player reads the description, and presses "W". There is no west door. The program's output is: YOU CANNOT MOVE THROUGH SOLID STONE and back to the main prompt. Pressing "S" moves the player through the South door into another room, where the status of the player is displayed, and the description of the new room. The data.py file, with the room descriptions is the biggest file in the procedural program. I've been told that a data class with a lot of random data in it is a CodeSmell. Is a data class that has room descriptions in it, with a function for each room, considered a bad design? And, since the setup table and the function that decides which room description is closely related, couldn't they also be a part of that data class? Is a data class a CodeSmell when all the functions are related? Or, should I have a room class that can instantiate 19 room objects which simply accesses the room functions from the data.py file as it is? As a side note: Really, the adventure game isn't too much different from the Bank Account program in your tutorial:: there are several accounts in the adventure game which are credited and debited as the game progresses. Pick up treasure: credit my wealth account. Fight a monster: debit strength account. Move from room to room: debit strength account. Eat food: credit wealth account. Buy a weapon: debit wealth account. The real difference between the two is: moving about the castle and exploring in the adventure game. In the Bank Account, you are pretty much in one room. You enter the bank, and leave the bank after taking care of business. Note: I haven't tried your code snippet below yet, so please keep that in mind. I may have other thoughts after I try it. These are just some things I thought about while reading your reply. I don't have any comments below. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] > > the second chapter deals with a Blackjack game. One thing I noticed > > (and remember, this is a Noob's viewpoint): The classes seemed to be > > designed from small to large, rather than from large to small. > > As I mentioned in an earlier mail it tends to oscillate in practice. > You start off looking at the problem to identify the basic classes. > Then you pick one or two and start designing those in detail and > that identifies lower level classes. When you reach the point of > being able to write some code you do so. The act of writing code > brings up issues that get reflected back up the design - maybe > even identifying new classes. Once you've written as much > code as you can you go back up to the problem level, using > your new found knowledge and design a bit more. Once you > know enough to start coding go back into code mode again. > > This constant iteration between top level class discovery and low > level class construction is what Grady Booch refers to in his book > as "Round Trip Gestalt Design" and in practice is how most > software other than the very biggest projects is built. > > > I've noticed in my tutorial that several small programs introduce > > various > > classes as the chapter proceeds, then at the end, it is all used to > > make > > the final program. That's fine for the book: no telling how long, or > > what he > > had to do to get it to work that way. > > One of the problems of tutorials (my own included) is that you > tend to focus on the code and never get round to explaining > to the student how you worked out which classes to build > in the first place! I tried to address that in the Games Framwork > case syudy in the paper book version (try your local library) > which deliberately sets out to create a class Framework step > by step. But its quite hard to explain design techniques at the > very early stages of programming. Thats why some of the > design books I mentioed earlier are good (especially Booch) > because they discuss the process of discovering classes and > objects in the first place, and provide some basic heuristics to > help. > > > There is a castle which has several levels and each level has rooms > > on it. > > The rooms have doors. The doors connect the rooms to each other. > > Each > > room can have either nothing in it, a treasure, or a monster. Each > > room > > has a description which describes 1) Is there a treasure in the > > room? (and > > if so, what is the amount), 2) Is there a monster in it (and if so, > > what is the > > Danger Level), 3) The room description, including where the doors > > are, > > (N,S,E,W,U,D). > > > > I'd like to try and design this small part so that the Explorer can > > move > > around the environment, from room to room, level to level. That's > > it. > > The Explorer will be able to see, but not pick-up treasure (keeping > > in > > mind that treasure can be picked-up in the final game). The Explorer > > will be warned about a monster in the room (keeping in mind that the > > monster can be fought in the final game). > > Thats fine so you probably can start with a single room and your > Explorer. Get the explorer to ask the room whats in it and then > the Explorer can tell the Game what it has found. > > >>> import room,explorer > >>> fred = Explorer('fred') > >>> room1 = Room(Dragon(),GoldRing(),Bread() > >>> room2 = Room(Serpent(),Bracelet(),Butter() > >>> fred.explore(room1) > >>> fred.describe() > I am in a room with a dragon, a gold ring and a loaf od bread" > >>> fred.explore(room2) > >>> fred.describe() > I am in a room with a serpent, a bracelet and a pack of butter" > >>> > > Once you have that working its a short step to make the > castle contain a list of rooms with linkages between - possibly > using a variant of your procedural table, but with Room objects > rather than the raw data. The Room initialisation could read > a data file to get the contents of each room... > And the castle initialisation could read the data file to get > the layout of the rooms - sounds like a job for the Python > config file module maybe? > > And hppefully from the codec above you can start to think > about what the expore method looks like inside? And maybe > what method the room might need to support that? > > > Design in small chucks. The Castle needs to be setup. Can the Travel > > Table from the procedural game be used? Setup requires that the > > floorplan, or map of the castle be used to define each room on a > > level, > > all the doors for the rooms, and treasure/terror. One array is used > > in > > the procedural program. Whoops! Sorry. I'm not supposed to think > > about it like that! > > No, thinking like that is fine when you are thinking about how > the methods inside the classes work. So long as the castle > stays concerned only with the layout of the rooms (how they > are connected to each other) and the rooms look after the > content within themselves. The Game class will then control the > movement and action of the explorer. So if the user wants the > explorer to go Siouth the Game can ask the Castle which room > (if any) is Sourth of the current Room - and the explorer knows > which room he is currently in so the Game can ask him that, > something like: > > while True: > direction = raw_input('What direction to move?[NSEW]").upper() > if direction not in 'NSEW': break > try: > new_room = castle.whichroom(explorer.where(), direction) > explorer.explore(new_room) > except RoomError: > print "Sorry you cannot move ", direction, "please try again" > > > But in this game, all the doors do is connect the rooms. They don't > > have knobs or locks. They don't open or close. (Although they MAY > > have that ability in some future game?). > > If they don;t do anything then leave them out for now. Remember > objects have behaviour. No behaviour suggests no object needed! > > > possibly think of all the future things an object can do or be, but > > if the class is designed in a very abstract way, then it will be > > easier > > to add a new behavior or characteristic in the future, if needed? > > Thats the hope. > And often the additional behaviour is added by subclassing because > often you will have found a special category of your more abstract > class - a special type of room say, maybe a dungeon with > no easy way out... or one that reduces strength and wealth > more than usual... > > And with that we again start to see how OOP allows us to extend > the game easily without breaking already working code. > > > The castle has levels. Each level has rooms. > > OK, Id start with a single level castle. Add up/down > between levels later only if needed. (A simple 3d mesh > might be all thats needed) > > > in the castle. The equivalent of the castle in the card game would > > be the "deck of cards". But the deck of cards holds "hands" (rooms?) > > which are shuffled and dealt to people. It does something. What does > > the castle DO? > > It determines the validity of movement between rooms. > Room 1 and Room 2 may be next door to each other but > the catle knows if they are connected (have a doorway?) or > whether you need to go via a corridor (another type of room?...) > > See the example code above for one way to use the castle. > > 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 > From kent37 at tds.net Sat Feb 9 17:43:53 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 09 Feb 2008 11:43:53 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ACBA8E.1020902@tds.net> <47ACCDB9.7000200@tds.net> <005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: <47ADD849.8000906@tds.net> bhaaluu wrote: > When you're designing a program, how do you go about dealing > with text descriptions, like the descriptions for a room? Here is an > example of a room description: > > THIS IS THE AUDIENCE CHAMBER > THERE IS A WINDOW TO THE WEST. BY LOOKING TO THE RIGHT > THROUGH IT YOU CAN SEE THE ENTRANCE TO THE CASTLE. > DOORS LEAVE THIS ROOM TO THE NORTH, EAST AND SOUTH. That would probably be an attribute of the Room class. > The player reads the description, and presses "W". There is no west door. > The program's output is: > > YOU CANNOT MOVE THROUGH SOLID STONE > > and back to the main prompt. Pressing "S" moves the player through > the South door into another room, where the status of the player is > displayed, and the description of the new room. It might make sense for Room to have a move(direction) method that returns the resulting Room. Then room.move('W') would print the above message and return self. room.move('S') would return the room to the south. This requires that the rooms be linked together - each room knows the rooms that are adjacent to it. Another reasonable design is to have some kind of a Map object that holds the linkages between all the rooms, and a method move(from, direction) that takes both a Room and a direction. I don't know which of these would work better for your game. > The data.py file, with the room descriptions is the biggest file in the > procedural program. I've been told that a data class with a lot of random > data in it is a CodeSmell. Is a data class that has room descriptions in > it, with a function for each room, considered a bad design? A data file is fine. > > And, since the setup table and the function that decides which room > description is closely related, couldn't they also be a part of that data > class? Is a data class a CodeSmell when all the functions are related? I'm not sure I follow you. Are you talking about Room as a data class or some other class? What functions do you mean? A class with data and related functions is not a data class, it is good design. > Or, should I have a room class that can instantiate 19 room objects > which simply accesses the room functions from the data.py file as > it is? Maybe you could give a short example of what you are doing. Kent From dkuhlman at rexx.com Sat Feb 9 19:10:12 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 9 Feb 2008 10:10:12 -0800 Subject: [Tutor] if ... else shorthand form ? In-Reply-To: References: Message-ID: <20080209181012.GA27057@cutter.rexx.com> On Sat, Feb 09, 2008 at 09:21:41AM +0000, dave selby wrote: > Hi all, > > Returning to python after a brief affair with C++, I have the following code ... > > if (items.has_keys('snapshot_interval')): > self.snap_init[i] = items['snapshot_interval'] > else: > self.snap_init[i] = 0 > > I thought Python had a shorthand version of something like .... > > self.snap_init[i] = > (items.has_keys('snapshot_interval'))?items['snapshot_interval']:0 For this specific task, if I understand it correctly, there is an easy and Pythonic idiom: self.snap_init[i] = items.get('snapshot_interval', 0) See: http://docs.python.org/lib/typesmapping.html For mappings/dictionaries: a.get(k[, x]) is equivalent to: a[k] if k in a, else x - (another) Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Sat Feb 9 19:41:19 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Feb 2008 18:41:19 -0000 Subject: [Tutor] designing POOP References: <47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net><005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: > ..., I'd like to have the finished program > be identical to the procedural program as far as I/O goes. You could do it but it would be easier to change it a little because the original games prompts etc betray its internal structure. You can just get the objects to return their attributes and use string formatting to insert those in your prompts. But it might be better to have the objercts return the whole string including values. Of course you can do that easily with a default parameter in a method: class Explorer(object): fmtStr = """ My name is %s and I have wealth of $%s and strength of %s""" # other code here def describe(withText=False) values = (self.name, self.wealth, self.strenth) if not withText: return values else return fmtStr % values We can then call that as e = Explorer() .... e.describe(withText=True) # gets the long version or print """ You are an explorer whose name is %s, You have wealth of %s and strength of %s """ % e.describe() # uses tuple result Using this technique you could use exactly the same text as in the original or create a more OO variant where the objects all know how to describe themselves. Alan G. From alan.gauld at btinternet.com Sat Feb 9 19:51:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Feb 2008 18:51:23 -0000 Subject: [Tutor] designing POOP References: <47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net><005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: "bhaaluu" wrote > When you're designing a program, how do you go about dealing > with text descriptions, like the descriptions for a room? Here is an > example of a room description: > > THIS IS THE AUDIENCE CHAMBER > THERE IS A WINDOW TO THE WEST. BY LOOKING TO THE RIGHT > THROUGH IT YOU CAN SEE THE ENTRANCE TO THE CASTLE. > DOORS LEAVE THIS ROOM TO THE NORTH, EAST AND SOUTH. You can use a class attribute as per my other email example. This attribute would contain %s markers to substitute the values as needed. And finally the actual text can be loaded from a data file by the init method. > The player reads the description, and presses "W". There is no west > door. > The program's output is: > > YOU CANNOT MOVE THROUGH SOLID STONE > > and back to the main prompt. Pressing "S" moves the player through > the South door into another room, where the status of the player is > displayed, and the description of the new room. OK, See my other porst but you could use the castle as a coordinator that determines which rooms are available from any other room. You can build that knowledge into the rooms - eg by passing the relationships in to the constructor but that gets hard to maintain, especially in 3D. So I prefer to have a coordinating object(the castle - or Kent suggested a Map) > The data.py file, with the room descriptions is the biggest file in > the > procedural program. I've been told that a data class with a lot of > random > data in it is a CodeSmell. Is a data class that has room > descriptions in > it, with a function for each room, considered a bad design? The data isn't the problem its the functions and data being mixed in a class. Having a data file that classes use to set up common data(class attribnutes) is perfectly valid. > And, since the setup table and the function that decides which room > description is closely related, couldn't they also be a part of that > data > class? Is a data class a CodeSmell when all the functions are > related? No a class with functions and the related data is exactly what you want. What you want to avoid is a classs that has data for two or more different object types. Or a class with only data. > Or, should I have a room class that can instantiate 19 room objects > which simply accesses the room functions from the data.py file as > it is? The room objects don't use the functions in data.py rather those functions become the methods of the class and the data gets loaded by those methods into the instances. Remember, objects do it to themselves. Nothing outside the class should be changing the internal attributes. But it is OK for the class to load the data from outside - as in a config file. This is a good thing because it allows you to change the displayed messages without changing code. For example to support multiple languages... > As a side note: Really, the adventure game isn't too much different > from the Bank Account program in your tutorial:: there are several > accounts in the adventure game which are credited and debited > as the game progresses. Pick up treasure: credit my wealth account. Exactly so. And the ability to recognise that is a big step forward in recognising abstraction. Alan G From kent37 at tds.net Sat Feb 9 19:58:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 09 Feb 2008 13:58:37 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net><005001c86aa9$48bd1e30$c7fce004@jslaptop> Message-ID: <47ADF7DD.9090209@tds.net> Alan Gauld wrote: > class Explorer(object): > fmtStr = """ > My name is %s > and I have wealth of $%s and > strength of %s""" > > # other code here > > def describe(withText=False) > values = (self.name, self.wealth, self.strenth) > if not withText: > return values > else > return fmtStr % values Should be self.fmtStr or Explorer.fmtStr > We can then call that as > > e = Explorer() > .... > e.describe(withText=True) # gets the long version > > or > > print """ > You are an explorer whose name is %s, > You have wealth of %s and strength of %s > """ % e.describe() # uses tuple result Um, yuck. A function that returns either a string or a tuple depending on its parameter? How about class Explorer: ... def __str__(self): fmtStr = """ My name is %s and I have wealth of $%s and strength of %s""" return fmtStr % self.values() def values(self): return (self.name, self.wealth, self.strenth) Or get rid of values() entirely and just refer to the attributes directly - what if you want to print the values in a different order? Kent From alan.gauld at btinternet.com Sat Feb 9 19:54:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Feb 2008 18:54:44 -0000 Subject: [Tutor] Adding network play to an open source game. References: <47ADBB12.4080901@tds.net> Message-ID: "Kent Johnson" wrote in message news:47ADBB12.4080901 at tds.net... > Timothy Sikes wrote: > >> Anyone have any advice on good tutorials/books/examples of python >> network programming? > > The book "Foundations of Python Network Programming" ;-) is pretty > good. > http://www.apress.com/book/view/9781590593714 Seconded! This is as near as I've seen to the classic Stephens' books on networking but in Python. Its never let me down yet. Alan G. From washakie at gmail.com Sat Feb 9 21:55:37 2008 From: washakie at gmail.com (washakie) Date: Sat, 9 Feb 2008 12:55:37 -0800 (PST) Subject: [Tutor] seek and slice a range in a list of dates Message-ID: <15389997.post@talk.nabble.com> Hello, I'm using the code below to select the closest dates in a dictionary of dates, to selected dates (Tstart, Tend)... Now, I need to get all the dates (slice) from the dictionary in between the two dates TstartNew and TendNew. Basically, I need to know what the 'index' is for them in the in the dictionay dates_dt. How can I get that information out of the lambda functions? does python have a 'find' function?? Thanks! dates_dt={} for i in range(len(dates_list)): dates_dt[i]=datetime.datetime(year,month,day,hour,minute,seconds) TstartNew=sorted(dates_dt.values(),key=lambda d: abs(Tstart - d))[0] TendNew=sorted(dates_dt.values(), key=lambda d: abs(Tend -d))[0] -- View this message in context: http://www.nabble.com/seek-and-slice-a-range-in-a-list-of-dates-tp15389997p15389997.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Sat Feb 9 22:22:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 09 Feb 2008 16:22:14 -0500 Subject: [Tutor] seek and slice a range in a list of dates In-Reply-To: <15389997.post@talk.nabble.com> References: <15389997.post@talk.nabble.com> Message-ID: <47AE1986.8060300@tds.net> washakie wrote: > Hello, > > I'm using the code below to select the closest dates in a dictionary of > dates, to selected dates (Tstart, Tend)... Now, I need to get all the dates > (slice) from the dictionary in between the two dates TstartNew and TendNew. > Basically, I need to know what the 'index' is for them in the in the > dictionay dates_dt. How can I get that information out of the lambda > functions? does python have a 'find' function?? > dates_dt={} > for i in range(len(dates_list)): > dates_dt[i]=datetime.datetime(year,month,day,hour,minute,seconds) Why do you use a dict here? A list seems more appropriate. Where are year,month,day,hour,minute,seconds coming from? > TstartNew=sorted(dates_dt.values(),key=lambda d: abs(Tstart - d))[0] > TendNew=sorted(dates_dt.values(), key=lambda d: abs(Tend -d))[0] You could use min() and max() instead of sorting (twice!) How about something like this (untested): dates_dt=[ datetime.datetime(year,month,day,hour,minute,seconds) for x in dates_list ] adjusted to actually get the dates from somewhere... TstartNew=min(range(len(dates_dt)), key=lambda i: abs(Tstart - dates_dt[i])) This gives you the index of the date with the min difference. TendNew=max(range(len(dates_dt)), key=lambda i: abs(Tend - dates_dt[i])) for the index of the max difference. The above will work if dates_dt is a dict or a list. Dates = dates_dt[TstartNew+1:TendNew] which gives you the dates between and not including the min and max, if dates_dt is a list. For a dict, use Dates = [ dates_dt[i] for i in range(TstartNew+1, TendNew) ] Kent From seon.kang at gmail.com Sat Feb 9 23:15:53 2008 From: seon.kang at gmail.com (Seon Kang) Date: Sat, 9 Feb 2008 17:15:53 -0500 Subject: [Tutor] Game Message-ID: First off, here is the code I am working with so far. import random from livewires import games, color games.init(screen_width = 640, screen_height = 480, fps = 50) controls = "Use The Arrow Keys to Move and the Spacebar to Shoot" game_controls = games.Message(value = controls, size = 25, color = color.black, x = 320, y = 240, lifetime = 250) Motivation_status = "Motivation:" motivation_text = games.Text(value = Motivation_status, size = 20, color = color.black, x = 30, y = 30) motivation = 5 score = games.Text(value = motivation, size = 25, color = color.black, x = 90, y = 30) class Evil_stickman(games.Sprite): missile_wait = 0 def update(self): self.shoot() def shoot(self): if self.missile_wait > 0: self.missile_wait -= 1 if self.missile_wait == 0: missile_image = games.load_image("Missile.bmp", transparent = True) new_missile = Bad_Missile(image = missile_image, x = self.x - 10, y = self.y - 3, angle = 270) games.screen.add(new_missile) self.missile_wait = 20 def Die(self): self.destroy() class Rolling(games.Sprite): def update(self): if self.x > 0: self.x -= 1 self.angle += 2 else: self.destroy() class Missile(games.Sprite): def update(self): if self.x < 640: self.x += 2 else: self.destroy() class Bad_Missile(games.Sprite): def update(self): if self.x > 0: self.x -= 2 else: self.destroy() class Stickman(games.Sprite): missile_wait = 0 level_number = 1 def update(self): if games.keyboard.is_pressed(games.K_RIGHT): self.x += 1 if self.missile_wait > 0: self.missile_wait -= 1 if games.keyboard.is_pressed(games.K_LEFT): if self.x >= 0: self.x -= 1 if games.keyboard.is_pressed(games.K_q): games.screen.quit() if games.keyboard.is_pressed(games.K_UP): if self.y >= 280: self.y -= 1 if games.keyboard.is_pressed(games.K_DOWN): if self.y <= 460: self.y += 1 if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0: missile_image = games.load_image("Missile.bmp", transparent = True) new_missile = Missile(image = missile_image, x = self.x + 20, y = self.y - 2, angle = 90) games.screen.add(new_missile) self.missile_wait = 25 if self.level_number == 1: evilstick_image = games.load_image("badguy.bmp", transparent = True) new_evilstick01 = Evil_stickman(image = evilstick_image, x = 580, y = 400) games.screen.add(new_evilstick01) if motivation == 0: self.destroy() class Introduction(games.Sprite): def update(self): if games.keyboard.is_pressed(games.K_RETURN): self.destroy() games.screen.add(the_stick) games.screen.add(game_controls) intro_sprite_image = games.load_image("Introduction.bmp", transparent = False) intro_sequence = Introduction(image = intro_sprite_image, x = 340, y = 240) games.screen.add(intro_sequence) wall_image = games.load_image("the-map.bmp", transparent = False) games.screen.background = wall_image stickman_image = games.load_image("stickman.bmp", transparent = True) the_stick = Stickman(image = stickman_image, x = 60, y = 380, angle = 90) games.screen.mainloop() The Evil_stickman class seems to have a problem with it. I have added the missile delay in the hope that he would fire missiles about 2 times every second, but instead, he shoots a constant stream. In addition, he slows my entire game down. What is the problem with the code? And how might I go about fixing it? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080209/08f1c634/attachment.htm From alan.gauld at btinternet.com Sun Feb 10 00:57:57 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 9 Feb 2008 23:57:57 -0000 Subject: [Tutor] designing POOP References: <47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net><005001c86aa9$48bd1e30$c7fce004@jslaptop> <47ADF7DD.9090209@tds.net> Message-ID: "Kent Johnson" wrote >> e = Explorer() >> .... >> e.describe(withText=True) # gets the long version >> >> or >> >> print """ >> You are an explorer whose name is %s, >> You have wealth of %s and strength of %s >> """ % e.describe() # uses tuple result > > Um, yuck. A function that returns either a string or a tuple > depending > on its parameter? How about Hmm, I don't have any problerm with that provided it's the same basic information thats returned in both formats. Using a flag to control format is quite common in report generators etc (either postscript or pdf or plain text etc) I would agree its not good if the actual data being returned was different. But in this case it's a caller selectable option so there should never be any confusion. > class Explorer: > ... > def __str__(self): > fmtStr = """ > My name is %s > and I have wealth of $%s and > strength of %s""" > return fmtStr % self.values() I thought about using the str method but decided against it since you couldn't easily get the string version for manipulation later - I thought - but of course you could just use the str() convertion: s = str(e) So yes that would be OK. > def values(self): > return (self.name, self.wealth, self.strenth) > > Or get rid of values() entirely and just refer to the attributes Nope, I don't like that as much since it encourages direct access. And although I don't object to that occasionally - and prefer it to writing getter methods - in the case where we are trying to generate a report I believe the object should support that directly by returning those values that represent it's state - which might include some that are dynamically calculated. - but mostly because the object (or its author) should decide what it wants the world to know about. > directly - what if you want to print the values in a different > order? returning a tuple means you can still access the individual elements via indexing if you don't like the order given. But you can (ie should) only access those attributes provided by the values() call. Alan G. From alan.gauld at btinternet.com Sun Feb 10 01:02:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Feb 2008 00:02:56 -0000 Subject: [Tutor] seek and slice a range in a list of dates References: <15389997.post@talk.nabble.com> Message-ID: "washakie" wrote > dates, to selected dates (Tstart, Tend)... Now, I need to get all > the dates > (slice) from the dictionary in between the two dates TstartNew and > TendNew. > Basically, I need to know what the 'index' is for them in the in the > dictionay dates_dt. How can I get that information out of the lambda > functions? does python have a 'find' function?? I think you might need to read up on hash tables - try wikipedia. There is no index as such. A dictionary is a hash table usually implented as a sparce array or tree structure so you cannot traverse it sequentially - thats why order is not guaranteed in a dictionary. I think you need to reconsider your data structure. Alan G From rob.rstevenson at gmail.com Sun Feb 10 01:01:48 2008 From: rob.rstevenson at gmail.com (Rob Stevenson) Date: Sun, 10 Feb 2008 00:01:48 +0000 Subject: [Tutor] How to... (a) write to files, (b) use try/except Message-ID: <3e12fcbf0802091601p1e46df5rfc77a6391b54a719@mail.gmail.com> Hello, Sorry to be dense, but I'm having trouble writing to a file... I have a list of book numbers - ISBNs in a file, one per line... (see list at bottom of this message) my code below... import amazon amazon.setLicense(' -- my amazon id is in here when I run - ') isbn_list = "c:\\ISBN.txt" amazon.setLocale("uk") fle=open("c:\\321.txt",'a') for isbn in file(isbn_list): isbn = isbn.strip() try: books=amazon.searchByKeyword(isbn) except: x=1 for book in books: try: Title = book.ProductName printstring = isbn + "\t" + book.ProductName + "\t" + book.Authors.Author + "\tUsed from...\t" + book.UsedPrice + "\tNew price\t" + book.OurPrice print printstring print printstring >> fle except: ignorance='notBliss' fle.close Now I have two problems 1) the file c:\321.txt (which does exist) never gets written to. I also tried using fle.write(printstring) and fle.writeline(printstring) but they didn't do anything either. 2) if any of the function calls from amazon.py, such as book.UsedPricefails then the rest of the details that may well have been retreived for that get lost in the jump to the except block. I'd really like to get whatever info I can on the printstring assignment line and ignore any errors, perhaps substituting 'none' instead of a retrieved value. Any help very appreciated. Also, a point of nettiquette for this list - how do I say thanks to people - not to the list, but in direct emails? Thanks all, Rob ==the ISBNs from my file === 0006755151 059304083X 0349112150 0141030143 0099740915 0552773123 0747590087 0571224121 0552997706 0099490730 0141009128 0670852473 0044409672 0722540523 0375720979 1862074534 0571169945 08685506 0330481886 0333618815 057120273X 0099526409 0753509024 0099476649 0316857912 0007179731 014027443X 000637977X 1568360231 1844832007 1844832058 1844832023 1846270057 0810112434 0141022280 0552152293 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080210/66c48726/attachment.htm From rob.rstevenson at gmail.com Sun Feb 10 01:03:00 2008 From: rob.rstevenson at gmail.com (Rob Stevenson) Date: Sun, 10 Feb 2008 00:03:00 +0000 Subject: [Tutor] How to (a) write to files, (b) use try/except (clarification) Message-ID: <3e12fcbf0802091603r33c6b8e6qcac7c4439d312435@mail.gmail.com> by amazon ID in my message I meant my web services license number. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080210/ef551b0a/attachment.htm From kent37 at tds.net Sun Feb 10 02:33:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 09 Feb 2008 20:33:21 -0500 Subject: [Tutor] How to... (a) write to files, (b) use try/except In-Reply-To: <3e12fcbf0802091601p1e46df5rfc77a6391b54a719@mail.gmail.com> References: <3e12fcbf0802091601p1e46df5rfc77a6391b54a719@mail.gmail.com> Message-ID: <47AE5461.8060000@tds.net> Rob Stevenson wrote: > Title = book.ProductName > printstring = isbn + "\t" + book.ProductName + "\t" + > book.Authors.Author + "\tUsed from...\t" + book.UsedPrice + "\tNew > price\t" + book.OurPrice > print printstring > print printstring >> fle > except: > ignorance='notBliss' > fle.close Should be fle.close(), you need the parentheses to make a function call. > Now I have two problems > > 1) the file c:\321.txt (which does exist) never gets written to. I also > tried using > > fle.write(printstring) > > and fle.writeline(printstring) but they didn't do anything either. Assuming that there are some results, it is probably the lack of a proper close that is the problem. > > 2) if any of the function calls from amazon.py, such as book.UsedPrice > fails then the rest of the details that may well have been retreived for > that get lost in the jump to the except block. I'd really like to get > whatever info I can on the printstring assignment line and ignore any > errors, perhaps substituting 'none' instead of a retrieved value. Instead of book.UsedPrice you can say getattr(book, 'UsedPrice', 'none') which will return the string 'none' if the attribute is not available. > Also, a point of nettiquette for this list - how do I say thanks to > people - not to the list, but in direct emails? I think either way is fine. Kent From washakie at gmail.com Sun Feb 10 02:34:05 2008 From: washakie at gmail.com (washakie) Date: Sat, 9 Feb 2008 17:34:05 -0800 (PST) Subject: [Tutor] seek and slice a range in a list of dates In-Reply-To: References: <15389997.post@talk.nabble.com> Message-ID: <15392327.post@talk.nabble.com> It's not pretty, but this is what seems to work... I'd be happy hear more about a better approach... I like the idea of using a list, but ran into troubles with min and max, maybe I don't entirely understand the lambda function, but when I tried a list, I got an error that min() has no optional variable 'key' or something along those lines... Using a technique from: http://www.daniweb.com/code/snippet806.html def find_key(dic, val): """return the key of dictionary dic given the value""" return [k for k, v in dic.iteritems() if v == val][0] dates_dt={} for i in range(len(dates_list)): dates_dt[i]=datetime.datetime(int(dates_list[i][0][:4]),int(dates_list[i][0][4:6]),\ int(dates_list[i][0][6:8]),int(dates_list[i][0][8:10]),int(dates_list[i][0][10:12]),\ int(dates_list[i][0][12:])) TstartNew=sorted(dates_dt.values(),key=lambda d: abs(Tstart - d))[0] Tstart_i=find_key(dates_dt,TstartNew) TendNew=sorted(dates_dt.values(), key=lambda d: abs(Tend -d))[0] Tend_i=find_key(dates_dt,TendNew) try: TF=file(os.path.join(TMP_DIR,'dates_file'),'w') if userInput['animation']=='movie': for i in range(Tstart_i,Tend_i): TF.write("%s\n" % dates_dt[i].strftime("%Y%m%d%H0000")) else: TF.write("%s\n" % time_begin ) TF.close() -- View this message in context: http://www.nabble.com/seek-and-slice-a-range-in-a-list-of-dates-tp15389997p15392327.html Sent from the Python - tutor mailing list archive at Nabble.com. From washakie at gmail.com Sun Feb 10 02:35:23 2008 From: washakie at gmail.com (washakie) Date: Sat, 9 Feb 2008 17:35:23 -0800 (PST) Subject: [Tutor] seek and slice a range in a list of dates Message-ID: <15392327.post@talk.nabble.com> It's not pretty, but this is what seems to work... I'd be happy hear more about a better approach... I like the idea of using a list, but ran into troubles with min and max, maybe I don't entirely understand the lambda function, but when I tried a list, I got an error that min() has no optional variable 'key' or something along those lines... Using a technique from: http://www.daniweb.com/code/snippet806.html def find_key(dic, val): """return the key of dictionary dic given the value""" return [k for k, v in dic.iteritems() if v == val][0] dates_dt={} for i in range(len(dates_list)): dates_dt[i]=datetime.datetime(int(dates_list[i][0][:4]),int(dates_list[i][0][4:6]),\ int(dates_list[i][0][6:8]),int(dates_list[i][0][8:10]),int(dates_list[i][0][10:12]),\ int(dates_list[i][0][12:])) TstartNew=sorted(dates_dt.values(),key=lambda d: abs(Tstart - d))[0] Tstart_i=find_key(dates_dt,TstartNew) TendNew=sorted(dates_dt.values(), key=lambda d: abs(Tend -d))[0] Tend_i=find_key(dates_dt,TendNew) try: TF=file(os.path.join(TMP_DIR,'dates_file'),'w') if userInput['animation']=='movie': for i in range(Tstart_i,Tend_i): TF.write("%s\n" % dates_dt[i].strftime("%Y%m%d%H0000")) else: TF.write("%s\n" % TstartNew.strftime("%Y%m%d%H0000") ) TF.close() -- View this message in context: http://www.nabble.com/seek-and-slice-a-range-in-a-list-of-dates-tp15389997p15392327.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Sun Feb 10 02:42:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 09 Feb 2008 20:42:04 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ACBA8E.1020902@tds.net><47ACCDB9.7000200@tds.net><005001c86aa9$48bd1e30$c7fce004@jslaptop> <47ADF7DD.9090209@tds.net> Message-ID: <47AE566C.6040206@tds.net> Alan Gauld wrote: >> def values(self): >> return (self.name, self.wealth, self.strenth) >> >> Or get rid of values() entirely and just refer to the attributes > > Nope, I don't like that as much since it encourages direct > access. Maybe we just need to agree to disagree here. I don't see how returning a tuple is better encapsulation than direct access to named attributes. And what if an attribute is added? Do you add another value to the tuple, forcing every client to change? Start returning a value object with named attributes? :-) >> directly - what if you want to print the values in a different >> order? > > returning a tuple means you can still access the individual > elements via indexing if you don't like the order given. But > you can (ie should) only access those attributes provided > by the values() call. So to print, say, strength, wealth and name, we can have values = explr.values() print values[2], values[1], values[0] or unpack the tuple and give them names again: strength, wealth, name = explr.values() print strength, wealth, name or just use the perfectly good names they already have: print explr.strength, explr.wealth, explr.name and of course unless you take extra steps to prevent it, direct attribute access is still available even with the values() method... Kent From kent37 at tds.net Sun Feb 10 02:50:37 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 09 Feb 2008 20:50:37 -0500 Subject: [Tutor] seek and slice a range in a list of dates In-Reply-To: <15392327.post@talk.nabble.com> References: <15389997.post@talk.nabble.com> <15392327.post@talk.nabble.com> Message-ID: <47AE586D.50406@tds.net> washakie wrote: > It's not pretty, but this is what seems to work... I'd be happy hear more > about a better approach... I like the idea of using a list, but ran into > troubles with min and max, maybe I don't entirely understand the lambda > function, but when I tried a list, I got an error that min() has no optional > variable 'key' or something along those lines... You must be using an older version of Python, the key= parameter was introduced in Python 2.5. You can still do it more easily with a list using your sort technique: dates_dt=[] for i in range(len(dates_list)): dates_dt.append(datetime.datetime(int(dates_list[i][0][:4]),int(dates_list[i][0][4:6]),\ int(dates_list[i][0][6:8]),int(dates_list[i][0][8:10]),int(dates_list[i][0][10:12]),\ int(dates_list[i][0][12:]))) TstartNew=sorted(dates_dt,key=lambda d: abs(Tstart - d))[0] Tstart_i=dates_dt.index(TstartNew) TendNew=sorted(dates_dt, key=lambda d: abs(Tend -d))[0] Tend_i=dates_dt.index(TendNew) Kent From varsha.purohit at gmail.com Sun Feb 10 07:12:35 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sat, 9 Feb 2008 22:12:35 -0800 Subject: [Tutor] [tutor] Problem in saving image file which is modified by ImageEnhance Message-ID: Hello All, I am using PIL function to change brightness of an image. But i am getting an error when i am trying to save that image. Here is the code.. import Image import ImageChops, ImageEnhance import math, operator file1 = Image.open("r10001t0.jpg") file2 = Image.open("r10001t1.jpg") diff = ImageChops.difference(file1,file2) enhancer = ImageEnhance.Brightness(diff) ext = ".jpg" enhancer.save("diff1" + ext, "JPEG", quality =100) I am getting error as ImageEnhance doesn't have attribute called save... how should i save the enhanced image... or alternatively when i am comparing two images using imagechops i am getting a black back ground... how should i make it little brighter or use another colour instead of black ??? -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080209/fc5808df/attachment.htm From washakie at gmail.com Sun Feb 10 12:01:55 2008 From: washakie at gmail.com (washakie) Date: Sun, 10 Feb 2008 03:01:55 -0800 (PST) Subject: [Tutor] seek and slice a range in a list of dates In-Reply-To: <47AE586D.50406@tds.net> References: <15389997.post@talk.nabble.com> <15392327.post@talk.nabble.com> <47AE586D.50406@tds.net> Message-ID: <15395230.post@talk.nabble.com> Yes, I'm using 2.4, and will not likely be able to upgrade... so, the final, as you suggested Kent: dates_dt=([datetime.datetime(int(dates_list[i][0][:4]),int(dates_list[i][0][4:6]), int(dates_list[i][0][6:8]),int(dates_list[i][0][8:10]), int(dates_list[i][0][10:12]),int(dates_list[i][0][12:])) for i in range(len(dates_list))]) TstartNew=sorted(dates_dt,key=lambda d: abs(Tstart - d))[0] Tstart_i=dates_dt.index(TstartNew) TendNew=sorted(dates_dt, key=lambda d: abs(Tend -d))[0] Tend_i=dates_dt.index(TendNew) This definitely seems to cleanest way... thank you! One question, how would this handle duplicates in the dates_dt list? -- View this message in context: http://www.nabble.com/seek-and-slice-a-range-in-a-list-of-dates-tp15389997p15395230.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Sun Feb 10 14:20:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Feb 2008 08:20:24 -0500 Subject: [Tutor] seek and slice a range in a list of dates In-Reply-To: <15395230.post@talk.nabble.com> References: <15389997.post@talk.nabble.com> <15392327.post@talk.nabble.com> <47AE586D.50406@tds.net> <15395230.post@talk.nabble.com> Message-ID: <47AEFA18.6090702@tds.net> washakie wrote: > Yes, I'm using 2.4, and will not likely be able to upgrade... so, the final, > as you suggested Kent: > > > dates_dt=([datetime.datetime(int(dates_list[i][0][:4]),int(dates_list[i][0][4:6]), > > int(dates_list[i][0][6:8]),int(dates_list[i][0][8:10]), > > int(dates_list[i][0][10:12]),int(dates_list[i][0][12:])) > for i in range(len(dates_list))]) You don't need the outermost parentheses here. > > TstartNew=sorted(dates_dt,key=lambda d: abs(Tstart - d))[0] > Tstart_i=dates_dt.index(TstartNew) > TendNew=sorted(dates_dt, key=lambda d: abs(Tend -d))[0] > Tend_i=dates_dt.index(TendNew) > > This definitely seems to cleanest way... thank you! One question, how would > this handle duplicates in the dates_dt list? index() will return the first found element. If you want Tend_i to be the last match you will have to write your own rindex() function. Some suggestions are here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b25cb46b54cc5ee5/120d04e029e934c5?hl=en&lnk=gst This one looks good to me: def rindex(seq, item): for pos, el in enumerate(reversed(seq)): if item == el: return len(seq) - 1 - pos else: raise ValueError("rindex(list, item): item not in list") Kent From kent37 at tds.net Sun Feb 10 14:24:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Feb 2008 08:24:20 -0500 Subject: [Tutor] [tutor] Problem in saving image file which is modified by ImageEnhance In-Reply-To: References: Message-ID: <47AEFB04.5080905@tds.net> Varsha Purohit wrote: > Hello All, > I am using PIL function to change brightness of an image. But i > am getting an error when i am trying to save that image. Here is the code.. > > import Image > import ImageChops, ImageEnhance > import math, operator > > file1 = Image.open("r10001t0.jpg") > file2 = Image.open("r10001t1.jpg") > > diff = ImageChops.difference(file1,file2) > > enhancer = ImageEnhance.Brightness(diff) This creates an ImageEnhance.Brightness instance. Then you need something like enhanced = enhancer.enhance(2.0) after which enhanced is the enhanced image that you should save. Kent From dkuhlman at rexx.com Sun Feb 10 18:28:05 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 10 Feb 2008 09:28:05 -0800 Subject: [Tutor] designing POOP In-Reply-To: <47AE566C.6040206@tds.net> References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net> Message-ID: <20080210172805.GA47675@cutter.rexx.com> On Sat, Feb 09, 2008 at 08:42:04PM -0500, Kent Johnson wrote: > Alan Gauld wrote: > > >> def values(self): > >> return (self.name, self.wealth, self.strenth) > >> > >> Or get rid of values() entirely and just refer to the attributes > > > > Nope, I don't like that as much since it encourages direct > > access. > > Maybe we just need to agree to disagree here. I don't see how returning > a tuple is better encapsulation than direct access to named attributes. Here is something relevant to this argument, although I'm not sure that I agree with it: "Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the 'property' built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in 'property'. That means that until you prove that you need anything more than a simple attribute access, don't write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well. "In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up front. In Python, this is silly, because you can start with a normal attribute and change your mind at any time, without affecting any clients of the class. So, don't write getters and setters." extracted from: http://dirtsimple.org/2004/12/python-is-not-java.html Maybe I'm "old school", but I still use getters and setters for access from outside the class and direct access from within methods in the class. - Dave [some good arguments snipped] -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Sun Feb 10 19:05:56 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Feb 2008 13:05:56 -0500 Subject: [Tutor] designing POOP In-Reply-To: <20080210172805.GA47675@cutter.rexx.com> References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net> <20080210172805.GA47675@cutter.rexx.com> Message-ID: <47AF3D04.3050805@tds.net> Dave Kuhlman wrote: > Here is something relevant to this argument, although I'm not sure > that I agree with it: > > "Getters and setters are evil. Evil, evil, I say! Python objects > are not Java beans. Do not write getters and setters. This is > what the 'property' built-in is for. And do not take that to > mean that you should write getters and setters, and then wrap > them in 'property'. That means that until you prove that you > need anything more than a simple attribute access, don't write > getters and setters. They are a waste of CPU time, but more > important, they are a waste of programmer time. Not just for > the people writing the code and tests, but for the people who > have to read and understand them as well. > > "In Java, you have to use getters and setters because using > public fields gives you no opportunity to go back and change > your mind later to using getters and setters. So in Java, you > might as well get the chore out of the way up front. In Python, > this is silly, because you can start with a normal attribute > and change your mind at any time, without affecting any clients > of the class. So, don't write getters and setters." > > extracted from: > http://dirtsimple.org/2004/12/python-is-not-java.html > > Maybe I'm "old school", but I still use getters and setters for > access from outside the class and direct access from within methods > in the class. I agree with the quote and I think it represents mainstream thought in the Python community. AFAIK there is no advantage in Python to using an explicit getter or setter. Alan doesn't like direct attribute access *or* getters and setters, IIUC. He wants all access to the attributes of a class instance to be through higher-level methods. I think it is a good goal and technique to look for higher-level methods, and to create classes that are amenable to same, but that on a practical level attribute access works and I don't avoid it on principle. Kent From norman at khine.net Sun Feb 10 19:55:59 2008 From: norman at khine.net (Norman Khine) Date: Sun, 10 Feb 2008 19:55:59 +0100 Subject: [Tutor] Change dictionary value depending on a conditional statement. Message-ID: <47AF48BF.2060901@khine.net> Hello, Is there a better way to do this: >>> list = [] >>> total = 0 >>> if total > 0: ... x = {'id': 'name', 'link': 'XX'} ... list.append(x) ... else: ... y = {'id': 'name', 'link': 'YY'} ... list.append(y) ... I would like to change the key 'link' value depending on the value of 'total' so for example if total == 2, then append x else y to the list. Thanks From keridee at jayco.net Sun Feb 10 21:01:28 2008 From: keridee at jayco.net (Tiger12506) Date: Sun, 10 Feb 2008 15:01:28 -0500 Subject: [Tutor] Change dictionary value depending on a conditionalstatement. References: <47AF48BF.2060901@khine.net> Message-ID: <000601c86c1f$c155f0c0$8afce004@jslaptop> >>> list = [] > >>> total = 0 > >>> if total > 0: > ... x = {'id': 'name', 'link': 'XX'} > ... list.append(x) > ... else: > ... y = {'id': 'name', 'link': 'YY'} > ... list.append(y) > ... > Yeah. list = [] x = {'id':'name'} if total > 0: x['link'] = 'XX' else: x['link'] = 'YY' list.append(x) From norman at khine.net Sun Feb 10 20:09:07 2008 From: norman at khine.net (Norman Khine) Date: Sun, 10 Feb 2008 20:09:07 +0100 Subject: [Tutor] Change dictionary value depending on a conditionalstatement. In-Reply-To: <000601c86c1f$c155f0c0$8afce004@jslaptop> References: <47AF48BF.2060901@khine.net> <000601c86c1f$c155f0c0$8afce004@jslaptop> Message-ID: <47AF4BD3.6000009@khine.net> thanks Tiger12506 wrote: > >>> list = [] >>>>> total = 0 >>>>> if total > 0: >> ... x = {'id': 'name', 'link': 'XX'} >> ... list.append(x) >> ... else: >> ... y = {'id': 'name', 'link': 'YY'} >> ... list.append(y) >> ... >> > > Yeah. > > list = [] > x = {'id':'name'} > if total > 0: > x['link'] = 'XX' > else: > x['link'] = 'YY' > list.append(x) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From washakie at gmail.com Sun Feb 10 23:41:24 2008 From: washakie at gmail.com (washakie) Date: Sun, 10 Feb 2008 14:41:24 -0800 (PST) Subject: [Tutor] permissions problem using subprocess Message-ID: <15402550.post@talk.nabble.com> Hello, I'm converting a perl script which calls shell scripts which call fortran routines into a python cgi that calls fortran directly (well, not yet using f2py), but using subprocess.popen. Here's my code: def run_cmd(cmd): """RUN A BASH CMD""" import subprocess as sub p = sub.Popen(['/bin/bash', '-c', cmd], stdout=sub.PIPE, stderr=sub.STDOUT) output = urllib.unquote(p.stdout.read()) return output newpath='/path/to/program/directory' cmd=os.path.join(newpath,'a.out') output=run_cmd(cmd); The code crashes, and I get this message: ? System Error: ? Permission denied ? OPEN(UNIT=10,... As output from the FORTRAN a.out program I know when I do the exact same thing with the shell script called from the perl script, I have no problems, so there is something strange with permissions... in both cases they are run as 'nobody'.. the directory is a temp directory, with permissions set (for debugging) even to 0777.. and still nothing! Why would python have a problem but not the shell script? Thanks! -- View this message in context: http://www.nabble.com/permissions-problem-using-subprocess-tp15402550p15402550.html Sent from the Python - tutor mailing list archive at Nabble.com. From washakie at gmail.com Mon Feb 11 00:03:20 2008 From: washakie at gmail.com (washakie) Date: Sun, 10 Feb 2008 15:03:20 -0800 (PST) Subject: [Tutor] permissions problem using subprocess In-Reply-To: <15402550.post@talk.nabble.com> References: <15402550.post@talk.nabble.com> Message-ID: <15402849.post@talk.nabble.com> Answering my own question here, but for the sake of it... adding: os.chdir(newpath) makes it all work... so we have: def run_cmd(cmd): """RUN A BASH CMD""" import subprocess as sub p = sub.Popen(['/bin/bash', '-c', cmd], stdout=sub.PIPE, stderr=sub.STDOUT) output = urllib.unquote(p.stdout.read()) return output newpath='/path/to/program/directory' os.chdir(newpath) cmd=os.path.join(newpath,'a.out') output=run_cmd(cmd); -- View this message in context: http://www.nabble.com/permissions-problem-using-subprocess-tp15402550p15402849.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Mon Feb 11 01:19:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2008 00:19:51 -0000 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com> <47AF3D04.3050805@tds.net> Message-ID: "Kent Johnson" wrote > Alan doesn't like direct attribute access *or* getters and setters, > IIUC. He wants all access to the attributes of a class instance to > be > through higher-level methods. I'd moderate that slightly. I really, really, don't like getters/setters. So, if you really need to get at an attribute then use direct access. However if a real responsibility of the class is to present it's overall state then I prefer to have a method to do that with state returned as a whole. For small numbers of attributes that could be a tuple or for longer sets of data as a dictionary. Over-use of direct access tends, in my experience, to lead to the temptation to move code that should be in the class (or a subclass) into client code. And it is avoidance of that temptation that is my main reason for providing a values() or state() type method, rather than using multiple attribute access. The secondary reason is that a class author should be free to change the internal data of a class provided he doesn't change the message interface, but allowing direct access greatly increases the risk that a change will break some users code. Particularly if the change involves removing an attribute or converting it to a derived value. Of course, as Kent pointed out if you add attributes then you have the question of whether to modify the state() method too, which also breaks client code - another reason state() methods should only return those attributes really needed by the clients!. They are less likely to change. > I think it is a good goal and technique to look for higher-level > methods, and to create classes that are amenable to same, but that > on a > practical level attribute access works and I don't avoid it on > principle. I prefer it to getter/setter but try to avoid it if possible. Pragmatism means that sometimes its useful or even necessary, but I always question why I'm doing it and whether I should instead be adding a method or subclassing. And to close, the reason I made it an issue in this thread is that this is about a beginner learning good (P)OOP practice so I thought it would be good to highlight that direct access carries risk and is frowned on from a purist OOP perspective Hopefully this side discussion has done that :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Feb 11 02:38:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 10 Feb 2008 20:38:11 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com> <47AF3D04.3050805@tds.net> Message-ID: <47AFA703.9070601@tds.net> Alan Gauld wrote: > Over-use of direct access tends, in my experience, to lead to > the temptation to move code that should be in the class (or a > subclass) into client code. And it is avoidance of that temptation > that is my main reason for providing a values() or state() type > method, rather than using multiple attribute access. I agree that it is easy to write code in a client, using attribute access, that really should be in the class as a method. I'm not sure how providing a value() method prevents that, other than making the client code more awkward. In either case the solution is to recognize the code smell (Feature Envy or Inappropriate Intimacy) and refactor to fix the problem. > The secondary reason is that a class author should be free > to change the internal data of a class provided he doesn't change > the message interface, but allowing direct access greatly increases > the risk that a change will break some users code. Particularly > if the change involves removing an attribute or converting it to a > derived value. That is the usual argument for getters and setters in Java and C++ (at least). It makes sense for those languages but it doesn't hold water in Python where a simple attribute can be changed to a property with whatever underlying functionality you like and no change in client code. From Nick.Treloar at education.nsw.gov.au Mon Feb 11 03:48:55 2008 From: Nick.Treloar at education.nsw.gov.au (Treloar, Nick) Date: Mon, 11 Feb 2008 13:48:55 +1100 Subject: [Tutor] lan with python Message-ID: <42E18E55C3B8C24FBE1633506D22EC1303833315@DET-MAIL-EVS03.DETISP.LOCAL> hey i was just wondering if any one could tell me if they know if you can make multi player games through lan with python heres the code i want to lan. just hash out the sound files #NiCk TrEloaR PrOgRaMiNg Co. #scissors paper rock #10/6/07 from Tkinter import* import pygame from random import choice class Application(Frame): def __init__(self,master): """Initalize Frame.""" Frame.__init__(self,master) self.grid() self.create_widget() self.comput_count = 0 self.user_count = 0 pygame.mixer.init() self.gun = pygame.mixer.Sound("shotgun1.wav") self.bang = pygame.mixer.Sound("explosion.wav") self.laugh = pygame.mixer.Sound("evil_laf.wav") self.music = pygame.mixer.Sound("Unholy_confessions.wav") self.music.play() self.music.set_volume(0.4) self.bang.set_volume(1.0) self.laugh.set_volume(1.0) #creating user indstructions def create_widget(self): root.configure(bg = "green") #create description label Label(self, text="scissors paper rock ", font = ("Bauhaus 93", 28, "bold", ) ).grid(row = 1,column = 0,sticky = W, columnspan = 4) #create the exit button self.exit_bttn = Button(self, text = "Exit", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.end ) self.exit_bttn.grid(row = 16, column = 3, sticky = W) #create the rock button self.rock_bttn = Button(self, text = "rock", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.rock) self.rock_bttn.grid(row = 3, column = 0, sticky = W) #create the scissors button self.scissors_bttn = Button(self, text = "scissors", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.scissors) self.scissors_bttn.grid(row = 5, column = 0, sticky = W) #create the paper button self.paper_bttn = Button(self, text = "paper", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.paper) self.paper_bttn.grid(row = 7, column = 0, sticky = W) # reset button self.reset_bttn = Button(self, text = "new game", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.reset) self.reset_bttn.grid(row = 16, column = 0, sticky = W) # dynamite self.reset_bttn = Button(self, text = "dynamite", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.dynamite) self.reset_bttn.grid(row = 8, column = 0, sticky = W) #dynamite lable Label(self, text="you can only use the dynamie button when you have a score of ten", font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 17,column = 0,sticky = S, columnspan = 8) # help button self.reset_bttn = Button(self, text = "help", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.help1) self.reset_bttn.grid(row = 16, column = 2, sticky = W) def rock(self): if self.user_count ==(20): self.victory() if self.comput_count ==(20): self.loss() value = "rock" computer_guess = choice(["scissors", "paper", "rock"]) if computer_guess == "rock": Label(self, text = "this is a draw!! ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) elif computer_guess == "paper": self.laugh.stop() self.laugh.play() Label(self, text = "you lose paper smothers rock ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.comput_count = (self.comput_count+1) else: self.laugh.stop() self.gun.play() Label(self, text = "you win rock smashes scissors ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.user_count = (self.user_count+1) self.ps = Label(self, text=("player score",self.user_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 10,column = 0,sticky = W) self.cs = Label(self, text=("computer score",self.comput_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 11,column = 0,sticky = W) def scissors(self): if self.user_count ==(20): self.victory() if self.comput_count ==(20): self.loss() value = "scissors" computer_guess = choice(["scissors", "paper", "rock"]) if computer_guess == "rock": self.laugh.stop() self.laugh.play() Label(self, text = "computer wins rock smashes scissors ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.comput_count = (self.comput_count+1) elif computer_guess == "paper": self.laugh.stop() self.gun.play() Label(self, text = "you win scissors cut paper ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.user_count = (self.user_count+1) else: Label(self, text = "this is a draw ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.ps = Label(self, text=("player score",self.user_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 10,column = 0,sticky = W) self.cs = Label(self, text=("computer score",self.comput_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 11,column = 0,sticky = W) def paper(self): if self.user_count ==(20): self.victory() if self.comput_count ==(20): self.loss() value = "paper" computer_guess = choice(["scissors", "paper", "rock"]) if computer_guess == "rock": self.laugh.stop() self.gun.play() Label(self, text = "you win paper smothers rock ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.user_count = (self.user_count+1) elif computer_guess == "paper": Label(self, text = "this is a draw ", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) else: self.laugh.stop() self.laugh.play() Label(self, text = "computer wins scissors cut paper ", fg = "Blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.comput_count = (self.comput_count+1) self.ps = Label(self, text=("player score",self.user_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 10,column = 0,sticky = W) self.cs = Label(self, text=("computer score",self.comput_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 11,column = 0,sticky = W) def reset(self): Label(self, text=(" "), font = ("Bauhaus 93", 16,) ).grid(row = 9,column = 0,sticky = W) self.user_count = 0 self.comput_count = 0 self.create_widget() self.music.stop() self.music.play() self.ps = Label(self, text="\t\t\t\t\t", font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 10,column = 0,sticky = W) self.cs = Label(self, text="\t\t\t\t\t", font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 11,column = 0,sticky = W) def dynamite(self): if self.user_count==(10): self.bang.play() Label(self, text = "you win dynamite kills every thing 5 times", fg = "blue", font = ("Bauhaus 93", 14, "bold"), ).grid(row = 9, column = 0, sticky = W) self.user_count = (self.user_count+5) self.ps = Label(self, text=("player score",self.user_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 10,column = 0,sticky = W) self.cs = Label(self, text=("computer score",self.comput_count), font = ("Bauhaus 93", 14, "bold", "underline", ) ).grid(row = 11,column = 0,sticky = W) def end(self): self.music.stop() root.destroy() def victory(self): Label(self, text = "you are victorious press new game to play again", fg = "blue", font = ("Bauhaus 93",28 , "bold"), ).grid(row = 1, column = 0, sticky = W, columnspan = 7) def loss(self): Label(self, text="you have been defeted press new game to start again", font = ("Bauhaus 93", 28, "bold", "underline", ) ).grid(row = 1,column = 0,sticky = W, columnspan = 7) def help1(self): global c1 c1 = Toplevel(root) c1.title("Child One") c1.transient(root) Label(c1,text="help scissors paper rock is based on a simple principal n\n rock beats scissors, \n scissors beats paper \n and paper beats rock").grid() # create done button self.done_bttn = Button(c1, text = "done", bg = "red", fg = "blue", font = ("Bauhaus 93", 12, "bold",), command = self.done) self.done_bttn.grid(row = 5, column = 0, sticky = W) c1.geometry("600x600") c1.configure(bg = "green") def done(self): c1.destroy() root=Tk() root.configure(bg = "green") root.title("scissors paper rock") root.geometry("950x550") app = Application(root) root.mainloop() This message is intended for the addressee named and may contain privileged information or confidential information or both. If you are not the intended recipient please delete it and notify the sender. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080211/7f024e1c/attachment-0001.htm From alan.gauld at btinternet.com Mon Feb 11 09:49:33 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2008 08:49:33 -0000 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com> <47AF3D04.3050805@tds.net> <47AFA703.9070601@tds.net> Message-ID: "Kent Johnson" wrote >> The secondary reason is that a class author should be free >> to change the internal data of a class provided he doesn't change >> the message interface, but allowing direct access greatly increases >> the risk that a change will break some users code. Particularly >> if the change involves removing an attribute or converting it to a >> derived value. > > That is the usual argument for getters and setters in Java and C++ > (at > least). It makes sense for those languages but it doesn't hold water > in > Python where a simple attribute can be changed to a property with > whatever underlying functionality you like and no change in client > code. While that's true, it does move the onus onto the class maintainer to develop backwards compatible properties that may no longer have any releavance to the internal method code. For example a circle shape which moves from using a centre+radius system to one which uses a bounding box, or vice versa. (Although it could be argued that regardless of the implementation the radius/centre should be properties of the circle) But more dangerous is a database access class that stores the tablename and then changes database schema such that two names are needed, or vice versa, and direct access to that kind of attribute would be a very bad smell indeed! Why does the client need the tablename?! I think we are in general agreement, albeit with different levels of trust/toleration of the technique. Direct access is preferred to getter/setter methods but is in turn less desirable that higher level methods where they exist. The only contention seems to be whether a values() type mutilple-return method is worth anything over direct access. My personal taste is that if I need the entire "official" state of an object I'd like a method to give it me in one piece, but others obviously may feel differently. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Mon Feb 11 11:31:59 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 11 Feb 2008 04:31:59 -0600 Subject: [Tutor] lan with python In-Reply-To: <42E18E55C3B8C24FBE1633506D22EC1303833315@DET-MAIL-EVS03.DETISP.LOCAL> References: <42E18E55C3B8C24FBE1633506D22EC1303833315@DET-MAIL-EVS03.DETISP.LOCAL> Message-ID: <47B0241F.3020501@gmail.com> Treloar, Nick wrote: > hey i was just wondering if any one could tell me if they know if you > can make multi player games through lan with python heres the code i > want to lan. > > just hash out the sound files > [snip lots of code] Hi Nick. Please don't send huge amounts of code inline in an e-mail. The chances of it coming out correctly are slim. If you must, use attachments. Yes, you can create multiplayer games through lan with python. There are many ways to go about this. You can use the Socket module to do low-level network programming, or you can use Twisted for a more robust solution. There are other alternatives as well. Might I ask why your code uses Pygame and TKinter together? Why didn't you just code the GUI of your game in Pygame? Did you use Pygame just because of the sound-playing abilities? (I don't have time to read it in detail.) Best wishes, -Luke From bhaaluu at gmail.com Mon Feb 11 13:29:07 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 11 Feb 2008 07:29:07 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net> <20080210172805.GA47675@cutter.rexx.com> <47AF3D04.3050805@tds.net> <47AFA703.9070601@tds.net> Message-ID: On Feb 11, 2008 3:49 AM, Alan Gauld wrote: > > I think we are in general agreement, albeit with different levels of > trust/toleration of the technique. Direct access is preferred to > getter/setter methods but is in turn less desirable that higher > level methods where they exist. The only contention seems to be > whether a values() type mutilple-return method is worth anything over > direct access. My personal taste is that if I need the entire > "official" > state of an object I'd like a method to give it me in one piece, but > others obviously may feel differently. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld States, getters-setters, direct access....... I'm still in toilet-training here/ 8^D Can you provide some simple examples that illustrate exactly what and why there is any contention at all? TIA -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From bgailer at alum.rpi.edu Mon Feb 11 19:05:38 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Mon, 11 Feb 2008 13:05:38 -0500 Subject: [Tutor] Change dictionary value depending on a conditional statement. In-Reply-To: <47AF48BF.2060901@khine.net> References: <47AF48BF.2060901@khine.net> Message-ID: <47B08E72.7000508@alum.rpi.edu> Norman Khine wrote: > Hello, > Is there a better way to do this: > > >>> list = [] > >>> total = 0 > >>> if total > 0: > ... x = {'id': 'name', 'link': 'XX'} > ... list.append(x) > ... else: > ... y = {'id': 'name', 'link': 'YY'} > ... list.append(y) > ... > > I would like to change the key 'link' value depending on the value of > 'total' so for example if total == 2, then append x else y to the list. > The terse version: list.append({'id': 'name', 'link': ('XX','YY')[total > 0]}) -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Mon Feb 11 20:00:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Feb 2008 14:00:48 -0500 Subject: [Tutor] Change dictionary value depending on a conditional statement. In-Reply-To: <47B08E72.7000508@alum.rpi.edu> References: <47AF48BF.2060901@khine.net> <47B08E72.7000508@alum.rpi.edu> Message-ID: <47B09B60.5010006@tds.net> bob gailer wrote: > The terse version: > > list.append({'id': 'name', 'link': ('XX','YY')[total > 0]}) I think you have it backwards: In [1]: total=0 In [2]: ('XX','YY')[total > 0] Out[2]: 'XX' In [3]: total=1 In [4]: ('XX','YY')[total > 0] Out[4]: 'YY' Try list.append({'id': 'name', 'link': ('YY','XX')[total > 0]}) Or, in Python 2.5, list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')}) Kent From tucalipe at gmail.com Mon Feb 11 19:46:25 2008 From: tucalipe at gmail.com (Artur Sousa) Date: Mon, 11 Feb 2008 16:46:25 -0200 Subject: [Tutor] Beginner in need In-Reply-To: <29c144020802111044j7a95108cu7d70fe2a82408245@mail.gmail.com> References: <29c144020802111044j7a95108cu7d70fe2a82408245@mail.gmail.com> Message-ID: <29c144020802111046w7dba9ff7qb10b499caf4cf9fb@mail.gmail.com> Sorry... forgot to add the code... 2008/2/11, Artur Sousa : > > > Hi. Just started on programming, as well on Python. I'm having a little > problem: > What's the difference between: > for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # loop fell through without finding a factor print n, 'is a prime number' and for a in range(2, 10): for n in range(2, a): if a % n ==0: print a, 'equals', n, '*', a/n break else: print a, 'is a prime number' each of the first spaces should be a "Tab". -- Sorry for any inconvenience... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080211/d52741b9/attachment.htm From tucalipe at gmail.com Mon Feb 11 19:44:18 2008 From: tucalipe at gmail.com (Artur Sousa) Date: Mon, 11 Feb 2008 16:44:18 -0200 Subject: [Tutor] Beginner in need Message-ID: <29c144020802111044j7a95108cu7d70fe2a82408245@mail.gmail.com> Hi. Just started on programming, as well on Python. I'm having a little problem: What's the difference between: > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080211/2b4f0592/attachment.htm From kent37 at tds.net Mon Feb 11 20:11:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 11 Feb 2008 14:11:36 -0500 Subject: [Tutor] Beginner in need In-Reply-To: <29c144020802111046w7dba9ff7qb10b499caf4cf9fb@mail.gmail.com> References: <29c144020802111044j7a95108cu7d70fe2a82408245@mail.gmail.com> <29c144020802111046w7dba9ff7qb10b499caf4cf9fb@mail.gmail.com> Message-ID: <47B09DE8.1020205@tds.net> Artur Sousa wrote: > Sorry... forgot to add the code... > > 2008/2/11, Artur Sousa >: > > > Hi. Just started on programming, as well on Python. I'm having a > little problem: It helps if you describe the problem. If you are getting an error message, copy/paste the entire error message, including the traceback, into your email. > What's the difference between: > > > for n in range(2, 10): > for x in range(2, n): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > # loop fell through without finding a factor > print n, 'is a prime number' > > and > > > for a in range(2, 10): > for n in range(2, a): > if a % n ==0: The above line is missing an indent, it needs to be indented more than the 'for' line. Kent From steve at alchemy.com Mon Feb 11 20:22:29 2008 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 11 Feb 2008 12:22:29 -0700 Subject: [Tutor] Change dictionary value depending on a conditional statement. In-Reply-To: <47B09B60.5010006@tds.net> References: <47AF48BF.2060901@khine.net> <47B08E72.7000508@alum.rpi.edu> <47B09B60.5010006@tds.net> Message-ID: <47B0A075.20403@alchemy.com> Kent Johnson wrote: > Try > list.append({'id': 'name', 'link': ('YY','XX')[total > 0]}) I'd caution against that, though. It's clever and cute, sure, but the meaning of it is obfuscated enough to be unpythonic because [total > 0] as a subscript doesn't mean anything unless you know you're taking advantage of an implementation detail that booleans are 0 for false and 1 for true. No matter how reliable that fact may be, I don't think that value should be stuck into a numeric context like that. > Or, in Python 2.5, > list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')}) This is much more clear, and would IMHO be fine. From bgailer at alum.rpi.edu Mon Feb 11 21:30:24 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Mon, 11 Feb 2008 15:30:24 -0500 Subject: [Tutor] [Python-Help] help@python.org In-Reply-To: <29c144020802111051m4d5e6dbbtfc346aa37db03af8@mail.gmail.com> References: <29c144020802111051m4d5e6dbbtfc346aa37db03af8@mail.gmail.com> Message-ID: <47B0B060.1020108@alum.rpi.edu> Artur Sousa wrote: > What's the difference between: > > > for a in range(2, 10): > for n in range(2, a): > if a % n == 0: > print a, 'equals', n, '*', a/n > break > else: > print a, 'is a prime number' > > > and > > > for a in range(2, 10): > for n in range(2, a): > if a % n ==0: > print a, 'equals', n, '*', a/n > break > else: > print a, 'is a prime number' > > Most of us monitor tutor and help - so initially pleas just post to one. Tutor is probably the best in this case. The obvious difference is the placement of the else statement. In the first else pairs with for and is invoked when no break happens. In the second else pairs with if and is invoked each time the divisor test fails. If that does not help you decide which is correct (it should) then run the 2 programs examine the results and that should reveal which gives you what you want. -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Mon Feb 11 21:37:32 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2008 20:37:32 -0000 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net> <20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net> <47AFA703.9070601@tds.net> Message-ID: "bhaaluu" wrote > States, getters-setters, direct access....... > I'm still in toilet-training here/ 8^D > Can you provide some simple examples that > illustrate exactly what and why there is any > contention at all? I'll try. State is just a bit of jargon to describe the combined values of an objects attributes. Here is an example: class Counter(object): def __init__(self, initial=0, delta=1): self.value = initial self.delta = delta def inc(self) self.value += delta return self.value def state(self): return (self.value,self.delta) a = Counter() b = Counter(1) c = Counter(0,5) print a.state, b.state, c.state So all 3 objects have different combinations of values so they have different states. The state determines the value returned by the objects inc method x = a.inc() # x-> 1 y = b.inc() # y -> 2 z = c.inc() # z -> 5 This is fine and dandy but what if we want to find out the current value of a.value without calling inc? Thats where hetter/setter/direct access comes into the picture. In Java and some other languages the idiomatic thing to do is provide methods prefixed with get/set for each attribute class Counter(object): def __init__(self, initial=0, delta=1):... def inc(self)... def state(self):... def getDelta(self): return self.delta def getValue(self): return self.value def setValue(self, val): self.value = val def setDelta(self, val): self.delta = val Now this is a lot of typing! It also isn't necessary in Python because Python allows you to access the attributes diectly - direct access. Like so: a.delta = 42 a.inc() print a.value This gives rise to a debate between the OOP purists who say that you should only access the internals of an object via a method(get/set) and the pragmatists who say its OK to use direct access. And old school OOPers like me say it would be better if you didn't need to use either since you should define the object in terms of higher level abstractions/methods. Now, with my pragmatic hat on I see no point whatsoever in writing reams of get/set code just for the salke of it, so if you must bypass the abstract methods use direct access. But what if you want all of the attributes - to print state say? Thats where the question of direct access versus a state() method comes in. My preference is to provide a single method that returns the values that you need (and in many cases thats less than all of the attributes!) rather than allowing, or even encouraging, direct access. The danger with direct access is that we use it not only for reading but also for directly modifying the attributes - and that is a bad OOP habit! (Remember: Objects do it to themselves!) For example we want to decrement a counter instead of incrementing. we could do it directly: c.value = c.value -5 But it would be better to do it in an OOP way. So the final issue (and Kent will no doubt have more to add from his perspective!) is if we do want to modify the Counter how do we do it (assuming we don't own the original class or too many other projects already use it to risk breaking them)? Well, the pure OOP way is by sub classing. Thus if we want a counter with a dec() method as well as an inc(), we can create one: class UpDownCounter(Counter): def dec(self): self.value -= self.delta return self.value Now if we make c an instance of UpDownCounter we can do: c = UpDownCounter(0,5) c.inc() print c.state() c.dec() print c.state() And this has the advantage that there is no impact on the other objects derived from the initial Counter class. Note that as well as adding methods you can also modify, or change entirely, the existing methods, that's called "overriding a method" and is probably left for later! I hope that makes sense, its about the simplest example I could come up with. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Tue Feb 12 05:08:10 2008 From: keridee at jayco.net (Tiger12506) Date: Mon, 11 Feb 2008 23:08:10 -0500 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> Message-ID: <001401c86d2d$06354750$97fce004@jslaptop> > "bhaaluu" wrote > >> States, getters-setters, direct access....... >> I'm still in toilet-training here/ 8^D >> Can you provide some simple examples that >> illustrate exactly what and why there is any >> contention at all? One clear example I can think of that shows the views is this: Imagine you have a video game. You model it with a class. class VideoGame: pass But this video game will up your score if you hit this a particular button, which means that it needs to a) keep track of its score b) know what to do when the button is pushed class VideoGame: def __init__(self): self.score = 0 def buttonpush(self): self.score += 1 This is all fine and dandy, but the video game is pretty worthless unless it can show us what the score is. There are two ways to go about this. A) Give the video game a display which it updates, or B) Tear open the case of the video game and look at the actual gears that increment the score to read it. (imagine it's an old, old game - work with me here!) So, to print, you can... vg = VideoGame() howmany = rand.randint(0,100) for i in range(howmany): vg.buttonpush() print vg.score #Tear open the case (hope you have a screwdriver) OR class VideoGame(): def __init__(self): self.score = 0 def updatedisp(): print self.score def buttonpush(): self.score += 1 self.updatedisp() vg = VideoGame() howmany = rand.randint(0,100) for i in range(howmany): vg.buttonpush() #Let the videogame display your score however it wishes The second way is preferable for many reasons... A) The game designer decides to change the display, you don't have to change any code that uses the class B) Clearly, tearing open a videogame is pretty low-level from an object perspective. This is what Alan is saying with OOP purism. Now. Alan's suggestion to have a state method is like... having a sticker on the side of the video game that constantly changes to show the internal state of the machine. (yeah yeah, stickers change, sure...) Anyway, This is very nice from a debugging standpoint, where you find out that the game does something incredibly weird, (like after 2**16 buttonpushes it jumps to negative numbers), so that you can watch exactly what happens inside the machine without tearing it apart. There are a few drawbacks though. As soon as you change the internal mechanism, the sticker is at a loss because it can't tell you the state anymore! So every time you change the internals, you have to change the sticker on the outside to reflect that change. This is what Kent is trying to say here about the lack of advantage to a state method. However, the advantage of pure OOP here is that if the videogame model is designed correctly, never would you have to change the actual display if you changed how the score was calculated. Well, I don't know if this whole email was of use, but it makes the crux of the argument make sense to me. From wesbrooks at gmail.com Tue Feb 12 09:36:14 2008 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 12 Feb 2008 08:36:14 +0000 Subject: [Tutor] Closing file objects when object is garbage collected? Message-ID: Dear Python Users, How do I ensure that when an object is deleted by the garbage collector that the file objects contained within the object are closed, or collected by the garbage collector? I'd like to avoid having to read the whole file object into a string and close the file immediately because the files can potentially be large, and I'm dealing with many files at a time. I'm having issues when I test my software on XP, but not Linux. When I run the progam it fails after running for a while but not at exactly the same point each time. It fails in one of two ways, the user interface either completely disappears, or gives a OS error message unhanded exception error. Thanks in advance of any help, Wesley Brooks. From alan.gauld at btinternet.com Tue Feb 12 10:03:12 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Feb 2008 09:03:12 -0000 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> Message-ID: "Tiger12506" wrote > Well, I don't know if this whole email was of use, but it makes the > crux of > the argument make sense to me. I thought it was pretty clear. And it highlights that the choices are like anything else in the world of engineering - a compromise. And the best compromise in any given situation might be different from the last time. Engineering is not an exact science. Alan G From jjhartley at gmail.com Tue Feb 12 10:24:23 2008 From: jjhartley at gmail.com (James Hartley) Date: Tue, 12 Feb 2008 01:24:23 -0800 Subject: [Tutor] opening a pipe? Message-ID: A Perl script can easily serve as a filter within a pipe as seen in the following: use strict; use warnings; open(IN, 'cat hello.txt |') or die 'unable to open file'; while () { print; } close(IN); Can I do the same within Python? Thanks. Jim From norman at khine.net Tue Feb 12 10:03:57 2008 From: norman at khine.net (Norman Khine) Date: Tue, 12 Feb 2008 10:03:57 +0100 Subject: [Tutor] Change dictionary value depending on a conditional statement. In-Reply-To: <47B0A075.20403@alchemy.com> References: <47AF48BF.2060901@khine.net> <47B08E72.7000508@alum.rpi.edu> <47B09B60.5010006@tds.net> <47B0A075.20403@alchemy.com> Message-ID: <47B160FD.1020106@khine.net> Thank you all, very nice. Steve Willoughby wrote: > Kent Johnson wrote: >> Try >> list.append({'id': 'name', 'link': ('YY','XX')[total > 0]}) > > I'd caution against that, though. It's clever and cute, sure, but the > meaning of it is obfuscated enough to be unpythonic because [total > 0] > as a subscript doesn't mean anything unless you know you're taking > advantage of an implementation detail that booleans are 0 for false and > 1 for true. No matter how reliable that fact may be, I don't think that > value should be stuck into a numeric context like that. > >> Or, in Python 2.5, >> list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')}) > > This is much more clear, and would IMHO be fine. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ricaraoz at gmail.com Tue Feb 12 12:34:06 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 12 Feb 2008 08:34:06 -0300 Subject: [Tutor] designing POOP In-Reply-To: <001401c86d2d$06354750$97fce004@jslaptop> References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> Message-ID: <47B1842E.4010400@bigfoot.com> Tiger12506 wrote: > This is all fine and dandy, but the video game is pretty worthless unless it > can show us what the score is. There are two ways to go about this. A) Give > the video game a display which it updates, or B) Tear open the case of the > video game and look at the actual gears that increment the score to read it. Mmmm... that's not really so. If the object's creator meant the score to be read that way then it would not be 'Tear open the case' but just 'read the score'. The language with which we describe an action does matter. > > vg = VideoGame() > howmany = rand.randint(0,100) > for i in range(howmany): > vg.buttonpush() > print vg.score #Tear open the case (hope you have a screwdriver) > > OR > > class VideoGame(): > def __init__(self): > self.score = 0 > def updatedisp(): > print self.score > def buttonpush(): > self.score += 1 > self.updatedisp() > > vg = VideoGame() > howmany = rand.randint(0,100) > for i in range(howmany): > vg.buttonpush() #Let the videogame display your score > however it wishes > > The second way is preferable for many reasons... > A) The game designer decides to change the display, you don't have to change > any code that uses the class > B) Clearly, tearing open a videogame is pretty low-level from an object > perspective. This is what Alan is saying with OOP purism. > Did we think about REUSABILITY? What if in some other application I want to USE the score, not just display it? What if I want to display it in a different form (multiplying it by 100)? Then you are back to our original options : either check the score directly, define a getter, or a .... 'stater'(?) which returns the state of the object (in this case it would be a tuple with only the score in it, a getter in disguise if you ask me). AFAIK the python way is to just check the score, if later the object's author changes something he has ways built in in the language to keep the interface unchanged (yes, I think the score would be part of the interface, otherwise it would be _score). From ricaraoz at gmail.com Tue Feb 12 13:19:50 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 12 Feb 2008 09:19:50 -0300 Subject: [Tutor] designing POOP In-Reply-To: <001401c86d2d$06354750$97fce004@jslaptop> References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> Message-ID: <47B18EE6.7010603@bigfoot.com> Tiger12506 wrote: > This is all fine and dandy, but the video game is pretty worthless unless it > can show us what the score is. There are two ways to go about this. A) Give > the video game a display which it updates, or B) Tear open the case of the > video game and look at the actual gears that increment the score to read it. Mmmm... that's not really so. If the object's creator meant the score to be read that way then it would not be 'Tear open the case' but just 'read the score'. The language with which we describe an action does matter. > > vg = VideoGame() > howmany = rand.randint(0,100) > for i in range(howmany): > vg.buttonpush() > print vg.score #Tear open the case (hope you have a screwdriver) > > OR > > class VideoGame(): > def __init__(self): > self.score = 0 > def updatedisp(): > print self.score > def buttonpush(): > self.score += 1 > self.updatedisp() > > vg = VideoGame() > howmany = rand.randint(0,100) > for i in range(howmany): > vg.buttonpush() #Let the videogame display your score > however it wishes > > The second way is preferable for many reasons... > A) The game designer decides to change the display, you don't have to change > any code that uses the class > B) Clearly, tearing open a videogame is pretty low-level from an object > perspective. This is what Alan is saying with OOP purism. > Did we think about REUSABILITY? What if in some other application I want to USE the score, not just display it? What if I want to display it in a different form (multiplying it by 100)? Then you are back to our original options : either check the score directly, define a getter, or a .... 'stater'(?) which returns the state of the object (in this case it would be a tuple with only the score in it, a getter in disguise if you ask me). AFAIK the python way is to just check the score, if later the object's author changes something he has ways built in in the language to keep the interface unchanged (yes, I think the score would be part of the interface, otherwise it would be _score). From bhaaluu at gmail.com Tue Feb 12 14:23:40 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 12 Feb 2008 08:23:40 -0500 Subject: [Tutor] designing POOP In-Reply-To: <47B18EE6.7010603@bigfoot.com> References: <47ADF7DD.9090209@tds.net> <20080210172805.GA47675@cutter.rexx.com> <47AF3D04.3050805@tds.net> <47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B18EE6.7010603@bigfoot.com> Message-ID: On Feb 12, 2008 7:19 AM, Ricardo Ar?oz wrote: > > Did we think about REUSABILITY? What if in some other application I want > to USE the score, not just display it? What if I want to display it in a > different form (multiplying it by 100)? Then you are back to our > original options : either check the score directly, define a getter, or > a .... 'stater'(?) which returns the state of the object (in this case > it would be a tuple with only the score in it, a getter in disguise if > you ask me). AFAIK the python way is to just check the score, if later > the object's author changes something he has ways built in in the > language to keep the interface unchanged (yes, I think the score would > be part of the interface, otherwise it would be _score). > Everything in this discussion seems relevant to designing Python OOP. (Python is not java, not javascript, not c++, not visual whatever etc.) We can see from this that Python does it the Python way. The Java examples are pretty much wasted on me. (I don't know anything about Java at all.) The POOP tutorials rarely get into design considerations. They introduce the mechanics of making a program, make a sample program, and keep on trucking. I'm trying to learn how to design a program with Python. So far, two beginner techniques have been shown: the noun/verb/adjective method (Alan), and the TDD (Test Driven Design) method (Kent). Of the two, the noun/verb/adjective method seems more approachable (to me). I think that once I have some experience doing that, then the TDD method may have something to offer. Baby steps first. Walk before running. 8^D Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From bgailer at alum.rpi.edu Tue Feb 12 14:46:10 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 12 Feb 2008 08:46:10 -0500 Subject: [Tutor] Closing file objects when object is garbage collected? In-Reply-To: References: Message-ID: <47B1A322.1060309@alum.rpi.edu> Wesley Brooks wrote: > Dear Python Users, > > How do I ensure that when an object is deleted by the garbage > collector that the file objects contained within the object are > closed, or collected by the garbage collector? > When there are no more references to a file object the file is closed. This happens in your case when the containing object is deleted. All of this happens before garbage collection. > I'd like to avoid having to read the whole file object To be precise you should say "avoid having to read the whole file". The file object is just the interface to the file contents. > into a string > and close the file immediately because the files can potentially be > large, and I'm dealing with many files at a time. > > -- Bob Gailer 919-636-4239 Chapel Hill, NC From thomas.pani at gmail.com Tue Feb 12 15:03:42 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Tue, 12 Feb 2008 15:03:42 +0100 Subject: [Tutor] opening a pipe? In-Reply-To: References: Message-ID: <47B1A73E.80009@gmail.com> The subprocess module is what you're looking for. Your example would look like --------------------%<-------------------- import subprocess p = subprocess.Popen('cat hi.txt', shell=True, stdout=subprocess.PIPE) for line in p.stdout: print line --------------------%<-------------------- I assume you know that you can just open a file for reading instead of piping cat. thomas James Hartley wrote: > A Perl script can easily serve as a filter within a pipe as seen in > the following: > > use strict; > use warnings; > > open(IN, 'cat hello.txt |') or die 'unable to open file'; > while () { > print; > } > close(IN); > > Can I do the same within Python? Thanks. > > Jim > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From narayan at qmaxtest.com Tue Feb 12 08:01:23 2008 From: narayan at qmaxtest.com (Narain) Date: Tue, 12 Feb 2008 12:31:23 +0530 Subject: [Tutor] How to Set python path Message-ID: <00af01c86d45$17b02550$4500a8c0@softwarebuild> Hi, Iam facing problems in Environment variables for python path as follows >Iam using Windows XP operating system in system variable iam appending two path,in this case only first path is working but second path is not working,if i remove first path means second path is working ,two paths are seperated by semicolon but two paths are same only slight diffrences.how to work with both paths????? kindly give Solution for this problem.. regards Narayana Moorthy.V -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080212/82921ebc/attachment.htm From mlangford.cs03 at gtalumni.org Tue Feb 12 16:44:27 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 12 Feb 2008 10:44:27 -0500 Subject: [Tutor] How to Set python path In-Reply-To: <00af01c86d45$17b02550$4500a8c0@softwarebuild> References: <00af01c86d45$17b02550$4500a8c0@softwarebuild> Message-ID: <82b4f5810802120744h6245e480i8887c329baf7f35e@mail.gmail.com> Show us both path statements, then we might be able to fix it. --Michael On Feb 12, 2008 2:01 AM, Narain wrote: > > > Hi, > > Iam facing problems in Environment variables for python path as > follows > >Iam using Windows XP operating system in system variable iam > appending two path,in this case only first path is working but second path > is not working,if > i remove first path means second path is working ,two paths are seperated > by semicolon but two paths are same only slight diffrences.how to work with > both paths????? kindly give Solution for this problem.. > > > > regards > Narayana Moorthy.V > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From mlangford.cs03 at gtalumni.org Tue Feb 12 17:19:04 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 12 Feb 2008 11:19:04 -0500 Subject: [Tutor] Closing file objects when object is garbage collected? In-Reply-To: References: Message-ID: <82b4f5810802120819k402e5cf3o2b8fdf8bd939e679@mail.gmail.com> > How do I ensure that when an object is deleted by the garbage > collector that the file objects contained within the object are > closed, or collected by the garbage collector? __del__ is called after the reference count gets to zero for an object. You can explicitly call close on the file there if you're worried you have a dangling reference to the file somewhere. I'd use the class below first to help. If you'd like to see when if your files are being closed, a class such as this may help your debugging. Use it in the place of your file or open call in the class that is at issue: class LoudFile(file): """Shows when a file is closed""" def close(self): file.close(self) if self.closed: print "%s is now closed" % self.name def __del__(self): """shows when a file is garbage collected""" print "%s fileobject is being deleted" % self.name > I'm having issues when I test my software on XP, but not Linux. When I > run the progam it fails after running for a while but not at exactly > the same point each time. It fails in one of two ways, the user > interface either completely disappears, or gives a OS error message > unhanded exception error. Run the program from the pdb debugger (it comes installed with python). Here is an excellent introduction to it: http://www.onlamp.com/pub/a/python/2005/09/01/debugger.html It will allow you to poke around at the innards of your program right as it dies. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From ricaraoz at gmail.com Tue Feb 12 19:17:47 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 12 Feb 2008 15:17:47 -0300 Subject: [Tutor] Mail revisited Message-ID: <47B1E2CB.6020407@bigfoot.com> Ok, so I've started the path to put a GUI to the "MandarMails.py" program. For starters I've included a progress bar. Any enhancements you may suggest will be appreciated. Note: not tested yet ###################### ### MandarMails.py ### ###################### #!/usr/bin/env python import time import smtplib import email import ConfigParser import logging class Mensaje(object) : def __init__(self) : cfg = ConfigParser.ConfigParser() try : cfg.readfp(open('config.cfg')) except Exception, e : logging.error('No pude leer "config.cfg" : %s', e.strerror) self.direcciones = cfg.get('Archivos', 'Direcciones') self.excluidas = cfg.get('Archivos', 'Excluir') self.cuantos = cfg.getint('Correo', 'MailsPorVez') self.intervalo = cfg.getint('Correo', 'IntervaloEnSegundos') try : htmlFile = open(cfg.get('Archivos', 'Mensaje')) htmlMessage = htmlFile.read() htmlFile.close() except Exception, e : logging.error('No pude leer "%s" : %s', cfg.get('Archivos', 'Mensaje'), e.strerror) self.messg = email.MIMEMultipart.MIMEMultipart() self.messg['From'] = cfg.get('Encabezados', 'De') self.messg['To'] = '' self.messg['Subject'] = cfg.get('Encabezados', 'Encabezado') self.messg['Reply-To'] = cfg.get('Encabezados', 'ResponderA') self.messg.preamble = 'This is a multi-part message in MIME format' self.messg.attach(email.MIMEText.MIMEText(htmlMessage, 'html')) self.servidor = cfg.get('Correo', 'Servidor') self.usuario = cfg.get('Correo', 'Usuario') self.contra = cfg.get('Correo', 'Contrasenia') class Correo(object) : def __init__(self, mensaje) : self.mensaje = mensaje self.conexion = smtplib.SMTP() def connect(self) : try : self.conexion.connect(self.mensaje.servidor) self.conexion.set_debuglevel(False) self.conexion.ehlo() self.conexion.starttls() self.conexion.ehlo() self.conexion.login(self.mensaje.usuario, self.mensaje.contra) return True except : logging.error('No me pude conectar al Servidor') return False def disconnect(self) : self.conexion.close() def enviar(self, addr) : self.mensaje.messg.replace_header('To', addr) try : self.conexion.sendmail(self.mensaje.messg['From'], self.mensaje.messg['To'], self.mensaje.messg.as_string()) logging.info('Enviado a : %s', self.mensaje.messg['To']) except smtplib.SMTPRecipientsRefused : logging.error('El destinatario fue rechazado por el servidor') except smtplib.SMTPHeloError : logging.error('El servidor no respondio apropiadamente') except smtplib.SMTPSenderRefused : logging.error('El From: fue rechazado por el servidor') except smtplib.SMTPDataError : logging.error('El servidor respondio con un error desconocido') class Envio(object) : def __init__(self, mensaje) : self._mensaje = mensaje self.totAEnviar = 0 self.enviados = 0 self._mails = [] self._miCorreo = None self._timer = 0 try : try : fIncl = open(self._mensaje.direcciones) except Exception, e : logging.error('Error!!! No pude abrir "%s" : %s', self._mensaje.direcciones, e.strerror) raise try : fExcl = open(self._mensaje.excluidas) except Exception, e : logging.error('No pude abrir "%s" : %s', self._mensaje.excluidas, e.strerror) fIncl.close() raise except : pass else : self._mails = enumerate(set(addr.strip() for addr in fIncl) - set(excl.strip() for excl in fExcl)) fIncl.close() fExcl.close() self.TotAEnviar = len(self._mails) self._miCorreo = Correo(self._mensaje) def enviar() : dormir = self._mensaje.intervalo - (time.clock() - self._timer) if dormir > 0 : time.sleep(dormir) self._timer = time.clock() if not self._miCorreo.connect() : logging.info('Terminando') return False for nro, addr in self._mails[:self._mensaje.cuantos] : self._miCorreo.enviar(addr) self._miCorreo.disconnect() self._mails = self._mails[self._mensaje.cuantos:] return (len(self._mails) > 0) if __name__ == '__main__' : from Tkinter import * from ProgressBar import ProgressBar logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename=time.strftime('informe-%Y-%m-%d-%H-%M-%S.log'), filemode='w') miEnvio = Envio(Mensaje()) root = Tk() labelfont = ('times', 12, 'bold') titulo = Label(root, text='Progreso del Envio') titulo.config(font=labelfont) titulo.config(height=1, width=20) titulo.pack(expand=YES, fill=X) myBar = ProgressBar(root, width=200, max=miEnvio.totAEnviar) myBar.pack() while miEnvio.enviar() : myBar.updateProgress(miEnvio.enviados) ###################### ### ProgressBar.py ### ###################### from Tkinter import * import time class ProgressBar(Frame) : def __init__(self, parent=None, orientation="horizontal", min=0, max=100, width=100, height=18, doLabel=1, relief="sunken", fillColor="blue", background="gray", labelColor="yellow", labelFont="Verdana", labelText="", labelFormat="%d%%", value=0, bd=2) : self.parent = parent self.orientation = orientation self.min = min self.max = max self.width = width self.height = height self.doLabel = doLabel self.fillColor = fillColor self.labelFont = labelFont self.labelColor = labelColor self.background = background self.labelText = labelText self.labelFormat = labelFormat self.value = value Frame.__init__(self, parent, relief=relief, bd=bd) self.pack() self.canvas=Canvas(self, height=height, width=width, bd=0, highlightthickness=0, background=background) self.scale=self.canvas.create_rectangle(0, 0, width, height, fill=fillColor) self.label=self.canvas.create_text(self.canvas.winfo_reqwidth() / 2, height / 2, text=labelText, anchor="c", fill=labelColor, font=self.labelFont) self.update() self.canvas.pack(side='top', fill='x', expand='no') def updateProgress(self, newValue, newMax=None): if newMax: self.max = newMax self.value = newValue self.update() def update(self): cnvs = self.canvas # Trim the values to be between min and max value=self.value if value > self.max: value = self.max if value < self.min: value = self.min # Adjust the rectangle if self.orientation == "horizontal": cnvs.coords(self.scale, 0, 0, float(value) / self.max * self.width, self.height) else: cnvs.coords(self.scale, 0, self.height - (float(value) / self.max*self.height), self.width, self.height) # Now update the colors cnvs.itemconfig(self.scale, fill=self.fillColor) cnvs.itemconfig(self.label, fill=self.labelColor) # And update the label if self.doLabel: if value: if value >= 0: pvalue = int((float(value) / float(self.max)) * 100.0) else: pvalue = 0 cnvs.itemconfig(self.label, text=self.labelFormat % pvalue) else: cnvs.itemconfig(self.label, text='') else: cnvs.itemconfig(self.label, text=self.labelFormat % self.labelText) cnvs.update_idletasks() if __name__ == '__main__' : root = Tk() labelfont = ('times', 12, 'bold') titulo = Label(root, text='Progreso') titulo.config(font=labelfont) titulo.config(height=1, width=10) titulo.pack(expand=YES, fill=X) myBar = ProgressBar(root, width=200) myBar.pack() for i in range(100) : myBar.updateProgress(i) time.sleep(0.1) root.quit() From org.python.tutor at pooryorick.com Tue Feb 12 19:48:45 2008 From: org.python.tutor at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Tue, 12 Feb 2008 18:48:45 +0000 Subject: [Tutor] opening a pipe? Message-ID: <20080212184845.2289.qmail@station198.com> > From: James Hartley <> > Subject: [Tutor] opening a pipe? > Sent: 2008-02-12 09:24 > > A Perl script can easily serve as a filter within a pipe as seen in > the following: > > use strict; > use warnings; > > open(IN, 'cat hello.txt |') or die 'unable to open file'; > while () { > print; > } > close(IN); > > Can I do the same within Python? Thanks. > os.popen can do this. The 'commands' module provides even more flexibility. If you are on a posix platform and want to avoid shell interpretation, you could also try my pipeline package at http://pypi.python.org/pypi/pipeline.py/0.1 -- Yorick "Our servers are using too much electricity. We need to virtualize." From keridee at jayco.net Wed Feb 13 03:37:47 2008 From: keridee at jayco.net (Tiger12506) Date: Tue, 12 Feb 2008 21:37:47 -0500 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B1842E.4010400@bigfoot.com> Message-ID: <003d01c86de9$cd725990$58fce004@jslaptop> >> This is all fine and dandy, but the video game is pretty worthless unless >> it >> can show us what the score is. There are two ways to go about this. A) >> Give >> the video game a display which it updates, or B) Tear open the case of >> the >> video game and look at the actual gears that increment the score to read >> it. > > Mmmm... that's not really so. If the object's creator meant the score to > be read that way then it would not be 'Tear open the case' but just > 'read the score'. The language with which we describe an action does > matter. You just invalidated your own argument. Sure, the object's creator may have designated that "the way to read the score is to take these screws out and measure the angle of these gears in ratio to those gears" but what are you really doing here? ...(you are thinking procedurally)... You are really just overlooking the fact that the object is being *read*, meaning that the *object itself returns a representation*. This tearing apart should be abstracted with a method. The meer fact that you say 'tearing open the case' as just another way to say 'read the score' suggests a method called readscore(). You are exactly right. It does not matter with what language you describe an action, because the interface should still remain the same whether you are reading an attribute, or calculating high level summation probabilities to find the score. You are still just vg.readscore() Your particular issue is with the simplicity of the attribute, we don't need a getter method. True. But that in agreement with the concept of OOP. If you decide to pick and choose whether an object does it or whether the developer does it, not only do you have inconsistency in your programming style, but you are no longer OBJECT-Oriented. PS This is one of the big issues that developers have with the win32api. It is procedural in this section, OOP in this section, etc. and more time is spent actually look up these subtle differences to prevent errors than is used in actual coding. A perfect OOP library does not Need a reference book. A good OOP library should only need to propose a pattern. >> The second way is preferable for many reasons... >> A) The game designer decides to change the display, you don't have to >> change >> any code that uses the class >> B) Clearly, tearing open a videogame is pretty low-level from an object >> perspective. This is what Alan is saying with OOP purism. >> > > Did we think about REUSABILITY? What if in some other application I want > to USE the score, not just display it? What if I want to display it in a > different form (multiplying it by 100)? Then you are back to our > original options : either check the score directly, define a getter, or > a .... 'stater'(?) which returns the state of the object (in this case > it would be a tuple with only the score in it, a getter in disguise if > you ask me). AFAIK the python way is to just check the score, if later > the object's author changes something he has ways built in in the > language to keep the interface unchanged (yes, I think the score would > be part of the interface, otherwise it would be _score). I completely disagree with your issue on REUSABILITY here. Are you familiar with the concept of subclassing? Or if you wish to ignore the power of OOP, you can just add another method, which is still more realistic and intuitive than directly accessing an internal state variable. Perhaps your major issue here is whether or not score should be public? Alright. Give me one instance in daily usage of any video game where the score of a video game is changed without the video game knowing it. (example - cosmic rays change a bit in the storage of the score and the video game is not aware of it) This concept would allow a violation of a pure OOP VideoGame class, and allow an otherwise private internal state to be made public. PS - for fun. I can think of a more common reason why the score of video games would change without using the actual video game interface. I watched a tv episode of masterminds where the criminal thought up the perfect plan to trick a slot machine by directly accessing the physical chip that determined a winning combination. If the developer of the slot machine had wanted this to be the way that winning combinations are chosen, he should have provided a method which allowed for this. From keridee at jayco.net Wed Feb 13 03:43:32 2008 From: keridee at jayco.net (Tiger12506) Date: Tue, 12 Feb 2008 21:43:32 -0500 Subject: [Tutor] Closing file objects when object is garbage collected? References: Message-ID: <005a01c86dea$3c6c3b40$58fce004@jslaptop> > I'm having issues when I test my software on XP, but not Linux. When I > run the progam it fails after running for a while but not at exactly > the same point each time. It fails in one of two ways, the user > interface either completely disappears, or gives a OS error message > unhanded exception error. Could you give code for this, or provide a link? From ricaraoz at gmail.com Wed Feb 13 06:01:14 2008 From: ricaraoz at gmail.com (=?windows-1252?Q?Ricardo_Ar=E1oz?=) Date: Wed, 13 Feb 2008 02:01:14 -0300 Subject: [Tutor] designing POOP In-Reply-To: <003d01c86de9$cd725990$58fce004@jslaptop> References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B1842E.4010400@bigfoot.com> <003d01c86de9$cd725990$58fce004@jslaptop> Message-ID: <47B2799A.109@bigfoot.com> Tiger12506 wrote: >>> This is all fine and dandy, but the video game is pretty worthless unless >>> it >>> can show us what the score is. There are two ways to go about this. A) >>> Give >>> the video game a display which it updates, or B) Tear open the case of >>> the >>> video game and look at the actual gears that increment the score to read >>> it. >> Mmmm... that's not really so. If the object's creator meant the score to >> be read that way then it would not be 'Tear open the case' but just >> 'read the score'. The language with which we describe an action does >> matter. > > You just invalidated your own argument. Sure, the object's creator may have > designated that "the way to read the score is to take these screws out and > measure the angle of these gears in ratio to those gears" No, the object's creator designed that "the way to get the score is to read it". > but what are you > really doing here? ...(you are thinking procedurally)... You are really > just overlooking the fact that the object is being *read*, meaning that the > *object itself returns a representation*. This tearing apart should be > abstracted with a method. Why? Because you are used to do it that way? > The meer fact that you say 'tearing open the case' YOU are saying it. I'm saying 'read the score'. > as just another way to say 'read the score' suggests a method called > readscore(). Maybe it suggests that to you, not to me. But hey, if it did suggest readscore() or getscore() then it might also suggest setscore() and then we might also make sure that score is an integer so we'd better "declare" it an integer and have an exception if it is ever used to hold another type, they we might just see the light and start programming Java. > You are exactly right. It does not matter with what language > you describe an action, because the interface should still remain the same > whether you are reading an attribute, or calculating high level summation > probabilities to find the score. You are still just vg.readscore() Nope, I'm just myVar = vg.score and there are even ways to make sure that when the user of the class writes that line he receives a "high level summation probability" just as if he'd called a method, remember this is Python. > > Your particular issue is with the simplicity of the attribute, we don't need > a getter method. True. But that in agreement with the concept of OOP. Sorry, which concept? According to whom? > If you > decide to pick and choose whether an object does it or whether the developer > does it, not only do you have inconsistency in your programming style, but > you are no longer OBJECT-Oriented. Says who? Anyway, I'm no theoretician, I'm a mere programmer. We programmers deal with practical things so I don't really care if I'm in or out of your concept of object orientation. So long as my code is maintainable, extendable, and does what it's supposed to do I'm ok with it, object or non-object oriented. Anyway if you wish for better people than me to expose this to you I suggest you address the python-list (python-list at python.org) and post a message saying "We should access properties through setters and getters, otherwise it is not TRUE OOP". I won't take responsibility for any flames. > PS This is one of the big issues that developers have with the win32api. It > is procedural in this section, OOP in this section, etc. and more time is > spent actually look up these subtle differences to prevent errors than is > used in actual coding. A perfect OOP library does not Need a reference book. > A good OOP library should only need to propose a pattern. I like good references, I like good documentation. But hey, different strokes... >>> The second way is preferable for many reasons... >>> A) The game designer decides to change the display, you don't have to >>> change >>> any code that uses the class >>> B) Clearly, tearing open a videogame is pretty low-level from an object >>> perspective. This is what Alan is saying with OOP purism. >>> >> Did we think about REUSABILITY? What if in some other application I want >> to USE the score, not just display it? What if I want to display it in a >> different form (multiplying it by 100)? Then you are back to our >> original options : either check the score directly, define a getter, or >> a .... 'stater'(?) which returns the state of the object (in this case >> it would be a tuple with only the score in it, a getter in disguise if >> you ask me). AFAIK the python way is to just check the score, if later >> the object's author changes something he has ways built in in the >> language to keep the interface unchanged (yes, I think the score would >> be part of the interface, otherwise it would be _score). > > I completely disagree with your issue on REUSABILITY here. Are you familiar > with the concept of subclassing? So if I subclass the class it's ok to mess with the property but if I use the class it's not? Why should that be so? What advantage would that give me? If I subclass it, then declare a getter that reads the property and returns it, then the original class gets changed and I'm in the same predicament as if I'd used the property straight ahead. > Or if you wish to ignore the power of OOP, > you can just add another method, which is still more realistic and intuitive > than directly accessing an internal state variable. An internal state variable? You mean it's 'protected', then it should be _state instead of state, shouldn't it? And why should it be more 'protected' than that? Aren't we all adults here? May I suggest you read http://dirtsimple.org/2004/12/python-is-not-java.html? Specially : """ Getters and setters are evil. Evil, evil, I say! Python objects are not Java beans. Do not write getters and setters. This is what the ?property? built-in is for. And do not take that to mean that you should write getters and setters, and then wrap them in ?property?. That means that until you prove that you need anything more than a simple attribute access, don?t write getters and setters. They are a waste of CPU time, but more important, they are a waste of programmer time. Not just for the people writing the code and tests, but for the people who have to read and understand them as well. """ If you think a property should not be touched then underscore it, that will tell the user that he messes with it at his own risk. If you want to check on changes to a property, that can be easily done without using a setter. > Perhaps your major issue > here is whether or not score should be public? Alright. Give me one instance > in daily usage of any video game where the score of a video game is changed > without the video game knowing it. Didn't you ever use a "trick" (key combination) to get more lives or another weapon in Doom? > (example - cosmic rays change a bit in > the storage of the score and the video game is not aware of it) This concept > would allow a violation of a pure OOP VideoGame class, and allow an > otherwise private internal state to be made public. You care too much about "purity". This is a trade, we do what works we drop what doesn't. And again, if the property is not considered public it should be underscored. > PS - for fun. I can think of a more common reason why the score of video > games would change without using the actual video game interface. I watched > a tv episode of masterminds where the criminal thought up the perfect plan > to trick a slot machine by directly accessing the physical chip that > determined a winning combination. If the developer of the slot machine had > wanted this to be the way that winning combinations are chosen, he should > have provided a method which allowed for this. We should have told the crook that he should have just subclassed the slot machine. Then he wouldn't even be a crook, he'd be legal. Don't you think? ;c) From ricaraoz at gmail.com Wed Feb 13 06:47:35 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 13 Feb 2008 02:47:35 -0300 Subject: [Tutor] designing POOP In-Reply-To: References: Message-ID: <47B28477.2060009@bigfoot.com> To further document some points. This comes from PEP 8 (http://www.python.org/dev/peps/pep-0008/) For those who need "authority" : Author: Guido van Rossum , Barry Warsaw """ With this in mind, here are the Pythonic guidelines: - Public attributes should have no leading underscores. - If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule, 'cls' is the preferred spelling for any variable or argument which is known to be a class, especially the first argument to a class method.) Note 1: See the argument name recommendation above for class methods. - For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax. Note 1: Properties only work on new-style classes. Note 2: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine. Note 3: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap. - If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name. Note 1: Note that only the simple class name is used in the mangled name, so if a subclass chooses both the same class name and attribute name, you can still get name collisions. Note 2: Name mangling can make certain uses, such as debugging and __getattr__(), less convenient. However the name mangling algorithm is well documented and easy to perform manually. Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers. """ HTH From kent37 at tds.net Wed Feb 13 13:21:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Feb 2008 07:21:52 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ADF7DD.9090209@tds.net> <47AE566C.6040206@tds.net> <20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net> <47AFA703.9070601@tds.net> Message-ID: <47B2E0E0.4040201@tds.net> Alan Gauld wrote: > This is fine and dandy but what if we want to find out the > current value of a.value without calling inc? > Thats where hetter/setter/direct access comes into the > picture. > In Java and some other languages the idiomatic thing > to do is provide methods prefixed with get/set for each attribute > > class Counter(object): > def __init__(self, initial=0, delta=1):... > def inc(self)... > def state(self):... > def getDelta(self): return self.delta > def getValue(self): return self.value > def setValue(self, val): self.value = val > def setDelta(self, val): self.delta = val > > Now this is a lot of typing! It also isn't necessary in Python > because Python allows you to access the attributes > diectly - direct access. To amplify and clarify a little: - Other languages can also give direct access to attributes, this is not unique to Python. Java and C++, at least (the languages I know), also have a way to *restrict* direct access to attributes which Python does not really have. - There is a good reason for using setters and getters in Java and C++ - they have no way to convert an attribute access into a method call. So if you start with attribute access and then realize you want to add some code to the access, you are stuck - you have to change the interface to the class. Python does not have this problem - attribute access can be converted to a method call using properties. For this reason, there is IMO (and as generally accepted usage) no advantage to using getters & setters in Python for simple attribute access. Introduction to properties: http://personalpages.tds.net/~kent37/kk/00008.html - Python does have a convention for documenting which attributes (including methods) are considered part of the public interface and which are not. Non-public attribute names are prefixed with _ (single underscore). This is a signal to users of the class that the attribute is considered an internal implementation detail and to use it at your own risk. This is consistent with the Python philosophy that "we're all consenting adults here" - i.e. that the users of a class don't need to be protected from shooting themselves in the foot - it is enough to put a warning sign on the gun and the foot :-) Kent From kent37 at tds.net Wed Feb 13 13:38:06 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Feb 2008 07:38:06 -0500 Subject: [Tutor] designing POOP In-Reply-To: <001401c86d2d$06354750$97fce004@jslaptop> References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> Message-ID: <47B2E4AE.5070409@tds.net> Tiger12506 wrote: > vg = VideoGame() > howmany = rand.randint(0,100) > for i in range(howmany): > vg.buttonpush() > print vg.score #Tear open the case (hope you have a screwdriver) > > OR > > class VideoGame(): > def __init__(self): > self.score = 0 > def updatedisp(): > print self.score > def buttonpush(): > self.score += 1 > self.updatedisp() > > vg = VideoGame() > howmany = rand.randint(0,100) > for i in range(howmany): > vg.buttonpush() #Let the videogame display your score > however it wishes > > The second way is preferable for many reasons... Hmm. Not to me. The second version couples the game state with the display. I would rather have - a Game object that maintains the state of the game and has methods to manipulate the state - a Display object that displays the state of the game - a Controller object that mediates between user interaction, the Game and the Display. Something like: class Game(object): def __init__(self): self.score = 0 def handleSomethingGood(self): self.score += 1 class Display(object): def showScore(self, score): print score class Controller(object): def __init__(self, game, display): self.game = game self.display = display def handleButton(self): self.game.handleSomethingGood() self.display.showScore(self.game.score) Now Game.handleSomethingGood() is decoupled from both the display and the actual UI event that signals SomethingGood happened. This is an example of Model-View-Controller architecture (google it). Notice that the Game and Display are now reusable (maybe there are both GUI and text interfaces to the game, for example, or versions for wxPython and PyQt) and testable independently of each other. A more advanced design might register the Display as an observer of the Game score but I don't want to get into that... Kent From sierra_mtnview at sbcglobal.net Wed Feb 13 15:26:42 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 13 Feb 2008 06:26:42 -0800 Subject: [Tutor] Various Topics from IDLE to ImageDraw Options In-Reply-To: <47B2799A.109@bigfoot.com> References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B1842E.4010400@bigfoot.com> <003d01c86de9$cd725990$58fce004@jslaptop> <47B2799A.109@bigfoot.com> Message-ID: <47B2FE22.2080003@sbcglobal.net> I'm just getting started in Python but have begun with a challenging project. It's a 2000+ line program that provides works with a GUI for essentially a video device. As such, it displays dialogs, still images, push buttons, menus, and the like. It uses OOP. Ten years ago I was into OOP with C++ and Java for several years. It's been awhile. I'm interested in modifying the GUI interface. I've begun with IDLE and have a few questions about it. Although, I've been able to set breakpoints, I see no way to clear then all. Is there a way, and is there a way to tell what line # I'm on when examining source text? I'm not quite sure why, but when I start the Python shell via IDLE, an Open leads me to the Python 2.4.4 folder. This is not where my programs are. Is there some way to start in a directory closer where I want to be? Although I have a popular book on Python (Lucas?), I just found a short intro to Python OOP on the web that looks like a good quick start into the subject. Maybe there are others. I just figured out how to draw a line on one of the still images the program. I'm not quite sure how I did that, but it did work. Eventually, the line effort will allow me to draw a compass over the image. In any case, for that, I started getting acquainted with the ImageDraw class (Object). My question here is are there more detailed explanations somewhere for the options? For example, I found a rather helpful document at New Mexico Tech, which goes into considerable detail on options for Tkinter. See page 4 of by John Shipman. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "I know that this defies the law of gravity, but you see, I never studied law." -- Bugs Bunny Web Page: From nomb85 at comcast.net Wed Feb 13 17:37:30 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Wed, 13 Feb 2008 11:37:30 -0500 Subject: [Tutor] beginner pexpect question Message-ID: <47B31CCA.9060608@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hey guys, I'm practically still a beginner with python. I am working on a program that originally I used popen for but then switched to pexpect because it was easier for me to understand. I was hoping someone could help me get this working: I do a: child = pexpect.spawn ('cryptsetup --verbose --cipher "aes-cbc-essiv:sha256" --key-size 256 --verify-passphrase luksFormat ' + self.loopdevice) i = child.expect ([pexpect.TIMEOUT, '.*']) if i == 0: print 'ERROR!' print child.before, child.after child.sendline ('YES') print "Sent YES" child.expect ('.*') #child.sendline ('Test') child.send ('Test\n') print "Sent Pass 1" child.expect ('.*') child.send ('Test\n') print "Sent Pass 2" #child.sendline ('Test') This runs without errors but then to test I do a: [root at localhost project]# losetup /dev/loop0 /home/user/deleteme [root at localhost project]# cryptsetup luksOpen /dev/loop0 encr-container1 Enter LUKS passphrase: /dev/loop0 is not a LUKS partition Command failed: No key available with this passphrase. I can't understand this at all. If anyone can help I would appreciate it a lot. Thanks very much, Nate -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFHsxnq/n+duykW6K8RAufNAKDP3BNCDAC/ALFuH8ht8qyETy5/xQCfS4i7 2aA9UoTLBZDRst0LPA9YstM= =rcB6 -----END PGP SIGNATURE----- From alan.gauld at btinternet.com Wed Feb 13 21:05:18 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Feb 2008 20:05:18 -0000 Subject: [Tutor] Various Topics from IDLE to ImageDraw Options References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B1842E.4010400@bigfoot.com> <003d01c86de9$cd725990$58fce004@jslaptop><47B2799A.109@bigfoot.com> <47B2FE22.2080003@sbcglobal.net> Message-ID: "Wayne Watson" wrote Hi Wayne, welcome to the tutor list. One wee point, dont reply to existing messages with a new subject. Those of us using threaded readers are likely to miss it unless we are folowing the thread. tHis one popped up halfway through the long thread on POOP! Now to your questions: > I've begun with IDLE and have a few questions about it. > Although, I've been able to set breakpoints, I see no > way to clear then all. Is there a way, I don;t think there is a clear all option. If you are on Windows I recommend you get the Pythonwin IDE (in the winall package) it has a much better debugger and in fact is better in almost every way than IDLE. If you are on Linux using Eclipse and the PyDev plugin might be a better option. Alternatively try WinPdb as a stand alone Pyton debugger. > and is there a way to tell what line # I'm on when > examining source There should be a part of the status bar at the bottom right that tells you line and column. > though I have a popular book on Python (Lucas?), I just found a > short > tro to Python OOP on the web that looks like a good quick start into > e subject. Most tutorials should have an OOP tiopic, mine certainly has... Try the python web site for lots of tutorials and how-tos etc. Explote the topic guides. > ttp://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf> by John Shipman. Again, check the Tkinter section of the web site for lots more links. My tutorial also has a very basic intro, but it sounds like you are past it already :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Wed Feb 13 23:15:16 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 13 Feb 2008 14:15:16 -0800 Subject: [Tutor] Understanding the ImageDraw Options Message-ID: <47B36BF4.7050706@sbcglobal.net> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080213/7ed7f98c/attachment.htm From nomb85 at comcast.net Wed Feb 13 23:15:56 2008 From: nomb85 at comcast.net (Nathan McBride) Date: Wed, 13 Feb 2008 17:15:56 -0500 Subject: [Tutor] beginner pexpect question In-Reply-To: <47B31CCA.9060608@comcast.net> References: <47B31CCA.9060608@comcast.net> Message-ID: <47B36C1C.30307@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Anyone have any recomendations? Seems like it is giving it the passwords since it finishes cleanly, but maybe not like I think? Nate Nathan McBride wrote: > Hey guys, > > I'm practically still a beginner with python. I am working on a program > that originally I used popen for but then switched to pexpect because it > was easier for me to understand. > I was hoping someone could help me get this working: > > I do a: > > child = pexpect.spawn ('cryptsetup --verbose --cipher > "aes-cbc-essiv:sha256" --key-size 256 --verify-passphrase luksFormat ' + > self.loopdevice) > i = child.expect ([pexpect.TIMEOUT, '.*']) > if i == 0: > print 'ERROR!' > print child.before, child.after > child.sendline ('YES') > print "Sent YES" > child.expect ('.*') > #child.sendline ('Test') > child.send ('Test\n') > print "Sent Pass 1" > child.expect ('.*') > child.send ('Test\n') > print "Sent Pass 2" > #child.sendline ('Test') > > This runs without errors but then to test I do a: > > [root at localhost project]# losetup /dev/loop0 /home/user/deleteme > [root at localhost project]# cryptsetup luksOpen /dev/loop0 encr-container1 > Enter LUKS passphrase: > /dev/loop0 is not a LUKS partition > Command failed: No key available with this passphrase. > > I can't understand this at all. If anyone can help I would appreciate > it a lot. > > Thanks very much, > Nate > _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFHs2wb/n+duykW6K8RAhcgAJ0T9f5WlxYCFtUtjBirdhxs3jfzzACeJNXr x8TGYUdeRNbjzw51pG8J+Jg= =qoOB -----END PGP SIGNATURE----- From kent37 at tds.net Thu Feb 14 00:09:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 13 Feb 2008 18:09:08 -0500 Subject: [Tutor] Understanding the ImageDraw Options In-Reply-To: <47B36BF4.7050706@sbcglobal.net> References: <47B36BF4.7050706@sbcglobal.net> Message-ID: <47B37894.3090408@tds.net> Wayne Watson wrote: > I started getting acquainted with the ImageDraw class (Object). > My question here is are > there more detailed explanations somewhere for the options? > > It gives no idea what the choices are for options in the argument list. There is an Options section on the page you reference. It lists the options as outline, fill and font. Outline and fill seem to take color arguments. The Colours section tells how to specify colors. The font argument is specified as taking an ImageFont value. It doesn't explicitly say, but from the example the options seem to be keyword arguments. > This contrasts with the more detailed descriptions in the document at > New Mexico Tech, which goes into considerable detail on options for the > Tkinter class. Which really has nothing to do with the ImageDraw docs at all. Different projects have docs of different quality... Kent From alan.gauld at btinternet.com Thu Feb 14 00:29:47 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Feb 2008 23:29:47 -0000 Subject: [Tutor] Understanding the ImageDraw Options References: <47B36BF4.7050706@sbcglobal.net> Message-ID: "Wayne Watson" wrote Caveat, I've never used ImageDraw.... >I started getting acquainted with the ImageDraw class (Object). > My question > here is are there more detailed explanations somewhere > for the options? There is an Options section on the page linked which describes the available options: Options # outline outline integer or tuple fill fill integer or tuple font font ImageFont instance > It gives no idea what the choices are for options in the argument > list. I believe its intended to be any of the standard options that are applicable, for lines that would just be fill. (Although a note suggests a new width option which is not listed under options!) I agree the documentation is limited but unfortunately thats one of the common penalties of using open source software. If yopu really need to know read the module source code... At least thats possible with open source! :-) > This contrasts with the more detailed descriptions in > the document at New Mexico Tech, which goes into considerable > detail on options for the Tkinter class. Yes, but Tk and Tkinter have both been around for a very long time and are widely used. Plenty time for documentation to be written. PIL has been around for a while but is much less widely used and ImageDraw is even more recent and more specialised. Your best bet may be to ask on a PIL mailing list or try the main comp.lang.python usenet group. HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Thu Feb 14 00:53:09 2008 From: carroll at tjc.com (Terry Carroll) Date: Wed, 13 Feb 2008 15:53:09 -0800 (PST) Subject: [Tutor] Change dictionary value depending on a conditional statement. In-Reply-To: <47B160FD.1020106@khine.net> Message-ID: I don't think I saw anyone point this out yet, but, using "list" as a variable name is a bad idea, because it hides the list method. >>> x = list("abcdefg") >>> x ['a', 'b', 'c', 'd', 'e', 'f', 'g'] This works. You now have a variable named "x" that is a list. >>> list = list("hijklmnop") >>> list ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'] This works, sort of. You now have a variable named "list" that is a list. But since you reused the name "list," it can no longer point to the list function. >>> y = list("qrstuv") Traceback (most recent call last): File "", line 1, in TypeError: 'list' object is not callable And so this fails. On Tue, 12 Feb 2008, Norman Khine wrote: > Thank you all, very nice. > > Steve Willoughby wrote: > > Kent Johnson wrote: > >> Try > >> list.append({'id': 'name', 'link': ('YY','XX')[total > 0]}) > > > > I'd caution against that, though. It's clever and cute, sure, but the > > meaning of it is obfuscated enough to be unpythonic because [total > 0] > > as a subscript doesn't mean anything unless you know you're taking > > advantage of an implementation detail that booleans are 0 for false and > > 1 for true. No matter how reliable that fact may be, I don't think that > > value should be stuck into a numeric context like that. > > > >> Or, in Python 2.5, > >> list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')}) > > > > This is much more clear, and would IMHO be fine. > > > > > > > > _______________________________________________ > > 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 soulguidedtelescope at gmail.com Thu Feb 14 01:49:47 2008 From: soulguidedtelescope at gmail.com (Arun Srinivasan) Date: Wed, 13 Feb 2008 16:49:47 -0800 Subject: [Tutor] Binary chop function - this works, but I'm not sure why Message-ID: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> I'm trying to learn Python, and I decided to try kata 2 from the CodeKate website. It's basically just a challenge to implement a binary search in different ways. I wrote an implementation that works, but I'm confused as to why. def chop(search_int, sorted_list): if len(sorted_list) == 1 or 2: for x in sorted_list: if x == search_int: return sorted_list.index(x) return -1 midpoint = (len(sorted_list) - 1) / 2 mp_value = sorted_list[midpoint] if mp_value == search_int: return midpoint elif mp_value > search_int: return chop(search_int, sorted_list[:midpoint]) else: return chop(search_int, sorted_list[midpoint + 1:]) Basically, it only returns the index if it matches in the if statement at the beginning of the function, but since that is limited to lists of length 2 or 1, why doesn't it return only 0 or 1 as the index? I think there is something about recursion here that I'm not fully comprehending. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080213/1844543f/attachment.htm From cfuller084 at thinkingplanet.net Thu Feb 14 02:10:49 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 13 Feb 2008 19:10:49 -0600 Subject: [Tutor] Binary chop function - this works, but I'm not sure why In-Reply-To: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> References: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> Message-ID: <200802131910.49273.cfuller084@thinkingplanet.net> On Wednesday 13 February 2008 18:49, Arun Srinivasan wrote: > I'm trying to learn Python, and I decided to try kata 2 from the > CodeKate website. It's basically just a challenge to implement a binary > search in different ways. > > I wrote an implementation that works, but I'm confused as to why. > > def chop(search_int, sorted_list): > if len(sorted_list) == 1 or 2: This condition is always true. You meant to say: len(sorted_list) == 1 or len(sorted_list) == 2" or: "len(sorted_list) in 1,2" Cheers From andrei.petre at gmail.com Thu Feb 14 03:57:36 2008 From: andrei.petre at gmail.com (Andrei Petre) Date: Thu, 14 Feb 2008 04:57:36 +0200 Subject: [Tutor] read from standard input Message-ID: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> Hello, I want to read from the standard input numbers until i reach a certain value or to the end of the "file". What is the simplest, straightforward, pythonic way to do it? a sketch of how i tried to do it: [code] while 1 < 2: x = raw_input() if type(x) != int or x == 11: break else: print x [/code] but don't work. and i'm interest in a general way to read until it is nothing to read. to ilustrate that in C: [code] int x; while( scanf("%d",&x) == 1 && x != 11) printf("%d\n", x); [/code] Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080214/44cef5a9/attachment.htm From john at fouhy.net Thu Feb 14 05:27:28 2008 From: john at fouhy.net (John Fouhy) Date: Thu, 14 Feb 2008 17:27:28 +1300 Subject: [Tutor] read from standard input In-Reply-To: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> Message-ID: <5e58f2e40802132027w4432d9e0n3847f28fbc48794@mail.gmail.com> On 14/02/2008, Andrei Petre wrote: > Hello, > > I want to read from the standard input numbers until i reach a certain value > or to the end of the "file". > What is the simplest, straightforward, pythonic way to do it? > > a sketch of how i tried to do it: > [code] > while 1 < 2: > x = raw_input() > if type(x) != int or x == 11: > break > else: > print x > [/code] This won't work because raw_input() always returns a string. The pythonic way to make that code work is: while True: raw_x = raw_input() try: x = int(raw_x) except ValueError: break if x == 11: break print x (actually, you would be better giving x an initial value and then writing 'while x != 11' ..) > but don't work. and i'm interest in a general way to read until it is > nothing to read. sys.stdin is a file-like object corresponding to standard in. You can do this: import sys special = 11 for line in sys.stdin: try: x = int(line) except ValueError: print 'Bad input.' break if x == special: print 'Special value reached.' break else: print 'End of input reached.' -- John. From alan.gauld at btinternet.com Thu Feb 14 09:21:46 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Feb 2008 08:21:46 -0000 Subject: [Tutor] Binary chop function - this works, but I'm not sure why References: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> Message-ID: "Arun Srinivasan" wrote > I wrote an implementation that works, but I'm confused as to why. > > def chop(search_int, sorted_list): > if len(sorted_list) == 1 or 2: |This is not doing what you think it is. Pythopn sees this as: if ( len(sorted_list == 1) or 2: So it evaluates whether the list is one element, if it isn't it then checks if 2 is true, which it always is. So the if condition is always trie and yuou code always executes the if block. Now the if block as written will always find the element in the list if it exists. If you rewrote the if test like so you would get a more effective test: if len(sorted_list) in [1,2]: > for x in sorted_list: > if x == search_int: > return sorted_list.index(x) > return -1 You could also rewrite the block as: if sorted_list[0] == search_int: return 0 elif len(sorted_list) == 2 and sorted_list[1] == search_int: return 1 else return -1 Which should be marginally faster and only works for lists of length 1 or 2. > midpoint = (len(sorted_list) - 1) / 2 > mp_value = sorted_list[midpoint] > > if mp_value == search_int: > return midpoint > elif mp_value > search_int: > return chop(search_int, sorted_list[:midpoint]) > else: > return chop(search_int, sorted_list[midpoint + 1:]) > > Basically, it only returns the index if it matches in the if > statement at > the beginning of the function, but since that is limited to lists of > length > 2 or 1, why doesn't it return only 0 or 1 as the index? I think > there is > something about recursion here that I'm not fully comprehending. The rest of the code is broken because, as you say, it only returns 0 or 1. you need to add the lower bound to the return value but you don't track the lower bound! Alan G. From bgailer at alum.rpi.edu Thu Feb 14 14:27:25 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Thu, 14 Feb 2008 08:27:25 -0500 Subject: [Tutor] Binary chop function - this works, but I'm not sure why In-Reply-To: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> References: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> Message-ID: <47B441BD.3080809@alum.rpi.edu> Arun Srinivasan wrote: > I'm trying to learn Python, and I decided to try kata 2 from the > CodeKate website. It's basically just a challenge to implement a > binary search in different ways. > > I wrote an implementation that works, but I'm confused as to why. > > def chop(search_int, sorted_list): > if len(sorted_list) == 1 or 2: Yet another way to express that is: if 1 <= len(sorted_list) <= 2: > for x in sorted_list: > if x == search_int: > return sorted_list.index(x) > return -1 > > midpoint = (len(sorted_list) - 1) / 2 > mp_value = sorted_list[midpoint] > > if mp_value == search_int: > return midpoint > elif mp_value > search_int: > return chop(search_int, sorted_list[:midpoint]) > else: > return chop(search_int, sorted_list[midpoint + 1:]) > > Basically, it only returns the index if it matches in the if statement > at the beginning of the function, but since that is limited to lists > of length 2 or 1, why doesn't it return only 0 or 1 as the index? I > think there is something about recursion here that I'm not fully > comprehending. > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill, NC From soulguidedtelescope at gmail.com Thu Feb 14 20:41:16 2008 From: soulguidedtelescope at gmail.com (Arun Srinivasan) Date: Thu, 14 Feb 2008 11:41:16 -0800 Subject: [Tutor] Binary chop function - this works, but I'm not sure why In-Reply-To: <47B441BD.3080809@alum.rpi.edu> References: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> <47B441BD.3080809@alum.rpi.edu> Message-ID: <78d3f9e00802141141u2a1b25f3h43ef431e2daa5bf1@mail.gmail.com> On Thu, Feb 14, 2008 at 5:27 AM, bob gailer wrote: > > Arun Srinivasan wrote: > > I'm trying to learn Python, and I decided to try kata 2 from the > > CodeKate website. It's basically just a challenge to implement a > > binary search in different ways. > > > > I wrote an implementation that works, but I'm confused as to why. > > > > def chop(search_int, sorted_list): > > if len(sorted_list) == 1 or 2: > Yet another way to express that is: > > if 1 <= len(sorted_list) <= 2: > > > for x in sorted_list: > > if x == search_int: > > return sorted_list.index(x) > > return -1 > > > > midpoint = (len(sorted_list) - 1) / 2 > > mp_value = sorted_list[midpoint] > > > > if mp_value == search_int: > > return midpoint > > elif mp_value > search_int: > > return chop(search_int, sorted_list[:midpoint]) > > else: > > return chop(search_int, sorted_list[midpoint + 1:]) > > > > Basically, it only returns the index if it matches in the if statement > > at the beginning of the function, but since that is limited to lists > > of length 2 or 1, why doesn't it return only 0 or 1 as the index? I > > think there is something about recursion here that I'm not fully > > comprehending. > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > Oy, I should have seen that. Thanks for the responses - time to go back and fix this. From soulguidedtelescope at gmail.com Thu Feb 14 21:36:18 2008 From: soulguidedtelescope at gmail.com (Arun Srinivasan) Date: Thu, 14 Feb 2008 12:36:18 -0800 Subject: [Tutor] Binary chop function - this works, but I'm not sure why In-Reply-To: <78d3f9e00802141141u2a1b25f3h43ef431e2daa5bf1@mail.gmail.com> References: <78d3f9e00802131649j16cddc49v54c6f011010e54ba@mail.gmail.com> <47B441BD.3080809@alum.rpi.edu> <78d3f9e00802141141u2a1b25f3h43ef431e2daa5bf1@mail.gmail.com> Message-ID: <78d3f9e00802141236v65eedcf0tfe103a1763c37edd@mail.gmail.com> On Thu, Feb 14, 2008 at 11:41 AM, Arun Srinivasan wrote: > > On Thu, Feb 14, 2008 at 5:27 AM, bob gailer wrote: > > > > Arun Srinivasan wrote: > > > I'm trying to learn Python, and I decided to try kata 2 from the > > > CodeKate website. It's basically just a challenge to implement a > > > binary search in different ways. > > > > > > I wrote an implementation that works, but I'm confused as to why. > > > > > > def chop(search_int, sorted_list): > > > if len(sorted_list) == 1 or 2: > > Yet another way to express that is: > > > > if 1 <= len(sorted_list) <= 2: > > > > > for x in sorted_list: > > > if x == search_int: > > > return sorted_list.index(x) > > > return -1 > > > > > > midpoint = (len(sorted_list) - 1) / 2 > > > mp_value = sorted_list[midpoint] > > > > > > if mp_value == search_int: > > > return midpoint > > > elif mp_value > search_int: > > > return chop(search_int, sorted_list[:midpoint]) > > > else: > > > return chop(search_int, sorted_list[midpoint + 1:]) > > > > > > Basically, it only returns the index if it matches in the if statement > > > at the beginning of the function, but since that is limited to lists > > > of length 2 or 1, why doesn't it return only 0 or 1 as the index? I > > > think there is something about recursion here that I'm not fully > > > comprehending. > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > Bob Gailer > > 919-636-4239 Chapel Hill, NC > > > > > > Oy, I should have seen that. Thanks for the responses - time to go > back and fix this. > Turns out it was simple to fix - just needed to fix that test so it wasn't silly, add the lower bound tracking (thanks Alan), and make sure to test for empty lists. Here's the function in all (rather, what little there is) of its glory: def chop(search_int, sorted_list, lbound = 0): if len(sorted_list) == 0: return -1 if len(sorted_list) in [1,2]: if sorted_list[0] == search_int: return lbound elif len(sorted_list) == 2 and sorted_list[1] == search_int: return lbound + 1 else: return -1 midpoint = (len(sorted_list) - 1) / 2 mp_value = sorted_list[midpoint] if mp_value == search_int: return midpoint elif mp_value > search_int: return chop(search_int, sorted_list[:midpoint]) else: return chop(search_int, sorted_list[midpoint + 1:], lbound + midpoint + 1) Alan, could you please explain why if sorted_list[0] == search_int: return 0 elif len(sorted_list) == 2 and sorted_list[1] == search_int: return 1 else: return -1 is faster than: > for x in sorted_list: > if x == search_int: > return sorted_list.index(x) > return -1 Thanks for the help! From keridee at jayco.net Thu Feb 14 13:49:41 2008 From: keridee at jayco.net (Tiger12506) Date: Thu, 14 Feb 2008 07:49:41 -0500 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B2E4AE.5070409@tds.net> Message-ID: <000201c86f4b$2766fbb0$52fce004@jslaptop> > Hmm. Not to me. The second version couples the game state with the > display. I would rather have True... > This is an example of Model-View-Controller architecture (google it). > Notice that the Game and Display are now reusable (maybe there are both > GUI and text interfaces to the game, for example, or versions for wxPython > and PyQt) and testable independently of each other. Ah yes... I don't like the Model-View-Controller architecture. That the major reason why I dislike most information available on C++. This is a personal issue though. The Model-View-Controller is a very common thing, and everyone but me would be wise to use it. :-) From keridee at jayco.net Thu Feb 14 22:06:53 2008 From: keridee at jayco.net (Tiger12506) Date: Thu, 14 Feb 2008 16:06:53 -0500 Subject: [Tutor] read from standard input References: <3576e740802131857u44da9f5coa07656c1f97f5d91@mail.gmail.com> Message-ID: <00a401c86f4f$bbfe8be0$03fce004@jslaptop> > while 1 < 2: while 1: or while True: is more common > x = raw_input() raw_input() always return a string, no matter what you type in. > if type(x) != int or x == 11: type(x) is always x can never be 11, but can possibly be '11'. (Notice quotes indicating string instead of integer) If you want an integer you must say x = int(raw_input()) > break > else: > print x > [/code] > > but don't work. and i'm interest in a general way to read until it is > nothing to read. > > > to ilustrate that in C: > [code] > int x; > while( scanf("%d",&x) == 1 && x != 11) > printf("%d\n", x); > [/code] > > > Thanks! > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cspears2002 at yahoo.com Fri Feb 15 01:10:53 2008 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 14 Feb 2008 16:10:53 -0800 (PST) Subject: [Tutor] most efficient way to do this Message-ID: <207749.60171.qm@web51607.mail.re2.yahoo.com> I created a file called arrays.py: #!/usr/bin/python locations = ["/home/", "/office/" , "/basement/" , "/attic/"] Now I want to add the word "chris" on to each element of the locations list, so I wrote another script called chris_arrays.py: #!/usr/bin/python/ from arrays import locations add_on = "chris" new_loc = [] for i in range(len(locations)): new_loc.append(locations[i] + add_on) print new_loc Is this the most efficient way to do this? I'm using these scripts to test some changes I want to make to a script at work. Basically, I want one file to hold a list of paths. The other file imports the list and then asks the user for input that it then adds on to each string in the list. I want the paths to be in a separate file, so I can access these paths with different scripts. From alan.gauld at btinternet.com Fri Feb 15 01:38:30 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Feb 2008 00:38:30 -0000 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop><47B2E4AE.5070409@tds.net> <000201c86f4b$2766fbb0$52fce004@jslaptop> Message-ID: "Tiger12506" wrote > Ah yes... I don't like the Model-View-Controller architecture. That > the > major reason why I dislike most information available on C++. This > is a > personal issue though. The Model-View-Controller is a very common > thing, and > everyone but me would be wise to use it. :-) Now I'm curious. MVC is one of the oldest, best established and well proven design patterns going. It first appeared in Smalltalk in the late 1970's and has been copied in almost every GUI and Web framework ever since. I've used it on virtually(*) every GUI I've ever built(**) to the extent that I don't even think about it much anymore, therefore: What do you dislike about it? And what do you use in its place? (*)The only exceptions were ObjectVision, a strange graphical Windows app builder from Borland and a weird scripting language for the very early X Windows toolkits(X10), which looked like csh and produced truly ugly GUIs very quickly. And, of course, native Tcl/Tk has a slightly different model. (**)Those include GUIs built in Smalltalk, Lisp, TurboPascal, Delphi, C/C++, ObjectiveC, Java, Python (of course) and even PL/SQL An alternative perspective is always interesting. Alan G. From alan.gauld at btinternet.com Fri Feb 15 01:48:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Feb 2008 00:48:56 -0000 Subject: [Tutor] most efficient way to do this References: <207749.60171.qm@web51607.mail.re2.yahoo.com> Message-ID: "Christopher Spears" wrote > from arrays import locations > > add_on = "chris" > new_loc = [] > > for i in range(len(locations)): > new_loc.append(locations[i] + add_on) > > print new_loc > > Is this the most efficient way to do this? No. For a start you could use a direct for loop rather than the index method. But even better this is a standard list comprehension job: add_on = 'chris' new_loc = [item+add_on for item in locations] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Fri Feb 15 03:49:06 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Thu, 14 Feb 2008 21:49:06 -0500 Subject: [Tutor] most efficient way to do this In-Reply-To: <207749.60171.qm@web51607.mail.re2.yahoo.com> References: <207749.60171.qm@web51607.mail.re2.yahoo.com> Message-ID: <47B4FDA2.2020703@alum.rpi.edu> Christopher Spears wrote: > I created a file called arrays.py: > > #!/usr/bin/python > > locations = ["/home/", > "/office/" , > "/basement/" , > "/attic/"] > > Now I want to add the word "chris" on to each element > of the locations list, so I wrote another script > called chris_arrays.py: > > #!/usr/bin/python/ > > from arrays import locations > > add_on = "chris" > new_loc = [] > > for i in range(len(locations)): > new_loc.append(locations[i] + add_on) > Alan gave the "best" answer. FWIW I offer an intermediate improvement: for location in locations: new_loc.append(location + add_on) -- Bob Gailer 919-636-4239 Chapel Hill, NC From keridee at jayco.net Fri Feb 15 04:36:44 2008 From: keridee at jayco.net (Tiger12506) Date: Thu, 14 Feb 2008 22:36:44 -0500 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop><47B2E4AE.5070409@tds.net><000201c86f4b$2766fbb0$52fce004@jslaptop> Message-ID: <000801c86f84$003b4670$1cfce004@jslaptop> > Now I'm curious. > > MVC is one of the oldest, best established and well proven design > patterns going. It first appeared in Smalltalk in the late 1970's and > has been copied in almost every GUI and Web framework ever since. > I've used it on virtually(*) every GUI I've ever built(**) to the > extent that > I don't even think about it much anymore, therefore: > > What do you dislike about it? And what do you use in its place? I may not be the most newbie around here, but I am certainly very newbish compared to you and Kent. That means that I do not have perhaps an adequate amount of experience in practical application, but I dislike the concept because in every situation that I have encountered so far, it has tripped me up. I like things to be explicit, and don't care for the level of abstraction common in MVC. I know it seems naive, but I like to be able to model object designs after tangible things, and to me, a View does not know how to keep a state or execute methods because it does not exist. A Controller does not exist alone of the model, and without the view it fails to work. Sure it helps tremendously in interchanging code pieces-reusability a big issue here, but for my purposes, it just seems extraneous. Seperating drawing and computations can be/cannot be convenient for me depending on the application, (my 'plotting' library is a code reusability mess) but in general my style of coding (more procedural) tends to get the job done and also tends to cut corners in just enough places to make me feel that the application is more efficient with resources. Asking what I use in its place very neatly makes me blush because I use no set model, but tend to mix them at my convenience. Have you noticed that I haven't posted code on this list in a long, long time??? Hehe. At any rate, I had noticed that I stepped past my line of authority and experience to the point at which I was significantly less capable to pose as an expert, and therefore I wrote "everyone but me would be wise to use it". My apologies. > (*)The only exceptions were ObjectVision, a strange graphical > Windows app builder from Borland and a weird scripting language for > the > very early X Windows toolkits(X10), which looked like csh and produced > truly ugly GUIs very quickly. And, of course, native Tcl/Tk has a > slightly > different model. > > (**)Those include GUIs built in Smalltalk, Lisp, TurboPascal, Delphi, > C/C++, ObjectiveC, Java, Python (of course) and even PL/SQL > > An alternative perspective is always interesting. > > Alan G. From dave-lists-tutor at weller-fahy.com Fri Feb 15 05:25:37 2008 From: dave-lists-tutor at weller-fahy.com (David J. Weller-Fahy) Date: Thu, 14 Feb 2008 22:25:37 -0600 (CST) Subject: [Tutor] Question regarding list editing (in place) In-Reply-To: <47A8BC77.5080300@tds.net> References: <47A8B5DC.6090700@alum.rpi.edu> <47A8BC77.5080300@tds.net> Message-ID: Sorry for the delayed reply - the list software was "helping" me by not sending me the list copy. Heh. * Kent Johnson [2008-02-05 13:43]: > bob gailer wrote: >> dirs = [dir for dir in dirs if not dir.startswith(u'.')] > > Except to filter the directory list for os.walk() you have to modify the > list in place. Use this: > dirs[:] = [dir for dir in dirs if not dir.startswith(u'.')] That is exactly what I was missing! Thanks for the nudge, that works. ... later ... Of course, if I had paid more attention to section "3.1.4 Lists" in the python tutorial, I might have noticed the example which is similar to that form: #v+ >>> # Clear the list: replace all items with an empty list >>> a[:] = [] >>> a [] #v- Ah, well. Thanks again for the tips, gentlemen. Regards, -- David J. Weller-Fahy | 'These are the questions that kept me out largely at innocent dot com | of the really *good* schools.' dave at weller-fahy dot com | - One of The Group From alan.gauld at btinternet.com Fri Feb 15 10:07:54 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Feb 2008 09:07:54 -0000 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop><47B2E4AE.5070409@tds.net><000201c86f4b$2766fbb0$52fce004@jslaptop> <000801c86f84$003b4670$1cfce004@jslaptop> Message-ID: "Tiger12506" wrote > up. I like things to be explicit, and don't care for the level of > abstraction common in MVC. I know it seems naive, but I like to be > able to > model object designs after tangible things, and to me, a View does > not know > how to keep a state or execute methods because it does not exist. A > Controller does not exist alone of the model, and without the view > it fails > to work. That's an interesting take and depending on which description of MVC you read you could be forgiven for seeing it that way. The original Smalltalk MVC however was very tied to the hardware. The Model was the abstract thing, the View was the Output device (usually the screen representation) and the Controller was the Input device (usually the keyboard/mouse combo). You could swap controllers to accomodate pens, sensors or whatever, and you could swap Views to accomodate plotters and printers as well as just showing different graphical forms. Other versions of MVC have tended to move away from that style and focus purely on the software elements but the concept of mapping Views to screens and Controllers to mice/keyboars is usually still there. So in principle its the View and Controlller that are real, the model is just abstract data... > Sure it helps tremendously in interchanging code pieces-reusability > a big issue here, but for my purposes, it just seems extraneous. It is a big reuse benefit but you need to write a lot of apps on the same platform for that to become obvious. The other tangible benefit s the flexibility it gives an app. It becomes almost trivial to add a new perspective on the data or to convert an app from CLI to GUI to Web. But if you are writing apps for a strictly one-off use the benefits of those are a moot point. > Asking what I use in its place very neatly makes me blush > because I use no set model, but tend to mix them at my > convenience. Don't blush, if you can get a GUI app to work without using MVC you are probably approaching it with a fresher mind than I would since I have been "trained" into MVC thinking. I would literally struggle to architect a GUI application without MVC nowadays! Or at the very least the MV parts of it, I do often work without an explicit controller element in smaller apps, especially in Delphi and Tkinter. Alan G. From kent37 at tds.net Fri Feb 15 14:38:47 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Feb 2008 08:38:47 -0500 Subject: [Tutor] designing POOP In-Reply-To: <000801c86f84$003b4670$1cfce004@jslaptop> References: <47ADF7DD.9090209@tds.net><47AE566C.6040206@tds.net><20080210172805.GA47675@cutter.rexx.com><47AF3D04.3050805@tds.net><47AFA703.9070601@tds.net> <001401c86d2d$06354750$97fce004@jslaptop><47B2E4AE.5070409@tds.net><000201c86f4b$2766fbb0$52fce004@jslaptop> <000801c86f84$003b4670$1cfce004@jslaptop> Message-ID: <47B595E7.9040001@tds.net> Tiger12506 wrote: > I like things to be explicit, and don't care for the level of > abstraction common in MVC. I know it seems naive, but I like to be able to > model object designs after tangible things, and to me, a View does not know > how to keep a state or execute methods because it does not exist. A > Controller does not exist alone of the model, and without the view it fails > to work. I agree that this is a naive view, for the same reason I objected to Alan's "find the nouns" approach to OO design. For me considerations of cohesion, encapsulation, DRY, testability, and any required reuse or flexibility are far more important to design than correspondence with tangible objects. Kent From mlangford.cs03 at gtalumni.org Fri Feb 15 16:39:58 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Fri, 15 Feb 2008 10:39:58 -0500 Subject: [Tutor] designing POOP In-Reply-To: <47B595E7.9040001@tds.net> References: <47ADF7DD.9090209@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B2E4AE.5070409@tds.net> <000201c86f4b$2766fbb0$52fce004@jslaptop> <000801c86f84$003b4670$1cfce004@jslaptop> <47B595E7.9040001@tds.net> Message-ID: <82b4f5810802150739h686ecd13j3f242723761a29cb@mail.gmail.com> I'm firmly with Kent here: OO programming is not about simulation. You are not modeling real world items. You are making code easier to maintain and making parts of code that have to do with one another be near one another. If you spend all your time trying to make your objects into real world things you're actually doing simulation, not programming. As a person who's actually done simulation, I'll state that 's not really a great way to structure code. You spend a lot of time arguing about highly abstract responsibilities of each object in your system, as well as how much it will actually model the real world. Neither one is especially helpful, as neither one is addressing the Why of OO programing. The Why of OO programming today is: To make code more maintainable/usable and to group and to use data in such a way the human mind can easily grasp all the abstract data types that a program operates on. OO programing came from simulation people. They used a language (Simula) to do simulation. It allowed each object to have behavior linked to its type. They were simulating combat and needed to model the behaviors of all the objects (ships) when they all interacted together. Other people saw this (Smalltalk), then copied the system (which they were incidentally using to build Smalltalk at first), but not to simulate real world objects, but to instead better group functions with the data that those functions operate on. Objects could be created on the fly in there system. They first coined the term "Object Oriented Programming". They real novel thing they did with all of this was to build the first windowing GUI's and mice into a programming language. They were not modeling anything in the real world, they were putting all the components and methods pertaining to building a little square on the screen into a class, or all the methods pertaining to a mouse input into a class. When Bjarne Stroustrup made C++, he copied some of the ideas in order to make a better type system, where the functions that operated on a type were put together with the data into an abstract data type by his preprocessor (C++ was a preprocessor for many years before it was a compiler). In his own words: "Object-oriented programming is programming using inheritance. Data abstraction is programming using user-defined types. With few exceptions, object-oriented programming can and ought to be a superset of data abstraction." The key feature of object is *that you make types* (and you put the methods with the type, as part of the type). That you can do polymorphism. Etc. OO is not a glorified simulation system, and you will feel pain if you overemphasize the generalization "Model objects on real world objects". Objects do have to have an idea (Cohesion). It is just, that idea doesn't have to be congruous with something you can walk over to and pick up in the real world. Often it feels like the "Model objects on real world objects" is how people are taught so they get the idea of an object. Actually designing all code that way is a needless proscription that really really hurts many projects. --Michael On Fri, Feb 15, 2008 at 8:38 AM, Kent Johnson wrote: > Tiger12506 wrote: > > > I like things to be explicit, and don't care for the level of > > abstraction common in MVC. I know it seems naive, but I like to be able to > > model object designs after tangible things, and to me, a View does not know > > how to keep a state or execute methods because it does not exist. A > > Controller does not exist alone of the model, and without the view it fails > > to work. > > I agree that this is a naive view, for the same reason I objected to > Alan's "find the nouns" approach to OO design. For me considerations of > cohesion, encapsulation, DRY, testability, and any required reuse or > flexibility are far more important to design than correspondence with > tangible objects. > > Kent > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From babycode at gmail.com Fri Feb 15 17:42:08 2008 From: babycode at gmail.com (jeff) Date: Fri, 15 Feb 2008 11:42:08 -0500 Subject: [Tutor] Processing .NK2 files Message-ID: I need to delete records in an MS Outlook .NK2 file if they contain a specific email address. This code has been inspired mainly by: http://code.google.com/p/debunk2/wiki/fileformat. import re NUL='\x00' sep1 = '\x04H\xfe\x13' # record separator sep2 = '\x00\xdd\x01\x0fT\x02\x00\x00\x01' # record separator p = re.compile('@emaildomain', re.IGNORECASE) props = open('nk2properties.txt', 'r') lines = props.readlines() infile = lines[0].strip() outfile = lines[1].strip() props.close() f = open(infile, 'rb') filedata = f.read() f.close() out = open(outfile, 'wb') for z in filedata.split(sep1): for y in z.split(sep2): split1 = [x.replace(NUL, '') for x in y.split(NUL*3)] for item in split1: m = p.search(item) if m: print m.group() out.write(item) out.close() nk2properties.txt contents: Outlook.NK2 outputfile I'm sure all matches are found. The trouble, it seems, is determining where the records begin and end so I can delete them and keep them in a separate file in case I have to reimport them later. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080215/01d9a2c5/attachment.htm From toby.pas at gmail.com Fri Feb 15 20:44:49 2008 From: toby.pas at gmail.com (Toby) Date: Fri, 15 Feb 2008 13:44:49 -0600 (CST) Subject: [Tutor] total beginner stuff Message-ID: <002101c8700b$3a06bb50$3901a8c0@careplus.local> I've been doing the tutorials online and learning on my own for less than a week (not sure if I'll get blasted for posting questions this soon or not but here goes): I've tried to do some of the online tutorials but they are ALL similar and quickly bypass very basic questions that I'm having difficulty getting past. First off they all want you into interactive mode quickly and it took some time for me to realize why. once I tried using files created in text editors to run code nothing worked! I've run across some tutorials that use for example input() which for whatever reason isn't built into the language??? It just errors out on me and when I remove the input() function it works, well not really works but it doesn't error out on me anymore. There were others like math (which I realized you have to import from somewhere else, still no clue where unless it just works because it does) but this is really causing me a lot of headaches because clearly I missed something pretty basic. Is there some files or libraries that I need to download and do a from whatever import * in order to use a lot of what you guys would consider basic functions? Again, blast me if you wish but please do point me to the correct place to take care of this issue as I'm really interested in learning python but I have as yet to find somewhere that explains this seemingly simple step (I've even tried using idle in hopes it would magically import everything I need, and currently am downloading eclipse with the pydev plug-in from sourceforge) Help! Toby -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080215/ff8b89c0/attachment.htm From kent37 at tds.net Fri Feb 15 21:14:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Feb 2008 15:14:01 -0500 Subject: [Tutor] total beginner stuff In-Reply-To: <002101c8700b$3a06bb50$3901a8c0@careplus.local> References: <002101c8700b$3a06bb50$3901a8c0@careplus.local> Message-ID: <47B5F289.30006@tds.net> Toby wrote: > I?ve been doing the tutorials online and learning on my own for less > than a week (not sure if I?ll get blasted for posting questions this > soon or not but here goes): We don't do much blasting around here, don't worry! > I?ve tried to do some of the online tutorials but they are ALL similar > and quickly bypass very basic questions that I?m having difficulty > getting past. First off they all want you into interactive mode quickly > and it took some time for me to realize why? once I tried using files > created in text editors to run code nothing worked! Specific details are helpful. It's hard to help with "nothing worked". It's much easier if you tell us in detail what you tried and what happened. Start with the simplest thing that is giving you trouble and we'll go from there. > I?ve run across > some tutorials that use for example input() which for whatever reason > isn?t built into the language??? It just errors out on me and when I > remove the input() function it works, well not really works but it > doesn?t error out on me anymore. input() is built into the language. It helps us a lot if you can show the specific error message, including the traceback. Just copy/paste the whole thing into your email. input() asks you for input at the console; possibly you are running your programs in a way that there is no console available? Again, details would help. > There were others like math (which I > realized you have to import from somewhere else, still no clue where > unless it just works because it does) but this is really causing me a > lot of headaches because clearly I missed something pretty basic. You don't really have to understand the details of where files are imported from yet. > Is there some files or libraries that I need to download and do a from > whatever import * in order to use a lot of what you guys would consider > basic functions? No, input() and "import math" should both work out of the box. > Again, blast me if you wish but please do point me to the correct place > to take care of this issue as I?m really interested in learning python > but I have as yet to find somewhere that explains this seemingly simple > step (I?ve even tried using idle in hopes it would magically import > everything I need, and currently am downloading eclipse with the pydev > plug-in from sourceforge) This is a good place for your questions. Take a deep breath, back up to where you were when you first started having trouble and let us know what you tried. Kent From kent37 at tds.net Fri Feb 15 21:46:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Feb 2008 15:46:30 -0500 Subject: [Tutor] total beginner stuff In-Reply-To: <002f01c87013$18ac6560$3901a8c0@careplus.local> References: <002f01c87013$18ac6560$3901a8c0@careplus.local> Message-ID: <47B5FA26.4010507@tds.net> Toby wrote: > Ok well while I was preparing examples and writing down error messages for > posting I realized I was using a single quote instead of a double quote and > it was highlighting the input function but it really did not have a problem > with the function but rather the quotes. That still sounds strange, Python doesn't make any distinction between single and double quotes. You do have to correctly match them, of course... > Wow, five years from now this will undoubtedly be hilarious looking back. > For now I think I'll just bury my head for a while and stfu. Don't worry about it! Kent PS Please use Reply All to reply to the list. From kent37 at tds.net Fri Feb 15 22:15:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 15 Feb 2008 16:15:54 -0500 Subject: [Tutor] [Fwd: RE: total beginner stuff] Message-ID: <47B6010A.3050905@tds.net> Forwarding to the list. -------- Original Message -------- Subject: RE: [Tutor] total beginner stuff Date: Fri, 15 Feb 2008 15:09:38 -0600 (CST) From: Toby To: 'Kent Johnson' Sorry I was using 2 single quotes not 1 so it ''looked'' like a double quote but wasn't. Thanks, I will reply to all from now on! Toby -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Friday, February 15, 2008 2:47 PM To: Toby; tutor-python Subject: Re: [Tutor] total beginner stuff Toby wrote: > Ok well while I was preparing examples and writing down error messages for > posting I realized I was using a single quote instead of a double quote and > it was highlighting the input function but it really did not have a problem > with the function but rather the quotes. That still sounds strange, Python doesn't make any distinction between single and double quotes. You do have to correctly match them, of course... > Wow, five years from now this will undoubtedly be hilarious looking back. > For now I think I'll just bury my head for a while and stfu. Don't worry about it! Kent PS Please use Reply All to reply to the list. From jason at asahnekec.com Sat Feb 16 03:07:13 2008 From: jason at asahnekec.com (Jason Coggins) Date: Fri, 15 Feb 2008 21:07:13 -0500 Subject: [Tutor] the bios serial number References: Message-ID: <006001c87040$a7f72930$6403a8c0@dunamis34752e9> How do you pull up the bios serial number in Python? Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080215/ee28c214/attachment.htm From jason at asahnekec.com Sat Feb 16 03:08:05 2008 From: jason at asahnekec.com (Jason Coggins) Date: Fri, 15 Feb 2008 21:08:05 -0500 Subject: [Tutor] Processing .NK2 files References: Message-ID: <006a01c87040$c728b210$6403a8c0@dunamis34752e9> How can I check the speed of the internet connection in Python? Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080215/863cba7d/attachment.htm From sierra_mtnview at sbcglobal.net Sat Feb 16 05:09:51 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 15 Feb 2008 20:09:51 -0800 Subject: [Tutor] Producing a pop-up on graphics area? Message-ID: <47B6620F.2040801@sbcglobal.net> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080215/a5faad38/attachment.htm From kent37 at tds.net Sat Feb 16 12:50:03 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Feb 2008 06:50:03 -0500 Subject: [Tutor] Producing a pop-up on graphics area? In-Reply-To: <47B6620F.2040801@sbcglobal.net> References: <47B6620F.2040801@sbcglobal.net> Message-ID: <47B6CDEB.1020006@tds.net> Wayne Watson wrote: > I want to allow a user who is looking at a graphic area that contains > an image to be able to right-click on the graphic to produce a menu > of choices. What's available to do that? Typically you would install a right-click handler on the graphic area. The handler pops up the menu. The details depend on what GUI framework you are using. Here is a Tkinter example (though on my Mac seems to be the middle button; changing to makes it use right-click): http://effbot.org/zone/tkinter-popup-menu.htm Kent From murderbystealth at gmail.com Sat Feb 16 14:53:16 2008 From: murderbystealth at gmail.com (=?ISO-8859-1?Q?Michael_Bernhard_Arp_S=F8rensen?=) Date: Sat, 16 Feb 2008 14:53:16 +0100 Subject: [Tutor] Tread or threading Message-ID: <1618520802160553m11145890ye7f72935074fccac@mail.gmail.com> Hi there. I've been reading in books and homepages about threads. Apparently, "threading" is better than "thread", right? I've been trying to write a simple proof of concept code using "treading" inside a class. It was easely done with "thread", but it was a lot harder with "threading". I want to be able to write a program like this: class myapp(): def __init__(self): self.queue = queue.Queue() self.lock = threading.Lock() def inputthread(self): data = get_user_input() self.lock.aquire() self.queue.put(data) self.lock.notifyall() self.lock.release() def outputthread(self): self.lock.aquire() data = self.queue.get() self.lock.notifyall() self.lock.release() print data def main(self): start_inputthread() start_outputthread() wait_for_both_threads_to_end() app = myapp() app.main() All the examples I've seen was done by creating a class as a subclass of threading.Thread. Isn't there a way to make individual methods a thread like we do with the simpler "thread" module, but by using threading? Otherwise would it mean that I should write each method as a threading class. It doesn't make sense yet. Please help me. Thanks in advance. -- Med venlig hilsen/Kind regards Michael B. Arp S?rensen Programm?r / BOFH I am /root and if you see me laughing you better have a backup. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080216/5adf992b/attachment.htm From kent37 at tds.net Sat Feb 16 16:50:32 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 16 Feb 2008 10:50:32 -0500 Subject: [Tutor] Tread or threading In-Reply-To: <1618520802160553m11145890ye7f72935074fccac@mail.gmail.com> References: <1618520802160553m11145890ye7f72935074fccac@mail.gmail.com> Message-ID: <47B70648.20704@tds.net> Michael Bernhard Arp S?rensen wrote: > Hi there. > > I've been reading in books and homepages about threads. Apparently, > "threading" is better than "thread", right? > > I've been trying to write a simple proof of concept code using > "treading" inside a class. It was easely done with "thread", but it was > a lot harder with "threading". I want to be able to write a program like > this: > > class myapp(): > def __init__(self): > self.queue = queue.Queue() > self.lock = threading.Lock() Queue.Queue is already threadsafe, you don't have to add a lock around it. Queue.get() and Queue.put() already have the semantics you are trying to achieve with the lock. > def main(self): > start_inputthread() > start_outputthread() > wait_for_both_threads_to_end() t1 = Thread(target=self.inputthread) # Note no parentheses after inputthread t1.start() t2 = Thread(target=self.outputthread) t2.start() t1.join() t2.join() > All the examples I've seen was done by creating a class as a subclass of > threading.Thread. Isn't there a way to make individual methods a thread > like we do with the simpler "thread" module, but by using threading? Use the target parameter to Thread() to pass an individual method or function. Here is an example: http://redclay.altervista.org/wiki/doku.php?id=projects:python-threading#example_4empy_full_queue Kent From gulfgeek at gmail.com Sat Feb 16 21:49:12 2008 From: gulfgeek at gmail.com (C B Gambrell) Date: Sat, 16 Feb 2008 14:49:12 -0600 Subject: [Tutor] Suggestions to improve this first effort? Message-ID: I am just getting started with Python and wonder if folks here might look at this attempt in Python and offer me your thoughts. Several years ago I used QBasic to convert one our reports to a csv file so we could import the data into another program. That very old QBasic script has been serving me well but I decided to try to make it work in Python. I used the same logic in Python I had used in QBasic and the resulting output is exactly what I need. Here is how the data looks in the input file. ===== ===== .block name 1 address1 city st 11111 .endblock .report .block name 2 address 2 city st 11111 .endblock .report ==== ==== The input file goes on for several thousand addresses. Here is what worked for me in QBasic. === === clin1$ = "" clin2$ = "" infile$ = "ad.txt" outfile$ = "ad.csv" ' OPEN infile$ FOR INPUT AS #1 OPEN outfile$ FOR OUTPUT AS #2 ' DO WHILE NOT EOF(1) LINE INPUT #1, lin$ clin1$ = RTRIM$(LTRIM$(lin$)) IF clin1$ = "" THEN clin1$ = "" ELSEIF clin1$ = ".report" THEN clin1$ = "" ELSEIF clin1$ = ".block" THEN clin1$ = "" ELSEIF clin1$ = ".endblock" THEN WRITE #2, MID$(clin2$, 4) PRINT MID$(clin2$, 4) clin2$ = "" ELSE clin2$ = clin2$ + CHR$(34) + CHR$(44) + CHR$(34) + clin1$ END IF LOOP END ==== ==== And here is my I got work for me in Python. === === import sys infile=sys.argv[1] outfile=sys.argv[1]+".csv" f1=open(infile) f2=open(outfile, 'w') s2="" for line in f1: s=line.strip() if s=="": continue elif s==".block": continue elif s==".report": continue elif s==".endblock": s="\n" s2=s2[:-1]+s f2.write(s2) s2="" continue s2=s2+"\""+s+"\""+"," f1.close() f2.close() === === The script works but what you suggest to improve the logic or make the script more Pythonic? Thanks for this list. I am enjoying reading and learning from the many conversations here. Charles From crunchman2600 at gmail.com Sun Feb 17 00:18:35 2008 From: crunchman2600 at gmail.com (John Luke) Date: Sat, 16 Feb 2008 18:18:35 -0500 Subject: [Tutor] Noob requesting help... Message-ID: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> Hi, I've recently started to get into Python, and I've made a bit a progress so far, but I still have a long way to go. Along my search for tutorials, I've come across this: # Waits until a password has been entered. Use Control-C to break out without # the password #Note that this must not be the password so that the # while loop runs at least once. password = "foobar" # note that != means not equal while password != "unicorn": password = raw_input("Password: ") print "Welcome in" I understand *what's* going on, but I don't understand *why* it's happening. To be more specific, I don't understand why the actual password, "unicorn", is what it is, even though I set the password to "foobar"(password = 'foobar'), and later even stated that the password wasn't "unicorn"(while password != 'unicorn':). Any help would be greatly appreciated. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080216/d74f133a/attachment.htm From marc.tompkins at gmail.com Sun Feb 17 01:59:59 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 16 Feb 2008 16:59:59 -0800 Subject: [Tutor] Fwd: Noob requesting help... In-Reply-To: <40af687b0802161658u2d0ca3bfqf7c791a2f91e0748@mail.gmail.com> References: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> <40af687b0802161658u2d0ca3bfqf7c791a2f91e0748@mail.gmail.com> Message-ID: <40af687b0802161659j62459ab2x7139dc36fbba4ce0@mail.gmail.com> Sorry, I ALWAYS forget to hit 'Reply All'... On Feb 16, 2008 3:18 PM, John Luke wrote: > I understand *what's* going on, but I don't understand *why* it's > happening. To be more specific, I don't understand why the actual password, > "unicorn", is what it is, even though I set the password to > "foobar"(password = 'foobar'), and later even stated that the password > wasn't "unicorn"(while password != 'unicorn':). Any help would be greatly > appreciated. Thanks! > The "while" loop is saying: get input from the user, and as long as the response does NOT equal "unicorn", keep looping. You can't check the value of a variable that doesn't exist yet, so the line 'password = "foobar" ' merely served to to create/initialize the 'password' variable. Faced with a similar situation, I would have said ' password = "" ' to avoid exactly this sort of confusion. In fact, I would have done something like the following: tmp_str = "" # this creates the variable so we can check against its value later on password = "unicorn" while tmp_str != password: tmp_str =raw_input("Password: ") print "Welcome in" I hope that makes things a bit clearer... -- www.fsrtechnologies.com -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080216/0f9a6ea4/attachment.htm From keridee at jayco.net Sun Feb 17 02:21:26 2008 From: keridee at jayco.net (Tiger12506) Date: Sat, 16 Feb 2008 20:21:26 -0500 Subject: [Tutor] Suggestions to improve this first effort? References: Message-ID: <00f801c87103$6e17c030$e5fce004@jslaptop> > And here is my I got work for me in Python. > > === > === > import sys > infile=sys.argv[1] > outfile=sys.argv[1]+".csv" > > f1=open(infile) > f2=open(outfile, 'w') > > s2="" > > for line in f1: > s=line.strip() > if s=="": > continue > elif s==".block": > continue > elif s==".report": > continue > elif s==".endblock": > s="\n" > s2=s2[:-1]+s > f2.write(s2) > s2="" > continue > s2=s2+"\""+s+"\""+"," > > f1.close() > f2.close() > === > === Indentation is paramount in python. Your QBasic code is indented in the email, so I can safely assume that the email is not what's messing up the indentation. You say for line in f1: and then say s = line.strip() why not just for s in f1: s = s.strip() or the same thing with 'line'. You can say if s in ("",".block",".report"): continue elif s == ".endblock": And s2 = s2[:-1] + s can be written as s2 = s2+s beyond that I can't say because the indentation is not there. From keridee at jayco.net Sun Feb 17 02:23:40 2008 From: keridee at jayco.net (Tiger12506) Date: Sat, 16 Feb 2008 20:23:40 -0500 Subject: [Tutor] Suggestions to improve this first effort? References: Message-ID: <00fb01c87103$bdf3c810$e5fce004@jslaptop> > infile$ = "ad.txt" > outfile$ = "ad.csv" > infile=sys.argv[1] > outfile=sys.argv[1]+".csv" And these will give two different results. The QBasic version says "ad.txt" "ad.csv" whereas the python version will give "ad.txt" "ad.txt.csv" so you need to say infile = sys.argv[1] outfile = sys.argv[1][:-3]+'csv' or something equivalent. From marc.tompkins at gmail.com Sun Feb 17 03:04:11 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 16 Feb 2008 18:04:11 -0800 Subject: [Tutor] Noob requesting help... In-Reply-To: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> References: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> Message-ID: <40af687b0802161804j59113f14t25514d6e5972cf5a@mail.gmail.com> John, Luke, Marc... can we get a Matthew to join this thread? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080216/f8926cb9/attachment.htm From bgailer at alum.rpi.edu Sun Feb 17 03:55:20 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 16 Feb 2008 21:55:20 -0500 Subject: [Tutor] Suggestions to improve this first effort? In-Reply-To: References: Message-ID: <47B7A218.8040909@alum.rpi.edu> C B Gambrell wrote: > I am just getting started with Python and wonder if folks here might > look at this attempt in Python and offer me your thoughts. > > Several years ago I used QBasic to convert one our reports to a csv > file so we could import the data into another program. That very old > QBasic script has been serving me well but I decided to try to make it > work in Python. I used the same logic in Python I had used in QBasic > and the resulting output is exactly what I need. > > Here is how the data looks in the input file. > > ===== > ===== > .block > name 1 > address1 > city st > 11111 > .endblock > .report > > > .block > name 2 > address 2 > city st > 11111 > .endblock > .report > ==== > ==== > > The input file goes on for several thousand addresses. > > Here is what worked for me in QBasic. > > === > === > clin1$ = "" > clin2$ = "" > infile$ = "ad.txt" > outfile$ = "ad.csv" > ' > OPEN infile$ FOR INPUT AS #1 > OPEN outfile$ FOR OUTPUT AS #2 > ' > DO WHILE NOT EOF(1) > LINE INPUT #1, lin$ > clin1$ = RTRIM$(LTRIM$(lin$)) > IF clin1$ = "" THEN > clin1$ = "" > ELSEIF clin1$ = ".report" THEN > clin1$ = "" > ELSEIF clin1$ = ".block" THEN > clin1$ = "" > ELSEIF clin1$ = ".endblock" THEN > WRITE #2, MID$(clin2$, 4) > PRINT MID$(clin2$, 4) > clin2$ = "" > ELSE > clin2$ = clin2$ + CHR$(34) + CHR$(44) + CHR$(34) + clin1$ > END IF > LOOP > END > ==== > ==== > > And here is my I got work for me in Python. > > === > === > import sys > infile=sys.argv[1] > outfile=sys.argv[1]+".csv" > > f1=open(infile) > f2=open(outfile, 'w') > > s2="" > > for line in f1: > s=line.strip() > if s=="": > continue > elif s==".block": > continue > elif s==".report": > continue > elif s==".endblock": > s="\n" > s2=s2[:-1]+s > f2.write(s2) > s2="" > continue > s2=s2+"\""+s+"\""+"," > > f1.close() > f2.close() > === > === > > The script works but what you suggest to improve the logic or make the > script more Pythonic? > Dunno if this is more Pythonic, but it's how I'd code it: ... f2 = open(outfile, 'w') for line in f1: if s.startswith(".block"): # start of block s2 = [] elif s==".endblock": f2.write(",".join(s2) + "\n") else: # data record s2.append('"%s"' % line.strip()) ... -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Sun Feb 17 03:58:21 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 16 Feb 2008 21:58:21 -0500 Subject: [Tutor] Noob requesting help... In-Reply-To: <40af687b0802161804j59113f14t25514d6e5972cf5a@mail.gmail.com> References: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> <40af687b0802161804j59113f14t25514d6e5972cf5a@mail.gmail.com> Message-ID: <47B7A2CD.3030504@alum.rpi.edu> Marc Tompkins wrote: > John, Luke, Marc... can we get a Matthew to join this thread? You thinking of Matthew Dixon Coles? But then wouldn't Paul want to get into the Act? -- Bob Gailer 919-636-4239 Chapel Hill, NC From varsha.purohit at gmail.com Sun Feb 17 08:26:13 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sat, 16 Feb 2008 23:26:13 -0800 Subject: [Tutor] [tutor] PIL versus matlab Message-ID: Hello All, I wanted to know what are the advantages and disadvantages of using pIL instead of matlab software to deal to image processing. thanks, -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080216/67227238/attachment.htm From kent37 at tds.net Sun Feb 17 20:54:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Feb 2008 14:54:54 -0500 Subject: [Tutor] Suggestions to improve this first effort? In-Reply-To: <00f801c87103$6e17c030$e5fce004@jslaptop> References: <00f801c87103$6e17c030$e5fce004@jslaptop> Message-ID: <47B8910E.2060507@tds.net> Tiger12506 wrote: > And s2 = s2[:-1] + s > can be written as > s2 = s2+s No, these are not equivalent, the original version strips the last character from s2. Kent From kent37 at tds.net Sun Feb 17 21:05:25 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Feb 2008 15:05:25 -0500 Subject: [Tutor] Suggestions to improve this first effort? In-Reply-To: <47B7A218.8040909@alum.rpi.edu> References: <47B7A218.8040909@alum.rpi.edu> Message-ID: <47B89385.4010901@tds.net> bob gailer wrote: > f2 = open(outfile, 'w') > for line in f1: > if s.startswith(".block"): # start of block > s2 = [] > elif s==".endblock": > f2.write(",".join(s2) + "\n") > else: # data record > s2.append('"%s"' % line.strip()) This is nice & concise. I'm surprised though that no one has mentioned the csv module yet. Rather than inserting the quotes and commas yourself, let the module do it, e.g. import csv f2 = open(outfile, 'wb') # Note: open in binary mode for CSV writer = csv.writer(f2) for line in f1: s = line.strip() if s.startswith(".block"): # start of block s2 = [] elif s==".endblock": writer.writerow(s2) else: # data record s2.append(s) And FWIW I would probably have written it like this, which is a bit wordier, more explicit and less flexible than the above, which may be good or not depending on your data and expectations: import csv ... f2 = open(outfile, 'wb') # Note: open in binary mode for CSV writer = csv.writer(f2) itr = iter(f1) try: while True: s = itr.next().strip() if not s: continue assert s=='.block' name = itr.next().strip() addr = itr.next().strip() city_st = itr.next().strip() zip = itr.next().strip() writer.writerow([name, addr, city_st, zip]) itr.next() itr.next() except StopIteration: pass f2.close() Kent From kent37 at tds.net Sun Feb 17 21:44:16 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 17 Feb 2008 15:44:16 -0500 Subject: [Tutor] Suggestions to improve this first effort? In-Reply-To: <00f801c87103$6e17c030$e5fce004@jslaptop> References: <00f801c87103$6e17c030$e5fce004@jslaptop> Message-ID: <47B89CA0.9050904@tds.net> Tiger12506 wrote: > Indentation is paramount in python. Your QBasic code is indented in the > email, so I can safely assume that the email is not what's messing up the > indentation. The indentation came through fine for me. The Basic code is indented with spaces, the Python code with tabs. Perhaps your mail reader doesn't correctly interpret the tabs. Kent From marc.tompkins at gmail.com Sun Feb 17 22:55:01 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 17 Feb 2008 13:55:01 -0800 Subject: [Tutor] Suggestions to improve this first effort? In-Reply-To: <47B89CA0.9050904@tds.net> References: <00f801c87103$6e17c030$e5fce004@jslaptop> <47B89CA0.9050904@tds.net> Message-ID: <40af687b0802171355j2dee6bdcwc539957af83e25be@mail.gmail.com> > > The indentation came through fine for me. The Basic code is indented > with spaces, the Python code with tabs. Perhaps your mail reader doesn't > correctly interpret the tabs. > This presents a perfect opportunity to remind our new Pythonistas that tabs can be evil (for precisely this reason), and that any decent text editor can easily be set to expand tabs into spaces (either 4 or 8 spaces, depending on your visual preferences, but I believe 4 spaces is pretty standard.) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080217/d3124b18/attachment.htm From sierra_mtnview at sbcglobal.net Mon Feb 18 06:19:25 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 17 Feb 2008 21:19:25 -0800 Subject: [Tutor] Following the Mouse in a Graphics Area Message-ID: <47B9155D.3090706@sbcglobal.net> Win XP. Is there a way to read out the pixel position in a graphics area, and display it so the user knows the x-y values? I want the user to specify the center of a circle he wants drawn on an image. When he specifies the center, then I want to use it as a reference point. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "I know that this defies the law of gravity, but you see, I never studied law." -- Bugs Bunny Web Page: From kent37 at tds.net Mon Feb 18 13:53:45 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Feb 2008 07:53:45 -0500 Subject: [Tutor] Following the Mouse in a Graphics Area In-Reply-To: <47B9155D.3090706@sbcglobal.net> References: <47B9155D.3090706@sbcglobal.net> Message-ID: <47B97FD9.5030003@tds.net> Wayne Watson wrote: > Win XP. > Is there a way to read out the pixel position in a graphics area, and > display it so the user knows the x-y values? I want the user to specify > the center of a circle he wants drawn on an image. When he specifies the > center, then I want to use it as a reference point. Presuming you are still using Tkinter, when the user clicks, the Event object includes the x, y coordinates of the click relative to the top-left of the widget that was clicked. If you want to track mouse motion in a widget, register a handler for the widget. Kent From reed at reedobrien.com Mon Feb 18 15:30:25 2008 From: reed at reedobrien.com (Reed O'Brien) Date: Mon, 18 Feb 2008 09:30:25 -0500 Subject: [Tutor] Noob requesting help... In-Reply-To: <47B7A2CD.3030504@alum.rpi.edu> References: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> <40af687b0802161804j59113f14t25514d6e5972cf5a@mail.gmail.com> <47B7A2CD.3030504@alum.rpi.edu> Message-ID: <0B67DCF4-7E2E-4ABC-AE02-056F4E948F13@reedobrien.com> On Feb 16, 2008, at 9:58 PM, bob gailer wrote: > Marc Tompkins wrote: >> John, Luke, Marc... can we get a Matthew to join this thread? > You thinking of Matthew Dixon Coles? > > But then wouldn't Paul want to get into the Act? For Pete's sake... ~ro From sierra_mtnview at sbcglobal.net Mon Feb 18 16:09:32 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 18 Feb 2008 07:09:32 -0800 Subject: [Tutor] tkSimpleDialog, Tkinter, and IDLE Message-ID: <47B99FAC.1030400@sbcglobal.net> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080218/1537531c/attachment.htm From gulfgeek at gmail.com Mon Feb 18 18:45:13 2008 From: gulfgeek at gmail.com (C B Gambrell) Date: Mon, 18 Feb 2008 11:45:13 -0600 Subject: [Tutor] Suggestions to improve this first effort? In-Reply-To: References: Message-ID: Thanks for the responses. I appreciate your help and pointers to statements and modules I was not aware of. I appreciate leaning about the "evil tab" and attempt to vanish it from any future emails form me. Charles From marc.tompkins at gmail.com Mon Feb 18 19:25:46 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 18 Feb 2008 10:25:46 -0800 Subject: [Tutor] Noob requesting help... In-Reply-To: <0B67DCF4-7E2E-4ABC-AE02-056F4E948F13@reedobrien.com> References: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> <40af687b0802161804j59113f14t25514d6e5972cf5a@mail.gmail.com> <47B7A2CD.3030504@alum.rpi.edu> <0B67DCF4-7E2E-4ABC-AE02-056F4E948F13@reedobrien.com> Message-ID: <40af687b0802181025v18a0249u2dd066cbfb77c40d@mail.gmail.com> Mother Mary comes to me Speaking words of wisdom: Let it be, let it be... On Feb 18, 2008 6:30 AM, Reed O'Brien wrote: > On Feb 16, 2008, at 9:58 PM, bob gailer wrote: > > > Marc Tompkins wrote: > >> John, Luke, Marc... can we get a Matthew to join this thread? > > You thinking of Matthew Dixon Coles? > > > > But then wouldn't Paul want to get into the Act? > > For Pete's sake... > > ~ro > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080218/7e981d94/attachment.htm From bgailer at alum.rpi.edu Mon Feb 18 19:35:43 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Mon, 18 Feb 2008 13:35:43 -0500 Subject: [Tutor] Noob requesting help... In-Reply-To: <40af687b0802181025v18a0249u2dd066cbfb77c40d@mail.gmail.com> References: <35918e020802161518l86e53f8r32035810958387a1@mail.gmail.com> <40af687b0802161804j59113f14t25514d6e5972cf5a@mail.gmail.com> <47B7A2CD.3030504@alum.rpi.edu> <0B67DCF4-7E2E-4ABC-AE02-056F4E948F13@reedobrien.com> <40af687b0802181025v18a0249u2dd066cbfb77c40d@mail.gmail.com> Message-ID: <47B9CFFF.9030801@alum.rpi.edu> This seems to focus on the NT, but from a Python Tutor List perspective I think we are OT. -- Bob Gailer 919-636-4239 Chapel Hill, NC From silas428 at gmail.com Mon Feb 18 19:42:14 2008 From: silas428 at gmail.com (Ryan) Date: Mon, 18 Feb 2008 10:42:14 -0800 Subject: [Tutor] tkSimpleDialog, Tkinter, and IDLE In-Reply-To: <47B99FAC.1030400@sbcglobal.net> References: <47B99FAC.1030400@sbcglobal.net> Message-ID: <1203360134.9195.0.camel@Ubuntu> I don't know anything about tkSimpleDialog, but when you try "import tkinter", make sure it's "import Tkinter". The "T" in Tkinter must be capitalized. On Mon, 2008-02-18 at 07:09 -0800, Wayne Watson wrote: > Is tkSimpleDialog really a part of Tkinter? The reason I ask is that it seems to be neglected in material on Tkinter. For example, in <http://infohost.nmt.edu/tcc/help/pubs/tkinter/> by Shipman. Further, I sometimes see code that has: > > from tkinter import * > import tkSimpleDialog > > The from gets all the names, functions too, so why is it importing the name tkSimpleDialog. Hasn't it just been obtained with from? > > When I enter import tkinter into IDLE, it objects. However, if I run a program in idle that imports it, then all is OK. What's up there? > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > "I know that this defies the law of gravity, but > you see, I never studied law." -- Bugs Bunny > > Web Page: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From silas428 at gmail.com Mon Feb 18 19:57:06 2008 From: silas428 at gmail.com (Ryan) Date: Mon, 18 Feb 2008 10:57:06 -0800 Subject: [Tutor] Web Server Message-ID: <1203361026.7200.0.camel@Ubuntu> I copied a webserver from one O'Reilly's books, but it only works under windows. Can anyone tell me what to change to get it to work under linux? Here is the code: webdir = '.' port = 80 import os, sys from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler if len(sys.argv) > 1: webdir = sys.argv[1] if len(sys.argv) > 2: port = int(sys.argv[2]) print 'webdir "%s", port %s' % (webdir, port) if sys.platform[:3] == 'win': CGIHTTPRequestHandler.have_popen2 = False CGIHTTPRequestHandler.have_popen3 = False sys.path.append('cgi-bin') os.chdir(webdir) srvaddr = ("", port) srvobj = HTTPServer(srvaddr, CGIHTTPRequestHandler) srvobj.serve_forever() From kent37 at tds.net Mon Feb 18 20:05:56 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Feb 2008 14:05:56 -0500 Subject: [Tutor] Web Server In-Reply-To: <1203361026.7200.0.camel@Ubuntu> References: <1203361026.7200.0.camel@Ubuntu> Message-ID: <47B9D714.6080301@tds.net> Ryan wrote: > I copied a webserver from one O'Reilly's books, but it only works under > windows. Can anyone tell me what to change to get it to work under > linux? What happens when you try it? My guess is you get an error opening a socket to listen to port 80. Try port 8000. Kent > Here is the code: > > webdir = '.' > port = 80 > > import os, sys > from BaseHTTPServer import HTTPServer > from CGIHTTPServer import CGIHTTPRequestHandler > > if len(sys.argv) > 1: webdir = sys.argv[1] > if len(sys.argv) > 2: port = int(sys.argv[2]) > print 'webdir "%s", port %s' % (webdir, port) > > if sys.platform[:3] == 'win': > CGIHTTPRequestHandler.have_popen2 = False > CGIHTTPRequestHandler.have_popen3 = False > sys.path.append('cgi-bin') > > os.chdir(webdir) > srvaddr = ("", port) > srvobj = HTTPServer(srvaddr, CGIHTTPRequestHandler) > srvobj.serve_forever() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Feb 18 20:11:24 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Feb 2008 14:11:24 -0500 Subject: [Tutor] tkSimpleDialog, Tkinter, and IDLE In-Reply-To: <47B99FAC.1030400@sbcglobal.net> References: <47B99FAC.1030400@sbcglobal.net> Message-ID: <47B9D85C.6090104@tds.net> Wayne Watson wrote: > Is tkSimpleDialog really a part of Tkinter? It's kind of an add-on, I guess, not in the main Tkinter module: http://docs.python.org/lib/node685.html > I sometimes see code that has: > > from tkinter import * > import tkSimpleDialog > > The from gets all the names, functions too, so why is it importing the name tkSimpleDialog. Because tkSimpleDialog is a separate module, not part of Tkinter proper. > Hasn't it just been obtained with from? No: In [1]: from Tkinter import * In [2]: tkSimpleDialog ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : name 'tkSimpleDialog' is not defined In [3]: import tkSimpleDialog In [4]: tkSimpleDialog Out[4]: > When I enter import tkinter into IDLE, it objects. However, if I run a program in idle that imports it, then all is OK. What's up there? Objects in what way? Error messages are very helpful. IDLE is written in Tkinter so it can sometimes be a problem to develop Tkinter apps in IDLE. Maybe someone else can give details. Kent From silas428 at gmail.com Mon Feb 18 20:16:27 2008 From: silas428 at gmail.com (Ryan) Date: Mon, 18 Feb 2008 11:16:27 -0800 Subject: [Tutor] Web Server In-Reply-To: <47B9D714.6080301@tds.net> References: <1203361026.7200.0.camel@Ubuntu> <47B9D714.6080301@tds.net> Message-ID: <1203362187.7314.0.camel@Ubuntu> Awesome, thanks, I also forgot to check the error messages(had to go to command line and run it as root) On Mon, 2008-02-18 at 14:05 -0500, Kent Johnson wrote: > Ryan wrote: > > I copied a webserver from one O'Reilly's books, but it only works under > > windows. Can anyone tell me what to change to get it to work under > > linux? > > What happens when you try it? My guess is you get an error opening a > socket to listen to port 80. Try port 8000. > > Kent > > > Here is the code: > > > > webdir = '.' > > port = 80 > > > > import os, sys > > from BaseHTTPServer import HTTPServer > > from CGIHTTPServer import CGIHTTPRequestHandler > > > > if len(sys.argv) > 1: webdir = sys.argv[1] > > if len(sys.argv) > 2: port = int(sys.argv[2]) > > print 'webdir "%s", port %s' % (webdir, port) > > > > if sys.platform[:3] == 'win': > > CGIHTTPRequestHandler.have_popen2 = False > > CGIHTTPRequestHandler.have_popen3 = False > > sys.path.append('cgi-bin') > > > > os.chdir(webdir) > > srvaddr = ("", port) > > srvobj = HTTPServer(srvaddr, CGIHTTPRequestHandler) > > srvobj.serve_forever() > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From sierra_mtnview at sbcglobal.net Mon Feb 18 21:37:02 2008 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 18 Feb 2008 12:37:02 -0800 Subject: [Tutor] Putting the Output of Help to a File Message-ID: <47B9EC6E.5040609@sbcglobal.net> See Subject. Is it possible? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "I know that this defies the law of gravity, but you see, I never studied law." -- Bugs Bunny Web Page: From scottwolcott at gmail.com Mon Feb 18 23:17:21 2008 From: scottwolcott at gmail.com (Scott Wolcott) Date: Mon, 18 Feb 2008 16:17:21 -0600 Subject: [Tutor] Silly question: Modifying code while the script is running Message-ID: Okay, I've got this ircbot that i wrote in python, and while we were all making Terminator jokes, it occurred to me that it would actually be reletively easy to have redqueen (that's the bot) write code into another file. Then you just have to specify the file and import the code and run it. It sounds possible, but there are a couple of things i'm not sure how to do. The biggest problem is I'm not sure how to run the external code. Does anyone know of good way to do this, or can someone just point me in the right direction? -Scott -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080218/01e5cb8f/attachment.htm From eike.welk at gmx.net Tue Feb 19 00:09:19 2008 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 19 Feb 2008 00:09:19 +0100 Subject: [Tutor] [tutor] PIL versus matlab In-Reply-To: References: Message-ID: <200802190009.20185.eike.welk@gmx.net> On Sunday 17 February 2008 08:26, Varsha Purohit wrote: > Hello All, > I wanted to know what are the advantages and disadvantages > of using pIL instead of matlab software to deal to image > processing. PIL is for simple tasks like resizing images. It can read and write very many image formats. Matlab sees an image as an array and lets you perform arbitrary mathematical operations on the image. I suppose it also includes the most common image analysis operations as a library. If you want someting comparable to Matlab, but in Python, use Ndimage from Scipy: http://www.scipy.org/SciPyPackages/Ndimage From mlangford.cs03 at gtalumni.org Tue Feb 19 01:01:47 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 18 Feb 2008 19:01:47 -0500 Subject: [Tutor] Silly question: Modifying code while the script is running In-Reply-To: References: Message-ID: <82b4f5810802181601l24bb950fke114fe89fc9c0f1a@mail.gmail.com> import sys code = """import datetime print 'This is a pile of arbitrary code to execute' print sys.argv print datetime.datetime.now()""" if len(sys.argv) > 2: exec(code) else: print "Fooless" --Michael On Feb 18, 2008 5:17 PM, Scott Wolcott wrote: > Okay, I've got this ircbot that i wrote in python, and while we were all > making Terminator jokes, it occurred to me that it would actually be > reletively easy to have redqueen (that's the bot) write code into another > file. Then you just have to specify the file and import the code and run it. > It sounds possible, but there are a couple of things i'm not sure how to do. > > The biggest problem is I'm not sure how to run the external code. Does > anyone know of good way to do this, or can someone just point me in the > right direction? > > -Scott > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From wtfwhoami at gmail.com Tue Feb 19 02:46:39 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Mon, 18 Feb 2008 17:46:39 -0800 Subject: [Tutor] reading webpage Message-ID: <8c64f3990802181746m7d7cc171kf292db693b3023d9@mail.gmail.com> Hi All, I am trying to read a webpage into a variable. My intention is to search for patterns within the page. I am stuck because I get this error shown below .... I have 2.5.1 Windows installer. I have tried repairing it but it takes me down in the same hole ...everything else seems to work fine in python Anyone else who encountered similar problem? Funny thing is it works on my second computer :-| Thanks Gagan >>> import urllib >>> sock = urllib.urlopen("http://www.cnn.com/") Traceback (most recent call last): File "", line 1, in sock = urllib.urlopen("http://www.cnn.com/") File "C:\Python25\lib\urllib.py", line 82, in urlopen return opener.open(url) File "C:\Python25\lib\urllib.py", line 190, in open return getattr(self, name)(url) File "C:\Python25\lib\urllib.py", line 314, in open_http h = httplib.HTTP(host) File "C:\Python25\lib\httplib.py", line 1155, in __init__ self._setup(self._connection_class(host, port, strict)) File "C:\Python25\lib\httplib.py", line 635, in __init__ self._set_hostport(host, port) File "C:\Python25\lib\httplib.py", line 647, in _set_hostport raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) InvalidURL: nonnumeric port: 'port' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080218/4b60fb30/attachment.htm From kent37 at tds.net Tue Feb 19 04:26:29 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 18 Feb 2008 22:26:29 -0500 Subject: [Tutor] reading webpage In-Reply-To: <8c64f3990802181746m7d7cc171kf292db693b3023d9@mail.gmail.com> References: <8c64f3990802181746m7d7cc171kf292db693b3023d9@mail.gmail.com> Message-ID: <47BA4C65.2010409@tds.net> Guess?!? wrote: > Hi All, > > I am trying to read a webpage into a variable. My intention is to search > for patterns within the page. I am stuck because I get this error shown > below .... > I have 2.5.1 Windows installer. I have tried repairing it but it takes > me down in the same hole ...everything else seems to work fine in python > Anyone else who encountered similar problem? A wild guess is that you have a mis-configured proxy on the broken machine. Try this on both machines: import urllib print urllib.getproxies() Kent > > Funny thing is it works on my second computer :-| > > Thanks > Gagan > > >>> import urllib > >>> sock = urllib.urlopen("http://www.cnn.com/") > Traceback (most recent call last): > File "", line 1, in > sock = urllib.urlopen("http://www.cnn.com/") > File "C:\Python25\lib\urllib.py", line 82, in urlopen > return opener.open(url) > File "C:\Python25\lib\urllib.py", line 190, in open > return getattr(self, name)(url) > File "C:\Python25\lib\urllib.py", line 314, in open_http > h = httplib.HTTP(host) > File "C:\Python25\lib\httplib.py", line 1155, in __init__ > self._setup(self._connection_class(host, port, strict)) > File "C:\Python25\lib\httplib.py", line 635, in __init__ > self._set_hostport(host, port) > File "C:\Python25\lib\httplib.py", line 647, in _set_hostport > raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) > InvalidURL: nonnumeric port: 'port' > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From wtfwhoami at gmail.com Tue Feb 19 06:12:36 2008 From: wtfwhoami at gmail.com (Guess?!?) Date: Mon, 18 Feb 2008 21:12:36 -0800 Subject: [Tutor] reading webpage In-Reply-To: <47BA4C65.2010409@tds.net> References: <8c64f3990802181746m7d7cc171kf292db693b3023d9@mail.gmail.com> <47BA4C65.2010409@tds.net> Message-ID: <8c64f3990802182112j212d4fa8qaa636397ff46572a@mail.gmail.com> Hi Kent, Broken machine gives IDLE 1.2.1 >>> import urllib >>> print urllib.getproxies() {'http': 'http://proxy-address:port'} >>> correct machine gives empty dictionary ... { } Thanks Gagan Arora On Feb 18, 2008 7:26 PM, Kent Johnson wrote: > Guess?!? wrote: > > Hi All, > > > > I am trying to read a webpage into a variable. My intention is to search > > for patterns within the page. I am stuck because I get this error shown > > below .... > > I have 2.5.1 Windows installer. I have tried repairing it but it takes > > me down in the same hole ...everything else seems to work fine in python > > Anyone else who encountered similar problem? > > A wild guess is that you have a mis-configured proxy on the broken > machine. Try this on both machines: > import urllib > print urllib.getproxies() > > Kent > > > > > Funny thing is it works on my second computer :-| > > > > Thanks > > Gagan > > > > >>> import urllib > > >>> sock = urllib.urlopen("http://www.cnn.com/") > > Traceback (most recent call last): > > File "", line 1, in > > sock = urllib.urlopen("http://www.cnn.com/") > > File "C:\Python25\lib\urllib.py", line 82, in urlopen > > return opener.open(url) > > File "C:\Python25\lib\urllib.py", line 190, in open > > return getattr(self, name)(url) > > File "C:\Python25\lib\urllib.py", line 314, in open_http > > h = httplib.HTTP(host) > > File "C:\Python25\lib\httplib.py", line 1155, in __init__ > > self._setup(self._connection_class(host, port, strict)) > > File "C:\Python25\lib\httplib.py", line 635, in __init__ > > self._set_hostport(host, port) > > File "C:\Python25\lib\httplib.py", line 647, in _set_hostport > > raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) > > InvalidURL: nonnumeric port: 'port' > > > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > 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/20080218/59932015/attachment.htm From flaper87 at gmail.com Tue Feb 19 10:34:28 2008 From: flaper87 at gmail.com (Flaper87) Date: Tue, 19 Feb 2008 10:34:28 +0100 Subject: [Tutor] Change mouse cursor position Message-ID: Hey Guys!!! is it possible to change the mouse position by passing it the coords? I'm developing an application that needs to be able to change the cursor's possition. O.S. Linux Debian Sid Python: 2.4=< Thanks -- Flavio Percoco Premoli, A.K.A. [Flaper87] http://www.flaper87.org Usuario Linux registrado #436538 Geek by nature, Linux by choice, Debian of course. Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 The Solution to everything: python -c "from struct import pack; print pack('5b', (41*len('99')), pow(8,2)+20, 4900**0.5, range(78)[-1], 10)" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080219/10078746/attachment-0001.htm From kent37 at tds.net Tue Feb 19 13:46:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 19 Feb 2008 07:46:48 -0500 Subject: [Tutor] reading webpage In-Reply-To: <8c64f3990802182112j212d4fa8qaa636397ff46572a@mail.gmail.com> References: <8c64f3990802181746m7d7cc171kf292db693b3023d9@mail.gmail.com> <47BA4C65.2010409@tds.net> <8c64f3990802182112j212d4fa8qaa636397ff46572a@mail.gmail.com> Message-ID: <47BACFB8.9090508@tds.net> Guess?!? wrote: > Hi Kent, > > Broken machine gives > > IDLE 1.2.1 > >>> import urllib > >>> print urllib.getproxies() > {'http': 'http://proxy-address:port' } > >>> > > correct machine gives empty dictionary ... { } Well that is the problem. Now you have to fix it. The proxy comes either from the environment variable HTTP_PROXY or from the Windows registry, I think it is the proxyServer value of the key Software\Microsoft\Windows\CurrentVersion\Internet Settings but I'm not on Windows and this is no longer a Python question so that is as far as I will take it. Kent From bgailer at alum.rpi.edu Tue Feb 19 14:56:50 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 19 Feb 2008 08:56:50 -0500 Subject: [Tutor] Change mouse cursor position In-Reply-To: References: Message-ID: <47BAE022.3090608@alum.rpi.edu> Flaper87 wrote: > Hey Guys!!! > > is it possible to change the mouse position by passing it the coords? > > I'm developing an application that needs to be able to change the > cursor's possition. We need more information. Is this a GUI application? If so which GUI software? Or are you trying to control the mouse in another application? > > O.S. Linux Debian Sid > Python: 2.4=< -- Bob Gailer 919-636-4239 Chapel Hill, NC From flaper87 at gmail.com Tue Feb 19 16:48:11 2008 From: flaper87 at gmail.com (Flaper87) Date: Tue, 19 Feb 2008 16:48:11 +0100 Subject: [Tutor] Change mouse cursor position In-Reply-To: <47BAE022.3090608@alum.rpi.edu> References: <47BAE022.3090608@alum.rpi.edu> Message-ID: it is not a GUI application, i need to be able to change the cursor position if an event happens. 2008/2/19, bob gailer : > > Flaper87 wrote: > > Hey Guys!!! > > > > is it possible to change the mouse position by passing it the coords? > > > > I'm developing an application that needs to be able to change the > > cursor's possition. > We need more information. Is this a GUI application? If so which GUI > software? Or are you trying to control the mouse in another application? > > > > O.S. Linux Debian Sid > > Python: 2.4=< > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > -- Flavio Percoco Premoli, A.K.A. [Flaper87] http://www.flaper87.org Usuario Linux registrado #436538 Geek by nature, Linux by choice, Debian of course. Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 The Solution to everything: python -c "from struct import pack; print pack('5b', (41*len('99')), pow(8,2)+20, 4900**0.5, range(78)[-1], 10)" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080219/6b15c4d5/attachment.htm From bgailer at alum.rpi.edu Tue Feb 19 17:12:19 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 19 Feb 2008 11:12:19 -0500 Subject: [Tutor] Change mouse cursor position In-Reply-To: References: <47BAE022.3090608@alum.rpi.edu> Message-ID: <47BAFFE3.2030801@alum.rpi.edu> Flaper87 wrote: > it is not a GUI application, i need to be able to change the cursor > position if an event happens. Sorry but that does not help at all. I guess you want a character-based console window and ability to respond to user keystrokes. If that is the case use the curses module. If not please explain your situation in more detail. And in future questions please give the relevant details in the original posting. Discovery processes like this are costly to everyone involved. -- Bob Gailer 919-636-4239 Chapel Hill, NC From mlangford.cs03 at gtalumni.org Tue Feb 19 21:02:44 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 19 Feb 2008 15:02:44 -0500 Subject: [Tutor] Change mouse cursor position In-Reply-To: References: Message-ID: <82b4f5810802191202ifa54d6bg23117bc94e60bd1e@mail.gmail.com> I do not know of a python library to do this. Therefore, I'd use a popen call to http://www.hoopajoo.net/projects/xautomation.html. --Michael PS: If we you were on windows, I'd use http://pywinauto.openqa.org/ On Feb 19, 2008 4:34 AM, Flaper87 wrote: > Hey Guys!!! > > is it possible to change the mouse position by passing it the coords? > > I'm developing an application that needs to be able to change the cursor's > possition. > > O.S. Linux Debian Sid > Python: 2.4=< > > Thanks > > -- > Flavio Percoco Premoli, A.K.A. [Flaper87] > http://www.flaper87.org > Usuario Linux registrado #436538 > Geek by nature, Linux by choice, Debian of course. > Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 > The Solution to everything: > python -c "from struct import pack; print pack('5b', (41*len('99')), > pow(8,2)+20, 4900**0.5, range(78)[-1], 10)" > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From cappy2112 at gmail.com Tue Feb 19 22:53:06 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 19 Feb 2008 13:53:06 -0800 Subject: [Tutor] How to deal with a thread that doesn't terminate Message-ID: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> When I executing a program external to the main program in a thread, and that thread hangs, can the thread be terminated? How does one handle this situation? From bgailer at alum.rpi.edu Tue Feb 19 23:02:16 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 19 Feb 2008 17:02:16 -0500 Subject: [Tutor] How to deal with a thread that doesn't terminate In-Reply-To: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> References: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> Message-ID: <47BB51E8.7070506@alum.rpi.edu> Tony Cappellini wrote: > When I executing a program external to the main program in a thread, > and that thread hangs, can the thread be terminated? > Please define "hangs". AFAIK that could mean waiting on an external event / signal / communication that never happens, or running in an "infinite loop". So which is it or is it something else? -- Bob Gailer 919-636-4239 Chapel Hill, NC From cappy2112 at gmail.com Tue Feb 19 23:03:59 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Tue, 19 Feb 2008 14:03:59 -0800 Subject: [Tutor] How to deal with a thread that doesn't terminate In-Reply-To: <47BB51E8.7070506@alum.rpi.edu> References: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> <47BB51E8.7070506@alum.rpi.edu> Message-ID: <8249c4ac0802191403n4efdd461w5fb51d8ff73c6d6b@mail.gmail.com> On Feb 19, 2008 2:02 PM, bob gailer wrote: > Tony Cappellini wrote: > > When I executing a program external to the main program in a thread, > > and that thread hangs, can the thread be terminated? > > > Please define "hangs". > AFAIK that could mean waiting on an external event / signal / > communication that never happens, or running in an "infinite loop". So > which is it or is it something else? Never happens. From bgailer at alum.rpi.edu Wed Feb 20 00:27:16 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 19 Feb 2008 18:27:16 -0500 Subject: [Tutor] How to deal with a thread that doesn't terminate In-Reply-To: <8249c4ac0802191403n4efdd461w5fb51d8ff73c6d6b@mail.gmail.com> References: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> <47BB51E8.7070506@alum.rpi.edu> <8249c4ac0802191403n4efdd461w5fb51d8ff73c6d6b@mail.gmail.com> Message-ID: <47BB65D4.8080706@alum.rpi.edu> Tony Cappellini wrote: > On Feb 19, 2008 2:02 PM, bob gailer wrote: > >> Tony Cappellini wrote: >> >>> When I executing a program external to the main program in a thread, >>> and that thread hangs, can the thread be terminated? >>> >>> >> Please define "hangs". >> > > >> AFAIK that could mean waiting on an external event / signal / >> communication that never happens, or running in an "infinite loop". So >> which is it or is it something else? >> > > Never happens. > Sorry. I don't understand that, so I can't help. Perhaps someone else can. -- Bob Gailer 919-636-4239 Chapel Hill, NC From john at fouhy.net Wed Feb 20 00:57:54 2008 From: john at fouhy.net (John Fouhy) Date: Wed, 20 Feb 2008 12:57:54 +1300 Subject: [Tutor] How to deal with a thread that doesn't terminate In-Reply-To: <47BB65D4.8080706@alum.rpi.edu> References: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> <47BB51E8.7070506@alum.rpi.edu> <8249c4ac0802191403n4efdd461w5fb51d8ff73c6d6b@mail.gmail.com> <47BB65D4.8080706@alum.rpi.edu> Message-ID: <5e58f2e40802191557r75ac1dfek2cf2a217e8004f96@mail.gmail.com> On 20/02/2008, bob gailer wrote: > Tony Cappellini wrote: > > On Feb 19, 2008 2:02 PM, bob gailer wrote: > > > >> Tony Cappellini wrote: > >> > >>> When I executing a program external to the main program in a thread, > >>> and that thread hangs, can the thread be terminated? > >>> > >>> > >> Please define "hangs". > >> > > > > > >> AFAIK that could mean waiting on an external event / signal / > >> communication that never happens, or running in an "infinite loop". So > >> which is it or is it something else? > >> > > > > Never happens. > > > > Sorry. I don't understand that, so I can't help. Perhaps someone else can. I presume he means he defines "hangs" as "waiting on an external event / signal / communicaiton that never happens". AFAIK, there's no good way to kill a thread (google for 'python kill thread' for lots of hits). IME most blocking operations have optional timeout parameters, so you could restructure your main thread loop to wait->work/timeout->repeat, which should make it easier to end the thread. -- John. From justin.mailinglists at gmail.com Wed Feb 20 02:33:35 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 20 Feb 2008 09:33:35 +0800 Subject: [Tutor] Putting the Output of Help to a File Message-ID: <3c6718980802191733n1e3cf250r64e49640730d76bc@mail.gmail.com> > From: Wayne Watson > > See Subject. Is it possible? > python -m pydoc sys > sys.txt more < sys.txt From mlangford.cs03 at gtalumni.org Wed Feb 20 08:23:11 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 20 Feb 2008 02:23:11 -0500 Subject: [Tutor] How to deal with a thread that doesn't terminate In-Reply-To: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> References: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> Message-ID: <82b4f5810802192323t4d53459j80b3343ac0d91102@mail.gmail.com> Instead of using a thread, you could see if you could use a second process. For instance, the following would work on windows (and is killable). import subprocess import win32api class SpawnController(object): def __init__(self,cmd): self.cmdline = cmd def start(self): self.process = subprocess.Popen([self.cmdline]) def stop(self): win32api.TerminateProcess(int(self.process._handle), -1 --michael On Feb 19, 2008 4:53 PM, Tony Cappellini wrote: > When I executing a program external to the main program in a thread, > and that thread hangs, can the thread be terminated? > How does one handle this situation? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From timmichelsen at gmx-topmail.de Wed Feb 20 13:15:28 2008 From: timmichelsen at gmx-topmail.de (Timmie) Date: Wed, 20 Feb 2008 12:15:28 +0000 (UTC) Subject: [Tutor] using os module on windows Message-ID: Dear list, I have some problems using the os module on windows. I kindly ask you do give me advice why os.remove and os.shutil fail here: ### using remove ## #!/usr/bin/env python # -*- coding: utf-8 -*- import shutil import os ###### config ###### source = 'C:/my/local/directory' dest = 'Z:/my/network/drive' ## start action #os.remove(dest) ## error output Traceback (most recent call last): File "test_os_on_win", line 14, in os.remove(dest) WindowsError: [Error 5] Zugriff verweigert: 'Z:/my/network/drive' #### using shutil #!/usr/bin/env python # -*- coding: utf-8 -*- import shutil import os ###### config ###### source = 'C:/my/local/directory' dest = 'Z:/my/network/drive' ## start action shutil.copytree(source, dest) Traceback (most recent call last): File "test_os_on_win", line 17, in shutil.copytree(source, dest) File "C:\python\lib\shutil.py", line 110, in copytree os.makedirs(dst) File "C:\python\lib\os.py", line 172, in makedirs mkdir(name, mode) WindowsError: [Error 183] Eine Datei kann nicht erstellt werden, wenn sie bereits vorhanden ist: 'Z:/my/network/drive' Thanks in advance an dkind regards, Timmie From kent37 at tds.net Wed Feb 20 14:42:54 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Feb 2008 08:42:54 -0500 Subject: [Tutor] using os module on windows In-Reply-To: References: Message-ID: <47BC2E5E.7040006@tds.net> Timmie wrote: > ###### config ###### > source = 'C:/my/local/directory' > dest = 'Z:/my/network/drive' > ## start action > #os.remove(dest) > > ## error output > Traceback (most recent call last): > File "test_os_on_win", line 14, in > os.remove(dest) > WindowsError: [Error 5] Zugriff verweigert: 'Z:/my/network/drive' os.remove() removes files, is Z:/my/network/drive a file or a directory? os.rmdir() removes *empty* directories IIRC. shutir.rmtree() will remove an entire directory tree and the files in it. > #!/usr/bin/env python > # -*- coding: utf-8 -*- > import shutil > import os > > ###### config ###### > source = 'C:/my/local/directory' > dest = 'Z:/my/network/drive' > ## start action > > shutil.copytree(source, dest) > > Traceback (most recent call last): > File "test_os_on_win", line 17, in > shutil.copytree(source, dest) > File "C:\python\lib\shutil.py", line 110, in copytree > os.makedirs(dst) > File "C:\python\lib\os.py", line 172, in makedirs > mkdir(name, mode) > WindowsError: [Error 183] Eine Datei kann nicht erstellt werden, wenn sie > bereits vorhanden ist: 'Z:/my/network/drive' The destination path should not already exist, it should end with the directory you want to create. Did you read the docs for copytree()? They say, "The destination directory, named by dst, must not already exist; it will be created as well as missing parent directories." Try shutil.copytree(source, os.path.join(dest, 'copy_of_c')) Kent From rabidpoobear at gmail.com Wed Feb 20 15:38:15 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 20 Feb 2008 08:38:15 -0600 Subject: [Tutor] Silly question: Modifying code while the script is running In-Reply-To: References: Message-ID: <47BC3B57.3080000@gmail.com> Scott Wolcott wrote: > Okay, I've got this ircbot that i wrote in python, and while we were > all making Terminator jokes, it occurred to me that it would actually > be reletively easy to have redqueen (that's the bot) write code into > another file. Then you just have to specify the file and import the > code and run it. It sounds possible, but there are a couple of things > i'm not sure how to do. If you have your script write properly-formatted python to a .py file, you can just import() the script it writes, and reload() it whenever you make changes. imported scripts are automatically executed. (I assume on reload they are also, but you should check this.) This is considered taboo unless it's very necessary, but I hope you have fun anyway. Let me know how it goes. HTH, -Luke From timmichelsen at gmx-topmail.de Wed Feb 20 16:59:43 2008 From: timmichelsen at gmx-topmail.de (Timmie) Date: Wed, 20 Feb 2008 15:59:43 +0000 (UTC) Subject: [Tutor] using os module on windows References: <47BC2E5E.7040006@tds.net> Message-ID: Thanks for your reply! > The destination path should not already exist, it should end with the > directory you want to create. Did you read the docs for copytree()? They > say, "The destination directory, named by dst, must not already exist; > it will be created as well as missing parent directories." Which command do you recommend if the destination already exists? I'd like to overwrite or sychronise a local with a remote directory and therefore the destinations files already exist. Regards, Timmie From cappy2112 at gmail.com Wed Feb 20 18:49:34 2008 From: cappy2112 at gmail.com (Tony Cappellini) Date: Wed, 20 Feb 2008 09:49:34 -0800 Subject: [Tutor] How to deal with a thread that doesn't terminate In-Reply-To: <82b4f5810802192323t4d53459j80b3343ac0d91102@mail.gmail.com> References: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com> <82b4f5810802192323t4d53459j80b3343ac0d91102@mail.gmail.com> Message-ID: <8249c4ac0802200949j260db66cp2d37bc9b75aae6dd@mail.gmail.com> Thanks Michael. On Feb 19, 2008 11:23 PM, Michael Langford wrote: > Instead of using a thread, you could see if you could use a second > process. For instance, the following would work on windows (and is > killable). > > import subprocess > import win32api > > class SpawnController(object): > def __init__(self,cmd): > self.cmdline = cmd > > def start(self): > self.process = subprocess.Popen([self.cmdline]) > > def stop(self): > win32api.TerminateProcess(int(self.process._handle), -1 > > --michael > > > On Feb 19, 2008 4:53 PM, Tony Cappellini wrote: > > When I executing a program external to the main program in a thread, > > and that thread hangs, can the thread be terminated? > > How does one handle this situation? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.RowdyLabs.com > From kent37 at tds.net Wed Feb 20 20:53:36 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Feb 2008 14:53:36 -0500 Subject: [Tutor] using os module on windows In-Reply-To: References: <47BC2E5E.7040006@tds.net> Message-ID: <47BC8540.7030606@tds.net> Timmie wrote: > Which command do you recommend if the destination already exists? > I'd like to overwrite or sychronise a local with a remote directory and > therefore the destinations files already exist. Delete, then copy. Or use rsync instead of Python... Kent From toby.pas at gmail.com Wed Feb 20 18:41:33 2008 From: toby.pas at gmail.com (Toby) Date: Wed, 20 Feb 2008 11:41:33 -0600 (CST) Subject: [Tutor] DATA TYPES In-Reply-To: Message-ID: <000f01c873e7$d6076e70$3901a8c0@careplus.local> As I understand it python is not a strongly typed language so no declaration of variables is necessary. My question is this: If I use a variable in a program that stores certain numbers and I'm porting it to say ... java where I must first declare the variables before I use them how do I find out what type to give that variable, specifically is there a way to identify the type of a variable used in a python program for reference? What I'm saying is if I have used a certain variable to hold literally dozens of different values and I BELIEVE them all to be integers but I'm not entirely sure that I have not stumbled into the float realm is there a way to have python list all variables contained in a program and tell me what type it has internally stored them as? I realize I could trudge through the entire 1000 lines and check all the variables and see what values I have assigned them one at a time but I'm wondering if there is an easier way to get that data? Thanks Toby -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of tutor-request at python.org Sent: Wednesday, February 20, 2008 1:23 AM To: tutor at python.org Subject: Tutor Digest, Vol 48, Issue 48 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: reading webpage (Kent Johnson) 2. Re: Change mouse cursor position (bob gailer) 3. Re: Change mouse cursor position (Flaper87) 4. Re: Change mouse cursor position (bob gailer) 5. Re: Change mouse cursor position (Michael Langford) 6. How to deal with a thread that doesn't terminate (Tony Cappellini) 7. Re: How to deal with a thread that doesn't terminate (bob gailer) 8. Re: How to deal with a thread that doesn't terminate (Tony Cappellini) 9. Re: How to deal with a thread that doesn't terminate (bob gailer) 10. Re: How to deal with a thread that doesn't terminate (John Fouhy) 11. Re: Putting the Output of Help to a File (Justin Ezequiel) 12. Re: How to deal with a thread that doesn't terminate (Michael Langford) ---------------------------------------------------------------------- Message: 1 Date: Tue, 19 Feb 2008 07:46:48 -0500 From: Kent Johnson Subject: Re: [Tutor] reading webpage To: "Guess?!?" Cc: tutor at python.org Message-ID: <47BACFB8.9090508 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Guess?!? wrote: > Hi Kent, > > Broken machine gives > > IDLE 1.2.1 > >>> import urllib > >>> print urllib.getproxies() > {'http': 'http://proxy-address:port' } > >>> > > correct machine gives empty dictionary ... { } Well that is the problem. Now you have to fix it. The proxy comes either from the environment variable HTTP_PROXY or from the Windows registry, I think it is the proxyServer value of the key Software\Microsoft\Windows\CurrentVersion\Internet Settings but I'm not on Windows and this is no longer a Python question so that is as far as I will take it. Kent ------------------------------ Message: 2 Date: Tue, 19 Feb 2008 08:56:50 -0500 From: bob gailer Subject: Re: [Tutor] Change mouse cursor position To: Flaper87 Cc: Tutor at python.org Message-ID: <47BAE022.3090608 at alum.rpi.edu> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Flaper87 wrote: > Hey Guys!!! > > is it possible to change the mouse position by passing it the coords? > > I'm developing an application that needs to be able to change the > cursor's possition. We need more information. Is this a GUI application? If so which GUI software? Or are you trying to control the mouse in another application? > > O.S. Linux Debian Sid > Python: 2.4=< -- Bob Gailer 919-636-4239 Chapel Hill, NC ------------------------------ Message: 3 Date: Tue, 19 Feb 2008 16:48:11 +0100 From: Flaper87 Subject: Re: [Tutor] Change mouse cursor position To: "bob gailer" Cc: Tutor at python.org Message-ID: Content-Type: text/plain; charset="iso-8859-1" it is not a GUI application, i need to be able to change the cursor position if an event happens. 2008/2/19, bob gailer : > > Flaper87 wrote: > > Hey Guys!!! > > > > is it possible to change the mouse position by passing it the coords? > > > > I'm developing an application that needs to be able to change the > > cursor's possition. > We need more information. Is this a GUI application? If so which GUI > software? Or are you trying to control the mouse in another application? > > > > O.S. Linux Debian Sid > > Python: 2.4=< > -- > Bob Gailer > 919-636-4239 Chapel Hill, NC > > -- Flavio Percoco Premoli, A.K.A. [Flaper87] http://www.flaper87.org Usuario Linux registrado #436538 Geek by nature, Linux by choice, Debian of course. Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 The Solution to everything: python -c "from struct import pack; print pack('5b', (41*len('99')), pow(8,2)+20, 4900**0.5, range(78)[-1], 10)" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080219/6b15c4d5/attachm ent-0001.htm ------------------------------ Message: 4 Date: Tue, 19 Feb 2008 11:12:19 -0500 From: bob gailer Subject: Re: [Tutor] Change mouse cursor position To: Flaper87 Cc: Tutor at python.org Message-ID: <47BAFFE3.2030801 at alum.rpi.edu> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Flaper87 wrote: > it is not a GUI application, i need to be able to change the cursor > position if an event happens. Sorry but that does not help at all. I guess you want a character-based console window and ability to respond to user keystrokes. If that is the case use the curses module. If not please explain your situation in more detail. And in future questions please give the relevant details in the original posting. Discovery processes like this are costly to everyone involved. -- Bob Gailer 919-636-4239 Chapel Hill, NC ------------------------------ Message: 5 Date: Tue, 19 Feb 2008 15:02:44 -0500 From: "Michael Langford" Subject: Re: [Tutor] Change mouse cursor position To: Flaper87 Cc: Tutor at python.org Message-ID: <82b4f5810802191202ifa54d6bg23117bc94e60bd1e at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 I do not know of a python library to do this. Therefore, I'd use a popen call to http://www.hoopajoo.net/projects/xautomation.html. --Michael PS: If we you were on windows, I'd use http://pywinauto.openqa.org/ On Feb 19, 2008 4:34 AM, Flaper87 wrote: > Hey Guys!!! > > is it possible to change the mouse position by passing it the coords? > > I'm developing an application that needs to be able to change the cursor's > possition. > > O.S. Linux Debian Sid > Python: 2.4=< > > Thanks > > -- > Flavio Percoco Premoli, A.K.A. [Flaper87] > http://www.flaper87.org > Usuario Linux registrado #436538 > Geek by nature, Linux by choice, Debian of course. > Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 > The Solution to everything: > python -c "from struct import pack; print pack('5b', (41*len('99')), > pow(8,2)+20, 4900**0.5, range(78)[-1], 10)" > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com ------------------------------ Message: 6 Date: Tue, 19 Feb 2008 13:53:06 -0800 From: "Tony Cappellini" Subject: [Tutor] How to deal with a thread that doesn't terminate To: "Tutor Python" Message-ID: <8249c4ac0802191353n7b07c87dxed50af4df38ade63 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 When I executing a program external to the main program in a thread, and that thread hangs, can the thread be terminated? How does one handle this situation? ------------------------------ Message: 7 Date: Tue, 19 Feb 2008 17:02:16 -0500 From: bob gailer Subject: Re: [Tutor] How to deal with a thread that doesn't terminate To: cappy2112 at gmail.com Cc: Tutor Python Message-ID: <47BB51E8.7070506 at alum.rpi.edu> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Tony Cappellini wrote: > When I executing a program external to the main program in a thread, > and that thread hangs, can the thread be terminated? > Please define "hangs". AFAIK that could mean waiting on an external event / signal / communication that never happens, or running in an "infinite loop". So which is it or is it something else? -- Bob Gailer 919-636-4239 Chapel Hill, NC ------------------------------ Message: 8 Date: Tue, 19 Feb 2008 14:03:59 -0800 From: "Tony Cappellini" Subject: Re: [Tutor] How to deal with a thread that doesn't terminate To: "bob gailer" Cc: Tutor Python Message-ID: <8249c4ac0802191403n4efdd461w5fb51d8ff73c6d6b at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On Feb 19, 2008 2:02 PM, bob gailer wrote: > Tony Cappellini wrote: > > When I executing a program external to the main program in a thread, > > and that thread hangs, can the thread be terminated? > > > Please define "hangs". > AFAIK that could mean waiting on an external event / signal / > communication that never happens, or running in an "infinite loop". So > which is it or is it something else? Never happens. ------------------------------ Message: 9 Date: Tue, 19 Feb 2008 18:27:16 -0500 From: bob gailer Subject: Re: [Tutor] How to deal with a thread that doesn't terminate To: cappy2112 at gmail.com Cc: Tutor Python Message-ID: <47BB65D4.8080706 at alum.rpi.edu> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Tony Cappellini wrote: > On Feb 19, 2008 2:02 PM, bob gailer wrote: > >> Tony Cappellini wrote: >> >>> When I executing a program external to the main program in a thread, >>> and that thread hangs, can the thread be terminated? >>> >>> >> Please define "hangs". >> > > >> AFAIK that could mean waiting on an external event / signal / >> communication that never happens, or running in an "infinite loop". So >> which is it or is it something else? >> > > Never happens. > Sorry. I don't understand that, so I can't help. Perhaps someone else can. -- Bob Gailer 919-636-4239 Chapel Hill, NC ------------------------------ Message: 10 Date: Wed, 20 Feb 2008 12:57:54 +1300 From: "John Fouhy" Subject: Re: [Tutor] How to deal with a thread that doesn't terminate To: "bob gailer" Cc: Tutor Python , cappy2112 at gmail.com Message-ID: <5e58f2e40802191557r75ac1dfek2cf2a217e8004f96 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On 20/02/2008, bob gailer wrote: > Tony Cappellini wrote: > > On Feb 19, 2008 2:02 PM, bob gailer wrote: > > > >> Tony Cappellini wrote: > >> > >>> When I executing a program external to the main program in a thread, > >>> and that thread hangs, can the thread be terminated? > >>> > >>> > >> Please define "hangs". > >> > > > > > >> AFAIK that could mean waiting on an external event / signal / > >> communication that never happens, or running in an "infinite loop". So > >> which is it or is it something else? > >> > > > > Never happens. > > > > Sorry. I don't understand that, so I can't help. Perhaps someone else can. I presume he means he defines "hangs" as "waiting on an external event / signal / communicaiton that never happens". AFAIK, there's no good way to kill a thread (google for 'python kill thread' for lots of hits). IME most blocking operations have optional timeout parameters, so you could restructure your main thread loop to wait->work/timeout->repeat, which should make it easier to end the thread. -- John. ------------------------------ Message: 11 Date: Wed, 20 Feb 2008 09:33:35 +0800 From: "Justin Ezequiel" Subject: Re: [Tutor] Putting the Output of Help to a File To: tutor at python.org Message-ID: <3c6718980802191733n1e3cf250r64e49640730d76bc at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 > From: Wayne Watson > > See Subject. Is it possible? > python -m pydoc sys > sys.txt more < sys.txt ------------------------------ Message: 12 Date: Wed, 20 Feb 2008 02:23:11 -0500 From: "Michael Langford" Subject: Re: [Tutor] How to deal with a thread that doesn't terminate To: cappy2112 at gmail.com Cc: Tutor Python Message-ID: <82b4f5810802192323t4d53459j80b3343ac0d91102 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 Instead of using a thread, you could see if you could use a second process. For instance, the following would work on windows (and is killable). import subprocess import win32api class SpawnController(object): def __init__(self,cmd): self.cmdline = cmd def start(self): self.process = subprocess.Popen([self.cmdline]) def stop(self): win32api.TerminateProcess(int(self.process._handle), -1 --michael On Feb 19, 2008 4:53 PM, Tony Cappellini wrote: > When I executing a program external to the main program in a thread, > and that thread hangs, can the thread be terminated? > How does one handle this situation? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 48, Issue 48 ************************************* From bhaaluu at gmail.com Wed Feb 20 21:23:57 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 20 Feb 2008 15:23:57 -0500 Subject: [Tutor] results not quite 100 percent yet In-Reply-To: <479FE03D.5050406@tds.net> References: <479FE03D.5050406@tds.net> Message-ID: As far as I can see, these routines give me the results I'm looking for. I get a distribution of four negative numbers, four positive integers in the range 10 to 110, and nothing is placed in room 6 or room 11: #!/usr/bin/python import random #print "\n"*30 table= [[ 0, 2, 0, 0, 0, 0, 0], # 1 [ 1, 3, 3, 0, 0, 0, 0], # 2 [ 2, 0, 5, 2, 0, 0, 0], # 3 [ 0, 5, 0, 0, 0, 0, 0], # 4 [ 4, 0, 0, 3,15,13, 0], # 5 [ 0, 0, 1, 0, 0, 0, 0], # 6 [ 0, 8, 0, 0, 0, 0, 0], # 7 [ 7,10, 0, 0, 0, 0, 0], # 8 [ 0,19, 0, 0, 0, 8, 0], # 9 [ 8, 0,11, 0, 0, 0, 0], # 10 [ 0, 0,10, 0, 0, 0, 0], # 11 [ 0, 0, 0,13, 0, 0, 0], # 12 [ 0, 0,12, 0, 5, 0, 0], # 13 [ 0,15,17, 0, 0, 0, 0], # 14 [14, 0, 0, 0, 0, 5, 0], # 15 [17, 0,19, 0, 0, 0, 0], # 16 [18,16, 0,14, 0, 0, 0], # 17 [ 0,17, 0, 0, 0, 0, 0], # 18 [ 9, 0, 0,16, 0, 0, 0]] # 19 # Distribute the treasure J = 0 while J <= 3: T = int(random.random()*19)+1 if T == 6: continue if T == 11: continue if T == 13: continue if table[T-1][6] != 0: continue b = range(10,110) treasure = random.choice(b) table[T-1][6] = treasure J += 1 # Place androids/aliens in rooms J = 4 while J > 0: T = int(random.random()*19)+1 if T == 6: continue if T == 11: continue if T == 13: continue if table[T-1][6] != 0: continue table[T-1][6] = -J J -= 1 #print dir(table) for i in range(0,19): print ("%3d" % table[i][6]), "Rm#",i+1 I simply threw away all the previous attempts that weren't quite 100% and started over. The final test will be to put these routines in the old games, and see how they work. -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Wed Feb 20 21:26:04 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Feb 2008 15:26:04 -0500 Subject: [Tutor] DATA TYPES In-Reply-To: <000f01c873e7$d6076e70$3901a8c0@careplus.local> References: <000f01c873e7$d6076e70$3901a8c0@careplus.local> Message-ID: <47BC8CDC.3090009@tds.net> Toby wrote: > As I understand it python is not a strongly typed language so no declaration > of variables is necessary. Actually Python has strong, dynamic typing but I guess that is a discussion for another thread. > If I use a variable in a program that stores certain numbers and I'm porting > it to say ... java Do you know about Jython? Maybe you don't have to port it. > where I must first declare the variables before I use > them how do I find out what type to give that variable, specifically is > there a way to identify the type of a variable used in a python program for > reference? Not easily. > What I'm saying is if I have used a certain variable to hold literally > dozens of different values and I BELIEVE them all to be integers but I'm not > entirely sure that I have not stumbled into the float realm is there a way > to have python list all variables contained in a program and tell me what > type it has internally stored them as? I realize I could trudge through the > entire 1000 lines and check all the variables and see what values I have > assigned them one at a time but I'm wondering if there is an easier way to > get that data? I guess this is possible in principle at least using sys.settrace(): http://docs.python.org/lib/debugger-hooks.html#debugger-hooks For example CodeInvestigator gathers the information you want, though it doesn't present it in the fashion you want. You could look at how they do it...the trace module is another example. http://codeinvestigator.googlepages.com/main http://docs.python.org/lib/trace-api.html Kent From mlangford.cs03 at gtalumni.org Wed Feb 20 21:53:06 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 20 Feb 2008 15:53:06 -0500 Subject: [Tutor] DATA TYPES In-Reply-To: <000f01c873e7$d6076e70$3901a8c0@careplus.local> References: <000f01c873e7$d6076e70$3901a8c0@careplus.local> Message-ID: <82b4f5810802201253g27e54050n767beb11ddd479af@mail.gmail.com> On Wed, Feb 20, 2008 at 12:41 PM, Toby wrote: > I have used a certain variable to hold literally > dozens of different values and I BELIEVE them all to be integers but I'm not > entirely sure that I have not stumbled into the float realm is there a way > to have python list all variables contained in a program and tell me what > type it has internally stored them as? fyi, it sounds like you did something bad here. Reusing variables to stand in for several different things, in general, a bad idea. It is very confusing to humans (including you, later on). You should try to keep names alive for a short a distance as possible (there is a metric for this, called span, which you should try to minimize. There are tools that help you practice this). Now Kent can probably testify to as to if this is a good idea (he knows a lot more about these python innards than I do), but you can print out the type of the local variables at the end of your functions. i.e.: for var in locals().copy(): print "varname: %s type: %s" (var,type(var)) After you've done that, you can see what type is referred to by each name at the end of the function, then with some unit tests you should be able to tell if you temporarily changed to a different data type in the middle. If nothing else, you should be able to write the unit tests in jython/cpython compatable code so you don't have to write them twice. Or you can absolutely litter your code with this loop and go through the output for lines that are wrong. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From kent37 at tds.net Wed Feb 20 22:21:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Feb 2008 16:21:40 -0500 Subject: [Tutor] DATA TYPES In-Reply-To: <82b4f5810802201253g27e54050n767beb11ddd479af@mail.gmail.com> References: <000f01c873e7$d6076e70$3901a8c0@careplus.local> <82b4f5810802201253g27e54050n767beb11ddd479af@mail.gmail.com> Message-ID: <47BC99E4.4080904@tds.net> Michael Langford wrote: >you can > print out the type of the local variables at the end of your > functions. > > i.e.: > > for var in locals().copy(): > print "varname: %s type: %s" (var,type(var)) I was thinking more or less along the same lines, but - you don't need the copy() - locals is a dict mapping names to values, so something like for name, value in locals().iteritems(): print "varname: %s type: %s" (name,type(value)) would work better - Since the OP is trying to find cases where the same variable is assigned different types, presumably in a single scope, checking just at the end of a function won't help. > After you've done that, you can see what type is referred to by each > name at the end of the function, then with some unit tests you should > be able to tell if you temporarily changed to a different data type in > the middle. If nothing else, you should be able to write the unit > tests in jython/cpython compatable code so you don't have to write > them twice. Not sure how you would do that with unit tests? > Or you can absolutely litter your code with this loop and > go through the output for lines that are wrong. That is basically what you could do with settrace(). Rather than printing a bunch of output, perhaps maintaining a dict that maps name to a set of types would work. settrace() notifies it's target when a scope is entered or exited so you could monitor values in each scope separately. It gets tricky though, with things like this: def square(x): return x*x square(1) # x is an integer square(1+1j) # x is a complex number or def foo(): for i in range(3): print i # integer for j in range 3: i = j/2.0 # different type in a different block but same scope print i # float, is this an error? Bottom line: if you can define clearly what you want, there is probably a way to get it with settrace() and locals() but it is not a simple problem. Kent From keridee at jayco.net Thu Feb 21 00:02:58 2008 From: keridee at jayco.net (Tiger12506) Date: Wed, 20 Feb 2008 18:02:58 -0500 Subject: [Tutor] DATA TYPES References: <000f01c873e7$d6076e70$3901a8c0@careplus.local> Message-ID: <006b01c87416$543a5270$85fde004@jslaptop> > As I understand it python is not a strongly typed language so no > declaration > of variables is necessary. My question is this: > > If I use a variable in a program that stores certain numbers and I'm > porting > it to say ... java where I must first declare the variables before I use > them how do I find out what type to give that variable, specifically is > there a way to identify the type of a variable used in a python program > for > reference? > > What I'm saying is if I have used a certain variable to hold literally > dozens of different values and I BELIEVE them all to be integers but I'm > not > entirely sure that I have not stumbled into the float realm is there a way > to have python list all variables contained in a program and tell me what > type it has internally stored them as? I realize I could trudge through > the > entire 1000 lines and check all the variables and see what values I have > assigned them one at a time but I'm wondering if there is an easier way to > get that data? import copy di = copy.copy(globals()) for y, z in di.iteritems(): print y, "is of type: ",type(z) From keridee at jayco.net Thu Feb 21 00:13:14 2008 From: keridee at jayco.net (Tiger12506) Date: Wed, 20 Feb 2008 18:13:14 -0500 Subject: [Tutor] How to deal with a thread that doesn't terminate References: <8249c4ac0802191353n7b07c87dxed50af4df38ade63@mail.gmail.com><82b4f5810802192323t4d53459j80b3343ac0d91102@mail.gmail.com> <8249c4ac0802200949j260db66cp2d37bc9b75aae6dd@mail.gmail.com> Message-ID: <006c01c87416$5517e130$85fde004@jslaptop> Similar to the TerminateProcess function in win32api, there is the TerminateThread function which you can use if you know the handle of the thread, but it seems that you can only get the thread handle if you are calling from that thread, or if you were the one who created it (and saved the return of CreateThread). You can get the thread handle with GetCurrentThread. (these are all win32api functions) From keridee at jayco.net Thu Feb 21 00:23:00 2008 From: keridee at jayco.net (Tiger12506) Date: Wed, 20 Feb 2008 18:23:00 -0500 Subject: [Tutor] DATA TYPES References: <000f01c873e7$d6076e70$3901a8c0@careplus.local><82b4f5810802201253g27e54050n767beb11ddd479af@mail.gmail.com> <47BC99E4.4080904@tds.net> Message-ID: <007601c87417$af897470$85fde004@jslaptop> > I was thinking more or less along the same lines, but > - you don't need the copy() Hehehe, did you try it Kent? > - locals is a dict mapping names to values, so something like > for name, value in locals().iteritems(): > print "varname: %s type: %s" (name,type(value)) And this returns Traceback (most recent call last): File "C:\Documents and Settings\Jacob\Desktop\diction.py", line 2, in print "varname: %s type: %s" (name,type(value)) TypeError: 'str' object is not callable Which is not what I expected! Until I realized that you are missing the % sign in between the print string and the tuple of values to interpolate Then it returns this: varname: __builtins__ type: Traceback (most recent call last): File "C:\Documents and Settings\Jacob\Desktop\diction.py", line 1, in for name, value in locals().iteritems(): RuntimeError: dictionary changed size during iteration The .copy() is necessary. From kent37 at tds.net Thu Feb 21 00:38:44 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 20 Feb 2008 18:38:44 -0500 Subject: [Tutor] DATA TYPES In-Reply-To: <007601c87417$af897470$85fde004@jslaptop> References: <000f01c873e7$d6076e70$3901a8c0@careplus.local><82b4f5810802201253g27e54050n767beb11ddd479af@mail.gmail.com> <47BC99E4.4080904@tds.net> <007601c87417$af897470$85fde004@jslaptop> Message-ID: <47BCBA04.2020706@tds.net> Tiger12506 wrote: > Hehehe, did you try it Kent? Obviously not :-) > Which is not what I expected! > Until I realized that you are missing the % sign in between the print string > and the tuple of values to interpolate Blame that one on Michael, I copied from him :-) > Then it returns this: > varname: __builtins__ type: > > Traceback (most recent call last): > File "C:\Documents and Settings\Jacob\Desktop\diction.py", line 1, in > > for name, value in locals().iteritems(): > RuntimeError: dictionary changed size during iteration > > The .copy() is necessary. Ok. Or use locals().items() which implicitly copies by making a list of key, value pairs. Though I suspect a robust solution will involve inspecting the stack frame passed to a sys.settrace() callback, not looking at locals() directly... Kent From keridee at jayco.net Thu Feb 21 00:39:26 2008 From: keridee at jayco.net (Tiger12506) Date: Wed, 20 Feb 2008 18:39:26 -0500 Subject: [Tutor] results not quite 100 percent yet References: <479FE03D.5050406@tds.net> Message-ID: <009301c8741a$1ae11730$85fde004@jslaptop> > As far as I can see, these routines give me the results > I'm looking for. I get a distribution of four negative numbers, > four positive integers in the range 10 to 110, and nothing > is placed in room 6 or room 11: I'll throw a couple of thoughts out there since I know that you appreciate to see many points of view. > #!/usr/bin/python > > import random > > #print "\n"*30 > > table= [[ 0, 2, 0, 0, 0, 0, 0], # 1 > [ 1, 3, 3, 0, 0, 0, 0], # 2 > [ 2, 0, 5, 2, 0, 0, 0], # 3 > [ 0, 5, 0, 0, 0, 0, 0], # 4 > [ 4, 0, 0, 3,15,13, 0], # 5 > [ 0, 0, 1, 0, 0, 0, 0], # 6 > [ 0, 8, 0, 0, 0, 0, 0], # 7 > [ 7,10, 0, 0, 0, 0, 0], # 8 > [ 0,19, 0, 0, 0, 8, 0], # 9 > [ 8, 0,11, 0, 0, 0, 0], # 10 > [ 0, 0,10, 0, 0, 0, 0], # 11 > [ 0, 0, 0,13, 0, 0, 0], # 12 > [ 0, 0,12, 0, 5, 0, 0], # 13 > [ 0,15,17, 0, 0, 0, 0], # 14 > [14, 0, 0, 0, 0, 5, 0], # 15 > [17, 0,19, 0, 0, 0, 0], # 16 > [18,16, 0,14, 0, 0, 0], # 17 > [ 0,17, 0, 0, 0, 0, 0], # 18 > [ 9, 0, 0,16, 0, 0, 0]] # 19 Hard-coded. That means you have to change the program to change the game. It would not be difficult to store this/read it in from a file, making the same program suddenly handle an infinite number of games. (well not infinite, but at least 19*7*2147483647) > # Distribute the treasure > J = 0 > while J <= 3: > T = int(random.random()*19)+1 > if T == 6: > continue > if T == 11: > continue > if T == 13: > continue > if table[T-1][6] != 0: > continue > b = range(10,110) > treasure = random.choice(b) > table[T-1][6] = treasure > J += 1 > > # Place androids/aliens in rooms > J = 4 > while J > 0: > T = int(random.random()*19)+1 > if T == 6: > continue > if T == 11: > continue > if T == 13: > continue > if table[T-1][6] != 0: > continue > table[T-1][6] = -J > J -= 1 Those two block of code above are SO similar that sure they can be combined into one, or at least the first parts of them. From alan.gauld at btinternet.com Thu Feb 21 01:53:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Feb 2008 00:53:51 -0000 Subject: [Tutor] designing POOP References: <47ADF7DD.9090209@tds.net> <001401c86d2d$06354750$97fce004@jslaptop><47B2E4AE.5070409@tds.net> <000201c86f4b$2766fbb0$52fce004@jslaptop> <000801c86f84$003b4670$1cfce004@jslaptop><47B595E7.9040001@tds.net> <82b4f5810802150739h686ecd13j3f242723761a29cb@mail.gmail.com> Message-ID: "Michael Langford" wrote > I'm firmly with Kent here: OO programming is not about simulation. Wooah! I'm partly on board here and do agree the noun/verb thing is a gross simplification. But it does work and is how probably the majority of OOP programmers started out - in the 80's and 90's at least. Certainly when I started on OOP around 1984 it was the de-facto introduction. And it is a still an effective way to identify objects if you aren't sure where to start. But it is not a good way to model software, with that I agree. But OOP is still about suimulation. A lot of OOP code - especially on very large scale projects is as close a simulation as possible to the real world problem as you can get. If you are going to work on 5-10 million lines of code you had better organise it according to some tangible model you can understand or you will have problems. Performance and efficiency come a long way behind comprehensibility at that scale. But on more "normal" projects, say 100K-1 million lines then other factors come to the fore, and flexibility of design is one big area where OOP techniques can help. Unfortunately there seeems to be a lobby at work in OO these days (indeed in software engineering generally) that has forgotten about large scale stuff and treats the entire subject as if it were exclusively about small scale projects. This is unfortunate because software engineering was "invented" to tackle the large scale problems not the small, and this view also fails to recognise the very different approaches needed to cover both bases. Here in the Python community we rarely need to think big, I don't know of any really large projects being done in Python. But it is important to remember that topics like OOP cover all areas. > are not modeling real world items. You are making code easier to > maintain and making parts of code that have to do with one another > be > near one another. That's true of any design technique regardless of whether it is OOP or procedural or even of it's not software at all. However it's not somerthing that will help a beginner see objects in their code, especially since the resultant objects are often of the highly abstract or large grained variety. > If you spend all your time trying to make your objects into real > world > things you're actually doing simulation, not programming. As a > person > who's actually done simulation, I'll state that 's not really a > great > way to structure code. You spend a lot of time arguing about highly > abstract responsibilities of each object in your system, as well as > how much it will actually model the real world. Neither one is > especially helpful, This bit I do agree with. Model the real world to get a feel for the problem at hand, model the real world as an aid to identifying potential objects, model the real world while it helps solve the problem. But don't be a slave to it, you are writing a program to solve a problem not to model the world. Never forget which is the tool and which the result. But OTOH most of the programs I build or design are simulations, whether of a call centre, a manufacturing plant, a banking system or a local council, an airport traffic control system or a telephone switch - and the software invariably reflects that structure. It does not however model every feature of a PBX, lathe, teller etc It reflects the attributes of those objects that relate to the problem. > programing. The Why of OO programming today is: To make code more > maintainable/usable and to group and to use data in such a way the > human mind can easily grasp all the abstract data types that a > program > operates on. And the latter point is one area where modelling based on real world entities can be a big plus. But based on them, not slavishly reproducing them. > OO programing came from simulation people. They used a language > (Simula) to do simulation. It allowed each object to have behavior > linked to its type. And it is still used today within the simulation community. We have a fairly active Simula group at work doingnetwork analyses. > Other people saw this (Smalltalk), then copied the system (which > they > were incidentally using to build Smalltalk at first), but not to > simulate real world objects, Quite a lot of the early Smalltalk stuff did indeed copy real world objects but they also saw the potential in modelling virtual objects like the UI elements. They were using Smalltalk to teach/experiment with young children by that time and the correspondence between real objects - like pens - and computing devices was a beneficial side effect. > When Bjarne Stroustrup made C++, he copied some of the ideas in > order > to make a better type system, where the functions that operated on a Yes, although he was actually using the tool to build a simulation. That's why he started with Simula... > "Object-oriented programming is programming using inheritance. I never agreed with Bjarne on that. There are a number of OOP environmemnts that implement polymorphism without inheritance (Actor is one example). So I think he should have said that "OOP is about programming polymorphically" > OO is not a glorified simulation system, and you will feel pain if > you > overemphasize the generalization "Model objects on real world > objects". Objects do have to have an idea (Cohesion). It is just, > that > idea doesn't have to be congruous with something you can walk over > to > and pick up in the real world. And this is the key. Objects have responsibilities. The responsibilities should be related to some kind of conceptual thing, but it may not be a real world thing. But when you start out with objects it's nearly impossible to imagine non tangible things. And that takes us back to nouns/verbs. For all its imperfections it works as a way of gettig people to break down problems into things rather than functions. The resultant software may well be sub-optimal but that can be fixed, but if you can build something that works and is based on objects that is the starting point. Once you build a few you very quickly run into the analysis-paralysis issues of trying to follow the real world too far, and start to deviate., That's when you start to find the abstractions coming out and seeing objects more generally. But that's a huge jump for most procedural programmers. > Often it feels like the "Model objects on real world objects" is how > people are taught so they get the idea of an object. Actually > designing all code that way is a needless proscription that really > really hurts many projects. I agree with this too. It has to be emphasised that it's only a starting point to identify object candidates, the final solution may look very different. But in my experience the bigger the project the closer the abstractions get to reality at least at the object identity level - the operations and data are likely to be very different, and underneath that layer will be a wealth of lower level abstractions unguessed at by nouns/verbs. But heh, if you get presented with a requirements spec of 400 pages and over 1000 user storiers (as I just have!) it's as good a place to start as any! (IMHO of course! :-) And hopefully no newbies on the tutor list is in any danger of that happening to them! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld Which is currently dead awaiting a server repair, sorry! :-( From mlangford.cs03 at gtalumni.org Thu Feb 21 04:59:54 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 20 Feb 2008 22:59:54 -0500 Subject: [Tutor] DATA TYPES In-Reply-To: <47BC99E4.4080904@tds.net> References: <000f01c873e7$d6076e70$3901a8c0@careplus.local> <82b4f5810802201253g27e54050n767beb11ddd479af@mail.gmail.com> <47BC99E4.4080904@tds.net> Message-ID: <82b4f5810802201959x26eac4edrd6072a17e4519318@mail.gmail.com> > - Since the OP is trying to find cases where the same variable is > assigned different types, presumably in a single scope, checking just at > the end of a function won't help. This is a starting point to get the type for the variables when you start the port, before you run the unit tests. > > After you've done that, you can see what type is referred to by each > > name at the end of the function, then with some unit tests you should > > be able to tell if you temporarily changed to a different data type in > > the middle. If nothing else, you should be able to write the unit > > tests in jython/cpython compatable code so you don't have to write > > them twice. > > Not sure how you would do that with unit tests? You write unit tests for each of your functions that test their input and output. Presumably, if you used a float somewhere in the middle there, when you don't use the float in the java implementation, you'll get a different answer. If you don't get a different answer, presumably it didn't matter, or your tests don't provide good enough coverage of the number space. By writing the unit tests in cPython/Jython compatible code, you'll be able to run the same tests on both sets of functions and verify you've completed your port. ==Michael PS: Sorry about the missing %, it was there when I ran the code. Don't know where it went. -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From zebra05 at gmail.com Thu Feb 21 09:45:43 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 21 Feb 2008 10:45:43 +0200 Subject: [Tutor] web.py vs webwareforpython Message-ID: Which is better for large scale apps? I know YouOS and reddit use web.py - which big site successfully uses webware? Thanks. -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080221/bd08e1e8/attachment.htm From bhaaluu at gmail.com Thu Feb 21 12:48:35 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 21 Feb 2008 06:48:35 -0500 Subject: [Tutor] results not quite 100 percent yet In-Reply-To: <009301c8741a$1ae11730$85fde004@jslaptop> References: <479FE03D.5050406@tds.net> <009301c8741a$1ae11730$85fde004@jslaptop> Message-ID: On Wed, Feb 20, 2008 at 6:39 PM, Tiger12506 wrote: > > I'll throw a couple of thoughts out there since I know that you appreciate > to see many points of view. > > > > #!/usr/bin/python > > Hard-coded. That means you have to change the program to change the game. It > would not be difficult to store this/read it in from a file, making the same > program suddenly handle an infinite number of games. (well not infinite, but > at least 19*7*2147483647) > Noted. I'm sure that can be incorporated into a future version. Also wanted for a future version: SAVE feature, so a game can be quit in the middle, and not have to be started from scratch to get back to the same point. HI-SCORES feature shouldn't be too difficult to implement. etc. etc. etc. Thanks! 8^D > > > # Distribute the treasure > > > > # Place androids/aliens in rooms > > Those two block of code above are SO similar that sure they can be combined > into one, or at least the first parts of them. > Optimization is the LEAST of my worries at this point. What these routines DO, and DO 100% of the time (as far as my tests have shown) is: 1. puts a positive integer into the 6th element of 4 lists in the table 2. puts a negative integer into the 6th element of 4 lists in the table 3. neither routine puts an integer where there is not a zero (no overwriting) 4. neither routine puts an integer in list 6 or list 11 100% of the time! That's what I was looking for, and these routines do the job. First: get the routine to do exactly what you want it to do. Second: Readability. I can read and understand these routines. Third: Maintainabilty: They are easy to maintain! See Second. I made a test and ran it 10,000 times in a bash shell script. I got 100% results. Not 97%, 98%, 99%....... but 100%. If you're interested in my test, ask, and I'll send it. I used a bash shell script, so I don't know how well the test will work in MS-Windows: #!/bin/bash for i in `seq 1 100` ; do python setupTable.py >> setup.out ; done The new game has 43 rooms, not 19. These routines have already been ported to the new game, easily and quickly. No Zen required! Other beginning programers shouldn't have any problems using these routines. Plus, I was able to replace the old (97% reliable) routines with these routines simply by dropping these into place. They worked immediately, without a hitch, and I'm not greeted with treasure or a monster at the Entrance or Exit to the game (6 & 11 respectively). 100%!!!!!!!! 8^D I'll certainly keep your suggestions in mind! Thanks! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From kent37 at tds.net Thu Feb 21 13:04:20 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 07:04:20 -0500 Subject: [Tutor] DATA TYPES In-Reply-To: <000f01c873e7$d6076e70$3901a8c0@careplus.local> References: <000f01c873e7$d6076e70$3901a8c0@careplus.local> Message-ID: <47BD68C4.6060706@tds.net> Toby wrote: > What I'm saying is if I have used a certain variable to hold literally > dozens of different values and I BELIEVE them all to be integers but I'm not > entirely sure that I have not stumbled into the float realm is there a way > to have python list all variables contained in a program and tell me what > type it has internally stored them as? I realize I could trudge through the > entire 1000 lines and check all the variables and see what values I have > assigned them one at a time but I'm wondering if there is an easier way to > get that data? Isn't this exactly the kind of problem static typing is supposed to help with? If you write int i; i = 3.0; you will get a compile-time error I think. So just make your best guess and then let the compiler find your errors. Kent From kent37 at tds.net Thu Feb 21 13:06:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 07:06:11 -0500 Subject: [Tutor] DATA TYPES In-Reply-To: <82b4f5810802201959x26eac4edrd6072a17e4519318@mail.gmail.com> References: <000f01c873e7$d6076e70$3901a8c0@careplus.local> <82b4f5810802201253g27e54050n767beb11ddd479af@mail.gmail.com> <47BC99E4.4080904@tds.net> <82b4f5810802201959x26eac4edrd6072a17e4519318@mail.gmail.com> Message-ID: <47BD6933.70809@tds.net> Michael Langford wrote: >> Not sure how you would do that with unit tests? > > You write unit tests for each of your functions that test their input > and output. Presumably, if you used a float somewhere in the middle > there, when you don't use the float in the java implementation, you'll > get a different answer. If you don't get a different answer, > presumably it didn't matter, or your tests don't provide good enough > coverage of the number space. OK, yes, unit tests would be very helpful in verifying the correctness of the translation. As I noted separately, I think the compiler will answer the original question. Kent From kent37 at tds.net Thu Feb 21 13:16:21 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 07:16:21 -0500 Subject: [Tutor] web.py vs webwareforpython In-Reply-To: References: Message-ID: <47BD6B95.4030604@tds.net> OkaMthembo wrote: > Which is better for large scale apps? I know YouOS and reddit use web.py > - which big site successfully uses > webware? A starting point: http://wiki.w4py.org/who-is-using-webware.html? Probably a better place to ask: http://www.mail-archive.com/webware-discuss at lists.sourceforge.net/ I'm curious - how did you settle on those two? Kent From bhaaluu at gmail.com Thu Feb 21 13:19:19 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 21 Feb 2008 07:19:19 -0500 Subject: [Tutor] designing POOP In-Reply-To: References: <47ADF7DD.9090209@tds.net> <001401c86d2d$06354750$97fce004@jslaptop> <47B2E4AE.5070409@tds.net> <000201c86f4b$2766fbb0$52fce004@jslaptop> <000801c86f84$003b4670$1cfce004@jslaptop> <47B595E7.9040001@tds.net> <82b4f5810802150739h686ecd13j3f242723761a29cb@mail.gmail.com> Message-ID: On Wed, Feb 20, 2008 at 7:53 PM, Alan Gauld wrote: > "Michael Langford" wrote > > > I'm firmly with Kent here: OO programming is not about simulation. > > Wooah! > I'm partly on board here and do agree the noun/verb thing is > a gross simplification. But it does work and is how probably > the majority of OOP programmers started out - in the 80's > and 90's at least. Certainly when I started on OOP around 1984 > it was the de-facto introduction. And it is a still an effective > way to identify objects if you aren't sure where to start. > > [snipped for brevity] > > > Often it feels like the "Model objects on real world objects" is how > > people are taught so they get the idea of an object. Actually > > designing all code that way is a needless proscription that really > > really hurts many projects. > > I agree with this too. It has to be emphasised that it's only a > starting point to identify object candidates, the final solution > may look very different. But in my experience the bigger the > project the closer the abstractions get to reality at least at > the object identity level - the operations and data are likely > to be very different, and underneath that layer will be a wealth > of lower level abstractions unguessed at by nouns/verbs. > > But heh, if you get presented with a requirements spec > of 400 pages and over 1000 user storiers (as I just have!) it's > as good a place to start as any! (IMHO of course! :-) > And hopefully no newbies on the tutor list is in any danger > of that happening to them! > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > Which is currently dead awaiting a server repair, sorry! :-( Somewhere along the line (in the original thread) the idea of trying to teach a Beginner how to design an OOP in "Python" got lost in a bunch of java mumbo jumbo (at least, that's what it seemed like to me). After looking at a lot of stuff, and reading much more than I needed to, the technique that works best for me is the noun/verb technique. I think it is a good STARTING point! Now, I understand that there are many different levels of "beginner". Some beginners are higher up the ladder than others, and they enjoy looking in windows higher up. However, I'm still on the bottom rung. The technique that I can relate to is the noun/verb technique. Does this mean that if I get a grasp of POOP with this technique that I'll be stuck on the bottom rung forever? I doubt it. No more than someone who is using whatever technique they are currently using is stuck with that technique forever. The universe unfolds perfectly. Time exists so it doesn't unfold all at once. I think the noun/verb technique is good for Absolute beginners. I haven't seen anything else that is so introductory. Too bad there isn't a graded tutorial that systematically uses the technique to build several working PYTHON OOPs. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From zebra05 at gmail.com Thu Feb 21 13:27:58 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 21 Feb 2008 14:27:58 +0200 Subject: [Tutor] web.py vs webwareforpython In-Reply-To: <47BD6B95.4030604@tds.net> References: <47BD6B95.4030604@tds.net> Message-ID: Thanks Kent. Well, i looked about and initially settled on webware - because it seemed mature and is IMO well documented. Ive read Cheetah + webware docs and it looked good. Then i heard of web.py on some reddit write-up. Apparently really easy to use and lightweight. I found out YouOS uses it and thought there must be a good reason. I am just very curious as to which python web framework will ultimately be the best to work with; and i dont want to waste time trying if some arent worth the trouble. On Thu, Feb 21, 2008 at 2:16 PM, Kent Johnson wrote: > OkaMthembo wrote: > > Which is better for large scale apps? I know YouOS and reddit use web.py > > - which big site successfully uses > > webware? > > A starting point: > http://wiki.w4py.org/who-is-using-webware.html? > > Probably a better place to ask: > http://www.mail-archive.com/webware-discuss at lists.sourceforge.net/ > > I'm curious - how did you settle on those two? > > Kent > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080221/fc9cfffc/attachment.htm From kent37 at tds.net Thu Feb 21 13:32:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 07:32:14 -0500 Subject: [Tutor] results not quite 100 percent yet In-Reply-To: References: <479FE03D.5050406@tds.net> <009301c8741a$1ae11730$85fde004@jslaptop> Message-ID: <47BD6F4E.4090900@tds.net> bhaaluu wrote: >> Those two block of code above are SO similar that sure they can be combined >> into one, or at least the first parts of them. >> > > Optimization is the LEAST of my worries at this point. The suggested change is not an optimization for speed, it is a reorganization for clarity. You should be worried about readability and maintainability at the start of your project, because this is code you will be living with for a while. > What these routines DO, and DO 100% of the time > 100% of the time! > That's what I was looking for, and these routines do the job. OK, so it works. Congratulations! That doesn't mean there is no room for improvement. > First: get the routine to do exactly what you want it to do. A good place to start. > Second: Readability. I can read and understand these routines. Good. However they are longer than necessary. > Third: Maintainabilty: They are easy to maintain! See Second. Duplicated code is actually a major impediment to maintainability. > The new game has 43 rooms, not 19. These routines have already > been ported to the new game, easily and quickly. With a few changes I suspect - changing 19 to 43 in two places (don't miss one!) and probably changing 6, 11 and 13 to other numbers in two places as well. And what is so magic about those numbers, anyway? Will you remember when you come back to the code in two months? Plus the random selection and the use of the random numbers is mixed together. You could write a reusable function that selects from a range, skipping certain values. That function could be used as-is in multiple games, rather than cutting, pasting and editing a short code block for each game. I gave some suggestions in an earlier email that could be the start of such a function. > Other beginning programers shouldn't have any problems using > these routines. As long as they use the same number of rooms and entrance and exit rooms, or they know the places to make the magic edits... Kent From bhaaluu at gmail.com Thu Feb 21 14:13:36 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 21 Feb 2008 08:13:36 -0500 Subject: [Tutor] results not quite 100 percent yet In-Reply-To: <47BD6F4E.4090900@tds.net> References: <479FE03D.5050406@tds.net> <009301c8741a$1ae11730$85fde004@jslaptop> <47BD6F4E.4090900@tds.net> Message-ID: On Thu, Feb 21, 2008 at 7:32 AM, Kent Johnson wrote: > > > Other beginning programers shouldn't have any problems using > > these routines. > > As long as they use the same number of rooms and entrance and exit > rooms, or they know the places to make the magic edits... > > Kent > Well, no one was able to suggest anything that worked 100% of the time before. No one. One routine allots the treasure, The other routine allots the monsters. Each routine does one thing, and does it well (100%). It's a text adventure game. It has its own framework. What? You show me what you're talking about, and I'll run it through my test script. Your 'clarity' solution should be easily dropped in to replace the two routines that already work 100% of the time already. Python please. The reorganization should be for 'clarity' (a Noob should be able to understand it, and port it easily to other games that have more or less rooms [will they have to make any magic edits anywhere]. Oh, and these clarity routines should be shorter (in length?). > Good. However they are longer than necessary. Did I cover all the things needed? Wait! No duplications... and something about the random numbers and selection in the same place? I really don't understand that (yet). The table is directly related to the map of the game. In the old games, the monsters and treasures are all in the last column. In the new game, there are two colums, one for monsters, and the other for treasure. In the treasure column, numbers 4-18 are distributed randomly to 43 rooms, minus the entrance, exit, and a 'death' room, and not overwriting numbers 1-3 which are 'hard-wired' to certain rooms. These numbers reference lists of treasure names. Likewise, the monster column gets numbers 1-15 distributed randomly, except for the entrance, exit and 'death' room. These numbers are also references to list elements. I wrote the new routines for the new 43-room game. They work 100% of the time. With minor modifications, they dropped right into the old games. If I make another new game, with different entrance, exit, or other special rooms, these routines should drop right in and with minor modifications, just work. This is the 'framework' for these programs. 8^D Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From tyler.smith at mail.mcgill.ca Thu Feb 21 14:49:12 2008 From: tyler.smith at mail.mcgill.ca (Tyler Smith) Date: Thu, 21 Feb 2008 13:49:12 +0000 (UTC) Subject: [Tutor] results not quite 100 percent yet References: <479FE03D.5050406@tds.net> <009301c8741a$1ae11730$85fde004@jslaptop> <47BD6F4E.4090900@tds.net> Message-ID: On 2008-02-21, bhaaluu wrote: > On Thu, Feb 21, 2008 at 7:32 AM, Kent Johnson wrote: >> >> > Other beginning programers shouldn't have any problems using >> > these routines. >> >> As long as they use the same number of rooms and entrance and exit >> rooms, or they know the places to make the magic edits... >> >> Kent >> > > > What? You show me what you're talking about, and I'll run it through my > test script. Your 'clarity' solution should be easily dropped in to replace > the two routines that already work 100% of the time already. > Python please. > The reorganization should be for 'clarity' (a Noob should be able to understand > it, and port it easily to other games that have more or less rooms > [will they have > to make any magic edits anywhere]. Oh, and these clarity routines should be > shorter (in length?). Not shorter, but definitely clearer would be to replace your magic numbers with variables: entrance = 6 exit = 11 death_room = 13 Replacing each occurrence of those numbers in your code with the variables means you only have to make one change that propagates through the entire program if you change the map layout. It also means that if you're reading your code in a year you won't have to remember that '6' means something special in this context. I'm just a novice python programmer, but it's a good rule of thumb to avoid magic numbers in any language. Tyler From bhaaluu at gmail.com Thu Feb 21 15:02:56 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 21 Feb 2008 09:02:56 -0500 Subject: [Tutor] results not quite 100 percent yet In-Reply-To: References: <479FE03D.5050406@tds.net> <009301c8741a$1ae11730$85fde004@jslaptop> <47BD6F4E.4090900@tds.net> Message-ID: On Thu, Feb 21, 2008 at 8:49 AM, Tyler Smith wrote: > > Not shorter, but definitely clearer would be to replace your magic > numbers with variables: > > entrance = 6 > exit = 11 > death_room = 13 > > Replacing each occurrence of those numbers in your code with the > variables means you only have to make one change that propagates > through the entire program if you change the map layout. It also > means that if you're reading your code in a year you won't have to > remember that '6' means something special in this context. > > I'm just a novice python programmer, but it's a good rule of thumb to > avoid magic numbers in any language. > > Tyler Your suggestion is clear and to the point. Noted. I'm also aware of this 'rule of thumb', but simply forgot to implement it due to being so familiar with what the 'magic numbers' mean, that I just didn't remember to do it. But will I remember what it is six months from now? Probably not. This is, indeed, a good rule of thumb! Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From tyler.smith at mail.mcgill.ca Thu Feb 21 16:39:07 2008 From: tyler.smith at mail.mcgill.ca (Tyler Smith) Date: Thu, 21 Feb 2008 15:39:07 +0000 (UTC) Subject: [Tutor] results not quite 100 percent yet References: <479FE03D.5050406@tds.net> Message-ID: On 2008-02-20, bhaaluu wrote: > As far as I can see, these routines give me the results > I'm looking for. I get a distribution of four negative numbers, > four positive integers in the range 10 to 110, and nothing > is placed in room 6 or room 11: > Just for the hell of it, here's my stab at the problem. Note that your spec doesn't match your code, as there's something special about room 13, which is also excluded from this process. Also, since you appear to be adding treasure and aliens to the same cell in each list, I've rolled the procedure up into a single while loop. The algorithm, such as it is, is just four lines to build a list of modifiable rooms and a list of additions, and a four line loop that does the work. As I said, I'm new to Python, so I suspect someone who knows how to use list comprehensions or generators could clean it up further. Also, the tmp = random.choice() bit might be replaceable by some kind of random.pop() thing, but I couldn't figure that out. That would cut the last line out of the loop. Not the short is better than clear, but I don't think this is very complicated, and it takes advantage of Python's listy goodness. My 2 cents! Tyler import random entrance = 6 exit = 11 death_room = 13 table= [[ 0, 2, 0, 0, 0, 0, 0], [ 1, 3, 3, 0, 0, 0, 0], [ 2, 0, 5, 2, 0, 0, 0], [ 0, 5, 0, 0, 0, 0, 0], [ 4, 0, 0, 3,15,13, 0], [ 0, 0, 1, 0, 0, 0, 0], [ 0, 8, 0, 0, 0, 0, 0], [ 7,10, 0, 0, 0, 0, 0], [ 0,19, 0, 0, 0, 8, 0], [ 8, 0,11, 0, 0, 0, 0], [ 0, 0,10, 0, 0, 0, 0], [ 0, 0, 0,13, 0, 0, 0], [ 0, 0,12, 0, 5, 0, 0], [ 0,15,17, 0, 0, 0, 0], [14, 0, 0, 0, 0, 5, 0], [17, 0,19, 0, 0, 0, 0], [18,16, 0,14, 0, 0, 0], [ 0,17, 0, 0, 0, 0, 0], [ 9, 0, 0,16, 0, 0, 0]] room_list = range(0,19) ## the list of rooms to modify ## exclude the special rooms: for i in [entrance, exit, death_room]: room_list.remove(i) ## build a list of random treasure and four aliens: additions = random.sample(range(10,110), 3) additions.extend(range(-4,0)) while (additions): ## continue until all additions are added tmp = random.choice(room_list) ## randomly pick a room if table[tmp][6] == 0: table[tmp][6] = additions.pop() ## add a value room_list.remove(tmp) ## don't pick the same room twice! ## not strictly necessary for i in table: print i From alan.gauld at btinternet.com Thu Feb 21 17:34:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Feb 2008 16:34:39 -0000 Subject: [Tutor] web.py vs webwareforpython References: <47BD6B95.4030604@tds.net> Message-ID: "OkaMthembo" wrote > I am just very curious as to which python web framework will > ultimately be > the best to work with; and i dont want to waste time trying if some > arent > worth the trouble. I think that may be why Kent asked his question, since neither webware nor web.py are the dominant Python web frameworks as far as I can tell. If I was a gambling man my money would currently be on Django, mainly because my personal favourite TurboGears seems to have had a strategic stumble and lost clarity somewhat. But there are so many web frameworks for Python that it's a very difficult question to answer. Fortunately almost all web frameworks work in similar underlying ways so moving from one to the other is not as difficult as moving betweeen GUI tookits, say. Alan G. From zebra05 at gmail.com Thu Feb 21 17:45:58 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 21 Feb 2008 18:45:58 +0200 Subject: [Tutor] web.py vs webwareforpython In-Reply-To: References: <47BD6B95.4030604@tds.net> Message-ID: Thanks, Alan. Django was the first Python framework i ever considered. I had a perception that it was biased towards the publishing industry - then again, experiencewise im in no position to make the judgement. Lloyd Dube On Thu, Feb 21, 2008 at 6:34 PM, Alan Gauld wrote: > > "OkaMthembo" wrote > > > I am just very curious as to which python web framework will > > ultimately be > > the best to work with; and i dont want to waste time trying if some > > arent > > worth the trouble. > > I think that may be why Kent asked his question, since neither > webware nor web.py are the dominant Python web > frameworks as far as I can tell. > > If I was a gambling man my money would currently be on > Django, mainly because my personal favourite TurboGears > seems to have had a strategic stumble and lost clarity somewhat. > > But there are so many web frameworks for Python that it's > a very difficult question to answer. Fortunately almost all > web frameworks work in similar underlying ways so moving > from one to the other is not as difficult as moving betweeen > GUI tookits, say. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080221/5afc9c44/attachment.htm From brindly at gmail.com Thu Feb 21 18:15:57 2008 From: brindly at gmail.com (brindly sujith) Date: Thu, 21 Feb 2008 22:45:57 +0530 Subject: [Tutor] how to display terminal messages in dialog window using tkinter Message-ID: hi i m developing a application using tkinter i want the messages that we get in the terminal to be displayed in the tkinter dialog box do we have any option for that thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080221/05739a2a/attachment.htm From jeff at drinktomi.com Thu Feb 21 18:36:20 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Thu, 21 Feb 2008 09:36:20 -0800 Subject: [Tutor] results not quite 100 percent yet In-Reply-To: References: <479FE03D.5050406@tds.net> Message-ID: <8E52B1CD-D031-4572-B213-AB4FDCBEF8EE@drinktomi.com> Here is a strict translation of your code. The algorithm remains the same, but it has been cleaned up a bit. Duplications have been removed, and the various logical bits have been broken down into separate functions. I suspect you don't know about random.randint(low, high). It generates random integers between the low and high inclusively. E.g. random.randint(0, 1) will generate either 0 or 1. import random entrance = 6 exit = 11 death_room = 13 low_treasure_value = 10 high_treasure_value = 110 treasure_rooms = 3 monster_rooms = 4 table= [[ 0, 2, 0, 0, 0, 0, 0], [ 1, 3, 3, 0, 0, 0, 0], [ 2, 0, 5, 2, 0, 0, 0], [ 0, 5, 0, 0, 0, 0, 0], [ 4, 0, 0, 3,15,13, 0], [ 0, 0, 1, 0, 0, 0, 0], [ 0, 8, 0, 0, 0, 0, 0], [ 7,10, 0, 0, 0, 0, 0], [ 0,19, 0, 0, 0, 8, 0], [ 8, 0,11, 0, 0, 0, 0], [ 0, 0,10, 0, 0, 0, 0], [ 0, 0, 0,13, 0, 0, 0], [ 0, 0,12, 0, 5, 0, 0], [ 0,15,17, 0, 0, 0, 0], [14, 0, 0, 0, 0, 5, 0], [17, 0,19, 0, 0, 0, 0], [18,16, 0,14, 0, 0, 0], [ 0,17, 0, 0, 0, 0, 0], [ 9, 0, 0,16, 0, 0, 0]] def distribute_treasure(table, number_pieces): for x in range(0, number_pieces): place(table, random_treasure()) def distribute_monsters(table, number_monsters): for x in range(-number_monsters, 0): place(table, x) def place(table, item): table[any_available_room(table)][6] = item def any_available_room(table): room = random_room(table) while not is_available(table, room): room = random_room(table) return room def random_room(table): return random.randint(0, len(table)-1) def is_available(table, room): if room in [entrance, exit, death_room]: return False elif table[room][6] != 0: return False else: return True def random_treasure(): return random.randint(low_treasure_value, high_treasure_value) distribute_treasure(table, treasure_rooms) distribute_monsters(table, monster_rooms) for x in table: print x -jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080221/7e946610/attachment-0001.htm From kent37 at tds.net Thu Feb 21 19:30:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 13:30:55 -0500 Subject: [Tutor] web.py vs webwareforpython In-Reply-To: References: <47BD6B95.4030604@tds.net> Message-ID: <47BDC35F.4000007@tds.net> OkaMthembo wrote: > Thanks, Alan. > > Django was the first Python framework i ever considered. I had a > perception that it was biased towards the publishing industry - then > again, experiencewise im in no position to make the judgement. Django comes from the newspaper industry but it is broadly useful. Take a look at http://www.djangosites.org/ for many diverse examples. TurboGears and Pylons are also popular and actively developed. web.py is a newcomer that attained instant fame because it was used to rewrite Reddit (from Lisp). I think the differences between these are more a matter of taste than anything else. Webware is from an earlier generation of Python web frameworks. That doesn't mean there is anything wrong with it, but AFAIK it never caught on the way the more recent ones have. Kent > > Lloyd Dube > On Thu, Feb 21, 2008 at 6:34 PM, Alan Gauld > wrote: > > > "OkaMthembo" > wrote > > > I am just very curious as to which python web framework will > > ultimately be > > the best to work with; and i dont want to waste time trying if some > > arent > > worth the trouble. > > I think that may be why Kent asked his question, since neither > webware nor web.py are the dominant Python web > frameworks as far as I can tell. > > If I was a gambling man my money would currently be on > Django, mainly because my personal favourite TurboGears > seems to have had a strategic stumble and lost clarity somewhat. > > But there are so many web frameworks for Python that it's > a very difficult question to answer. Fortunately almost all > web frameworks work in similar underlying ways so moving > from one to the other is not as difficult as moving betweeen > GUI tookits, say. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Lloyd Dube > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From marc.tompkins at gmail.com Thu Feb 21 20:28:20 2008 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 21 Feb 2008 11:28:20 -0800 Subject: [Tutor] web.py vs webwareforpython In-Reply-To: <47BDC35F.4000007@tds.net> References: <47BD6B95.4030604@tds.net> <47BDC35F.4000007@tds.net> Message-ID: <40af687b0802211128l5cf9d73ct7fd15017f2eec24b@mail.gmail.com> Sorry to jump in the middle here, but I have a somewhat related question... I have a few websites set up for my clients, mostly using Mambo/Joomla (PHP-based). My clients tend to be small brick-and-mortar businesses (doctors, lawyers, etc.) who merely wish to use their website as an extension of their marketing effort, not as a storefront, and generally I set the thing up / perform updates, etc. and turn over the day-to-day running of the site (posting new articles/pictures/videos, running fora, sending newsletters) to a member of their staff. I'd love to switch to a Python-based solution for my future and ongoing projects, and Django looks very exciting to me, but... honestly, Django won't run on most commodity-grade web hosts. And I'm frankly sick of hearing the knee-jerk response "GoDaddy sucks! 1and1 sucks!" because, darn it, they work just fine with Joomla. Django requires "long-running processes", which a cheap webhost obviously doesn't like... I don't really have anything against Joomla - it's worked well for me - but I do feel pretty silly raving about how great Python is, and then when the subject of web development comes up having to shuffle my feet and say "...ummm... well, there I use PHP. But Python's really great!" I also don't have a love affair going with GoDaddy or 1and1, but they've both been very affordable and (especially GoDaddy) very easy to work with, which I can't say for a lot of other companies I've dealt with. They've also both been around for a few years, and I'm confident that they still will be there in a few more. These are all very important to me and my clients. I'd like - if possible - to use a relatively mature framework which I can then extend. I'm happy starting from scratch and experimenting with my own personal hobby projects, but in this area I'd like the core functionality to "just work". So my question is: does anybody have a good Python-based CMS / template / whatever framework up and running on a commodity-priced, shared webhost? If so, which one? Which host? Inquiring minds wanna know. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080221/8c7b7de3/attachment.htm From kent37 at tds.net Thu Feb 21 20:51:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 14:51:10 -0500 Subject: [Tutor] Django hosting In-Reply-To: <40af687b0802211128l5cf9d73ct7fd15017f2eec24b@mail.gmail.com> References: <47BD6B95.4030604@tds.net> <47BDC35F.4000007@tds.net> <40af687b0802211128l5cf9d73ct7fd15017f2eec24b@mail.gmail.com> Message-ID: <47BDD62E.9020407@tds.net> Marc Tompkins wrote: > So my question is: does anybody have a good Python-based CMS / template > / whatever framework up and running on a commodity-priced, shared > webhost? If so, which one? Which host? Inquiring minds wanna know. Here is a big list of DjangoFriendlyWebHosts: http://code.djangoproject.com/wiki/DjangoFriendlyWebHosts This page rates hosts by popularity and counts five sites running at oneandone.net: http://www.statopia.com/corporate/blog/2007/aug/05/PopularDjangoHostingService/ My experience with WebFaction has been very good, plans start at $9.50/month with substantial discounts for prepayment. Kent PS Please don't hijack threads - start a new thread for a new question. From timmichelsen at gmx-topmail.de Thu Feb 21 21:09:28 2008 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 21 Feb 2008 21:09:28 +0100 Subject: [Tutor] using os module on windows In-Reply-To: <47BC8540.7030606@tds.net> References: <47BC2E5E.7040006@tds.net> <47BC8540.7030606@tds.net> Message-ID: > Delete, then copy. Or use rsync instead of Python... Yes, I ended up writing a small *.bat file that uses unison for sychronization. I still do not understand why I got these permission errors when using the python script. Thanks for the help. From alan.gauld at btinternet.com Thu Feb 21 23:14:08 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Feb 2008 22:14:08 -0000 Subject: [Tutor] how to display terminal messages in dialog window usingtkinter References: Message-ID: "brindly sujith" wrote > i m developing a application using tkinter > > i want the messages that we get in the terminal to be displayed in > the > tkinter dialog box It depends what you mean. If you literally want print statements to appear in a dialog then no, you can't do that (so far as I know!). But if you want the Tkinter equivalent of a print statement you can either create your own logging dialog with a text widget and write to that or just use one of the standard dialogs such as import tkMessageBox tkMessageBox.showinfo("Window Text", "A short message") At this point I'd normally suggest visiting the GUI topic of my tutorial but sadly the ISP server is still dead :-(I hope that answers your question?-- Alan GauldAuthor of the Learn to Program web sitehttp://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Feb 21 23:39:31 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 17:39:31 -0500 Subject: [Tutor] [Fwd: Standalone Version] Message-ID: <47BDFDA3.6020007@tds.net> Forwarding to the list -------- Original Message -------- Subject: Standalone Version Date: Thu, 21 Feb 2008 18:05:59 -0300 From: Artur Sousa To: Kent Johnson Sorry to bother again. Is there a way to distribute a Python program freely on a standalone version, in which the other person doesn't have to actually open the Command Line and execute the .py file? And please, excuse me, but as english is not my native language, I couldn't quite understand how to concatenate str and int with % (modulo). ttaken = (quantity*3600)/phour str1 = "Para produzir " str2 = u" unidades desse recurso, serao necess\u00E1rios " if ttaken == 1: str3 = " segundo, ou " else: str3 = " segundos, ou " if ttaken/60 <= 1: str4 = " minuto, ou " else: str4 = " minutos, ou " if ttaken/3600 <= 1: str5 = " hora." else: str5 = " horas." print str1 print quantity print str2 print "" print ttaken print str3 print "" print ttaken/60.0 print str4 print "" print ttaken/3600.0 print str5 for quantity is an integer user input value and phour is another int based on a user inputted int. PS.: I'd also like to thank very much for all the support I've been receiving. From kent37 at tds.net Thu Feb 21 23:40:55 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 21 Feb 2008 17:40:55 -0500 Subject: [Tutor] Standalone Version In-Reply-To: <29c144020802211305i667269f0obb203a0bacbab728@mail.gmail.com> References: <29c144020802211305i667269f0obb203a0bacbab728@mail.gmail.com> Message-ID: <47BDFDF7.9050909@tds.net> Artur Sousa wrote: > > And please, excuse me, but as english is not my native language, I > couldn't quite understand how to concatenate str and int with % > (modulo). Please give an example of what you want to do - the variables and the desired output. Kent From alan.gauld at btinternet.com Fri Feb 22 00:58:16 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Feb 2008 23:58:16 -0000 Subject: [Tutor] Standalone Version] References: <47BDFDA3.6020007@tds.net> Message-ID: > From: Artur Sousa > To: Kent Johnson > > Sorry to bother again. > > Is there a way to distribute a Python program freely on a standalone > version, in which the other person doesn't have to actually open the > Command Line and execute the .py file? If the OS is configured properly then a normal python file can be run without opening a command prompt. Just dounble click in Explorer(assuming Windoze). However if you want to distribute a python program without Python being installed there are several options, the best known of which is py2exe - again for Windoze > And please, excuse me, but as english is not my native language, I > couldn't quite understand how to concatenate str and int with % > (modulo). In this context % is not the modulo operator but the string format operator. The trick is to create a format string which defines the structure of your output string by inserting markers into the format string. The marker for an integer is %d (for decimal) so you could write: fmtString = "%d is a number" This creates a template to create a string containing a number: print fmtString % 42 Here the number 42 is substituted into the format string. You must provide as many values as thee are martkers in the format string: print "%d plus %d equals: %d" % (22,7,22+7) Note the string has 3 markers, all decimals and we provide 3 numeric values. There are many other marker types as well as ways of specifying the space occuipied, justification, padding etc. If you don't understand any of that please reply with specifics to the list. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld (still broke! :-( > > > ttaken = (quantity*3600)/phour > str1 = "Para produzir " > str2 = u" unidades desse recurso, serao necess\u00E1rios " > if ttaken == 1: > str3 = " segundo, ou " > else: > str3 = " segundos, ou " > if ttaken/60 <= 1: > str4 = " minuto, ou " > else: > str4 = " minutos, ou " > if ttaken/3600 <= 1: > str5 = " hora." > else: > str5 = " horas." > print str1 > print quantity > print str2 > print "" > print ttaken > print str3 > print "" > print ttaken/60.0 > print str4 > print "" > print ttaken/3600.0 > print str5 > > > for quantity is an integer user input value and phour is another int > based on a user inputted int. > > PS.: I'd also like to thank very much for all the support I've been > receiving. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cfuller084 at thinkingplanet.net Fri Feb 22 02:12:00 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 21 Feb 2008 19:12:00 -0600 Subject: [Tutor] how to display terminal messages in dialog window using tkinter In-Reply-To: References: Message-ID: <200802211912.01036.cfuller084@thinkingplanet.net> There's a post on this list from me, with example code, from a couple of weeks ago that solves this: http://mail.python.org/pipermail/tutor/2008-February/060025.html Cheers On Thursday 21 February 2008 11:15, brindly sujith wrote: > hi > > i m developing a application using tkinter > > i want the messages that we get in the terminal to be displayed in the > tkinter dialog box > > do we have any option for that > > thank you From keridee at jayco.net Fri Feb 22 22:58:12 2008 From: keridee at jayco.net (Tiger12506) Date: Fri, 22 Feb 2008 16:58:12 -0500 Subject: [Tutor] how to display terminal messages in dialog windowusingtkinter References: Message-ID: <011001c875a1$ae44ad60$d2fce004@jslaptop> > If you literally want print statements to appear in a dialog then no, > you can't do that (so far as I know!). But if you want the Tkinter Alan??? Redirect standard output. It doesn't have to be a file object. It can be any object with a write method. From kent37 at tds.net Fri Feb 22 23:36:14 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 22 Feb 2008 17:36:14 -0500 Subject: [Tutor] how to display terminal messages in dialog windowusingtkinter In-Reply-To: <011001c875a1$ae44ad60$d2fce004@jslaptop> References: <011001c875a1$ae44ad60$d2fce004@jslaptop> Message-ID: <47BF4E5E.5070702@tds.net> Tiger12506 wrote: >> If you literally want print statements to appear in a dialog then no, >> you can't do that (so far as I know!). But if you want the Tkinter > > Alan??? Redirect standard output. It doesn't have to be a file object. It > can be any object with a write method. Another way to do this, if you have control over the print statements, is to use the logging package for output. It's not hard to make a log handler that captures the messages and outputs them to a GUI panel. Kent From alan.gauld at btinternet.com Sat Feb 23 02:55:39 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Feb 2008 01:55:39 -0000 Subject: [Tutor] how to display terminal messages indialog windowusingtkinter References: <011001c875a1$ae44ad60$d2fce004@jslaptop> <47BF4E5E.5070702@tds.net> Message-ID: "Kent Johnson" wrote >>> If you literally want print statements to appear in a dialog then >>> no, >>> you can't do that (so far as I know!). But if you want the Tkinter >> >> Alan??? Redirect standard output. It doesn't have to be a file >> object. It >> can be any object with a write method. > > Another way to do this, if you have control over the print > statements, > is to use the logging package for output. It's not hard to make a > log > handler that captures the messages and outputs them to a GUI panel. Both of these suggestions are what I had in mind when I said "create your own logging dialog with a text widget". I don't know of any way to turn vanilla print statements into GUI visible strings. Even redirecting stdout would require the creation of some kind of custom widget that wrote to the GUI. (But I'd love to be wrong! :-) Alan G. From kent37 at tds.net Sat Feb 23 03:10:18 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 22 Feb 2008 21:10:18 -0500 Subject: [Tutor] how to display terminal messages indialog windowusingtkinter In-Reply-To: References: <011001c875a1$ae44ad60$d2fce004@jslaptop> <47BF4E5E.5070702@tds.net> Message-ID: <47BF808A.9040602@tds.net> Alan Gauld wrote: > I don't know of any way to turn vanilla print statements into GUI > visible > strings. Even redirecting stdout would require the creation of some > kind > of custom widget that wrote to the GUI. (But I'd love to be wrong! :-) OK I'll bite. You don't need a custom GUI widget, you just need a simple adapter. Here is a simple proof of concept that redirects sys.stdout to a Text widget: import sys from Tkinter import * root = Tk() t1 = Text(root) t1.pack() class PrintToT1(object): def write(self, s): t1.insert(END, s) sys.stdout = PrintToT1() print 'Hello, world!' print "Isn't this fun!" mainloop() # Kent From meanburrito920 at yahoo.com Sat Feb 23 06:46:58 2008 From: meanburrito920 at yahoo.com (John Gunderman) Date: Fri, 22 Feb 2008 21:46:58 -0800 (PST) Subject: [Tutor] how to parse a multiple character words from plaintext Message-ID: <260523.97304.qm@web56304.mail.re3.yahoo.com> I am looking to parse a plaintext from a document. However, I am confused about the actual methodology of it. This is because some of the words will be multiple digits or characters. However, I don't know the length of the words before the parse. Is there a way to somehow have open() grab something until it sees a /t or ' '? I was thinking I could have it count ahead the number of spaces till the stopping point and then parse till that point using read(), but that seems sort of inefficient. Is there a better way to pull this off? Thanks in advance. John ____________________________________________________________________________________ Looking for last minute shopping deals? Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080222/5c1d2b99/attachment.htm From agoldgod at gmail.com Sat Feb 23 07:09:21 2008 From: agoldgod at gmail.com (goldgod a) Date: Sat, 23 Feb 2008 11:39:21 +0530 Subject: [Tutor] Tamil Language support for Tkinter Message-ID: <105c9ccc0802222209v2a73a951t14f2e6bbea20635@mail.gmail.com> Hi, I need the Tamil language support for Tkinter. How can I do that? I searched a lot I cannot find any solutions. Any idea to create a add ons for Tamil support. I am using "Debian -Sid(unstable)", Python 2.4, Tcl/Tk 8.4. -- Thanks & Regards, goldgod -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080223/9a51870e/attachment.htm From kent37 at tds.net Sat Feb 23 12:43:44 2008 From: kent37 at tds.net (Kent Johnson) Date: Sat, 23 Feb 2008 06:43:44 -0500 Subject: [Tutor] how to parse a multiple character words from plaintext In-Reply-To: <260523.97304.qm@web56304.mail.re3.yahoo.com> References: <260523.97304.qm@web56304.mail.re3.yahoo.com> Message-ID: <47C006F0.8020709@tds.net> John Gunderman wrote: > I am looking to parse a plaintext from a document. However, I am > confused about the actual methodology of it. This is because some of the > words will be multiple digits or characters. However, I don't know the > length of the words before the parse. Is there a way to somehow have > open() grab something until it sees a /t or ' '? I was thinking I could > have it count ahead the number of spaces till the stopping point and > then parse till that point using read(), but that seems sort of > inefficient. Is there a better way to pull this off? Thanks in advance. How big is the file? Can you just read the whole document and parse the resulting string? Or read by lines? Depending on how complex your parsing is, you might want to use pyparsing or one of the other Python parser libraries. http://pyparsing.wikispaces.com/ http://nedbatchelder.com/text/python-parsers.html Kent From alan.gauld at btinternet.com Sat Feb 23 13:13:40 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Feb 2008 12:13:40 -0000 Subject: [Tutor] how to parse a multiple character words from plaintext References: <260523.97304.qm@web56304.mail.re3.yahoo.com> Message-ID: "John Gunderman" wrote >I am looking to parse a plaintext from a document. When you say "a document" what kind of document do you mean? Is the document also in plain text, like HTML, or is it a binary format like MS Word? > some of the words will be multiple digits or characters. > However, I don't know the length of the words before the parse. Look at the regula5r expression module re. regular expressions allow you to define patterns and then search for those patterns within a string. > Is there a way to somehow have open() grab something > until it sees a /t or ' '? open() doesn't grab anything, it simply makes the file available for reading. You can then use read to either read the whole file or a fixed number of characers. You can also use readline() to read a single line or readlines() to read the emntire file into a list of lines. Which you use will depend a lot on the format of your data. > I was thinking I could have it count ahead the > number of spaces till the stopping point and then > parse till that point using read(), but that seems sort > of inefficient. It may or may not be efficiant but its certainly complex since it requires you to know in advance what the next bit of data looks like. If it follows a set pattern that may be OK. If possible you probably would be better reading the data line by line and parsing each line. However if the data spills across lines that will probably not be viable. If the file is not too big(a few MB say) then siomply reading the entire file as a single string and using regular expressions may be the easiest way. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From i.m.ozsvald at btinternet.com Sat Feb 23 13:57:03 2008 From: i.m.ozsvald at btinternet.com (Ian Ozsvald) Date: Sat, 23 Feb 2008 12:57:03 +0000 (GMT) Subject: [Tutor] Django hosting Message-ID: <534965.56394.qm@web86510.mail.ird.yahoo.com> I'll echo Kent and give +1 to WebFaction. As Kent mentions for the price of 2 pints of beer per month on the basic shared plan: http://www.webfaction.com/services/hosting you can run your long-running Django app and receive excellent tech-support from Remi, David and team. They are long-time Python supporters (along with other dynamic languages like Ruby) and really do know their stuff. My ShowMeDo.com has been running there (on the biggest Shared Host package, now looking towards a private server with them) for 2 years and the quality of their tech support really is excellent. I feel that we're in a very safe pair of hands which is rather invaluable when you want to spend your time developing, not administering. The 60mb memory allowance on Shared1 is enough to run one or two small Django or TurboGears applications (ShowMeDo is written in TurboGears). A basic instance of TurboGears uses about 20mb and I'd guess (but have no experience) that Django uses a similar amount of memory. In relation to this and the previous (hijacked) thread, I'd suggest a new user looks at Django as their first framework. It is mature, undergoing continuous growth and has a large support network via the forums, main site and book - that'll keep you productive when you might stumble with less-well-known frameworks. Personally I'm a TurboGears supporter and have high hopes for what could happen with TG2.0 later in the year, but right now I'd suggest Django as a first port of call. HTH, Ian. ps. this is my first post, I'll modify my posting format if this comes through mangled . Ian Ozsvald i.m.ozsvald at btinternet.com http://ianozsvald.com http://Services.ShowMeDo.com + http://ShowMeDo.com http://FivePoundApp.com/ + http://OpenCoffeeSussex.com http://tech.groups.yahoo.com/group/brightondigital/ From amonroe at columbus.rr.com Sat Feb 23 16:43:50 2008 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 23 Feb 2008 10:43:50 -0500 Subject: [Tutor] how to parse a multiple character words from plaintext In-Reply-To: <260523.97304.qm@web56304.mail.re3.yahoo.com> References: <260523.97304.qm@web56304.mail.re3.yahoo.com> Message-ID: <861655965352.20080223104350@columbus.rr.com> > I am looking to parse a plaintext from a document. However, I am > confused about the actual methodology of it. This is because some of > the words will be multiple digits or characters. However, I don't > know the length of the words before the parse. Is there a way to > somehow have open() grab something until it sees a /t or ' '? If your file format is not too fancy, split() may be all you need. Alan From alan.gauld at freenet.co.uk Sat Feb 23 18:55:48 2008 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat, 23 Feb 2008 17:55:48 -0000 Subject: [Tutor] My Web Site Message-ID: <000501c87645$52ee9e90$6601a8c0@xp> My web tutorial has been dead for the past week so I've set up a temporary mirror of the English section only. Hopefully Freenet will get their server running sometime soon. The new address is: http://uk.geocities.com/alan.gauld at btinternet.com/ Hopefully that will do until normal service is resumed... Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From varsha.purohit at gmail.com Sun Feb 24 00:53:33 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sat, 23 Feb 2008 15:53:33 -0800 Subject: [Tutor] [tutor] Question on multithreading Message-ID: Hello, i have a gui program in wxpython where i am spawning two threads. one for the mainloop of gui and other for some background tasks. I have to stop the background running thread once its work is done. I am trying to use the join method but it is giving me an error saying threads cannot be joined as the thread has just been created... whereas at that point the thread is done with its job. So i am confused whether i am putting it correctly or not. also, is there any method called stop() to stop the threads....Also, i want to see if the thread is alive or not.. but i donno where should i put the isAlive() method associated with the thread.. i tried putting it in the code where thread does execution but apparently it is not the correct place......... Here is the code... class GuiScript(threading.Thread): def __init__(self): self.run() def run(self): app = wx.PySimpleApp() MainWindow().Show() app.MainLoop() class RunScript(threading.Thread): def run(self): imFile=test() and when the stop button is pressed the two threads should stop executing... so i have written code like this... def OnCloseWindow(self,event): GuiScript().Stop() RunScript().Stop() self.Destroy() but seems stop() method is not existing... can anybody guide me plzzzz thanks, -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080223/48d66037/attachment.htm From thomas.pani at gmail.com Sun Feb 24 12:15:56 2008 From: thomas.pani at gmail.com (Thomas Pani) Date: Sun, 24 Feb 2008 12:15:56 +0100 Subject: [Tutor] Question on multithreading In-Reply-To: References: Message-ID: <47C151EC.9000909@gmail.com> Hi, Here are some thoughts: From the Python Library Reference: "If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread." You'll have to do that for your GuiScript class. You can't just stop a thread, you can only wait for it to finish using join(). Or you can set its deamon flag, so it will exit when no non-daemon threads are left. Is there any reason for starting the GUI code in a separate thread? You could just leave it in the main thread. For some general notes on this topic this might be helpful: http://wiki.wxpython.org/LongRunningTasks Cheers, Thomas Pani Varsha Purohit wrote: > Hello, > i have a gui program in wxpython where i am spawning two threads. > one for the mainloop of gui and other for some background tasks. I have > to stop the background running thread once its work is done. I am trying > to use the join method but it is giving me an error saying threads > cannot be joined as the thread has just been created... whereas at that > point the thread is done with its job. So i am confused whether i am > putting it correctly or not. also, is there any method called stop() to > stop the threads....Also, i want to see if the thread is alive or not.. > but i donno where should i put the isAlive() method associated with the > thread.. i tried putting it in the code where thread does execution but > apparently it is not the correct place......... > > Here is the code... > > class GuiScript(threading.Thread): > def __init__(self): > self.run() > def run(self): > app = wx.PySimpleApp() > MainWindow().Show() > app.MainLoop() > > class RunScript(threading.Thread): > def run(self): > imFile=test() > > and when the stop button is pressed the two threads should stop > executing... so i have written code like this... > > def OnCloseWindow(self,event): > GuiScript().Stop() > RunScript().Stop() > self.Destroy() > > but seems stop() method is not existing... can anybody guide me plzzzz > > thanks, > > > -- > Varsha Purohit, > Graduate Student > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From andrei.petre at gmail.com Sun Feb 24 13:36:53 2008 From: andrei.petre at gmail.com (Andrei Petre) Date: Sun, 24 Feb 2008 14:36:53 +0200 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) Message-ID: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> Hello, I wrote a code for a problem and submitted to an online judge, a program that runs my program against a set of predefined input data. I wrote it for exercise my python writing. In don't want to discuss the algorithm here! I dare to ask for help because the answer was : crashed with Runtime Error: NZEC (non-zero exit code). I heard that is a general error for most interpreters and elsewhere that NZEC error code has to do with exceptions. So, i'm seeking for a possible problem with the coding, not with the algorithm. Here, the code. (l also attached it in a file) Using characters of the string, the program should construct the maximum number which divides by fifteen without remainder. example *Input:* 1 02041 *Output:* 4200 [code] import sys def write(number): # assamble the number # assure the 5 divisibility if number[0] != 0: number[0] -= 1 last_d = 0 else: number[5] -= 1 last_d = 5 zero = True for i in reversed(range(1,10)): for j in range(digits[i]): sys.stdout.write(i) zero = False # leading zeroes should be omitted if zero == False: for i in range(digits[0]): sys.stdout.write(0) print last_d def remove_item(d,item): if type(item) != list: d[item] -= 1 else: d[item[0]] -= 1 d[item[1]] -= 1 def case5(d,item): # return True if i try to remove the only five that assure the divisibility with 5 return item == 5 and d[0] == 0 and d[item] == 1 def exist(d,item): found = False if type(item) != list: if d[item] != 0 and case5(d,item) == False: found = True else: p1 = d[item[0]] != 0 and case5(d,d[item[0]]) == False d[item[0]] -= 1 p2 = d[item[1]] != 0 and case5(d,d[item[1]]) == False d[item[0]] += 1 if p1 == True and p2 == True: found = True return found def remove(d, mult): found = False for item in mult: if exist(d,item) == True: remove_item(d,item) found = True break if found == False: d = [] return d def remove_all(digits,rest): # if the number is the form 3k+1, i try to remove one 3k+1 digit or two 3k+2 digits # if the number is the form 3k+2, i try to remove one 3k+2 digit or two 3k+2 digits one = [1,4,7,[2,2],[2,5],[2,8],[5,5],[5,8],[8,8]] two = [2,5,8,[1,1],[1,4],[1,7],[4,4],[4,7],[7,7]] if rest == 1: d = remove(digits, one) else: d = remove(digits, two) return d def resolve(digits): suma = 0 for i in range(10): suma += i*digits[i] rest = suma % 3 if rest != 0: # if it's not divisible with 3 i try to remove some digits digits = remove_all(digits,rest) return digits t = int(raw_input()) for tt in range(t): line = raw_input() digits = [0]*10 # counts the frequence of digits in the string for i in range(len(line)): digits[int(line[i])] += 1 # if it's not divisible with 5 if digits[0] == 0 and digits[5] == 0: print("impossible") else: number = resolve(digits) if(number == []): print("impossible") else: write(number) [/code] Any alternatives for the personal rambling(if it's a wrong way to do it, of course): L = [1,2,[3,4],[5,5]] for item in L: if type(item) == list: print L[item[0]], L[item[1]] else: print L[item] Thanks, Andrei -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080224/7682a3f9/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: div15.py Url: http://mail.python.org/pipermail/tutor/attachments/20080224/7682a3f9/attachment.txt From kent37 at tds.net Sun Feb 24 15:01:27 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Feb 2008 8:01:27 -0600 Subject: [Tutor] how to parse a multiple character words from plaintext In-Reply-To: <599905.6065.qm@web56301.mail.re3.yahoo.com> Message-ID: <20080224080127.BMPLM.215072.root@webfep11> ---- John Gunderman wrote: > I am parsing the output of the mork.pl, which is a DORK (the mozilla format) parser. I don't know Perl, so I decided to write a Python script to do what I wanted, which basically is to create a dictionary listing each site and its corresponding values instead of outputting into plaintext. Unfortunately, the output of mork.pl is 5000+ lines so reading the whole document wouldn't be that efficient. If you have enough memory for it to fit, reading the whole file at once is fine. > Currently it uses: > for line in history_file.readlines(): > but I dont know if this has to read all lines before it goes through it. Yes, readlines() reads the entire file. > if it does, then would it be more efficient to use > while line != '/t': > line = history_file.readline() Probably not. But why so much emphasis on efficiency? Get the program working first. Only if it is too slow should you worry about efficiency. Processing a 5000-line file should not be a problem in Python. > I was thinking of just appending each character to the string until it sees '/t', and then using int() on the string, but is there an easier way? It would really help to see a sample of the data and the results you want from it. There are many ways to parse data in Python, from simple string operations to regular expressions to full-blown parsers. Without knowing what you want to do it is impossible to suggest an appropriate method. Kent From kent37 at tds.net Sun Feb 24 15:21:10 2008 From: kent37 at tds.net (Kent Johnson) Date: Sun, 24 Feb 2008 8:21:10 -0600 Subject: [Tutor] how to parse a multiple character words from plaintext In-Reply-To: Message-ID: <20080224082110.KDO5C.215247.root@webfep11> ---- John Gunderman wrote: > I am parsing the output of the mork.pl, which is a DORK (the mozilla format) parser. I don't know Perl, so I decided to write a Python script to do what I wanted, which basically is to create a dictionary listing each site and its corresponding values instead of outputting into plaintext. Unfortunately, the output of mork.pl is 5000+ lines so reading the whole document wouldn't be that efficient. OK, I looked briefly at mork.pl. You should be able to process it line-by-line with something like this: for line in history_file: if not line.strip(): continue # skip blank lines; may not be needed time, count, url = line.split() # do something with time, count, url Kent Currently it uses: > for line in history_file.readlines(): > but I dont know if this has to read all lines before it goes through it. if it does, then would it be more efficient to use > while line != '/t': > line = history_file.readline() > I was thinking of just appending each character to the string until it sees '/t', and then using int() on the string, but is there an easier way? > > John > > ----- Original Message ---- > From: Kent Johnson > To: John Gunderman > Cc: tutor at python.org > Sent: Saturday, February 23, 2008 3:43:44 AM > Subject: Re: [Tutor] how to parse a multiple character words from plaintext > > John Gunderman wrote: > > I am looking to parse a plaintext from a document. However, I am > > confused about the actual methodology of it. This is because some of the > > words will be multiple digits or characters. However, I don't know the > > length of the words before the parse. Is there a way to somehow have > > open() grab something until it sees a /t or ' '? I was thinking I could > > have it count ahead the number of spaces till the stopping point and > > then parse till that point using read(), but that seems sort of > > inefficient. Is there a better way to pull this off? Thanks in advance. > > How big is the file? Can you just read the whole document and parse the > resulting string? Or read by lines? > > Depending on how complex your parsing is, you might want to use > pyparsing or one of the other Python parser libraries. > http://pyparsing.wikispaces.com/ > http://nedbatchelder.com/text/python-parsers.html > > Kent > > > > > > > ____________________________________________________________________________________ > Looking for last minute shopping deals? > Find them fast with Yahoo! Search. http://tools.search.yahoo.com/newsearch/category.php?category=shopping From dave6502 at googlemail.com Sun Feb 24 17:14:02 2008 From: dave6502 at googlemail.com (dave selby) Date: Sun, 24 Feb 2008 16:14:02 +0000 Subject: [Tutor] How do I destroy class instances ? Message-ID: I have created a list of class instances, works a treat. I need to be able to re __init__ the instances on a SIGHUP so I guess the best way is to destroy them & re make them. err ... how do I destroy an instance ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From alan.gauld at btinternet.com Sun Feb 24 18:48:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Feb 2008 17:48:51 -0000 Subject: [Tutor] How do I destroy class instances ? References: Message-ID: "dave selby" wrote >I have created a list of class instances, works a treat. I need to be > able to re __init__ the instances on a SIGHUP so I guess the best > way > is to destroy them & re make them. You could just call init on them... >>> class C: ... def __init__(s,x,y): ... s.x = x ... s.y = y ... def __str__(s): return 'x,y = %s, %s' % (s.x, s.y) ... >>> for n in range(3): L.append(C(n,n+1)) ... >>> for c in L: print c ... x,y = 0, 1 x,y = 1, 2 x,y = 2, 3 >>> # -- NOW CALL INIT >>> for c in L: C.__init__(c,42,66) >>> # or it could be >>> # for c in L: c.__init__(42,66) if you prefer ... >>> for c in L: print c ... x,y = 42, 66 x,y = 42, 66 x,y = 42, 66 >>> > err ... how do I destroy an instance ? Stop anything referring to it: In the above: L = [] will delete all the items in L - provided nothing else refers to them HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From dkuhlman at rexx.com Sun Feb 24 19:13:06 2008 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 24 Feb 2008 10:13:06 -0800 Subject: [Tutor] How do I destroy class instances ? In-Reply-To: References: Message-ID: <20080224181306.GA33487@cutter.rexx.com> On Sun, Feb 24, 2008 at 04:14:02PM +0000, dave selby wrote: > I have created a list of class instances, works a treat. I need to be > able to re __init__ the instances on a SIGHUP so I guess the best way > is to destroy them & re make them. > > err ... how do I destroy an instance ? It is not likely that you need to. When your instances are no longer referenced (nothing points to them, so to speak), they will be garbage collected. Here is an illustraction -- This code collects three instances of class MyClass in a list, then later "forgets" them: myinstances = [] myinstances.append(MyClass()) myinstances.append(MyClass()) myinstances.append(MyClass()) o o o myinstances = [] Or, if there are resources that are held onto by each instance and need to be cleaned up, for example an open file. Then do something like the following: for inst in myinstances: inst.cleanup() myinstances = [] where "cleanup" is a method implemented in each class that needs to cleanup/release resources. But, remember that, if there are objects that are referred to by your instances and *only* your instances, then when your instances go away (are garbage collected), those other things will also automatically go away, too. No extra work is needed. It takes a little thought before you will figure out that this is something that needs (almost) no thought. Hope this helps. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From bgailer at alum.rpi.edu Sun Feb 24 21:37:45 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sun, 24 Feb 2008 15:37:45 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> Message-ID: <47C1D599.6010502@alum.rpi.edu> Andrei Petre wrote: > Hello, > > I wrote a code for a problem and submitted to an online judge, a > program that runs my program against a set of predefined input data. Did you run the code yourself? It would appear that you did not. Before submitting to an online judge run the code on your own computer. Can you do that? Do you know how? When you run it you will discover an error. Fix that and try again. [snip] -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Sun Feb 24 21:41:14 2008 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 24 Feb 2008 15:41:14 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) WAIT!!! In-Reply-To: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> Message-ID: <47C1D66A.7060006@alum.rpi.edu> Hold the phone! Ignore previous email. Working... -- Bob Gailer 919-636-4239 Chapel Hill, NC From bgailer at alum.rpi.edu Sun Feb 24 21:47:42 2008 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 24 Feb 2008 15:47:42 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> Message-ID: <47C1D7EE.7020500@alum.rpi.edu> OK I maintain what I wrote earlier: Did you run the code yourself? It would appear that you did not. Before submitting to an online judge run the code on your own computer. Can you do that? Do you know how? When you run it you will discover an error. Fix that and try again. [snip] -- Bob Gailer 919-636-4239 Chapel Hill, NC From madpotential at gmail.com Sun Feb 24 22:25:25 2008 From: madpotential at gmail.com (Krystle Scott) Date: Sun, 24 Feb 2008 16:25:25 -0500 Subject: [Tutor] help beginner in python. Message-ID: <85f4993f0802241325h23a6ff86ndc4c7e4d38746125@mail.gmail.com> i need to write an algorithm for computing square roots. so far I have import math def main (): print " This program computes approximate square roots using Newton's method: " print input = (" Enter whose square root you wish to compute (a) : ") input = (" Enter the number of iterations :" ) discRoot = math.sqrt print print "The solutions of the square roots" I need to have it print out iterations and math.sqrt what am i doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080224/1f8f9411/attachment.htm From steve at alchemy.com Sun Feb 24 22:57:18 2008 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 24 Feb 2008 13:57:18 -0800 Subject: [Tutor] help beginner in python. In-Reply-To: <85f4993f0802241325h23a6ff86ndc4c7e4d38746125@mail.gmail.com> References: <85f4993f0802241325h23a6ff86ndc4c7e4d38746125@mail.gmail.com> Message-ID: <47C1E83E.8040305@alchemy.com> Krystle Scott wrote: > i need to write an algorithm for computing square roots. > so far I have This sounds like a class exercise. I think we can help you with Python questions, but you'll need to do the part that is directly related to your homework on your own. > import math > > def main (): Python doesn't explicitly need a main() function. You can just define what other classes and functions you need, and call them from your mainline (outer-level) script code. > print " This program computes approximate square roots using Newton's > method: " > print > > > input = (" Enter whose square root you wish to compute (a) : ") > input = (" Enter the number of iterations :" ) I suggest going through some of the Python tutorial material available on python.org. Going first through the getting-started material would be a lot of help for you here. These are just assigning strings to a variable called "input" which isn't really accomplishing anything for you. If you wanted to actually prompt for input and receive it, you need to call the input() function, like this: x = input("Enter a number: ") > discRoot = math.sqrt math.sqrt, like any function, needs to be passed a number to take the square root of, like math.sqrt(x). However, I suspect that's only going to help you check your work. You said you need to code an algorithm for computing square roots, so just calling the sqrt() function from the library isn't accomplishing that goal, and won't get you much credit for your class. You will need to figure out how that algorithm works, and define your own function to implement it. Call math.sqrt() to check your result, if you want. > > print > print "The solutions of the square roots" > > > I need to have it print out iterations and math.sqrt what am i doing wrong? To actually do iterations you'll want a for loop. To print values, you need to actually mention them in the print statements, like: print "The value of x is", x From dave6502 at googlemail.com Sun Feb 24 22:59:38 2008 From: dave6502 at googlemail.com (dave selby) Date: Sun, 24 Feb 2008 21:59:38 +0000 Subject: [Tutor] How do I destroy class instances ? In-Reply-To: <20080224181306.GA33487@cutter.rexx.com> References: <20080224181306.GA33487@cutter.rexx.com> Message-ID: On 24/02/2008, Dave Kuhlman wrote: > On Sun, Feb 24, 2008 at 04:14:02PM +0000, dave selby wrote: > > I have created a list of class instances, works a treat. I need to be > > able to re __init__ the instances on a SIGHUP so I guess the best way > > is to destroy them & re make them. > > > > err ... how do I destroy an instance ? > > > It is not likely that you need to. > > When your instances are no longer referenced (nothing points to > them, so to speak), they will be garbage collected. Here is an > illustraction -- This code collects three instances of class > MyClass in a list, then later "forgets" them: > > myinstances = [] > myinstances.append(MyClass()) > myinstances.append(MyClass()) > myinstances.append(MyClass()) > o > o > o > myinstances = [] > > Or, if there are resources that are held onto by each instance and > need to be cleaned up, for example an open file. Then do something > like the following: > > for inst in myinstances: > inst.cleanup() > myinstances = [] > > where "cleanup" is a method implemented in each class that needs to > cleanup/release resources. > > But, remember that, if there are objects that are referred to by > your instances and *only* your instances, then when your instances > go away (are garbage collected), those other things will also > automatically go away, too. No extra work is needed. > > It takes a little thought before you will figure out that this is > something that needs (almost) no thought. Thanks for replying, I have been away from Python for quite a while, being dabbleing in C++ on a KDE4 app. I Forgot just how friendly Python is :) Cheers Dave > > Hope this helps. > > - Dave > > > -- > Dave Kuhlman > http://www.rexx.com/~dkuhlman > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From bgailer at alum.rpi.edu Sun Feb 24 23:42:02 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Sun, 24 Feb 2008 17:42:02 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> Message-ID: <47C1F2BA.9070800@alum.rpi.edu> Andrei Petre wrote: > Hello, > > I wrote a code for a problem and submitted to an online judge url please, and link to the specific problem -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Sun Feb 24 23:53:23 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Feb 2008 22:53:23 -0000 Subject: [Tutor] help beginner in python. References: <85f4993f0802241325h23a6ff86ndc4c7e4d38746125@mail.gmail.com> Message-ID: "Krystle Scott" wrote >i need to write an algorithm for computing square roots. We don;t do homework here but we can help with specific questions and to resolve errors. > import math > > def main (): > print " This program computes approximate square roots using > Newton's > method: " > print > > > input = (" Enter whose square root you wish to compute (a) : ") > input = (" Enter the number of iterations :" ) OK, this is so far off base that I have to ask whether you have done any Python programming at all before? Where is this assignment (which I asume it is?) coming from? It seems kind of unfair to ask you to do this if you haven't even covered the basics of Python already! > discRoot = math.sqrt Calling python's square root function won't do anything for implementing Newtons methiod, except maybe prove the result when you get there is close... Can you give us a bit more background to where this challenge is coming from and your bbackground, otherwise I'd say you need to go through one of the beginners tutorials. There are many on the Python web site, pick one that looks good to you. HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From vimes656 at gmail.com Mon Feb 25 07:25:35 2008 From: vimes656 at gmail.com (Danny Navarro) Date: Mon, 25 Feb 2008 11:55:35 +0530 Subject: [Tutor] library to create venn diagrams? Message-ID: Hi all, Does anyone know a Python library to generate Venn diagrams with more than 3 datasets? The area of the datasets and the intersections should be proportional to the quantity of data. Thanks, Danny From zebra05 at gmail.com Mon Feb 25 10:46:27 2008 From: zebra05 at gmail.com (OkaMthembo) Date: Mon, 25 Feb 2008 11:46:27 +0200 Subject: [Tutor] web.py vs webwareforpython In-Reply-To: <40af687b0802211128l5cf9d73ct7fd15017f2eec24b@mail.gmail.com> References: <47BD6B95.4030604@tds.net> <47BDC35F.4000007@tds.net> <40af687b0802211128l5cf9d73ct7fd15017f2eec24b@mail.gmail.com> Message-ID: @Kent, that's some useful background info. @Marc, i also thought about the issue of Python hosts not supporting long-running processes. Do check with WebFaction though http://www.webfaction.com - apparently one can get Python hosting that allows installation of certain server modules e.g. mod_python, etc. I hope i understood you correctly. Lloyd Dube. On Thu, Feb 21, 2008 at 9:28 PM, Marc Tompkins wrote: > Sorry to jump in the middle here, but I have a somewhat related > question... > > I have a few websites set up for my clients, mostly using Mambo/Joomla > (PHP-based). My clients tend to be small brick-and-mortar businesses > (doctors, lawyers, etc.) who merely wish to use their website as an > extension of their marketing effort, not as a storefront, and generally I > set the thing up / perform updates, etc. and turn over the day-to-day > running of the site (posting new articles/pictures/videos, running fora, > sending newsletters) to a member of their staff. > > I'd love to switch to a Python-based solution for my future and ongoing > projects, and Django looks very exciting to me, but... honestly, Django > won't run on most commodity-grade web hosts. And I'm frankly sick of > hearing the knee-jerk response "GoDaddy sucks! 1and1 sucks!" because, darn > it, they work just fine with Joomla. Django requires "long-running > processes", which a cheap webhost obviously doesn't like... > > I don't really have anything against Joomla - it's worked well for me - > but I do feel pretty silly raving about how great Python is, and then when > the subject of web development comes up having to shuffle my feet and say > "...ummm... well, there I use PHP. But Python's really great!" > I also don't have a love affair going with GoDaddy or 1and1, but they've > both been very affordable and (especially GoDaddy) very easy to work with, > which I can't say for a lot of other companies I've dealt with. They've > also both been around for a few years, and I'm confident that they still > will be there in a few more. These are all very important to me and my > clients. > I'd like - if possible - to use a relatively mature framework which I can > then extend. I'm happy starting from scratch and experimenting with my own > personal hobby projects, but in this area I'd like the core functionality to > "just work". > > So my question is: does anybody have a good Python-based CMS / template / > whatever framework up and running on a commodity-priced, shared webhost? If > so, which one? Which host? Inquiring minds wanna know. > -- > www.fsrtechnologies.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080225/9ea0d7ae/attachment.htm From john at fouhy.net Mon Feb 25 22:08:17 2008 From: john at fouhy.net (John Fouhy) Date: Tue, 26 Feb 2008 10:08:17 +1300 Subject: [Tutor] library to create venn diagrams? In-Reply-To: References: Message-ID: <5e58f2e40802251308t30899f98x3499aa0c371bf328@mail.gmail.com> On 25/02/2008, Danny Navarro wrote: > Hi all, > > Does anyone know a Python library to generate Venn diagrams with more > than 3 datasets? The area of the datasets and the intersections should > be proportional to the quantity of data. I don't ... ... also, how would you draw in two dimensions a Venn diagram of four mutually-intersecting sets? I can't see how it is possible in general.. -- John. From carroll at tjc.com Tue Feb 26 01:18:42 2008 From: carroll at tjc.com (Terry Carroll) Date: Mon, 25 Feb 2008 16:18:42 -0800 (PST) Subject: [Tutor] library to create venn diagrams? In-Reply-To: <5e58f2e40802251308t30899f98x3499aa0c371bf328@mail.gmail.com> Message-ID: On Tue, 26 Feb 2008, John Fouhy wrote: > On 25/02/2008, Danny Navarro wrote: > > Hi all, > > > > Does anyone know a Python library to generate Venn diagrams with more > > than 3 datasets? The area of the datasets and the intersections should > > be proportional to the quantity of data. > > I don't ... I don't either, but... > ... also, how would you draw in two dimensions a Venn diagram of four > mutually-intersecting sets? I can't see how it is possible in > general.. Although with most Venn diagrams, the enclosing shapes are generally circles, they don't need to be the same shapes, and you can have Venn diagrams with more than three sets. Some examples here: http://en.wikipedia.org/wiki/Venn_diagram Also, a Venn diagram technically is a subset of the more general Euler diagram. The Venn diagram illustrates regions for all possible combinations of intersections, e.g., for three sets ABC, A-only, B-only, C-only, A+B only, A+C only, B+C only and A+B+C. A Euler diagram can be used where, for example, A intersects B but not C. More info at http://en.wikipedia.org/wiki/Euler_diagram I note the External Links section on the Venn diagram lists links to several tools to create Venn diagrams. I don't know if any of them are python, but if the OP is not limited to python-only solutions, they may help. From alan.gauld at btinternet.com Tue Feb 26 01:32:51 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Feb 2008 00:32:51 -0000 Subject: [Tutor] library to create venn diagrams? References: <5e58f2e40802251308t30899f98x3499aa0c371bf328@mail.gmail.com> Message-ID: "Terry Carroll" wrote > Also, a Venn diagram technically is a subset of the more general > Euler > diagram. The Venn diagram illustrates regions for all possible > combinations of intersections, e.g., for three sets ABC, A-only, > B-only, > C-only, A+B only, A+C only, B+C only and A+B+C. A Euler diagram can > be > used where, for example, A intersects B but not C. More info at > http://en.wikipedia.org/wiki/Euler_diagram Hmm, thats an interesting link. I studied math through to 5th year at university using sets all the way and never heard the term Euler diagram used, they were always just called Venn diagrams. You learn something new every day! :-) Alan G. From varsha.purohit at gmail.com Tue Feb 26 03:48:05 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Mon, 25 Feb 2008 18:48:05 -0800 Subject: [Tutor] [tutor] creating list of tuples Message-ID: Hello all, In my application i have to create a list of tuples. I have a for loop which will create (x,y) tuple each time it iterates, and i ahve to store each tuple in a list like list1= [(x1,y1), (x2,y2).....] any ideas how to do that ??? thanks, -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080225/086d9106/attachment.htm From kent37 at tds.net Tue Feb 26 03:52:52 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Feb 2008 21:52:52 -0500 Subject: [Tutor] [tutor] creating list of tuples In-Reply-To: References: Message-ID: <47C37F04.6040509@tds.net> Varsha Purohit wrote: > Hello all, > In my application i have to create a list of tuples. I have a for > loop which will create (x,y) tuple each time it iterates, and i ahve to > store each tuple in a list like > > list1= [(x1,y1), (x2,y2).....] > > any ideas how to do that ??? list1 = [] for ... # code to create x and y list1.append( (x, y) ) Note you do need the double parentheses; the inner pair creates a tuple, the outer pair is for the function call. Kent From kent37 at tds.net Tue Feb 26 03:27:40 2008 From: kent37 at tds.net (Kent Johnson) Date: Mon, 25 Feb 2008 21:27:40 -0500 Subject: [Tutor] Standalone Version In-Reply-To: <29c144020802231714n456c8db7ha7212723db3fc9ac@mail.gmail.com> References: <29c144020802211305i667269f0obb203a0bacbab728@mail.gmail.com> <47BDFDF7.9050909@tds.net> <29c144020802231714n456c8db7ha7212723db3fc9ac@mail.gmail.com> Message-ID: <47C3791C.3050304@tds.net> Artur Sousa wrote: > > level = (int(input(u"Digite o n\u00EDvel de seu bosque, po\u00E7o de > argila ou mina: "))) > quantity = (int(input(u"Digite a quantidade de recursos a serem > alcan\u00E7ados: "))) > if level == 1: phour = 60 > ... > ... > if level == 19: phour = 911 > ... > ... > if level == 30: phour = 4800 > ttaken = (quantity*3600)/phour > str1 = "Para produzir " > str2 = u" unidades desse recurso, serao necess\u00E1rios " > if ttaken == 1: > str3 = " segundo, ou " > else: > str3 = " segundos, ou " > if ttaken/60 <= 1: > str4 = " minuto, ou " > else: > str4 = " minutos, ou " > if ttaken/3600 <= 1: > str5 = " hora." > else: > str5 = " horas." > print str1 > print quantity > print str2 > print "" > print ttaken > print str3 > print "" > print ttaken/60.0 > print str4 > print "" > print ttaken/3600.0 > print str5 > > > So, by inputting level = 19, and quantity = 1822, the output should be > in one line only: > > Para produzir 1822 unidades desse recurso, serao necess?rios 7200 > segundos, ou 120.0 minutos, ou 2.0 horas. print "Para produzir", quantity, u"unidades desse recurso, serao necess\u00E1rios", ttaken, str3, ttaken/60.0, str4, ttaken/3600.0, str5 Kent PS Please use Reply All to reply to the list. From varsha.purohit at gmail.com Tue Feb 26 05:09:45 2008 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Mon, 25 Feb 2008 20:09:45 -0800 Subject: [Tutor] [tutor] creating list of tuples In-Reply-To: <47C37F04.6040509@tds.net> References: <47C37F04.6040509@tds.net> Message-ID: I think i got it.... i m creating a tuple of 2 elements everytime and i m adding it to a list. i m creating a new tup everytime and adding it to a list.... for x in file: value=0 tup = () for developerAgent in developers: #print developerAgent.disutility value +=developerAgent.disutility tup = (value,globalVar.cntr) globalVar.cntr +=1 globalVar.disutilList.append(tup) print globalVar.disutilList i am getting output as what i described... thanks for the help :) On Mon, Feb 25, 2008 at 6:52 PM, Kent Johnson wrote: > Varsha Purohit wrote: > > Hello all, > > In my application i have to create a list of tuples. I have a for > > loop which will create (x,y) tuple each time it iterates, and i ahve to > > store each tuple in a list like > > > > list1= [(x1,y1), (x2,y2).....] > > > > any ideas how to do that ??? > > list1 = [] > for ... > # code to create x and y > list1.append( (x, y) ) > > Note you do need the double parentheses; the inner pair creates a tuple, > the outer pair is for the function call. > > Kent > -- Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080225/463b7f43/attachment.htm From alan.gauld at btinternet.com Tue Feb 26 09:01:44 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Feb 2008 08:01:44 -0000 Subject: [Tutor] [tutor] creating list of tuples References: <47C37F04.6040509@tds.net> Message-ID: "Varsha Purohit" wrote One small point. > for x in file: > value=0 > tup = () There ia no point in creating an emnpty tuuple. Tuples are immutable so this tuple will simply be thrown away. It doesnm't do much harm, but it does no good either. > for developerAgent in developers: > #print developerAgent.disutility > value +=developerAgent.disutility > tup = (value,globalVar.cntr) This creates a brand new tuple and is all that is needed. BTW going by the names used are you sure a list of tuples is what you need? It looks like maybe a dictionary could be used instead storing the values against the cntr as a key. That would perform the role of borth list and tuple and make retrieval of the values easier later. Just a thought. HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From jmorcombe at westnet.com.au Tue Feb 26 09:50:35 2008 From: jmorcombe at westnet.com.au (Jim Morcobe) Date: Tue, 26 Feb 2008 17:50:35 +0900 Subject: [Tutor] How do I get GASP Message-ID: <47C3D2DB.4090909@westnet.com.au> Hi, I'd like to download a copy of GASP to run on Windows XP. Is there a simple Windows installer available anywhere so I can do it with minimal effort? Jim From alan.gauld at btinternet.com Tue Feb 26 14:02:56 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Feb 2008 13:02:56 -0000 Subject: [Tutor] How do I get GASP References: <47C3D2DB.4090909@westnet.com.au> Message-ID: "Jim Morcobe" wrote > > I'd like to download a copy of GASP to run on Windows XP. Is there > a > simple Windows installer available anywhere so I can do it with > minimal > effort? OK, I'll bite. What is GASP and why are you asking on a Python mailing list? I googled but came up with a mix of anti-smoking devices, Golf swing improvemt programmes and a small wb site design outfit among others. What are you talking about? -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From connorsml at gmail.com Tue Feb 26 14:13:21 2008 From: connorsml at gmail.com (Michael Connors) Date: Tue, 26 Feb 2008 14:13:21 +0100 Subject: [Tutor] How do I get GASP In-Reply-To: References: <47C3D2DB.4090909@westnet.com.au> Message-ID: > > OK, I'll bite. > What is GASP and why are you asking on a Python mailing list? > > I googled but came up with a mix of anti-smoking devices, > Golf swing improvemt programmes and a small wb site > design outfit among others. > > What are you talking about? This maybe: https://launchpad.net/gasp-code -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080226/19bc698e/attachment.htm From govind at adyasystems.com Tue Feb 26 08:00:22 2008 From: govind at adyasystems.com (Govind) Date: Tue, 26 Feb 2008 12:30:22 +0530 Subject: [Tutor] file transfer through serial modem -- pythin code Message-ID: <001c01c87845$43f056c0$1501a8c0@govind23639ac9> Hi All, I am new to python. I want to transfer files over serial modem.so can I have some sample python code or any helpful links so that I can implement it. All help will be highly appreciated. Thanks & Regards, Govind Goyal Adya Systems & Software Pvt. Ltd. 212, IInd Floor, Okhla Industrial Estate III, New Delhi - 110020 , India Ph: 91.11.41602431 Email ID- govind at adyasystems.com Disclaimer: The information contained in this message is confidential and may be legally privileged. The message is intended solely for the addressee(s). If you are not the intended recipient, you are hereby notified that any use, dissemination, or reproduction is strictly prohibited and may be unlawful. If you are not the intended recipient, please contact the sender by return e-mail and destroy all copies of the original message. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080226/7699cd8f/attachment.htm From cfuller084 at thinkingplanet.net Tue Feb 26 16:51:42 2008 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 26 Feb 2008 09:51:42 -0600 Subject: [Tutor] file transfer through serial modem -- pythin code In-Reply-To: <001c01c87845$43f056c0$1501a8c0@govind23639ac9> References: <001c01c87845$43f056c0$1501a8c0@govind23639ac9> Message-ID: <200802260951.42519.cfuller084@thinkingplanet.net> You probably want to start with PySerial: http://pyserial.sourceforge.net/ But, the details really depend on the application.. what are you talking to at the other end? Do you need a general terminal program? You can probably find xmodem and zmodem libraries, but if you control both ends, rolling your own would be easy enough, just be sure to check for data corruption. Zmodem is preferred, since Xmodem can pad the end of the file with NULLs. If you are working through a modem, you will need to be familiar with the Hayes AT Command Set. Google is your friend. Answering incoming calls is harder, you need access to the modem control lines (or you can tell the modem to answer manually). This is a platform specific problem. You might start out with a null modem cable between two computers (or even the same computer, with two serial ports), just to get familiar with the system. Cheers From bgailer at alum.rpi.edu Tue Feb 26 19:23:20 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 26 Feb 2008 13:23:20 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> Message-ID: <47C45918.2000504@alum.rpi.edu> Andrei Petre wrote: > https://www.spoj.pl/problems/DIV15/ I wrote my own version and submitted it. I got NZEC also. The evidence pointed to a character in the test data other than 0123456789. So I contrived a way to test for this and found that to be true. I don't know what the character is or which test case it is in but there is at least one bad character, and it is < chr(32) (i.e. a control character). After revising my program to eliminate these bad characters I now get wrong answer. So now I revise my algorithm. -- Bob Gailer 919-636-4239 Chapel Hill, NC From tavspamnofwd at googlemail.com Tue Feb 26 19:36:53 2008 From: tavspamnofwd at googlemail.com (Tom) Date: Tue, 26 Feb 2008 18:36:53 +0000 Subject: [Tutor] rss feed reader, but having trouble with unicode Message-ID: I'm trying to write a little rss feed reader, but having trouble with unicode. I would appreciate some help as I feel I'm going round in circles. Even when the save command works, ElementTree won't or vice-versa. You can see what I've been trying from my commented out lines. I think there is a problem with my understanding of unicode, so feel free to enlighten me. What encoding is the xml string before I do anything? Does my approach below make any sense??? import urllib, re, os, sys os.environ['DJANGO_SETTINGS_MODULE'] = 'djsite.settings' from djsite.djapp.models import Feed from xml.etree import ElementTree url = 'http://www.osirra.com/rss/rss20/1' #'http://www.michaelmoore.com/rss/mikeinthenews.xml' #'http://www.michaelmoore.com/rss/mustread.xml' f = urllib.urlopen(url) xml = f.read() f.close() feed = Feed.objects.get(url=url) if xml: ms = re.findall('\<\?xml version\=\"[^"]+\" encoding\=\"([^"]+)\"\?\>', xml) if ms: encoding = ms[0] else: encoding = 'utf-8' print 'using encoding:', encoding #xml = xml.encode(encoding, 'replace') ##xml = xml.decode(encoding, 'replace') #xml = unicode(xml, encoding) #xml = unicode(xml) elem = ElementTree.fromstring(xml) #do stuff with elem... feed.xml = xml feed.save() Thanks for your time :-) From alan.gauld at btinternet.com Tue Feb 26 19:38:42 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Feb 2008 18:38:42 -0000 Subject: [Tutor] How do I get GASP References: <47C3D2DB.4090909@westnet.com.au> Message-ID: "Michael Connors" wrote >> >> What are you talking about? > > This maybe: > > https://launchpad.net/gasp-code Yep, that looks more likely. I still can't help though. The downloadds page says no up to date Win installer exists just unzip the source. Alan G From bgailer at alum.rpi.edu Tue Feb 26 20:09:46 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 26 Feb 2008 14:09:46 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: <47C45918.2000504@alum.rpi.edu> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> Message-ID: <47C463FA.30005@alum.rpi.edu> I will share my algorithm just for the heck of it and to see if you see any problem. Underlying theory: Divisible by 15 == divisible by 3 and divisible by 5 If a number is divisible by 3 any rearrangement of its digits is also divisible by 3. Therefore to get the largest number, put the digits in descending order. If the number is not divisible by 3 it can be made divisible by 3 by removing one or 2 non-multiple-of-3 digits To be divisible by 5 the rightmost digit must be 0 or 5. If it is neither then a 5 must be moved from the interior to the end. s = the test case input If there are no '0's and no '5's in s then impossible. Convert s (string) to a list, sort it, reverse it. If rightmost digit is not '0' or '5', remove a '5' from the list (we will append it at checkout) On a "parallel path": i = int(s) # make numeric r = i % 3 # get modulo if r == 0 # divisible by 3 (regardless of the order of the digits) proceed to checkout else attempt to remove one or two digits to bring the modulo to 0 if possible remove just 1 digit (the lower the better) (the candidates are, for r ==1-1,4,7 r==2-2,5,8) otherwise if possible remove 2 digits (the lower the better) (the candidates are, for r ==2-1,4,7 r==1-2,5,8) otherwise impossible checkout: if we removed a '5' from the list, append it join and print the list -- Bob Gailer 919-636-4239 Chapel Hill, NC From kent37 at tds.net Tue Feb 26 19:56:08 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 26 Feb 2008 12:56:08 -0600 Subject: [Tutor] How do I get GASP In-Reply-To: Message-ID: <20080226125608.Z5QUG.4503.root@webfep14> ---- Alan Gauld wrote: > > "Michael Connors" wrote > >> > >> What are you talking about? > > > > This maybe: In which case - download from http://dev.laptop.org/pub/gasp/releases/SOURCES/python-gasp-0.1.1.tar.bz2 - unpack - copy the 'gasp' folder (NOT python-gasp-0.1.1, rather the subfolder called 'gasp') to your site-packages folder, e.g. C:\Python25\lib\site-packages Kent From ruivaldo at gmail.com Tue Feb 26 20:59:47 2008 From: ruivaldo at gmail.com (rui) Date: Tue, 26 Feb 2008 11:59:47 -0800 Subject: [Tutor] rss feed reader, but having trouble with unicode In-Reply-To: References: Message-ID: Hello Tom, Try doing this: xml = unicode(xml, encoding, "ignore") elem = ElementTree.fromstring(xml.encode("utf8")) > #do stuff with elem... > > feed.xml = xml > feed.save() > > > Thanks for your time :-) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Rui http://ruivaldo.wordpress.com "Rubi? Aquela novela do SBT?" ~ Carla Perez sobre Ruby "Em Python, tudo ? objeto, al?m de lindo e maravilhoso." ~ Caetano Veloso sobre Python From bgailer at alum.rpi.edu Tue Feb 26 22:31:42 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Tue, 26 Feb 2008 16:31:42 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: <3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> <47C463FA.30005@alum.rpi.edu> <3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> Message-ID: <47C4853E.6010602@alum.rpi.edu> Note I cc: tutor at python.org. Please do so also so the other tutors can follow the discussion. Andrei Petre wrote: > the theory seems just like mine :) > > your way to implement it looks fine ( although it supports some > optimization :)) > > But: > > - i don't understand : > i = int(s) > where s = the test case input (= a LIST ??) s is a string > > you should summs up the elements of the list In the pursuit of performance I chose int(s) as being potentially a lot faster than looping over all the chars, applying int() to each and summing. > > - it's not very clear in your implementation what happens with the > case : "815". try it I get 15. However 875 gives a wrong answer! Turns out that if the rightmost digit is not 0 I must remove a 5 even if that is the rightmost digit! Even after fixing that I still get "wrong answer"! > > and in one of your posts, you said: > > >The evidence pointed to a character in the test data other than > 0123456789. > > >So I contrived a way to test for this and found that to be true. I don't > >know what the character is or which test case it is in but there is at > >least one bad character, and it is < chr(32) (i.e. a control character). > >i don't understand , in your > > i don't really understand that. you are trying to say that the tests > from the online judge are not "exactly good" ? Yes that's exactly what I'm saying. At least one test case has a non-decimal character. > -- Bob Gailer 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Wed Feb 27 00:39:36 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Feb 2008 23:39:36 -0000 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> <47C463FA.30005@alum.rpi.edu><3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> <47C4853E.6010602@alum.rpi.edu> Message-ID: "bob gailer" wrote >> i don't really understand that. you are trying to say that the >> tests >> from the online judge are not "exactly good" ? > Yes that's exactly what I'm saying. At least one test case has a > non-decimal character. Which actually makes it a very good test since thats exactly the kind of thing you should be testing for :-) A test suite that only checks valid data is a bad test. Alan G. From kent37 at tds.net Wed Feb 27 05:17:48 2008 From: kent37 at tds.net (Kent Johnson) Date: Tue, 26 Feb 2008 23:17:48 -0500 Subject: [Tutor] [tutor] Question on multithreading In-Reply-To: References: Message-ID: <47C4E46C.4030602@tds.net> Varsha Purohit wrote: > Hello, > i have a gui program in wxpython where i am spawning two threads. > one for the mainloop of gui and other for some background tasks. It is unusual to start a new thread for the GUI. Usually the GUI is run in the main application thread. > I have > to stop the background running thread once its work is done. A thread will stop when its run() method returns, so if you want the thread to do some work, then stop, just have the run() method terminate. > is there any method called stop() to > stop the threads.... No. > Also, i want to see if the thread is alive or not.. > but i donno where should i put the isAlive() method associated with the > thread.. i tried putting it in the code where thread does execution but > apparently it is not the correct place......... You should put isAlive() in the code that cares whether the other thread is alive...it won't be useful to put the call to isAlive() in the thread you are testing, it will always be alive when the method is called! > Here is the code... > > class GuiScript(threading.Thread): > def __init__(self): > self.run() > def run(self): > app = wx.PySimpleApp() > MainWindow().Show() > app.MainLoop() > > class RunScript(threading.Thread): > def run(self): > imFile=test() Do you have code to instantiate and start the threads? The above only defines two thread classes, it doesn't actually start any threads. > and when the stop button is pressed the two threads should stop > executing... so i have written code like this... > > def OnCloseWindow(self,event): > GuiScript().Stop() This creates a GuiScript thread - by calling GuiScript() - then calls Stop() on the thread. The thread is never started and I don't know what Stop() is... wxPython has a Threads.py example that might be worth studying. Here is a threading intro: http://www.wellho.net/solutions/python-python-threads-a-first-example.html Kent From dineshbvadhia at hotmail.com Wed Feb 27 06:21:32 2008 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Tue, 26 Feb 2008 21:21:32 -0800 Subject: [Tutor] List Box for Web Message-ID: I know this isn't the right forum to ask but I'll try as someone might know. For my web application, I need a list box with a search capability. An example is the Python documentation (hit the F1 key under Windows from IDLE) and specifically the Index list ie. context-sensitive search through a list of phrases, but for use on a web page. Does anyone know if there are any open source UI widgets for such a capability? Any help/pointers appreciated. Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080226/bd924e14/attachment.htm From luciano at ramalho.org Wed Feb 27 07:06:27 2008 From: luciano at ramalho.org (Luciano Ramalho) Date: Wed, 27 Feb 2008 03:06:27 -0300 Subject: [Tutor] List Box for Web In-Reply-To: References: Message-ID: <4331ad810802262206x16572b3s6cfa486285e3ce62@mail.gmail.com> On Wed, Feb 27, 2008 at 2:21 AM, Dinesh B Vadhia wrote: > For my web application, I need a list box with a search capability. An > example is the Python documentation (hit the F1 key under Windows from IDLE) > and specifically the Index list ie. context-sensitive search through a list > of phrases, but for use on a web page. > > Does anyone know if there are any open source UI widgets for such a > capability? On the web, such functionality goes way beyond a mere widget, as it requires communication between the client browser and a web server. The server side of this is straightforward. It's the client that may be complicated in case you want to give users immediate feedback as they type. If that is so, you'd need to use AJAX. Anyhow, because Python does not run in browsers, you will not find a solution to this using only Python. I suggest you study how web apps work and start playing with Python modules and frameworks for server-side web programming. I'd start with the cgi module to make sure you understand the basics before progressing to more sophisticated and "magical" frameworks. Cheers, Luciano From tavspamnofwd at googlemail.com Wed Feb 27 14:58:46 2008 From: tavspamnofwd at googlemail.com (Tom) Date: Wed, 27 Feb 2008 13:58:46 +0000 Subject: [Tutor] rss feed reader, but having trouble with unicode In-Reply-To: References: Message-ID: Finally got it working. I used your suggestion Rui, but I also had to change the charset encoding that my database was using. Changed from Latin-1 to UCS2. I read http://www.joelonsoftware.com/articles/Unicode.html too. Essential reading. Thanks. On 26/02/2008, rui wrote: > Hello Tom, > > Try doing this: > > xml = unicode(xml, encoding, "ignore") > elem = ElementTree.fromstring(xml.encode("utf8")) > > > > #do stuff with elem... > > > > feed.xml = xml > > feed.save() > > > > > > Thanks for your time :-) > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Rui > http://ruivaldo.wordpress.com > > "Rubi? Aquela novela do SBT?" > ~ Carla Perez sobre Ruby > > "Em Python, tudo ? objeto, al?m de lindo e maravilhoso." > ~ Caetano Veloso sobre Python > From tavspamnofwd at googlemail.com Wed Feb 27 18:46:49 2008 From: tavspamnofwd at googlemail.com (Tom) Date: Wed, 27 Feb 2008 17:46:49 +0000 Subject: [Tutor] SSH with Python Message-ID: I have a webfaction server (highly recommended btw) and I'm trying to use automate some tasks over ssh but I'm not having much luck with pyssh http://pyssh.sourceforge.net/ . Some of the docs mention methods that don't exist in the version I downloaded, such as pyssh.run. I'm using windows vista (work pc). Any ideas? From brunson at brunson.com Wed Feb 27 19:03:34 2008 From: brunson at brunson.com (Eric Brunson) Date: Wed, 27 Feb 2008 11:03:34 -0700 Subject: [Tutor] SSH with Python In-Reply-To: References: Message-ID: <47C5A5F6.7060208@brunson.com> Tom wrote: > I have a webfaction server (highly recommended btw) and I'm trying to > use automate some tasks over ssh but I'm not having much luck with > pyssh http://pyssh.sourceforge.net/ . > > Some of the docs mention methods that don't exist in the version I > downloaded, such as pyssh.run. > > I'm using windows vista (work pc). Any ideas? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I've never used pyssh, so I can't comment directly on your problems. We use paramiko very successfully. It's well documented and has excellent example code included with the source. http://www.lag.net/paramiko/ From midnightjulia at gmail.com Wed Feb 27 21:51:18 2008 From: midnightjulia at gmail.com (Julia) Date: Wed, 27 Feb 2008 21:51:18 +0100 Subject: [Tutor] Textures using Pygame Message-ID: Hi everyone! I am currently working on a raycasting engine using pygame for graphics. The engine works great and now I'm thinking about adding support for textures. The problem is that I'm not really sure to with modules and methods to use. I need to be able to load textures, scale then to fit and then draw the scaled image. Any tips on a smart way to do this? Good tutorial url's are also appreciated :) / J -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080227/bc9b4055/attachment.htm From brunson at brunson.com Wed Feb 27 22:18:05 2008 From: brunson at brunson.com (Eric Brunson) Date: Wed, 27 Feb 2008 14:18:05 -0700 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> <47C463FA.30005@alum.rpi.edu><3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> <47C4853E.6010602@alum.rpi.edu> Message-ID: <47C5D38D.9040600@brunson.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080227/d91956d1/attachment.htm From andrei.petre at gmail.com Wed Feb 27 23:14:02 2008 From: andrei.petre at gmail.com (Andrei Petre) Date: Thu, 28 Feb 2008 00:14:02 +0200 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: <47C5D38D.9040600@brunson.com> References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> <47C463FA.30005@alum.rpi.edu> <3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> <47C4853E.6010602@alum.rpi.edu> <47C5D38D.9040600@brunson.com> Message-ID: <3576e740802271414q2ff8dc12s149991cb3620b577@mail.gmail.com> i'm thinking the same way Eric do. On Wed, Feb 27, 2008 at 11:18 PM, Eric Brunson wrote: > Alan Gauld wrote: > > "bob gailer" wrote > > > > i don't really understand that. you are trying to say that the > tests > from the online judge are not "exactly good" ? > > > Yes that's exactly what I'm saying. At least one test case has a > non-decimal character. > > > Which actually makes it a very good test since thats > exactly the kind of thing you should be testing for :-) > A test suite that only checks valid data is a bad test. > > > > > That's fine if writing a test suite for production software, but from the > problem description: "There is a string containing only decimal digit > characters." > > Testing for valid input seems to be outside the scope of the problem > definition. :-) > > > > _______________________________________________ > 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/20080228/d63141c8/attachment.htm From eric at ericwalstad.com Wed Feb 27 23:16:06 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 27 Feb 2008 14:16:06 -0800 Subject: [Tutor] SSH with Python In-Reply-To: <47C5A5F6.7060208@brunson.com> References: <47C5A5F6.7060208@brunson.com> Message-ID: <47C5E126.10307@ericwalstad.com> Eric Brunson wrote: > Tom wrote: >> I have a webfaction server (highly recommended btw) and I'm trying to >> use automate some tasks over ssh but I'm not having much luck with >> pyssh http://pyssh.sourceforge.net/ . >> >> Some of the docs mention methods that don't exist in the version I >> downloaded, such as pyssh.run. >> >> I'm using windows vista (work pc). Any ideas? >> > I've never used pyssh, so I can't comment directly on your problems. We > use paramiko very successfully. It's well documented and has excellent > example code included with the source. > > http://www.lag.net/paramiko/ Also have a look at pexpect which essentially wraps command line calls. I use it to automate mysql backups on my webfaction account. Here's the meat of the code: import pexpect cmd = "ssh foouser at foohost 'mysqldump --opt -p foodb > foodb.sql'" child = pexpect.spawn(cmd) # expect mysql to prompt for a db password child.expect('Enter password: ') # send the password child.sendline("nottherealpassword") Homepage: http://www.noah.org/wiki/Pexpect It looks like there is now a pexpect SSH module. I've not used it, just FYI: http://pexpect.sourceforge.net/pxssh.html I hope that helps. Eric. From brunson at brunson.com Wed Feb 27 23:34:48 2008 From: brunson at brunson.com (Eric Brunson) Date: Wed, 27 Feb 2008 15:34:48 -0700 Subject: [Tutor] SSH with Python In-Reply-To: <47C5E126.10307@ericwalstad.com> References: <47C5A5F6.7060208@brunson.com> <47C5E126.10307@ericwalstad.com> Message-ID: <47C5E588.1060305@brunson.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080227/dc41fa77/attachment.htm From aezell at gmail.com Wed Feb 27 23:46:04 2008 From: aezell at gmail.com (Alex Ezell) Date: Wed, 27 Feb 2008 16:46:04 -0600 Subject: [Tutor] Truncate First Line of File Message-ID: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> I must be missing some simple method on a file object or something. What I need to do is to truncate the first line of a file which has an unknown number of lines and an unknown size. The only thing I can think to do is to readlines() and then slice off the first line in the resulting list, then writelines(). pseduo-code: my_file = open('file.txt', 'wb') lines = my_file.readlines() del lines[0] my_file.writelines() my_file.close() Is there a better way? /alex From kent37 at tds.net Thu Feb 28 00:01:11 2008 From: kent37 at tds.net (Kent Johnson) Date: Wed, 27 Feb 2008 18:01:11 -0500 Subject: [Tutor] Truncate First Line of File In-Reply-To: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> Message-ID: <47C5EBB7.6020707@tds.net> Alex Ezell wrote: > I must be missing some simple method on a file object or something. > > What I need to do is to truncate the first line of a file which has an > unknown number of lines and an unknown size. > > The only thing I can think to do is to readlines() and then slice off > the first line in the resulting list, then writelines(). > > pseduo-code: > my_file = open('file.txt', 'wb') > lines = my_file.readlines() > del lines[0] > my_file.writelines() > my_file.close() > > Is there a better way? No, you have to rewrite the file, that is the way the filesystem works. Your code above is pretty buggy though, you should at least open file for read readlines close file open file for write writelines close file Even safer is to write to a new file, then rename. The fileinput module makes it convenient to safely overwrite a file with a new one. Kent From bill at celestial.net Thu Feb 28 00:02:49 2008 From: bill at celestial.net (Bill Campbell) Date: Wed, 27 Feb 2008 15:02:49 -0800 Subject: [Tutor] Truncate First Line of File In-Reply-To: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> Message-ID: <20080227230249.GB23247@ayn.mi.celestial.com> On Wed, Feb 27, 2008, Alex Ezell wrote: >I must be missing some simple method on a file object or something. > >What I need to do is to truncate the first line of a file which has an >unknown number of lines and an unknown size. > >The only thing I can think to do is to readlines() and then slice off >the first line in the resulting list, then writelines(). > >pseduo-code: >my_file = open('file.txt', 'wb') >lines = my_file.readlines() >del lines[0] >my_file.writelines() >my_file.close() > >Is there a better way? Defensive programming avoids slurping entire files of unknown size into memory. I would just open the file, use readline() to get rid of the first line, the loop writing the rest. If you're going to slurp the whole thing: infile = open('inputfile') lines = infile.readlines() outfile = open('outfile', 'wb') outfile.writelines(lines[1:]) outfile.close() Another way on *nix systems that might be better wouldn't use python at all. Edit the file in place with ed or ex: #!/bin/sh ex - filename < References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> <47C5EBB7.6020707@tds.net> Message-ID: <71dd7f400802271512w10f5ac6eh4ba47791daa99776@mail.gmail.com> On Wed, Feb 27, 2008 at 5:01 PM, Kent Johnson wrote: > > Alex Ezell wrote: > > I must be missing some simple method on a file object or something. > > > > What I need to do is to truncate the first line of a file which has an > > unknown number of lines and an unknown size. > > > > The only thing I can think to do is to readlines() and then slice off > > the first line in the resulting list, then writelines(). > > > > pseduo-code: > > my_file = open('file.txt', 'wb') > > lines = my_file.readlines() > > del lines[0] > > my_file.writelines() > > my_file.close() > > > > Is there a better way? > > No, you have to rewrite the file, that is the way the filesystem works. > > Your code above is pretty buggy though, you should at least > open file for read > readlines > close file > open file for write > writelines > close file > > Even safer is to write to a new file, then rename. The fileinput module > makes it convenient to safely overwrite a file with a new one. Oops, forgot to send this to the list before: Thanks Kent and Bill. I typed that out really quickly, hence the "pseudo-code" disclaimer. I know it wasn't pseudo enough :) I might do something like this: os.system("sed -i '1d' %s" % filename) I suspect it will be much faster on large files, but I haven't tested that yet. Of course, it's not Python ;) and it'd be cool to know a Python way to do it. Thanks again for the help. /alex From eric at ericwalstad.com Thu Feb 28 00:36:51 2008 From: eric at ericwalstad.com (Eric Walstad) Date: Wed, 27 Feb 2008 15:36:51 -0800 Subject: [Tutor] SSH with Python In-Reply-To: <47C5E588.1060305@brunson.com> References: <47C5A5F6.7060208@brunson.com> <47C5E126.10307@ericwalstad.com> <47C5E588.1060305@brunson.com> Message-ID: <47C5F413.1040308@ericwalstad.com> Hey Eric, Eric Brunson wrote: > Eric Walstad wrote: >> Eric Brunson wrote: >> >> import pexpect ... >> child.sendline("nottherealpassword") ... >> > > What's the path to ssh under windows vista? I hope I never have to find out :) > Paramiko is a pure python > implementation of the SSH protocol, so it should run on any platform. Cool! I'd like to give Paramiko a try some day when I don't need to be concerned with prompts from the remote command I am running. Yes, Paramiko looks interesting. > Besides, IMHO, expect, pexpect, Perl::Expect... the entire concept is a > horrible, horrible kludge and should only be used as a last resort when > no other interface is possible. I mostly agree, except when other priorities win, when time is of the essence, when I don't have root or when I'm just feeling nervous about hobgoblins. Yeah, it's ugly but it works for me and my needs and has been surprisingly stable over the years. That said, I admit that the OP might be better served by Paramiko, assuming it does what they need. From alan.gauld at btinternet.com Thu Feb 28 01:33:49 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Feb 2008 00:33:49 -0000 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> <47C463FA.30005@alum.rpi.edu><3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> <47C4853E.6010602@alum.rpi.edu> <47C5D38D.9040600@brunson.com> Message-ID: "Eric Brunson" wrote > Alan Gauld wrote: > Which actually makes it a very good test since thats > exactly the kind of thing you should be testing for :-) Note the smiley... > A test suite that only checks valid data is a bad test. > > Testing for valid input seems to be outside the scope of the problem > definition. :-) As I note yours... However, there is a bit of a serious point here too in that users never ask for data validation (at least mine never do!) they just expect it. So I still maintain that any test suite no matter how basic should always cover some tests for invalid input data. Even well intentioned users will make mistakes and a program that crashes on invalid input is not user friendly - even if the only user is the author! Alan G From alan.gauld at btinternet.com Thu Feb 28 01:39:58 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Feb 2008 00:39:58 -0000 Subject: [Tutor] Truncate First Line of File References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com><47C5EBB7.6020707@tds.net> <71dd7f400802271512w10f5ac6eh4ba47791daa99776@mail.gmail.com> Message-ID: "Alex Ezell" wrote >> > What I need to do is to truncate the first line of a file which >> has an >> > unknown number of lines and an unknown size. > I might do something like this: > os.system("sed -i '1d' %s" % filename) > > I suspect it will be much faster on large files, but I haven't > tested that yet. It might be a bit faster since sed is written in C, but then so is Pythons file handling code. What sed doesn't do is anything different to what Pyhon does, it still reads the file in and back out again. One slightly faster way of doing it is (in pseudo code): f = open(filena,me,'r') f.readline() # lose first line s = f.read() # get the rest as a string f.close() f = open(filename,'w') f.write(s) f.close() which avoids all the line splitting/list creation of readlines() HTH, -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Thu Feb 28 01:53:28 2008 From: keridee at jayco.net (Tiger12506) Date: Wed, 27 Feb 2008 19:53:28 -0500 Subject: [Tutor] Truncate First Line of File References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> <20080227230249.GB23247@ayn.mi.celestial.com> Message-ID: <00de01c879a5$0c1d9850$b6fce004@jslaptop> This is bill's method written out in code which is the python you seek, young warrior! inname = 'inputfile' outname = 'outfile' infile = open(inname,'r') outfile = open(outname,'w') infile.readline() line = infile.readline() while line != "": outfile.write(line) infile.close() outfile.close() os.rename(inname,outname) From brunson at brunson.com Thu Feb 28 02:06:32 2008 From: brunson at brunson.com (Eric Brunson) Date: Wed, 27 Feb 2008 18:06:32 -0700 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> <47C463FA.30005@alum.rpi.edu><3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> <47C4853E.6010602@alum.rpi.edu> <47C5D38D.9040600@brunson.com> Message-ID: <47C60918.7090305@brunson.com> Alan Gauld wrote: > "Eric Brunson" wrote > >> Alan Gauld wrote: >> Glad we both noted the smileys. :-) > However, there is a bit of a serious point here too in that > users never ask for data validation (at least mine never do!) > they just expect it. So I still maintain that any test suite > no matter how basic should always cover some tests > for invalid input data. > Definitely a valid point. I just spent twenty minutes this afternoon tracking down a problem in my own code where, because I was supplying the input from a database, I could count on converting the value to a float. However, that didn't account for not finding a value at all. > Even well intentioned users will make mistakes and a program > that crashes on invalid input is not user friendly - even if the > only user is the author! > Bingo. :-) Always a pleasure, e. From jeff at drinktomi.com Thu Feb 28 02:15:31 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Wed, 27 Feb 2008 17:15:31 -0800 Subject: [Tutor] SSH with Python In-Reply-To: <47C5E588.1060305@brunson.com> References: <47C5A5F6.7060208@brunson.com> <47C5E126.10307@ericwalstad.com> <47C5E588.1060305@brunson.com> Message-ID: <4180565A-2F83-45E4-88DB-338C4BAB161C@drinktomi.com> > What's the path to ssh under windows vista? Paramiko is a pure > python implementation of the SSH protocol, so it should run on any > platform. Paramiko rocks. I have a deployment system that works on linux, osx, and windows without a hitch. If you're writing a custom SSH server or doing tunneling then Paramiko is your choice. It is however something of a pain to use. > Besides, IMHO, expect, pexpect, Perl::Expect... the entire concept > is a horrible, horrible kludge and should only be used as a last > resort when no other interface is possible. In my experience most applications for SSH involve running other programs(via the command line on a remote machine. Pexpect gives you the tools to control those remote processes. Paramiko does not. It is a horrible, horrible hack but in 95% of the cases it works better than the sleek elegant way, and it takes far, far less time and effort. -jeff From kdsudac at yahoo.com Thu Feb 28 02:13:06 2008 From: kdsudac at yahoo.com (Keith Suda-Cederquist) Date: Wed, 27 Feb 2008 17:13:06 -0800 (PST) Subject: [Tutor] Python oddity Message-ID: <103255.68004.qm@web54307.mail.re2.yahoo.com> Hi, I'm using iPython and I've run into an occasional problem that I don't understand. Here is what I'm seeing: >>aa=range(0,10) >>bb=aa >>print aa [0,1,2,3,4,5,6,7,8,9] >>print bb [0,1,2,3,4,5,6,7,8,9] >> # okay, everything allright at this point >>bb[5]=0 #change bb >>print aa [0,1,2,3,4,0,6,7,8,9] #aa has changed!!! >>print bb [0,1,2,3,4,0,6,7,8,9] So the problem is that when I change bb, aa also changes even though I don't want it to. Is this supposed to happen? If it is can someone explain to me why this is a good thing? and finally, can someone give me some advice on how to avoid or work-around this problem. Thanks, Keith ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080227/1c432202/attachment-0001.htm From rabidpoobear at gmail.com Thu Feb 28 02:52:58 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 27 Feb 2008 19:52:58 -0600 Subject: [Tutor] Python oddity In-Reply-To: <103255.68004.qm@web54307.mail.re2.yahoo.com> References: <103255.68004.qm@web54307.mail.re2.yahoo.com> Message-ID: <47C613FA.9070503@gmail.com> Keith Suda-Cederquist wrote: > Hi, > > I'm using iPython and I've run into an occasional problem that I don't > understand. Here is what I'm seeing: > > >>aa=range(0,10) > >>bb=aa > >>print aa > [0,1,2,3,4,5,6,7,8,9] > >>print bb > [0,1,2,3,4,5,6,7,8,9] > >> # okay, everything allright at this point > >>bb[5]=0 #change bb > >>print aa > [0,1,2,3,4,0,6,7,8,9] #aa has changed!!! > >>print bb > [0,1,2,3,4,0,6,7,8,9] > > So the problem is that when I change bb, aa also changes even though I > don't want it to. Is this supposed to happen? If it is can someone > explain to me why this is a good thing? and finally, can someone give > me some advice on how to avoid or work-around this problem. In Python, variables are references to objects, they are not containers. Doing any sort of variable assignment results in you directing your new variable at the same object. If you do something like: a = 5 b = a b = 10 print a You will get 5 for output; this is because an integer is not mutable. Mutability is determined based upon whether the object can be changed directly, or whether a new object must be constructed in order for the value to change. Strings and integers are immutable in Python. Saying a = "hello" a += "hi" will not just tack on "hi" to the end of the string. Instead, it will allocate a new string, with 7 characters of room, place "hello" at the beginning, and copy "hi" into the last 2 characters. Then it will point the variable 'a' at this new string. This is one reason why you shouldn't write programs like: a = "" for x in range(2000): a += '1' By the time you get to the end, you will be allocating new strings of 1997, 1998, and 1999 characters each time in order to add this one variable. It's much faster to do: a = [] for x in range(2000): a.append('1') a = ''.join(a) The reason this is faster is that Python lists are mutable. So the .append() method doesn't have to create a new copy of your object to place it into the list. You can simply add it to the end without having to re-allocate memory. The mutability of certain objects unfortunately causes confusion early-on for beginners, but it's much more efficient that way. If you absolutely have to copy a list, you can use copy.copy() or copy.deepcopy() depending on your needs. I would suggest that you re-evaluate your code if you do need a copy, because a majority of the time you won't. One more snag to watch out for that involves mutability is in default values. Something like this: def foo(bar=[]): bar.append("Hi!") print bar Upon cursory examination, you might deduce that 'bar' will have a value of [] for every function call, if you don't specify a value to override the default. However, Python only evaluates default arguments on the first occurrence of them that it finds, so what really happens is that you receive one copy of bar for the entirety of your program. Thus, when you call append() on 'bar', it's actually manipulating the single copy that you have. So each time you call the function, you'll have another "Hi!" in bar. The usual method to avoid this is as follows: def foo(bar=None): if bar: print bar else: bar = "Hi!" print bar In other words, you make your default argument an immutable type (None). Then, when you modify it inside the function, it doesn't affect its original None value. So in this case, the variable 'bar' will always refer to the value 'None' whenever you don't pass any values to foo. Hope that helps, -Luke From keridee at jayco.net Thu Feb 28 02:56:04 2008 From: keridee at jayco.net (Tiger12506) Date: Wed, 27 Feb 2008 20:56:04 -0500 Subject: [Tutor] Python oddity References: <103255.68004.qm@web54307.mail.re2.yahoo.com> Message-ID: <002b01c879ad$178a93c0$d9fce004@jslaptop> Python lists are mutable. All mutable objects will behave in the fashion you described, whereas immutable objects -- tuples, integer, floats, etc. -- will behave in the fashion that you expect. This is because python keeps references to objects. When you say bb = aa, you are really saying, "Take the reference to the list 'aa' and copy it to 'bb' so that when you use the variable bb you are just using the a copy of the original reference to the *same* object." Here's another gotcha: s = [[]]*100 #Thinking that you can initialize a hundred lists easily s[0].append(1) #Add something to the first list And, oh crap, it added a one to all of the lists. From jim at well.com Thu Feb 28 02:57:20 2008 From: jim at well.com (jim stockford) Date: Wed, 27 Feb 2008 17:57:20 -0800 Subject: [Tutor] Python oddity In-Reply-To: <103255.68004.qm@web54307.mail.re2.yahoo.com> References: <103255.68004.qm@web54307.mail.re2.yahoo.com> Message-ID: <1a529f9ad882dae3ae66bab758d62d62@well.com> i'm guessing this is the "post-it effect". aa = range(0,10) print aa [0,1,2,3,4,5,6,7,8,9] # what you've done is to use the range function to # create the list of 0 to 9, then you associated the # name aa to the list. a popular teaching analogy # is that of putting a post-it that says aa on the list. bb = aa # now you've created another post-it that has bb # written on it and put that post-it on the list. bb[5] = 0 # you've told the interpreter "say, that list that has # the post-it saying bb on it? well, dig into that list # and change the value of the sixth member to be # 0". the interpreter does it, not caring that there's # also a post-it on the list that says aa. print aa [0,1,2,3,4,0,6,7,8,9] print "hey! what happened to my aa list?!!!" # in python, assignment is not a copy operation # that makes a new thing-um. assignment creates # a reference to an object, much like pasting a # post-it onto the object. you can have lots of # post-its tacked onto an object, it's still the same # object (a rose by any other name...). cc = bb dd = cc ee = aa # now the one and only list is referenced by five # different identifiers, aa, bb, cc, dd, and ee. dd[4] = "john jacob jingleheimer schmidt" print ee [0,1,2,3,"john jacob jingleheimer schmidt",0,6,7,8,9] On Feb 27, 2008, at 5:13 PM, Keith Suda-Cederquist wrote: > Hi, > > I'm using iPython and I've run into an occasional problem that I don't > understand.? Here is what I'm seeing: > > >>aa=range(0,10) > >>bb=aa > >>print aa > [0,1,2,3,4,5,6,7,8,9] > >>print bb > [0,1,2,3,4,5,6,7,8,9] > >> # okay, everything allright at this point > >>bb[5]=0? #change bb > >>print aa > [0,1,2,3,4,0,6,7,8,9]? #aa has changed!!! > >>print bb > [0,1,2,3,4,0,6,7,8,9] > > So the problem is that when I change bb, aa also changes even though I > don't want it to.? Is this supposed to happen?? If it is can someone > explain to me why this is a good thing?? and finally, can someone give > me some advice on how to avoid or work-around this problem. > > Thanks, > Keith > > Looking for last minute shopping deals? Find them fast with Yahoo! > Search._______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Thu Feb 28 03:12:18 2008 From: carroll at tjc.com (Terry Carroll) Date: Wed, 27 Feb 2008 18:12:18 -0800 (PST) Subject: [Tutor] Python oddity In-Reply-To: <103255.68004.qm@web54307.mail.re2.yahoo.com> Message-ID: On Wed, 27 Feb 2008, Keith Suda-Cederquist wrote: > Hi, > > I'm using iPython and I've run into an occasional problem that I don't > understand. Here is what I'm seeing: > > >>aa=range(0,10) > >>bb=aa > >>print aa > [0,1,2,3,4,5,6,7,8,9] > >>print bb > [0,1,2,3,4,5,6,7,8,9] > >> # okay, everything allright at this point > >>bb[5]=0 #change bb > >>print aa > [0,1,2,3,4,0,6,7,8,9] #aa has changed!!! > >>print bb > [0,1,2,3,4,0,6,7,8,9] > > So the problem is that when I change bb, aa also changes even though I > don't want it to. Is this supposed to happen? If it is can someone > explain to me why this is a good thing? and finally, can someone give > me some advice on how to avoid or work-around this problem. In addition to Luke's comments, let me try it from a slightly different angle: >>> aa=range(0,10) >>> bb=aa >>> id(aa) 12169048 >>> id(bb) 12169048 The id() function provides the unique ID number of an object. Note that aa and bb have the same ID; they are just two names for the same object. Once you realize that, it will be more clear that a change to aa is also a change to bb. In fact, here's something that really drives home they're the same object: >>> aa is bb True Instead of using the assignment statement, which just puts a new label on an object, you can subject your list to an operation that produces another list that is identical to the list it operates on. One example: >>> cc=list(aa) list() takes something as input and produces list from it. if you hand a list to list() you get a new list (i.e., a new object) that is identical to the list that was input. >>> id(cc) # note: new object id 12185688 >>> aa==cc # note: aa is equal to cc True >>> aa is cc # but they're not the same object False Another approach is to take a list "slice" that just happens to slice out the entire list: >>> dd=aa[:] >>> id(dd) # note: new object id 12168408 >>> aa==dd # note: aa is equal to dd True >>> aa is dd # but they're not the same object False From aezell at gmail.com Thu Feb 28 04:04:17 2008 From: aezell at gmail.com (Alex Ezell) Date: Wed, 27 Feb 2008 21:04:17 -0600 Subject: [Tutor] Truncate First Line of File In-Reply-To: <00de01c879a5$0c1d9850$b6fce004@jslaptop> References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> <20080227230249.GB23247@ayn.mi.celestial.com> <00de01c879a5$0c1d9850$b6fce004@jslaptop> Message-ID: <71dd7f400802271904s397f6e9bo4c854b63725e2a32@mail.gmail.com> Thanks to everyone for the help. My coworker seems to really prefer doing it via some system call. She seems to think it's possible quickly with csplit, which I've never used. I'll be investigating it in the morning, because she's really good at what she does. :) /alex On Wed, Feb 27, 2008 at 6:53 PM, Tiger12506 wrote: > This is bill's method written out in code which is the python you seek, > young warrior! > > inname = 'inputfile' > outname = 'outfile' > > infile = open(inname,'r') > outfile = open(outname,'w') > infile.readline() > line = infile.readline() > while line != "": > outfile.write(line) > infile.close() > outfile.close() > os.rename(inname,outname) > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at drinktomi.com Thu Feb 28 04:15:00 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Wed, 27 Feb 2008 19:15:00 -0800 Subject: [Tutor] Python oddity In-Reply-To: <103255.68004.qm@web54307.mail.re2.yahoo.com> References: <103255.68004.qm@web54307.mail.re2.yahoo.com> Message-ID: So the problem is that when I change bb, aa also changes even though I don't want it to. Is this supposed to happen? Yes Names are handles for objects. Assignment binds a name to an object. The same object can be bound simultaneously to many names. Python distinguishes between equality and identity, so there are two comparison operators: '==' and 'is'. Objects are equal if they have the same value (==) but they are identical only if they refer to the same object (is). The constructor expressions [], {}, and () produce new objects. >>> [1, 2] == [1, 2] # same value True >>> [1, 2] is [1, 2] # but different lists False >>> a = [1, 2] # this is assigned to a new list >>> b = [1, 2] # this is also assigned to a new list >>> a == b # the lists have the same value True >>> a is b # but they are not the same list False >>> a = [1, 2] # assign to a new list >>> b = a # attach the list in a to a new name >>> a == b # they have the same value True >>> a is b # because they are the same list True The list(FOO) function copies an list. >>> a = [1, 2] # new list >>> b = list(a) # make a copy of the list in b >>> a == b # the original and copy are equal True >>> a is b # but they are not the same list False - Jeff Younker - jeff at drinktomi.com - -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080227/a0c42fb4/attachment.htm From tonytraductor at linguasos.org Thu Feb 28 04:53:05 2008 From: tonytraductor at linguasos.org (tonytraductor at linguasos.org) Date: Wed, 27 Feb 2008 20:53:05 -0700 Subject: [Tutor] new on the list Message-ID: <20080227205304.07fcb9413df0eef145f094851c2af08f.5aa846c01b.wbe@email.secureserver.net> Hi, I'm Tony. I'm a translator. This is my first post to this list. I've been using Linux, pretty well exclusively, for about 8 years, but I never got under the hood more than learning the shell basics to do basic stuff that I needed to do, manipulating config files. (Although I did recently make my own "distro" for translators, but it's just a remaster of PCFluxboxOS with some changes to the software to include some tools for translators, linguasos.org). But, I've finally decided that I want more control over my machine than just manipulating configs, and I want some software that currently doesn't exist, too. So, I've decided to learn to program. This was in November, so, I'm very, very new to programming. I started learning to write bash scripts in November, first, and started learning Tcl in January (I feel like I'm making a lot of progress with Tcl, and have even written a program for translator project mgmt that a number of folks are using already transprocalc.org a very basic program, really, but tcl.tk makes it easy to build a gui, as easy as writing html, really). I've played a little with java, but haven't really gotten beyond "Hello, World!", same with C. But, ESR says if I want to be a hacker, Python is the best place to start, so, this week I started learning python. I have made a couple of friends on-line, real hackers, who have decided to help teach me. One gave me an assignment to write a program that would generate 5 random numbers, using a loop. I wrote: # Let's make a pizza. # pizza.py # escrito por anthony baldwin / tonytraductor at linguasos.org from random import randint print "I'm hungry!" print "Let's make a nice pizza, eh!" ing = ("pepperoni", "ham", "onions", "sausage", "bacon", "peppers", "spiders", "mozzarella", "anchovies", "chocolate chips", "dog hairs", "toe-nail clippings", "fried clams", "lollipops", "paper clips", "calamari", "m&ms", "broccoli", "gum drops", "green beans") print "Let's make a pizza with" for i in range(5): p = randint(0,19) # someone told me I could have done len(ing), but I do not know what 'len' is yet. print ing[p] print " " print "That's a nice pizza, eh! " print "Mangeamos!" The other told me that the following was used to separate the sheep from the goats, so to speak, which I don't quite understand, since it took me all of 10 minutes to figure it out. He told me to write a program that would print 5 lines, like this: * ** *** **** ***** With a loop, and in such fashion that it could be easily extended to continue up to any number of lines. I thought this one was easy. I did: # twinkle stars python / twinkle.py # escrito por anthony baldwin / tonytraductor at linguasos.org t = "*" print "Twinkle, twinkle little stars." for i in range(5): print t * (i+1) print "Twinkle, twinkle..." So. How'd I do? (I wrote these using a simple text editor that I made with Tcl, too, http://www.linguasos.org/tcltext.html ) /tony -- http://www.LinguasOS.org - Linux for Translators http://www.BaldwinLinguas.com - translating & interpreting http://www.TransProCalc.org - Free translation project mgmt software From bgailer at alum.rpi.edu Thu Feb 28 05:01:57 2008 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 27 Feb 2008 23:01:57 -0500 Subject: [Tutor] crashed with Runtime Error: NZEC (non-zero exit code) In-Reply-To: References: <3576e740802240436o45f25b00g5f3b6981c4e3f45c@mail.gmail.com> <47C1F2BA.9070800@alum.rpi.edu> <3576e740802242144j62c789femdd35cf186a79a9db@mail.gmail.com> <47C45918.2000504@alum.rpi.edu> <47C463FA.30005@alum.rpi.edu><3576e740802261156w639383fcg499cd72af820bb81@mail.gmail.com> <47C4853E.6010602@alum.rpi.edu> <47C5D38D.9040600@brunson.com> Message-ID: <47C63235.6080903@alum.rpi.edu> This thread got started due to the DIV15 problem on the Sphere Online Judge. This is almost a "black box" test environment. Submit a program. If it generates the expected output you get "accepted". The other results are " compilation error", "time limit exceeded", " runtime error (followed by (SIGSEGV), (SIGABRT), (other), (NZEC))", or "wrong answer". If the program did not exceed the time limit you also get the execution time. (Some problems give problem-specific results but that does not apply to the DIV15 problem) In looking over the status list of submitted programs I noted cases where the results were "100", "102". I wonder what that means and how it was generated So there is a (limited) way to get information out of a program, and that is to use time.sleep() to control the execution time. But that costs one program submission for each thing one might want to test. That's how I determined there was a bad character in the input. So now I imagine creating an automated program submitter, so I could create a large number of test cases and an automated way to read the execution times off the results page. Eventually one might garner enough information. Of course that might get the attention of the site operators and lead to a change in how things are run to discourage automated testing. -- Bob Gailer 919-636-4239 Chapel Hill, NC From andreas at kostyrka.org Thu Feb 28 09:58:00 2008 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 28 Feb 2008 09:58:00 +0100 Subject: [Tutor] user-given variable names for objects In-Reply-To: <008201c95d67$a8eed990$a1fce004@jslaptop> References: <4760E612.1030109@gmail.com> <008201c95d67$a8eed990$a1fce004@jslaptop> Message-ID: <47C67798.6040609@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Perhaps even nicer: [key for key, evtime in eventData.iteritems() if evtime < time.time()] This way the dictionary iterates over key, value tuples. Andreas Tiger12506 wrote: | I may sound like a know-it-all, but dictionaries *are* iterators. | | [a for a in eventData if eventData[a] < time.time()] | | This is more efficient. The keys method creates a list in memory first and | then it iterates over it. | Unnecessary. | |> "Che M" wrote |> |>> Although I was not familiar with what you can do with a list such |>> as you did here: |>> [a for a in eventData.keys() if eventData[a] < time.time()] |> This is known as a list comprehension (and is described in the |> Functional |> Programming topic of my tutorial - obligatory plug :-) |> |>> I guess .keys() is a built-in method for dictionaries to return a |>> list of all their values, then? |> To be accurate it returns a list of the keys, the values are the |> things you get when you access the dictionary using a key: |> |> value = dictionary[key] |> |> So you can do things like |> |> for key in dictionary.keys(): |> print dictionary[key] |> |>> By the way, what was the purpose of the line with |>> time.sleep(1) |> It pauses for 1 second. But i'm not sure why he wanted a pause! :-) |> |> Alan G. |> | | _______________________________________________ | Tutor maillist - Tutor at python.org | http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFHxneXHJdudm4KnO0RAnl3AJ4m+Uguik+C+1b6gXeaolcOhb0CwQCghNYt Hc1JuP17yefS3vW3tC2HO9I= =sMI9 -----END PGP SIGNATURE----- From lupin at orcon.net.nz Thu Feb 28 10:03:28 2008 From: lupin at orcon.net.nz (Brett Wilkins) Date: Thu, 28 Feb 2008 22:03:28 +1300 Subject: [Tutor] Python oddity In-Reply-To: <103255.68004.qm@web54307.mail.re2.yahoo.com> References: <103255.68004.qm@web54307.mail.re2.yahoo.com> Message-ID: <47C678E0.1060300@orcon.net.nz> As everybody else has told you, assigning bb = aa just gives bb the reference to the same object that aa has. Unless I missed something, then nobody's actually mentioned how to make this not happen... and it's actually rather easy... instead of bb = aa, do this: bb = aa[:] Looks like a splice, and indeed it is a splice, without bounds. When a splice is used like this, I believe it is known as the copy directive. See, when you start to do an assignment to an action on a variable (eg bb = aa*4, where a is a number, for example) bb then references an entirely new object. so, the boundless splice on aa from your examples would return a fresh copy of the original object stored in aa. Hope this helped, Brett Keith Suda-Cederquist wrote: > Hi, > > I'm using iPython and I've run into an occasional problem that I don't > understand. Here is what I'm seeing: > > >>aa=range(0,10) > >>bb=aa > >>print aa > [0,1,2,3,4,5,6,7,8,9] > >>print bb > [0,1,2,3,4,5,6,7,8,9] > >> # okay, everything allright at this point > >>bb[5]=0 #change bb > >>print aa > [0,1,2,3,4,0,6,7,8,9] #aa has changed!!! > >>print bb > [0,1,2,3,4,0,6,7,8,9] > > So the problem is that when I change bb, aa also changes even though I > don't want it to. Is this supposed to happen? If it is can someone > explain to me why this is a good thing? and finally, can someone give > me some advice on how to avoid or work-around this problem. > > Thanks, > Keith > > ------------------------------------------------------------------------ > Looking for last minute shopping deals? Find them fast with Yahoo! > Search. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Thu Feb 28 10:37:01 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Feb 2008 09:37:01 -0000 Subject: [Tutor] Truncate First Line of File References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com><20080227230249.GB23247@ayn.mi.celestial.com><00de01c879a5$0c1d9850$b6fce004@jslaptop> <71dd7f400802271904s397f6e9bo4c854b63725e2a32@mail.gmail.com> Message-ID: "Alex Ezell" wrote > Thanks to everyone for the help. My coworker seems to really prefer > doing it via some system call. > > She seems to think it's possible quickly with csplit, which I've > never > used. I'll be investigating it in the morning, because she's really > good at what she does. :) yes, csplit can do it too, as could awk,ml or sed or several other Unix tools. And if quick is quick to qwrite then using the shell is certainly best. Csplit again still has to read the whole file so it won't be massively quicker than any other method however. Alan G From alan.gauld at btinternet.com Thu Feb 28 10:51:22 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Feb 2008 09:51:22 -0000 Subject: [Tutor] new on the list References: <20080227205304.07fcb9413df0eef145f094851c2af08f.5aa846c01b.wbe@email.secureserver.net> Message-ID: wrote > This is my first post to this list. Welcome Tony. > I started learning to write bash scripts in November, first, > and started learning Tcl in January Good starts, although Python is a little different to Tcl its generally easier to read. But their capabilities are similar. > I've played a little with java, but haven't really > gotten beyond "Hello, World!", same with C. Compiled languages take a bit more getting used to, especially since both C and Java require more detailed work from the programmer. > from random import randint > > ing = ("pepperoni", "ham", "onions", "sausage", "bacon", "peppers", > "spiders", "mozzarella", "anchovies", "chocolate chips", "dog > hairs", "toe-nail clippings", "fried clams", "lollipops", "paper > clips", "calamari", "m&ms", "broccoli", "gum drops", "green beans") > > print "Let's make a pizza with" > > for i in range(5): > p = randint(0,19) # someone told me I could have done len(ing), but > I do not know what 'len' is yet. len() is a general purpose function inPython that will tell you the length of things. In this case it would tell you how many items in your tuple ing. It can also tell you how many characters in a string etc. There are lots of other things in the random module you could have used, including random.choice... > He told me to write a program that would print 5 lines, like this: > * > ** > *** > I thought this one was easy. Me too... > t = "*" > > for i in range(5): > print t * (i+1) > How'd I do? OK, but its not really configurable so maybe you should read the number of lines from the user somehow? Also you could avoid the addition each time by moving it to the range function for i in range(1, i+1): print t * i > (I wrote these using a simple text editor that I made with Tcl, > too, http://www.linguasos.org/tcltext.html ) Fine but it will be easier to use a syntax aware full featured editor like vim or Idle or emacs or Scite But overall you are on the right lines. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Thu Feb 28 11:49:11 2008 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 28 Feb 2008 04:49:11 -0600 Subject: [Tutor] Python oddity In-Reply-To: <47C678E0.1060300@orcon.net.nz> References: <103255.68004.qm@web54307.mail.re2.yahoo.com> <47C678E0.1060300@orcon.net.nz> Message-ID: <47C691A7.7020204@gmail.com> Brett Wilkins wrote: > As everybody else has told you, assigning bb = aa just gives bb the > reference to the same object that aa has. Unless I missed something, > then nobody's actually mentioned how to make this not happen... and it's > actually rather easy... instead of bb = aa, do this: > bb = aa[:] > Looks like a splice, and indeed it is a splice, without bounds. When a > splice is used like this, I believe it is known as the copy directive. Yes, Terry explained other ways as well. The problem with using slices is the following: >>> a = [['a'],'b'] >>> b = a >>> b is a True >>> b = a[:] >>> b is a False #okay, we're fine so far. >>> b[0] ['a'] >>> b[0].append('c') >>> b[0] ['a', 'c'] >>> a[0] ['a', 'c'] and here's where we run into problems. Turns out the slice notation just makes a shallow copy, so if you have any lists in your list, they will still refer to the same object. (I'm guessing that any mutable objects will still refer to the same object) copy.copy() has this same problem. The way to avoid this, as I mentioned before, is to use a deepcopy(), but as I said, you usually don't need to make a full copy of a list. Oh, and if you're curious: >>> b = list(a) >>> b is a False >>> b[0].append('d') >>> a[0] ['a', 'c', 'd'] So a list() does a shallow copy as well. Here's a continuation, with deepcopy(): >>> import copy >>> b = copy.deepcopy(a) >>> b is a False >>> b[0] is a[0] False >>> b[0].append('e') >>> a[0] ['a', 'c', 'd'] HTH, -Luke From lupin at orcon.net.nz Thu Feb 28 13:26:31 2008 From: lupin at orcon.net.nz (Brett Wilkins) Date: Fri, 29 Feb 2008 01:26:31 +1300 Subject: [Tutor] Python oddity In-Reply-To: <47C691A7.7020204@gmail.com> References: <103255.68004.qm@web54307.mail.re2.yahoo.com> <47C678E0.1060300@orcon.net.nz> <47C691A7.7020204@gmail.com> Message-ID: <47C6A877.40800@orcon.net.nz> Cheers, I actually forgot about the whole shallow-copy thing, and deepcopy(). I'm only new to the language myself, I just remembered about the slice copy and thought to mention it. Luke Paireepinart wrote: > Brett Wilkins wrote: >> As everybody else has told you, assigning bb = aa just gives bb the >> reference to the same object that aa has. Unless I missed something, >> then nobody's actually mentioned how to make this not happen... and >> it's actually rather easy... instead of bb = aa, do this: >> bb = aa[:] >> Looks like a splice, and indeed it is a splice, without bounds. When >> a splice is used like this, I believe it is known as the copy directive. > Yes, Terry explained other ways as well. > The problem with using slices is the following: > > >>> a = [['a'],'b'] > >>> b = a > >>> b is a > True > >>> b = a[:] > >>> b is a > False > #okay, we're fine so far. > >>> b[0] > ['a'] > >>> b[0].append('c') > >>> b[0] > ['a', 'c'] > >>> a[0] > ['a', 'c'] > > > and here's where we run into problems. > Turns out the slice notation just makes a shallow copy, so if you have > any lists in your list, they will still refer to the same object. > (I'm guessing that any mutable objects will still refer to the same > object) > copy.copy() has this same problem. > The way to avoid this, as I mentioned before, is to use a deepcopy(), > but as I said, you usually don't need to make a full copy of a list. > Oh, and if you're curious: > >>> b = list(a) > >>> b is a > False > >>> b[0].append('d') > >>> a[0] > ['a', 'c', 'd'] > > So a list() does a shallow copy as well. > > Here's a continuation, with deepcopy(): > >>> import copy > >>> b = copy.deepcopy(a) > >>> b is a > False > >>> b[0] is a[0] > False > >>> b[0].append('e') > >>> a[0] > ['a', 'c', 'd'] > > > HTH, > -Luke > From kent37 at tds.net Thu Feb 28 13:39:28 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Feb 2008 07:39:28 -0500 Subject: [Tutor] new on the list In-Reply-To: <20080227205304.07fcb9413df0eef145f094851c2af08f.5aa846c01b.wbe@email.secureserver.net> References: <20080227205304.07fcb9413df0eef145f094851c2af08f.5aa846c01b.wbe@email.secureserver.net> Message-ID: <47C6AB80.50506@tds.net> tonytraductor at linguasos.org wrote: > Hi, > > I'm Tony. I'm a translator. > This is my first post to this list. Welcome! > tcl.tk makes > it easy to build a gui, as easy as writing html, really). Python has a version of tk also, called Tkinter. You might want to learn about it: http://docs.python.org/lib/module-Tkinter.html > I have made a couple of friends on-line, real > hackers, who have decided to help teach me. There are several good Python tutorials for non-programmers available on-line, you might want to read one of them: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers The book "Python Programming for absolute beginners" is another good place to start. It has exercises similar to the ones your friends gave you. Kent From bhaaluu at gmail.com Thu Feb 28 14:04:47 2008 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 28 Feb 2008 08:04:47 -0500 Subject: [Tutor] new on the list In-Reply-To: References: <20080227205304.07fcb9413df0eef145f094851c2af08f.5aa846c01b.wbe@email.secureserver.net> Message-ID: On Thu, Feb 28, 2008 at 4:51 AM, Alan Gauld wrote: > wrote > > > (I wrote these using a simple text editor that I made with Tcl, > > too, http://www.linguasos.org/tcltext.html ) > > Fine but it will be easier to use a syntax aware full featured > editor like vim or Idle or emacs or Scite > > But overall you are on the right lines. > > > -- > Alan Gauld > Author of the Learn to Program web site > Temorarily at: > http://uk.geocities.com/alan.gauld at btinternet.com/ > Normally: > http://www.freenetpages.co.uk/hp/alan.gauld I also run Python on Linux. I've tried several of the Python IDEs (Integrated Development Environments), such as IDLE, Eric, and so forth, but the best (for me) has been vim. I use the following .vimrc file: -------------8<-----Cut Here----->8------------------- " .vimrc " " Created by Jeff Elkner 23 January 2006 " Last modified 2 February 2006 " " Turn on syntax highlighting and autoindenting syntax enable filetype indent on " set autoindent width to 4 spaces (see " http://www.vim.org/tips/tip.php?tip_id=83) set et set sw=4 set smarttab " set line number (added by bhaaluu) set nu " Bind key to running the python interpreter on the currently active " file. (courtesy of Steve Howell from email dated 1 Feb 2006). map :w\|!python % -------------8<-----Cut Here----->8------------------- I run vim in Konsole, but any Xterm works, AFAIK. Since the Traceback exceptions in Python usually have a line number, I added that 'feature' to the .vimrc file. Note the last line that starts with 'map'. That allows you to run your typed-in Python program from within vim by simply pressing the F2 function key. At the end of the run, you'll be prompted to press to return to editing your program in the vim editor. Since I have vim linked to the 'vi' command, all I have to do to start editing a new program is to enter a command similar to this at the bash prompt: $ vi myNewPythonProgram.py Then, I stay in vim to edit the program, run it, modify it, debug it, etc. The syntax highlighting and autoindent features enabled in the .vimrc file make programming in Python a fun and enjoyable experience. Happy Programming! -- b h a a l u u at g m a i l dot c o m "You assist an evil system most effectively by obeying its orders and decrees. An evil system never deserves such allegiance. Allegiance to it means partaking of the evil. A good person will resist an evil system with his or her whole soul." [Mahatma Gandhi] From imonthejazz at googlemail.com Thu Feb 28 15:36:55 2008 From: imonthejazz at googlemail.com (imonthejazz) Date: Thu, 28 Feb 2008 14:36:55 +0000 Subject: [Tutor] Errno 9 Message-ID: Hi All, I am trying to read a line in a file then split the words in the line up. This is what i thought would work: # filearray.py import string # THE FOLLOWING FOUR LINE ARE THE CORRECT START TO THE PROGRAM, # THE SIXTH AND SEVENTH LINES ARE ONLY FOR QUICK TEST PURPOSE!!! infilename = raw_input("What file would you like to re-arrange?: ") outfilename = raw_input("Where would you like to save to array?: ") infile = open(infilename, 'r') infile = open(outfilename, 'w') #infile = open("G:\gnet.nmap", 'r') #infile = open("G:\work2.txt", 'w') # process each line for line in infile.readlines(): words = string.split(line) print words # save and close files infile.close() infile.close() But i get an "IO Error: [Errno 9] Bad file descriptor" on line 16. Tried changing syntax and file names, thought it was fairly simple and i knew what i was doing. Any help appreciated. Thanks in advance! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080228/2ee97ebd/attachment.htm From kent37 at tds.net Thu Feb 28 15:49:01 2008 From: kent37 at tds.net (Kent Johnson) Date: Thu, 28 Feb 2008 09:49:01 -0500 Subject: [Tutor] Errno 9 In-Reply-To: References: Message-ID: <47C6C9DD.8050609@tds.net> imonthejazz wrote: > Hi All, > > I am trying to read a line in a file then split the words in the line up. > > This is what i thought would work: > > # filearray.py > > import string > > # THE FOLLOWING FOUR LINE ARE THE CORRECT START TO THE PROGRAM, > # THE SIXTH AND SEVENTH LINES ARE ONLY FOR QUICK TEST PURPOSE!!! > infilename = raw_input("What file would you like to re-arrange?: ") > outfilename = raw_input("Where would you like to save to array?: ") > infile = open(infilename, 'r') > infile = open(outfilename, 'w') outfile would be a better name! > > #infile = open("G:\gnet.nmap", 'r') > #infile = open("G:\work2.txt", 'w') > > # process each line > for line in infile.readlines(): > words = string.split(line) > print words Note you haven't written anything to outfile yet; print will go to the console. I'm not sure what you do want to write so I won't suggest anything. > # save and close files > infile.close() > infile.close() I guess this is line 16; you are closing the same file twice. Should be outfile.close() > But i get an "IO Error: [Errno 9] Bad file descriptor" on line 16. It would help to see the traceback, it includes the line with the error so we don't have to guess which is line 16. Kent From imonthejazz at googlemail.com Thu Feb 28 15:56:41 2008 From: imonthejazz at googlemail.com (imonthejazz) Date: Thu, 28 Feb 2008 14:56:41 +0000 Subject: [Tutor] Errno 9 In-Reply-To: <47C6C9DD.8050609@tds.net> References: <47C6C9DD.8050609@tds.net> Message-ID: I think my problem was naming of the files, changed them and its fine now. Man, i feel stupid. When I have finished my project i'll share it with you guys! On 28/02/2008, Kent Johnson wrote: > > imonthejazz wrote: > > Hi All, > > > > I am trying to read a line in a file then split the words in the line > up. > > > > This is what i thought would work: > > > > # filearray.py > > > > import string > > > > # THE FOLLOWING FOUR LINE ARE THE CORRECT START TO THE PROGRAM, > > # THE SIXTH AND SEVENTH LINES ARE ONLY FOR QUICK TEST PURPOSE!!! > > infilename = raw_input("What file would you like to re-arrange?: ") > > outfilename = raw_input("Where would you like to save to array?: ") > > infile = open(infilename, 'r') > > infile = open(outfilename, 'w') > > > outfile would be a better name! > > > > > > #infile = open("G:\gnet.nmap", 'r') > > #infile = open("G:\work2.txt", 'w') > > > > # process each line > > for line in infile.readlines(): > > words = string.split(line) > > print words > > > Note you haven't written anything to outfile yet; print will go to the > console. I'm not sure what you do want to write so I won't suggest > anything. > > > > # save and close files > > infile.close() > > infile.close() > > > I guess this is line 16; you are closing the same file twice. Should be > outfile.close() > > > > But i get an "IO Error: [Errno 9] Bad file descriptor" on line 16. > > > It would help to see the traceback, it includes the line with the error > so we don't have to guess which is line 16. > > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080228/c1143785/attachment.htm From mlangford.cs03 at gtalumni.org Thu Feb 28 16:07:00 2008 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 28 Feb 2008 10:07:00 -0500 Subject: [Tutor] rss feed reader, but having trouble with unicode In-Reply-To: References: Message-ID: <82b4f5810802280707w576745c6o3fc2cdc75883244f@mail.gmail.com> feedparser.org also works really well for this sort of thing. Does a lot of the unicode automagically for you. --michael On Wed, Feb 27, 2008 at 8:58 AM, Tom wrote: > Finally got it working. I used your suggestion Rui, but I also had to > change the charset encoding that my database was using. Changed from > Latin-1 to UCS2. > > I read http://www.joelonsoftware.com/articles/Unicode.html too. > Essential reading. > > Thanks. > > > > On 26/02/2008, rui wrote: > > Hello Tom, > > > > Try doing this: > > > > xml = unicode(xml, encoding, "ignore") > > elem = ElementTree.fromstring(xml.encode("utf8")) > > > > > > > #do stuff with elem... > > > > > > feed.xml = xml > > > feed.save() > > > > > > > > > Thanks for your time :-) > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > -- > > Rui > > http://ruivaldo.wordpress.com > > > > "Rubi? Aquela novela do SBT?" > > ~ Carla Perez sobre Ruby > > > > "Em Python, tudo ? objeto, al?m de lindo e maravilhoso." > > ~ Caetano Veloso sobre Python > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From tavspamnofwd at googlemail.com Thu Feb 28 16:20:27 2008 From: tavspamnofwd at googlemail.com (Tom) Date: Thu, 28 Feb 2008 15:20:27 +0000 Subject: [Tutor] rss feed reader, but having trouble with unicode In-Reply-To: <82b4f5810802280707w576745c6o3fc2cdc75883244f@mail.gmail.com> References: <82b4f5810802280707w576745c6o3fc2cdc75883244f@mail.gmail.com> Message-ID: Yeah I was considering using that. Thanks for the tip. On 28/02/2008, Michael Langford wrote: > feedparser.org also works really well for this sort of thing. Does a > lot of the unicode automagically for you. > > --michael > > > On Wed, Feb 27, 2008 at 8:58 AM, Tom wrote: > > Finally got it working. I used your suggestion Rui, but I also had to > > change the charset encoding that my database was using. Changed from > > Latin-1 to UCS2. > > > > I read http://www.joelonsoftware.com/articles/Unicode.html too. > > Essential reading. > > > > Thanks. > > > > > > > > On 26/02/2008, rui wrote: > > > Hello Tom, > > > > > > Try doing this: > > > > > > xml = unicode(xml, encoding, "ignore") > > > elem = ElementTree.fromstring(xml.encode("utf8")) > > > > > > > > > > #do stuff with elem... > > > > > > > > feed.xml = xml > > > > feed.save() > > > > > > > > > > > > Thanks for your time :-) > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > -- > > > Rui > > > http://ruivaldo.wordpress.com > > > > > > "Rubi? Aquela novela do SBT?" > > > ~ Carla Perez sobre Ruby > > > > > > "Em Python, tudo ? objeto, al?m de lindo e maravilhoso." > > > ~ Caetano Veloso sobre Python > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.RowdyLabs.com > From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= Thu Feb 28 17:30:47 2008 From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=) Date: Thu, 28 Feb 2008 19:30:47 +0300 Subject: [Tutor] [Off-Topic] 'ex' vs. 'sed'... In-Reply-To: <20080227230249.GB23247@ayn.mi.celestial.com> References: <71dd7f400802271446k17fcb6bbkd4c3257f18c94896@mail.gmail.com> <20080227230249.GB23247@ayn.mi.celestial.com> Message-ID: <1204216247.952.6.camel@gobuntu.zamb.pc> (sorry for hijacking the thread like this!) On Wed, 2008-02-27 at 15:02 -0800, Bill Campbell wrote: > Another way on *nix systems that might be better wouldn't use > python at all. Edit the file in place with ed or ex: > > #!/bin/sh > ex - filename < 1d > w > q > DONE > Errrr, how about: "sed -i.BACKUP -e '1d' filename"? Much shorter, elegant, and obvious. (and it creates a backup file of the original.) After all, "sed" stands for: Stream EDitor. Ziyad. (again, sorry for hijacking the thread.) From =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= Thu Feb 28 17:53:45 2008 From: =?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?= (=?UTF-8?Q?=D8=B2=D9=8A=D8=A7=D8=AF_=D8=A8=D9=86_?=) Date: Thu, 28 Feb 2008 19:53:45 +0300 Subject: [Tutor] [Off-Topic] 'vimrc' for Python... In-Reply-To: References: <20080227205304.07fcb9413df0eef145f094851c2af08f.5aa846c01b.wbe@email.secureserver.net> Message-ID: <1204217625.952.25.camel@gobuntu.zamb.pc> (Sorry for hijacking the thread. This is the second time in the same day... sigh!) On Thu, 2008-02-28 at 08:04 -0500, bhaaluu wrote: > I also run Python on Linux. I've tried several of the Python IDEs > (Integrated Development Environments), such as IDLE, Eric, and > so forth, but the best (for me) has been vim. I agree. > I use the following > .vimrc file: > > -------------8<-----Cut Here----->8------------------- > " .vimrc > " > " Created by Jeff Elkner 23 January 2006 > " Last modified 2 February 2006 > " > " Turn on syntax highlighting and autoindenting > syntax enable > filetype indent on This should be: if has("autocmd") " If Vim is compiled with support for 'autocommands'... filetype indent on " ...turn on indentation accordingly. endif > " set autoindent width to 4 spaces (see > " http://www.vim.org/tips/tip.php?tip_id=83) > set et > set sw=4 > set smarttab Not good. This will turn the above for all files edited with Vim. Here's a better setup (note: some of the lines bellow are longer than 80 column which might get wrapped by you mail reader! sorry.): if has("autocmd") " Only do this part when compiled with support for 'autocommands'. autocmd FileType python set ts=4 sw=4 et " Python autocmd FileType ruby set ts=2 sw=2 " Ruby autocmd FileType c,cpp set ts=4 sw=4 cindent " C & C++ autocmd FileType docbk,html,xhtml,xml set ts=2 sw=2 " DocBook, HTML, XHTML, and XML endif " has("autocmd") (You can add more specific options for any other file types you wish for.) > " set line number (added by bhaaluu) > set nu > " Bind key to running the python interpreter on the currently active > " file. (courtesy of Steve Howell from email dated 1 Feb 2006). > map :w\|!python % Grate! (You could use ':update' instead of ':w' which will write the file only if it has changed.) > -------------8<-----Cut Here----->8------------------- > > I run vim in Konsole, but any Xterm works, AFAIK. > > Happy Programming! Happy programming to all of you out there. Ziyad. (again, sorry for hijacking the thread!) From kdsudac at yahoo.com Thu Feb 28 19:03:07 2008 From: kdsudac at yahoo.com (Keith Suda-Cederquist) Date: Thu, 28 Feb 2008 10:03:07 -0800 (PST) Subject: [Tutor] Python oddity Message-ID: <871138.93667.qm@web54301.mail.re2.yahoo.com> Hey all, thanks for all the responses. I think I get the gist of just about everything. One thing to mention though is that I'm mainly working with scipy so most of what I'm working with in numpy.ndarrays. I think most of what was mentioned with respect to lists applies equally to numpy.ndarrays. The id() function/sub-routine is something that'll be handy in the future as is knowing the difference between 'is' and '= ='. I have a few follow-up questions: 1) A lot of what I'm doing is image processing that involves slicing and performing standard arithmetic and logic to arrays. So I think I've manage to avoid this trap most of the time since at least shallow copies are made. Are there any clear rules for when a shallow copy is made versus a deep copy? 2) Luke gave a tip on using the append rather than the += when creating strings in a for-loop to be more memory-efficient. Does this only apply to immutable objects such as strings?? I'm creating a lot of arrays by doing something like this: A=scipy.zeros(100,100) #initialize array for ii in xrange(0,shape(A)[0]): for jj in xrange(0,shape(A)[1]): A[ii,jj]=3*ii+jj+sqrt(ii*jj) I would think this is okay since the array is mutable, am I correct or is there a better technique? 3) Now you all have me a little worried that I'm not being very memory efficient with my programming style. A lot of the time, I'll perform a lot of operations in sequence on an array. For example: #B is a 1000x1000 pixel image that I've imported as an array. We'll call this B1 B=(B-B.min())/(B.max()-B.min()) #image array scaled from 0 to 1. We'll call this B2 B=B[B>0.5] #image with values less than 0.5 masked (set to zero). We'll call this B3 So in this example, is memory allocated for B1, B2 and B3? Does every operation force a new copy? Will this memory ever be 'recovered' by the python memory manger (garbage collector?)? 4) The typical knee-jerk reaction to this 'oddity' is "what a pain, how stupid" etc, but I'm sure there is a good explanation. Can someone explain why python acts this way? faster processing? preserve memory? etc? Thanks for all your help. -Keith ----- Original Message ---- From: Luke Paireepinart To: Brett Wilkins ; Tutor Sent: Thursday, February 28, 2008 2:49:11 AM Subject: Re: [Tutor] Python oddity Brett Wilkins wrote: > As everybody else has told you, assigning bb = aa just gives bb the > reference to the same object that aa has. Unless I missed something, > then nobody's actually mentioned how to make this not happen... and it's > actually rather easy... instead of bb = aa, do this: > bb = aa[:] > Looks like a splice, and indeed it is a splice, without bounds. When a > splice is used like this, I believe it is known as the copy directive. Yes, Terry explained other ways as well. The problem with using slices is the following: >>> a = [['a'],'b'] >>> b = a >>> b is a True >>> b = a[:] >>> b is a False #okay, we're fine so far. >>> b[0] ['a'] >>> b[0].append('c') >>> b[0] ['a', 'c'] >>> a[0] ['a', 'c'] and here's where we run into problems. Turns out the slice notation just makes a shallow copy, so if you have any lists in your list, they will still refer to the same object. (I'm guessing that any mutable objects will still refer to the same object) copy.copy() has this same problem. The way to avoid this, as I mentioned before, is to use a deepcopy(), but as I said, you usually don't need to make a full copy of a list. Oh, and if you're curious: >>> b = list(a) >>> b is a False >>> b[0].append('d') >>> a[0] ['a', 'c', 'd'] So a list() does a shallow copy as well. Here's a continuation, with deepcopy(): >>> import copy >>> b = copy.deepcopy(a) >>> b is a False >>> b[0] is a[0] False >>> b[0].append('e') >>> a[0] ['a', 'c', 'd'] HTH, -Luke _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080228/bf925d5a/attachment.htm From jeff at drinktomi.com Thu Feb 28 19:37:44 2008 From: jeff at drinktomi.com (Jeff Younker) Date: Thu, 28 Feb 2008 10:37:44 -0800 Subject: [Tutor] Python oddity In-Reply-To: <871138.93667.qm@web54301.mail.re2.yahoo.com> References: <871138.93667.qm@web54301.mail.re2.yahoo.com> Message-ID: <1ED952B8-D892-45D4-B923-48D229C097D9@drinktomi.com> > 4) The typical knee-jerk reaction to this 'oddity' is "what a pain, > how stupid" etc, but I'm sure there is a good explanation. Can > someone explain why python acts this way? faster processing? > preserve memory? etc? This comes down (largely) to a philosophical choice. Does the language work with things that are platonic mathematical entities, or does it work with things that have a concrete physical existence? Consider this: >>> k = Printer('csx2500') >>> print k.sheets_left() 200 >>> m = k >>> m.print_document(file="/tmp/my.pdf") >>> print m.sheets_left() 190 So what should k.print_sheets() show? There are many things in computers that work like this: hard drives, file systems, data bases, chunks of memory, printers, the screen, mice, keyboards, and user interfaces. Attaching a mouse to another name doesn't create a new mouse. Assigning a file to a different variable shouldn't create a new file. There are languages that work like you expect. They're called pure functional languages. They have their adherents, but they're known to have problems with certain things like, well, input and output. (On the other hand they do multiple threads of execution very well.) What it comes down to is this: does you program work with an idealized universe, or does it work with the messy innards of a computer? -jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080228/225a1433/attachment.htm From jim at well.com Thu Feb 28 20:07:29 2008 From: jim at well.com (jim stockford) Date: Thu, 28 Feb 2008 11:07:29 -0800 Subject: [Tutor] Python oddity In-Reply-To: <871138.93667.qm@web54301.mail.re2.yahoo.com> References: <871138.93667.qm@web54301.mail.re2.yahoo.com> Message-ID: i'd like to know, too. my take so far is * don't make any copies if you can avoid doing so, * make shallow copies if need be, * make deep copies only if you can't think of any other way to accomplish what you're up to. what's the truth? I'm hoping there's an OTW answer (OTW ~> "One True Way"). On Feb 28, 2008, at 10:03 AM, Keith Suda-Cederquist wrote: > Hey all, thanks for all the responses.? I think I get the gist of just > about everything.? One thing to mention though is that I'm mainly > working with scipy so most of what I'm working with in > numpy.ndarrays.? I think most of what was mentioned with respect to > lists applies equally to numpy.ndarrays.? The id() > function/sub-routine is something that'll be handy in the future as is > knowing the difference between 'is' and '= ='. > > I have a few follow-up questions: > > 1)? A lot of what I'm doing is image processing that involves slicing > and performing standard arithmetic and logic to arrays.? So I think > I've manage to avoid this trap most of the time since at least shallow > copies are made. Are there any clear rules for when a shallow copy is > made versus a deep copy? > 2)? Luke gave a tip on using the append rather than the += when > creating strings in a for-loop to be more memory-efficient.? Does this > only apply to immutable objects such as strings??? I'm creating a lot > of arrays by doing something like this: > > A=scipy.zeros(100,100)? #initialize array > for ii in xrange(0,shape(A)[0]): > ??? for jj in xrange(0,shape(A)[1]): > ??? ?? A[ii,jj]=3*ii+jj+sqrt(ii*jj) > > I would think this is okay since the array is mutable, am I correct or > is there a better technique??? ?? > 3)? Now you all have me a little worried that I'm not being very > memory efficient with my programming style.? A lot of the time, I'll > perform a lot of operations in sequence on an array.? For example: > > #B is a 1000x1000 pixel image that I've imported as an array.? We'll > call this B1 > B=(B-B.min())/(B.max()-B.min())? #image array scaled from 0 to 1.? > We'll call this B2 > B=B[B>0.5]? #image with values less than 0.5 masked (set to zero).? > We'll call this B3 > > So in this example, is memory allocated for B1, B2 and B3?? Does every > operation force a new copy? ? Will this memory ever be 'recovered' by > the python memory manger (garbage collector?)? > 4)? The typical knee-jerk reaction to this 'oddity' is "what a pain, > how stupid" etc, but I'm sure there is a good explanation.? Can > someone explain why python acts this way?? faster processing?? > preserve memory? etc? > > Thanks for all your help. > > -Keith > ----- Original Message ---- > From: Luke Paireepinart > To: Brett Wilkins ; Tutor > Sent: Thursday, February 28, 2008 2:49:11 AM > Subject: Re: [Tutor] Python oddity > > Brett Wilkins wrote: > > As everybody else has told you, assigning bb = aa just gives bb the > > reference to the same object that aa has. Unless I missed something, > > then nobody's actually mentioned how to make this not happen... and > it's > > actually rather easy... instead of bb = aa, do this: > > bb = aa[:] > > Looks like a splice, and indeed it is a splice, without bounds. When > a > > splice is used like this, I believe it is known as the copy > directive. > Yes, Terry explained other ways as well. > The problem with using slices is the following: > > >>> a = [['a'],'b'] > >>> b = a > >>> b is a > True > >>> b = a[:] > >>> b is a > False > #okay, we're fine so far. > >>> b[0] > ['a'] > >>> b[0].append('c') > >>> b[0] > ['a', 'c'] > >>> a[0] > ['a', 'c'] > > > and here's where we run into problems. > Turns out the slice notation just makes a shallow copy, so if you have > any lists in your list, they will still refer to the same object.? (I'm > guessing that any mutable objects will still refer to the same object) > copy.copy() has this same problem. > The way to avoid this, as I mentioned before, is to use a deepcopy(), > but as I said, you usually don't need to make a full copy of a list. > Oh, and if you're curious: > >>> b = list(a) > >>> b is a > False > >>> b[0].append('d') > >>> a[0] > ['a', 'c', 'd'] > > So a list() does a shallow copy as well. > > Here's a continuation, with deepcopy(): > >>> import copy > >>> b = copy.deepcopy(a) > >>> b is a > False > >>> b[0] is a[0] > False > >>> b[0].append('e') > >>> a[0] > ['a', 'c', 'd'] > > > HTH, > -Luke > _______________________________________________ > Tutor maillist? -? Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > Never miss a thing. Make Yahoo your homepage. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Fri Feb 29 03:02:52 2008 From: keridee at jayco.net (Tiger12506) Date: Thu, 28 Feb 2008 21:02:52 -0500 Subject: [Tutor] Python oddity References: <871138.93667.qm@web54301.mail.re2.yahoo.com> Message-ID: <006101c87a77$55e902d0$4afce004@jslaptop> > i'd like to know, too. my take so far is > > * don't make any copies if you can avoid doing so, > * make shallow copies if need be, > * make deep copies only if you can't think of any > other way to accomplish what you're up to. Yep. That's pretty much it, for space reasons, mostly. Imagine a list (or any other mutable object) as a table of contents. When you first create a list, all of the contents are stored in memory and the list becomes the table of contents. Now when you assign this table of contents to a new variable, no significant extra memory is stored. It's basically just another name (rose by any other name still smells as sweet) for the same table of contents. Now imagine that to save space, instead of the table of contents being only references to 'chapters' (objects), that whenever an immutable object is added to a list, it is written directly on the table of contents page. Mutable objects (they can be changed) are still just references to 'page numbers' in the actual contents of memory. Now when you copy a list (by default a shallow copy), you are really only copying the table of contents onto a different sheet of paper. This includes the slice, copy.copy, and the list() methodologies described. You see now how immutable objects have to become new copies because they are written directly on the table of content page, right? Shallow copying is less preferable to an alias (another name) because extra space is needed to store the extra copy of the table of contents. However, all mutable objects contained within the list will not be copied, and the two table of contents will still refer to the same 'page numbers' in the same 'book'. Finally, the deep copy. This recursively (is it true recursion???) runs through the table of contents of a list and makes a copy of each 'page' in the 'book' and constructs a completely new and seperate entity. From rdm at rcblue.com Fri Feb 29 13:28:50 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 29 Feb 2008 04:28:50 -0800 Subject: [Tutor] How to open IE7 to a certain URL? Message-ID: <20080229122924.14F8D1E4003@bag.python.org> I keep missing a certain weekly program on my local NPR station. My idea is to record it using software I have, Easy Hi-Q Recorder. I can set it to start recording when the program starts, 8pm, but I need to have the program playing on my computer. The URL for the station's audio is http://www.kuow.org/real.ram . I've got this so far: #!/usr/bin/env python #coding=utf-8 import time b = '20:00:00' while True: a = time.strftime('%H:%M:%S') time.sleep(0.5) if a == b: print "TIME!" break Obviously, I need to replace the 'print "TIME"' line with something that will open IE7 to http://www.kuow.org/real.ram . But what? Thanks, Dick Moores From h.fangohr at soton.ac.uk Fri Feb 29 13:29:42 2008 From: h.fangohr at soton.ac.uk (Hans Fangohr) Date: Fri, 29 Feb 2008 12:29:42 +0000 (GMT) Subject: [Tutor] comparison bug in python (or do I not get it?) Message-ID: Dear Python folks, here is a sequence of commands (ipython) that lead to a question. See my comments after leading '#': In [1]: 2 in [1,2,3] Out[1]: True #nothing special here, of course 2 is in the list. In [2]: 2 in [1,2,3] == True Out[2]: False #This is somewhat surprising, as one would hope that '2 in [1,2,3]' #evaluates to 'True', and then we expect 'True'=='True' to hold. #However, maybe it is an issue of operator precedence. Let's add parenthesis: In [3]: (2 in [1,2,3]) == True Out[3]: True #Okay, so this does what we expect. #However, if it is an issue of operator precedence, then what is the #operation that is carried out at prompt [2] above? # #Presumably, we work out In [4]: [1,2,3] == True Out[4]: False #which is false. So effectively, The statement at [2] seems to boil down to In [5]: 2 in False --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /Volumes/Minmax250a/Users2/fangohr/ TypeError: iterable argument required But this throws an error! And so does the full expression (with paranthesis): In [6]: 2 in ([1,2,3] == True) --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /Volumes/Minmax250a/Users2/fangohr/ TypeError: iterable argument required So what is the story here? In my view, the statement in line [2] should either produce True (as in [3]), or throw an error (as in [6]). Why does [2] return False? Would people agree that this is a bug? Thank you for your time, Hans PS I have tested this with Python 2.4, and Python 2.5 (on debian etch) -- Hans Fangohr School of Engineering Sciences University of Southampton Phone: +44 (0) 238059 8345 Email: fangohr at soton.ac.uk http://www.soton.ac.uk/~fangohr From mail at timgolden.me.uk Fri Feb 29 14:07:20 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 29 Feb 2008 13:07:20 +0000 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <20080229122924.14F8D1E4003@bag.python.org> References: <20080229122924.14F8D1E4003@bag.python.org> Message-ID: <47C80388.2070106@timgolden.me.uk> Dick Moores wrote: > I keep missing a certain weekly program on my local NPR station. My > idea is to record it using software I have, Easy Hi-Q Recorder. I can > set it to start recording when the program starts, 8pm, but I need to > have the program playing on my computer. The URL for the station's > audio is http://www.kuow.org/real.ram . > > I've got this so far: > > #!/usr/bin/env python > #coding=utf-8 > import time > b = '20:00:00' > while True: > a = time.strftime('%H:%M:%S') > time.sleep(0.5) > if a == b: > print "TIME!" > break > > Obviously, I need to replace the 'print "TIME"' line with something > that will open IE7 to http://www.kuow.org/real.ram . But what? Sidestepping slightly, the natural way to open a URL using whatever's set up to do so is with os.startfile: import os os.startfile ("http://whatever...ram") I was going to say that, to use IE7 explicitly, you should use the webbrowser module. But then I realised that, for reasons which I'm sure are extremely good but which elude me for now, iexplorer is not one of the registered browsers. As a fallback, you can look for its apppath entry in the registry and use subprocess to call that. TJG From kent37 at tds.net Fri Feb 29 14:14:30 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Feb 2008 08:14:30 -0500 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <20080229122924.14F8D1E4003@bag.python.org> References: <20080229122924.14F8D1E4003@bag.python.org> Message-ID: <47C80536.5070000@tds.net> Dick Moores wrote: > #!/usr/bin/env python > #coding=utf-8 > import time > b = '20:00:00' > while True: > a = time.strftime('%H:%M:%S') > time.sleep(0.5) > if a == b: You might want to learn how to use your OS's scheduler to do this part. I don't know what it is on Windows though. Kent From mail at timgolden.me.uk Fri Feb 29 14:19:57 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 29 Feb 2008 13:19:57 +0000 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <47C80536.5070000@tds.net> References: <20080229122924.14F8D1E4003@bag.python.org> <47C80536.5070000@tds.net> Message-ID: <47C8067D.2020109@timgolden.me.uk> Kent Johnson wrote: > Dick Moores wrote: > >> #!/usr/bin/env python >> #coding=utf-8 >> import time >> b = '20:00:00' >> while True: >> a = time.strftime('%H:%M:%S') >> time.sleep(0.5) >> if a == b: > > You might want to learn how to use your OS's scheduler to do this part. > I don't know what it is on Windows though. You've got a couple of options on Windows, actually (not including any roll-you-own or ported cron efforts). You can either use the AT command (from the command line or via WMI) or you can use the Windows scheduler, either from the control panel or programatically via the win32com.taskscheduler module from pywin32. TJG From kent37 at tds.net Fri Feb 29 14:21:09 2008 From: kent37 at tds.net (Kent Johnson) Date: Fri, 29 Feb 2008 08:21:09 -0500 Subject: [Tutor] comparison bug in python (or do I not get it?) In-Reply-To: References: Message-ID: <47C806C5.4060409@tds.net> Hans Fangohr wrote: > In [2]: 2 in [1,2,3] == True > Out[2]: False > > Why does [2] return False? Would people agree that this is a bug? No, not a bug. Don't be too quick to blame your tools! The equivalent expression is In [1]: (2 in [1,2,3]) and ([1,2,3]==False) Out[1]: False 'in' is considered a comparison operator and can be chained with other comparisons. For a clearer example, consider In [2]: 2 < 3 < 4 Out[2]: True which is not the same as In [3]: 2 < (3 < 4) Out[3]: False or In [4]: (2 < 3) < 4 Out[4]: True It is equivalent to In [5]: (2 < 3) and (3 < 4) Out[5]: True See http://docs.python.org/ref/comparisons.html Kent From h.fangohr at soton.ac.uk Fri Feb 29 14:42:43 2008 From: h.fangohr at soton.ac.uk (Hans Fangohr) Date: Fri, 29 Feb 2008 13:42:43 +0000 (GMT) Subject: [Tutor] comparison bug in python (or do I not get it?) In-Reply-To: <47C806C5.4060409@tds.net> References: <47C806C5.4060409@tds.net> Message-ID: Hi Kent, > Hans Fangohr wrote: > >> In [2]: 2 in [1,2,3] == True >> Out[2]: False >> >> Why does [2] return False? Would people agree that this is a bug? > > No, not a bug. Don't be too quick to blame your tools! That's good news. I'd be worried if this wasn't the desired behaviour -- I just hadn't understood the logic. > > The equivalent expression is > In [1]: (2 in [1,2,3]) and ([1,2,3]==False) > Out[1]: False Ah -- that's the way to read it! > > 'in' is considered a comparison operator and can be chained with other > comparisons. For a clearer example, consider > In [2]: 2 < 3 < 4 > Out[2]: True > > which is not the same as > In [3]: 2 < (3 < 4) > Out[3]: False > > or > In [4]: (2 < 3) < 4 > Out[4]: True > > It is equivalent to > In [5]: (2 < 3) and (3 < 4) > Out[5]: True > Well explained -- makes perfect sense now. Many thanks, Hans > See > http://docs.python.org/ref/comparisons.html > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Hans Fangohr School of Engineering Sciences University of Southampton Phone: +44 (0) 238059 8345 Email: fangohr at soton.ac.uk http://www.soton.ac.uk/~fangohr From luciano at ramalho.org Fri Feb 29 15:32:55 2008 From: luciano at ramalho.org (Luciano Ramalho) Date: Fri, 29 Feb 2008 11:32:55 -0300 Subject: [Tutor] comparison bug in python (or do I not get it?) In-Reply-To: <47C806C5.4060409@tds.net> References: <47C806C5.4060409@tds.net> Message-ID: <4331ad810802290632u3cdc3199o17769957aaba3fc2@mail.gmail.com> On Fri, Feb 29, 2008 at 10:21 AM, Kent Johnson wrote: > No, not a bug. Don't be too quick to blame your tools! Well said, Kent. Here's a generic tip to anyone learning Python. I learned Python after working professionally with several languages for many years, including Java and Delphi, and I can say that Python is *very* well designed, is implemented with the highest standards of software engineering and caters to a rigorous and expert audience. It is **extremely** unlikely that you will ever find a bug in the interpreter or the built-ins if you are using a released version of Python. I've been using Python professionally since 1998 and I never stumbled upon a single bug anywhere in a released Python distribution. Of course, there are bugs and even security hot-fixes are issued from time to time. But I've never been affected by a Python bug in my projects. So it's better to assume that any strange behaviour is actually some misunderstanding on your part than a bug. Cheers, Luciano From rdm at rcblue.com Fri Feb 29 15:58:57 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 29 Feb 2008 06:58:57 -0800 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <47C80388.2070106@timgolden.me.uk> References: <20080229122924.14F8D1E4003@bag.python.org> <47C80388.2070106@timgolden.me.uk> Message-ID: <20080229145903.10CD91E4003@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080229/a37eafbc/attachment.htm From rdm at rcblue.com Fri Feb 29 16:06:19 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 29 Feb 2008 07:06:19 -0800 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <47C8067D.2020109@timgolden.me.uk> References: <20080229122924.14F8D1E4003@bag.python.org> <47C80536.5070000@tds.net> <47C8067D.2020109@timgolden.me.uk> Message-ID: <20080229150625.90B191E401B@bag.python.org> At 05:19 AM 2/29/2008, Tim Golden wrote: >Kent Johnson wrote: > > Dick Moores wrote: > > > >> #!/usr/bin/env python > >> #coding=utf-8 > >> import time > >> b = '20:00:00' > >> while True: > >> a = time.strftime('%H:%M:%S') > >> time.sleep(0.5) > >> if a == b: > > > > You might want to learn how to use your OS's scheduler to do this part. > > I don't know what it is on Windows though. > >You've got a couple of options on Windows, actually (not including >any roll-you-own or ported cron efforts). You can either use the >AT command The XP help says that rather than AT, to use schtasks. I'm trying to figure it out now.. > (from the command line or via WMI) Windows Management Instrumentation is a whole new world to me, but I understand (from Wikipedia) that XP has it. I wish you'd quit opening up these cans of worms! ;-) >or you can use the >Windows scheduler, either from the control panel or programatically >via the win32com.taskscheduler module from pywin32. Thanks again, Dick Moores From steve at alchemy.com Fri Feb 29 17:29:41 2008 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 29 Feb 2008 08:29:41 -0800 Subject: [Tutor] comparison bug in python (or do I not get it?) In-Reply-To: <47C806C5.4060409@tds.net> References: <47C806C5.4060409@tds.net> Message-ID: <47C832F5.2060203@alchemy.com> Kent Johnson wrote: > Hans Fangohr wrote: > >> In [2]: 2 in [1,2,3] == True On a slightly different tangent from the other answers you've received to this question, if you're using a conditional expression, don't compare it explicitly with True or False, just state the condition: if 2 in [1,2,3]: blah The same holds even if a variable contains True or False: some_option = True ... if some_option: blah NOT: if some_option == True: blah From cfuller at thinkingplanet.net Fri Feb 29 17:40:10 2008 From: cfuller at thinkingplanet.net (Chris Fuller) Date: Fri, 29 Feb 2008 10:40:10 -0600 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <20080229122924.14F8D1E4003@bag.python.org> References: <20080229122924.14F8D1E4003@bag.python.org> Message-ID: <200802291040.10710.cfuller@thinkingplanet.net> On Friday 29 February 2008 06:28, Dick Moores wrote: > I keep missing a certain weekly program on my local NPR station. My > idea is to record it using software I have, Easy Hi-Q Recorder. I can > set it to start recording when the program starts, 8pm, but I need to > have the program playing on my computer. The URL for the station's > audio is http://www.kuow.org/real.ram . > > I've got this so far: > > #!/usr/bin/env python > #coding=utf-8 > import time > b = '20:00:00' > while True: > a = time.strftime('%H:%M:%S') > time.sleep(0.5) > if a == b: > print "TIME!" > break > > Obviously, I need to replace the 'print "TIME"' line with something > that will open IE7 to http://www.kuow.org/real.ram . But what? > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You might consider passing the URL directly to the audio player. This is usually all the web browser does for you, although its possible there's a different URL defined on that page each time, but then you could parse the page in python using urllib and re, or something similar. Not only that, launching IE7 is a time and memory consuming activity, and definitely lacks grace. I dunno how your media player works, but this did the job for me (from the command prompt): "c:\Program Files\Real Alternative\Media Player Classic\mplayerc.exe" http://www.kuow.org/real.ram You could put this directly into your windows scheduler, and not use python at all. Start Menu>All Programs>Accessories>System Tools>Scheduled Tasks You'll get an option to set the command line at the end of teh wizard, if you check "show advanced options" You could have a python process running in the background that executed this command through the subprocess module, at the appointed time. You could even use something like FireDaemon to turn it into a service. But, it seems better to use the windows scheduler. Cheers From alan.gauld at btinternet.com Fri Feb 29 19:14:20 2008 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Feb 2008 18:14:20 -0000 Subject: [Tutor] How to open IE7 to a certain URL? References: <20080229122924.14F8D1E4003@bag.python.org> <47C80536.5070000@tds.net> Message-ID: "Kent Johnson" wrote > You might want to learn how to use your OS's scheduler to do this > part. > I don't know what it is on Windows though. Start->Settings->Control Panel-Scheduled Tasks->Add New Task Starts a wizard. You can also try the 'at' command: -------------- C:\> help at ------------ The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" -------------------------------------- -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/alan.gauld at btinternet.com/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Fri Feb 29 19:24:50 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 29 Feb 2008 10:24:50 -0800 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: <200802291040.10710.cfuller@thinkingplanet.net> References: <20080229122924.14F8D1E4003@bag.python.org> <200802291040.10710.cfuller@thinkingplanet.net> Message-ID: <20080229182455.B37301E4003@bag.python.org> At 08:40 AM 2/29/2008, Chris Fuller wrote: >On Friday 29 February 2008 06:28, Dick Moores wrote: > > I keep missing a certain weekly program on my local NPR station. My > > idea is to record it using software I have, Easy Hi-Q Recorder. I can > > set it to start recording when the program starts, 8pm, but I need to > > have the program playing on my computer. The URL for the station's > > audio is http://www.kuow.org/real.ram . > > > > I've got this so far: > > > > #!/usr/bin/env python > > #coding=utf-8 > > import time > > b = '20:00:00' > > while True: > > a = time.strftime('%H:%M:%S') > > time.sleep(0.5) > > if a == b: > > print "TIME!" > > break > > > > Obviously, I need to replace the 'print "TIME"' line with something > > that will open IE7 to http://www.kuow.org/real.ram . But what? > > > > Thanks, > > > > Dick Moores > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > >You might consider passing the URL directly to the audio player. This is >usually all the web browser does for you, although its possible there's a >different URL defined on that page each time, but then you could parse the >page in python using urllib and re, or something similar. Not only that, >launching IE7 is a time and memory consuming activity, and definitely lacks >grace. Yes. Point taken. >I dunno how your media player works, but this did the job for me (from the >command prompt): > >"c:\Program Files\Real Alternative\Media Player Classic\mplayerc.exe" >http://www.kuow.org/real.ram Great! "E:\Programs\Real Player\realplay.exe" http://www.kuow.org/real.ram works fine at the command prompt! >You could put this directly into your windows scheduler, and not use >python at >all. Start Menu>All Programs>Accessories>System Tools>Scheduled Tasks >You'll get an option to set the command line at the end of teh wizard, if you >check "show advanced options" > >You could have a python process running in the background that executed this >command through the subprocess module, at the appointed time. You could even >use something like FireDaemon to turn it into a service. But, it seems >better to use the windows scheduler. I'm having a lot of trouble with the windows scheduler. It wants a password, and there isn't one. In any event, I'd like to do this with Python, especially if I could have "a Python process running in the background." Would you mind giving me a start on the code for this? Thanks, Dick Moores From toby.pas at gmail.com Fri Feb 29 19:12:19 2008 From: toby.pas at gmail.com (Toby) Date: Fri, 29 Feb 2008 12:12:19 -0600 (CST) Subject: [Tutor] iexplore scheduler In-Reply-To: Message-ID: <004b01c87afe$9f59e650$3901a8c0@careplus.local> Start-programs-accessories-system tools-scheduled tasks Browse to program files internet explorer and choose iexplore.exe Set the schedule to run at the right time Finish the schedule and then go back and edit the task and add the url after the command so it will look like this: "C:\Program Files\Internet Explorer\IEXPLORE.EXE" http://www.askjeeves.com Obviously you want your web addy at the end outside the ""'s That should do what you want, alternately you could call the command from inside python as suggested using the above system call Hope that helps Toby -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of tutor-request at python.org Sent: Friday, February 29, 2008 9:06 AM To: tutor at python.org Subject: Tutor Digest, Vol 48, Issue 71 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. How to open IE7 to a certain URL? (Dick Moores) 2. comparison bug in python (or do I not get it?) (Hans Fangohr) 3. Re: How to open IE7 to a certain URL? (Tim Golden) 4. Re: How to open IE7 to a certain URL? (Kent Johnson) 5. Re: How to open IE7 to a certain URL? (Tim Golden) 6. Re: comparison bug in python (or do I not get it?) (Kent Johnson) 7. Re: comparison bug in python (or do I not get it?) (Hans Fangohr) 8. Re: comparison bug in python (or do I not get it?) (Luciano Ramalho) 9. Re: How to open IE7 to a certain URL? (Dick Moores) 10. Re: How to open IE7 to a certain URL? (Dick Moores) ---------------------------------------------------------------------- Message: 1 Date: Fri, 29 Feb 2008 04:28:50 -0800 From: Dick Moores Subject: [Tutor] How to open IE7 to a certain URL? To: Python Tutor List Message-ID: <20080229122924.14F8D1E4003 at bag.python.org> Content-Type: text/plain; charset="us-ascii"; format=flowed I keep missing a certain weekly program on my local NPR station. My idea is to record it using software I have, Easy Hi-Q Recorder. I can set it to start recording when the program starts, 8pm, but I need to have the program playing on my computer. The URL for the station's audio is http://www.kuow.org/real.ram . I've got this so far: #!/usr/bin/env python #coding=utf-8 import time b = '20:00:00' while True: a = time.strftime('%H:%M:%S') time.sleep(0.5) if a == b: print "TIME!" break Obviously, I need to replace the 'print "TIME"' line with something that will open IE7 to http://www.kuow.org/real.ram . But what? Thanks, Dick Moores ------------------------------ Message: 2 Date: Fri, 29 Feb 2008 12:29:42 +0000 (GMT) From: Hans Fangohr Subject: [Tutor] comparison bug in python (or do I not get it?) To: tutor at python.org Cc: Thomas Fischbacher Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed Dear Python folks, here is a sequence of commands (ipython) that lead to a question. See my comments after leading '#': In [1]: 2 in [1,2,3] Out[1]: True #nothing special here, of course 2 is in the list. In [2]: 2 in [1,2,3] == True Out[2]: False #This is somewhat surprising, as one would hope that '2 in [1,2,3]' #evaluates to 'True', and then we expect 'True'=='True' to hold. #However, maybe it is an issue of operator precedence. Let's add parenthesis: In [3]: (2 in [1,2,3]) == True Out[3]: True #Okay, so this does what we expect. #However, if it is an issue of operator precedence, then what is the #operation that is carried out at prompt [2] above? # #Presumably, we work out In [4]: [1,2,3] == True Out[4]: False #which is false. So effectively, The statement at [2] seems to boil down to In [5]: 2 in False --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /Volumes/Minmax250a/Users2/fangohr/ TypeError: iterable argument required But this throws an error! And so does the full expression (with paranthesis): In [6]: 2 in ([1,2,3] == True) --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /Volumes/Minmax250a/Users2/fangohr/ TypeError: iterable argument required So what is the story here? In my view, the statement in line [2] should either produce True (as in [3]), or throw an error (as in [6]). Why does [2] return False? Would people agree that this is a bug? Thank you for your time, Hans PS I have tested this with Python 2.4, and Python 2.5 (on debian etch) -- Hans Fangohr School of Engineering Sciences University of Southampton Phone: +44 (0) 238059 8345 Email: fangohr at soton.ac.uk http://www.soton.ac.uk/~fangohr ------------------------------ Message: 3 Date: Fri, 29 Feb 2008 13:07:20 +0000 From: Tim Golden Subject: Re: [Tutor] How to open IE7 to a certain URL? Cc: Python Tutor List Message-ID: <47C80388.2070106 at timgolden.me.uk> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Dick Moores wrote: > I keep missing a certain weekly program on my local NPR station. My > idea is to record it using software I have, Easy Hi-Q Recorder. I can > set it to start recording when the program starts, 8pm, but I need to > have the program playing on my computer. The URL for the station's > audio is http://www.kuow.org/real.ram . > > I've got this so far: > > #!/usr/bin/env python > #coding=utf-8 > import time > b = '20:00:00' > while True: > a = time.strftime('%H:%M:%S') > time.sleep(0.5) > if a == b: > print "TIME!" > break > > Obviously, I need to replace the 'print "TIME"' line with something > that will open IE7 to http://www.kuow.org/real.ram . But what? Sidestepping slightly, the natural way to open a URL using whatever's set up to do so is with os.startfile: import os os.startfile ("http://whatever...ram") I was going to say that, to use IE7 explicitly, you should use the webbrowser module. But then I realised that, for reasons which I'm sure are extremely good but which elude me for now, iexplorer is not one of the registered browsers. As a fallback, you can look for its apppath entry in the registry and use subprocess to call that. TJG ------------------------------ Message: 4 Date: Fri, 29 Feb 2008 08:14:30 -0500 From: Kent Johnson Subject: Re: [Tutor] How to open IE7 to a certain URL? To: Dick Moores Cc: Python Tutor List Message-ID: <47C80536.5070000 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Dick Moores wrote: > #!/usr/bin/env python > #coding=utf-8 > import time > b = '20:00:00' > while True: > a = time.strftime('%H:%M:%S') > time.sleep(0.5) > if a == b: You might want to learn how to use your OS's scheduler to do this part. I don't know what it is on Windows though. Kent ------------------------------ Message: 5 Date: Fri, 29 Feb 2008 13:19:57 +0000 From: Tim Golden Subject: Re: [Tutor] How to open IE7 to a certain URL? Cc: Python Tutor List Message-ID: <47C8067D.2020109 at timgolden.me.uk> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Kent Johnson wrote: > Dick Moores wrote: > >> #!/usr/bin/env python >> #coding=utf-8 >> import time >> b = '20:00:00' >> while True: >> a = time.strftime('%H:%M:%S') >> time.sleep(0.5) >> if a == b: > > You might want to learn how to use your OS's scheduler to do this part. > I don't know what it is on Windows though. You've got a couple of options on Windows, actually (not including any roll-you-own or ported cron efforts). You can either use the AT command (from the command line or via WMI) or you can use the Windows scheduler, either from the control panel or programatically via the win32com.taskscheduler module from pywin32. TJG ------------------------------ Message: 6 Date: Fri, 29 Feb 2008 08:21:09 -0500 From: Kent Johnson Subject: Re: [Tutor] comparison bug in python (or do I not get it?) To: Hans Fangohr Cc: tutor at python.org Message-ID: <47C806C5.4060409 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Hans Fangohr wrote: > In [2]: 2 in [1,2,3] == True > Out[2]: False > > Why does [2] return False? Would people agree that this is a bug? No, not a bug. Don't be too quick to blame your tools! The equivalent expression is In [1]: (2 in [1,2,3]) and ([1,2,3]==False) Out[1]: False 'in' is considered a comparison operator and can be chained with other comparisons. For a clearer example, consider In [2]: 2 < 3 < 4 Out[2]: True which is not the same as In [3]: 2 < (3 < 4) Out[3]: False or In [4]: (2 < 3) < 4 Out[4]: True It is equivalent to In [5]: (2 < 3) and (3 < 4) Out[5]: True See http://docs.python.org/ref/comparisons.html Kent ------------------------------ Message: 7 Date: Fri, 29 Feb 2008 13:42:43 +0000 (GMT) From: Hans Fangohr Subject: Re: [Tutor] comparison bug in python (or do I not get it?) To: Kent Johnson , Thomas Fischbacher Cc: tutor at python.org Message-ID: Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed Hi Kent, > Hans Fangohr wrote: > >> In [2]: 2 in [1,2,3] == True >> Out[2]: False >> >> Why does [2] return False? Would people agree that this is a bug? > > No, not a bug. Don't be too quick to blame your tools! That's good news. I'd be worried if this wasn't the desired behaviour -- I just hadn't understood the logic. > > The equivalent expression is > In [1]: (2 in [1,2,3]) and ([1,2,3]==False) > Out[1]: False Ah -- that's the way to read it! > > 'in' is considered a comparison operator and can be chained with other > comparisons. For a clearer example, consider > In [2]: 2 < 3 < 4 > Out[2]: True > > which is not the same as > In [3]: 2 < (3 < 4) > Out[3]: False > > or > In [4]: (2 < 3) < 4 > Out[4]: True > > It is equivalent to > In [5]: (2 < 3) and (3 < 4) > Out[5]: True > Well explained -- makes perfect sense now. Many thanks, Hans > See > http://docs.python.org/ref/comparisons.html > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Hans Fangohr School of Engineering Sciences University of Southampton Phone: +44 (0) 238059 8345 Email: fangohr at soton.ac.uk http://www.soton.ac.uk/~fangohr ------------------------------ Message: 8 Date: Fri, 29 Feb 2008 11:32:55 -0300 From: "Luciano Ramalho" Subject: Re: [Tutor] comparison bug in python (or do I not get it?) To: "Kent Johnson" Cc: Hans Fangohr , tutor at python.org Message-ID: <4331ad810802290632u3cdc3199o17769957aaba3fc2 at mail.gmail.com> Content-Type: text/plain; charset=ISO-8859-1 On Fri, Feb 29, 2008 at 10:21 AM, Kent Johnson wrote: > No, not a bug. Don't be too quick to blame your tools! Well said, Kent. Here's a generic tip to anyone learning Python. I learned Python after working professionally with several languages for many years, including Java and Delphi, and I can say that Python is *very* well designed, is implemented with the highest standards of software engineering and caters to a rigorous and expert audience. It is **extremely** unlikely that you will ever find a bug in the interpreter or the built-ins if you are using a released version of Python. I've been using Python professionally since 1998 and I never stumbled upon a single bug anywhere in a released Python distribution. Of course, there are bugs and even security hot-fixes are issued from time to time. But I've never been affected by a Python bug in my projects. So it's better to assume that any strange behaviour is actually some misunderstanding on your part than a bug. Cheers, Luciano ------------------------------ Message: 9 Date: Fri, 29 Feb 2008 06:58:57 -0800 From: Dick Moores Subject: Re: [Tutor] How to open IE7 to a certain URL? To: Python Tutor List Message-ID: <20080229145903.10CD91E4003 at bag.python.org> Content-Type: text/plain; charset="us-ascii" An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080229/a37eafbc/attachm ent-0001.htm ------------------------------ Message: 10 Date: Fri, 29 Feb 2008 07:06:19 -0800 From: Dick Moores Subject: Re: [Tutor] How to open IE7 to a certain URL? To: Python Tutor List Message-ID: <20080229150625.90B191E401B at bag.python.org> Content-Type: text/plain; charset="us-ascii"; format=flowed At 05:19 AM 2/29/2008, Tim Golden wrote: >Kent Johnson wrote: > > Dick Moores wrote: > > > >> #!/usr/bin/env python > >> #coding=utf-8 > >> import time > >> b = '20:00:00' > >> while True: > >> a = time.strftime('%H:%M:%S') > >> time.sleep(0.5) > >> if a == b: > > > > You might want to learn how to use your OS's scheduler to do this part. > > I don't know what it is on Windows though. > >You've got a couple of options on Windows, actually (not including >any roll-you-own or ported cron efforts). You can either use the >AT command The XP help says that rather than AT, to use schtasks. I'm trying to figure it out now.. > (from the command line or via WMI) Windows Management Instrumentation is a whole new world to me, but I understand (from Wikipedia) that XP has it. I wish you'd quit opening up these cans of worms! ;-) >or you can use the >Windows scheduler, either from the control panel or programatically >via the win32com.taskscheduler module from pywin32. Thanks again, Dick Moores ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 48, Issue 71 ************************************* From ian at showmedo.com Fri Feb 29 20:02:43 2008 From: ian at showmedo.com (Ian Ozsvald) Date: Fri, 29 Feb 2008 19:02:43 +0000 Subject: [Tutor] ANN: Beginner Python screencasts in 'developing emol!' ShowMeDo series Message-ID: <47C856D3.3000703@showmedo.com> Summary - Erik Thompson is creating a long screencast series aimed at new Python programmers. You will learn to build a 3D Molecule Viewer, topics covered include Classes, Design, wxPython GUIs and pyOpenGL 3D graphics: http://showmedo.com/videos/series?name=vXJsRwlBX Detail - Currently at 14 episodes (with more to come) Erik shows you how he: * designs his application with Use Cases and Classes * uses Bazaar for source-code control * uses wxPython and pyOpenGL to create a 3D molecule viewer * bug fixes * uses the GPL and Copyright We have a total of 177 Python videos here: http://showmedo.com/videos/python?topic=all Please remember to *say Thank You* using the Comment form below the videos (or using the Quick Comments to the side of the videos) as Authors love to know that you appreciated their screencast. Alan - thanks for permission to post ANNounces. Regards, Ian Ozsvald (co-founder of ShowMeDo) -- http://Services.ShowMeDo.com http://ShowMeDo.com Ian at ShowMeDo.com From pylinuxian at gmail.com Fri Feb 29 21:56:56 2008 From: pylinuxian at gmail.com (linuxian iandsd) Date: Fri, 29 Feb 2008 20:56:56 +0000 Subject: [Tutor] authentication again a crm web application Message-ID: hi everyone, I need to get pass throught an authentication form (username & password) to access our client CRM web application automaticaly, which means at some intervals of time i need to log in to thier web site download a specific table parse it & then load it into my mysql database. the parsing & loading part is already done, the part about authenticating is still in progress, any help would be very appreciated. the site uses https. thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20080229/f4db5696/attachment.htm From janos.juhasz at VELUX.com Fri Feb 29 23:09:02 2008 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Fri, 29 Feb 2008 23:09:02 +0100 Subject: [Tutor] How to open IE7 to a certain URL? In-Reply-To: Message-ID: > > I've got this so far: > > > > #!/usr/bin/env python > > #coding=utf-8 > > import time > > b = '20:00:00' > > while True: > > a = time.strftime('%H:%M:%S') > > time.sleep(0.5) > > if a == b: > > print "TIME!" > > break > > It needn't to make this comparison in every 0.5 seconds. Calculate how long to sleep and ask that from the pc. import time b = '20:00:00' (bhour, bmin, bsec) = b.split(':') bsec = int(bsec) + int(bmin)*60 + int(bhour)*360 while True: act = time.localtime() actsec = act.tm_sec + act.tm_min*60 + act.tm_hour*360 wait = bsec - actsec if wait < 0: wait += 360*24 # it will be tomorrow time.sleep(wait) print 'I am doing!' break Regards, Janos From trey at opmstech.org Fri Feb 29 23:30:49 2008 From: trey at opmstech.org (Trey Keown) Date: Fri, 29 Feb 2008 16:30:49 -0600 (CST) Subject: [Tutor] Need help with encoder & decryption keys Message-ID: <64017.68.191.136.241.1204324249.squirrel@webmail.opmstech.org> Hey all, Been away for a while. So, I'm in the process of making a program for encrypting and decrypting strings of text. And I was wondering how it would be possible to perhaps keep keys in a .pyc file, and keep them from being isolated, and messages being intercepted. So... is it possible to decompile things within a .pyc file? This isn't for any serius project, just me attempting to make something to prove that I can do it. Thanks for any help.